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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(verse): rebuild the Verse as a starship, with a new level system (#736)
Ruben Lütke576c94f4e8fb
diff --git a/art/studies/starship-verse/review.md b/art/studies/starship-verse/review.mdnew file mode 100644index 0000000000..cc1779ee05--- /dev/null+++ b/art/studies/starship-verse/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/docs/agent-society/level-system.md b/docs/agent-society/level-system.mdindex ab9bf4101c..de2eec12b3 100644--- a/docs/agent-society/level-system.md+++ b/docs/agent-society/level-system.md@@ -1,190 +1,111 @@-# Jarvis Verse level system+# Dodaios Verse level system: the service record-Status: **built 2026-10-03.** Backend `dodaios/progression/`, REST-`/api/progression`, frontend `components/society/progression/`. The rulebook-in `dodaios/progression/rules.py` is the source of truth; this page is its+Status: **rebuilt for the starship (2026-10-19).** Backend `dodaios/progression/`,+REST `/api/progression`, data layer `components/society/progression/`, ship UI+`components/society/starship/levels/`. The rulebook in+`dodaios/progression/rules.py` is the source of truth; this page is itsreadable version.## 1. Who levels up| Subject | Id | Earns from ||---|---|---|-| The person | `person` | Talking to Jarvis, giving the team work, growing the team, small actions in the Verse |+| The captain (the person) | `person` | Talking to Jarvis, giving the crew work, growing the crew, small actions aboard || Every Jarvis agent | `agent:<agent_id>` | Finished work: results, quests, answers to teammates |-| The person's pet | `pet:<pet_id>` | Jarvis's own work (the pet IS Jarvis in the Verse) and walks with the person |+| The companion (the pet) | `pet:<pet_id>` | Jarvis's own work (the pet IS Jarvis aboard) and walks with the captain |-The lead agent (`jarvis`) never has an agent subject: it is drawn as the pet,-so its work pays the pet. Each pet keeps its own level; the pet chosen in-My Pets at the moment of the award earns it.--Coding-floor panes are not subjects: they are short-lived terminal sessions,-not members of the team.+The lead (`jarvis`) never has an agent subject: it is drawn as the pet, so+its work pays the pet. Coding panes are not subjects.## 2. XP rulesEvery award comes from one rule: a fixed amount, optionally a cooldown, adaily cap (local calendar day) or "once per reference". The server appliesevery limit against its own ledger, so a replayed event or a client that-reports twice never pays twice. Nothing calls a model; XP costs no tokens and-works with any single key.+reports twice never pays twice. Nothing calls a model.++**Server rules** (read off bus events) are unchanged: `chat_turn` 5 and+`voice_turn` 5 (100/day each), `quest_posted` 15 (75/day), `quest_completed`+20, `agent_hired` 50 (once per agent), `mission_completed` 30 (150/day);+agents `task_done` 40, `task_blocked` 8 (40/day), `quest_done` 60,+`answered_teammate` 5 (50/day); the pet `jarvis_answered` 4 (120/day) and+`delegated` 10 (100/day).-**Server rules** (read off bus events):+**World rules** (reported by the ship through `POST /api/progression/actions`):-| Source | Pays | XP | Limit | Event |+| Source | Pays | XP | Limit | Reported when ||---|---|---|---|---|-| `chat_turn` | person | 5 | 100/day | `JarvisChatTurnFinished` (done) |-| `voice_turn` | person | 5 | 100/day | `VoiceTurnCompleted` |-| `jarvis_answered` | pet | 4 | 120/day | either of the two above |-| `quest_posted` | person | 15 | 75/day | `SocietyQuestChanged` (new) |-| `quest_completed` | person | 20 | — | `SocietyQuestChanged` → done |-| `quest_done` | agent (taker) | 60 | — | `SocietyQuestChanged` → done |-| `task_done` | agent | 40 | — | `SocietyResultPosted` (done) |-| `task_blocked` | agent | 8 | 40/day | `SocietyResultPosted` (blocked) |-| `answered_teammate` | agent | 5 | 50/day | `SocietyMessageSent` ANSWER |-| `delegated` | pet | 10 | 100/day | `SocietyMessageSent` ASSIGN from the lead |-| `mission_completed` | person | 30 | 150/day | `MissionCompleted` (approved) |-| `agent_hired` | person | 50 | once per agent | `POST /api/society/agents` created a row |--**World rules** (reported by the Verse via `POST /api/progression/actions`):--| Source | Pays | XP | Limit |-|---|---|---|---|-| `daily_visit` | person | 25 | once per day (server date) |-| `floor_discovered` | person | 20 | once per floor (`agents`, `coding`, `arcade`, `hall`) |-| `dog_petted` | person | 3 | every 60 s, 30/day |-| `dog_treat` | person | 10 | every 5 min, 30/day |-| `arcade_round` | person | 8 | every 45 s, 80/day (a scored round) |-| `arcade_record` | person | 15 | every 45 s, 60/day (a new best) |-| `team_meeting` | person | 10 | every 10 min, 40/day |-| `walk_together` | pet | 3 | every 20 s, 60/day (each 50 m walked with the pet) |+| `daily_visit` | captain | 25 | once per day | the Verse opens |+| `deck_discovered` | captain | 20 | once per deck (`bridge`, `ops`, `engineering`, `holodeck`, `honors`) | the first visit of a deck |+| `holodeck_round` | captain | 8 | every 45 s, 80/day | a scored round on the holodeck |+| `holodeck_record` | captain | 15 | every 45 s, 60/day | a new best |+| `team_briefing` | captain | 10 | every 10 min, 40/day | a team gathered at its table |+| `warp_jump` | captain | 5 | every 10 min, 30/day | a jump to a known destination |+| `walk_together` | pet | 3 | every 20 s, 60/day | every 50 m walked with the companion |++The office's sources (`floor_discovered`, `dog_*`, `arcade_*`,+`team_meeting`) are retired; ledger rows that carry them still read.## 3. Level curve-Level *L* → *L + 1* costs `40 + 25·(L−1)^1.1` XP, rounded to 5; the cap is-level 50. Level 2 arrives after a handful of actions, level 10 after about a-week of ordinary use (~200 XP a day), level 50 after several months. The-server sends the whole curve (`level_xp`), so the client never re-derives it.+Unchanged, so earned XP keeps its meaning: level *L* → *L + 1* costs+`40 + 25·(L−1)^1.1` XP, rounded to 5; the cap is level 50. The server sends+the whole curve (`level_xp`).## 4. Ranks and rewards-Every subject climbs one military rank ladder; the rank is its title. A-promotion comes every two or three levels (`RANKS` in rules.py):+Everyone aboard climbs one naval ladder (`RANKS`; the frontend's copy with+the collar pips is `starship/levels/ranks.ts`, and a parity test pins them):++| Tier | Ranks (first level) | Insignia (original SVG, `Insignia.tsx`) |+|---|---|---|+| Enlisted | Cadet 1, Crewman 3, Specialist 5, Petty Officer 7, Chief Petty Officer 10 | silver chevrons (the chief over a rocker); the cadet an empty bar |+| Warrant | Warrant Officer 13 | one gold pip on a bar |+| Officers | Ensign 16, Lieutenant Junior Grade 19, Lieutenant 22, Lieutenant Commander 26, Commander 30, Captain 34 | gold pips, a hollow pip for the half grades |+| Flag | Commodore 38, Rear Admiral 42, Vice Admiral 46, Admiral 50 | a gold bar with one to four stars |++On a figure the rank is the collar: silver pips for enlisted ranks, gold for+officers, four gold for flag officers.++Rewards (`REWARDS`), each opening on a level:-| Tier | Ranks (first level) | Insignia |+| Slot | For | Pieces (level) ||---|---|---|-| Enlisted | Private (1, no insignia), Private Second Class (2), Private First Class (4), Specialist (6) | Gold chevrons on navy, worn on the upper sleeves |-| Non-commissioned officers | Corporal (8), Sergeant (10), Staff Sergeant (12), Sergeant First Class (14), Master Sergeant (16), First Sergeant (18), Sergeant Major (20), Command Sergeant Major (22), Sergeant Major of the Army (24) | Chevrons, rockers and their device (diamond, star, wreath, eagle), on the sleeves |-| Officers | Second Lieutenant (26), First Lieutenant (28), Captain (30), Major (32), Lieutenant Colonel (34), Colonel (36) | Gold and silver bars, oak leaves, the eagle, on navy shoulder boards |-| General officers | Brigadier General (38), Major General (41), Lieutenant General (44), General (47), General of the Army (50) | One to five silver stars on black boards edged in gold |--The insignia are vector art (`progression/insignia/rankArt.ts`): one set of-polygons drives the SVG icons, the Level Wall's canvas and the extruded 3D-pieces on figures and in the hall's cases.--Rewards are real uniform pieces in three slots, each unlocking on a-promotion. The person wears them; agents keep the outfit their owner dressed-them in and earn decorations only; the pet wears its rank on its name plate.--| Slot | Pieces (person level · agent level) |-|---|---|-| Uniform | service shirt and tie 4, field jacket 10, green service uniform 20, blue dress uniform 26, blue mess dress 41 |-| Headwear | patrol cap 6, garrison cap 14, black beret 24, service cap 32 |-| Decoration | service ribbons 8 · 3, full ribbon rack 18 · 16, gold aiguillette 36 · 32, full-size medals 47 · 44 |--Trims follow the rank: officers' dress uniforms carry gold cuff braid,-non-commissioned officers and up a trouser stripe; the patrol cap carries-the sewn rank, the garrison cap and beret an officer's pin (a unit crest for-enlisted ranks), and the service cap's visor one row of gold oak leaves for-field-grade officers and two for generals.--The person chooses per slot (automatic = the finest unlock, own clothes, or-any unlocked piece; stored per browser profile). Agents always wear their-best unlocks.--### Agent looks--Agents also unlock the wearable looks of their profile symbol-(`LOOK_UNLOCKS` in `rules.py`, ids from `companion/accessories.json`):--All ten looks are open from level 1 (the maintainer's choice); raising a-value in `LOOK_UNLOCKS` turns that look back into a level-up reward, and-every surface below follows on its own.--The snapshot carries them as `looks` and a level-up's `ProgressionAwarded`-names them in `unlocked_looks`. The agent's level-up toast shows the agent-already wearing its new look, the Level Hall's Team page lists every look-with its level and each agent's next one, and the Appearance picker marks a-locked look with the level it opens at. The lock is a reward, never a-penalty: a look an agent already wears stays wearable, and an unreachable-level system locks nothing.--## 5. The level-up moment--- **In the world:** a single gold ring runs out across the floor and a soft- light fades under the figure, while a plate rises over its head with the- new insignia — "Promoted · Sergeant" on a promotion, "Level 7" between- two. The person's figure hops and waves.-- **On screen:** person and pet get the promotion card — midnight blue with a- fine gold rule. On a promotion the old insignia stands, steps aside and- dims while the new one is laid on piece by piece and catches the light;- then the rank name, its grade and the rolling level number, the next- promotion between two, and each unlocked uniform piece. Agents get a quiet- toast in the corner. Level-ups that happened while the map was closed are- told once per subject ("While you were away").-- **Sound:** a synthesised fanfare (Web Audio, no files), a short chime for an- agent, a soft tick for "+XP"; switchable in the Level Hall screen.-- **Every gain:** a floating "+n XP" over whoever earned it; the HUD bar lights- the gain first and fills a beat later.--Reduced motion keeps the information (card, plate, toast) and drops the motion.--## 6. Surfaces--- Level card under the floor title: the rank insignia in a ring that fills- with XP, the rank and the bar (click or `L` opens the Level Hall screen).-- A rank chip (insignia and level) on every name plate; the lead's chip shows- the pet's.-- On the figures: enlisted insignia on both upper sleeves, officer and- general insignia on shoulder boards, the decoration over the left breast- pocket (the aiguillette from the right shoulder), the cap on the head.-- **The Level Hall**, the building's top floor (floor 3 in the elevator,- office-map.md §5f; its first visit pays `floor_discovered` like every floor): the rank wall,- the studio dais, a display case per uniform piece along the runner and the- service guide. Stepping on the dais opens the screen's Studio page, the- guide its Overview, a case its piece on the promotion road.-- **The Level Hall screen**, for the person or their pet (switch in the head):- - *Overview:* rank, level, XP bar with what is missing, the next promotion,- the next three uniform pieces (each opens in the Studio to try on) and the- quickest repeatable ways to earn.- - *Ranks:* the whole ladder as one chart, grouped by tier; ranks held in- full colour, the current one framed, the ones ahead as silhouettes with- the XP still missing.- - *Studio:* the dressing room. A live 3D preview of the person's figure on- the dais in the loadout and the insignia of their rank; per slot- "automatic", "own clothes" and every piece as a card with the rank it- comes with. An unlocked piece is put on with one click; a locked piece is- tried on in the preview, marked "Try-on" with the level and XP it still- needs. The pet's studio shows its rank.- - *Promotions:* the road from the first promotion to the cap with the- subject's position on it; the chosen step in the preview at that rank,- with its insignia, grade, tier, piece, missing XP and "Put it on" once- open.- - *How to level:* three steps (earn, level up, get promoted), the cost of- the next levels from the server's curve, and every rule for the person,- the pet and agents, grouped.- - *Team:* every agent's level and rank, best first.--## 7. Contracts--- `ProgressionAwarded` (core bus → WebSocket) carries `subject_id`,- `subject_kind`, `xp_source`, `xp`, `total_xp`, `level`, `previous_level`,- `title`, `unlocked`.-- `SocietyResultPosted` is new: `WorldFeed` forwards a board RESULT (id,- agent, status; never its text).-- `levelCatalog.ts` mirrors the ids (kinds, slots, rewards, ranks, sources) and- each rank's grade and tier;- `tests/unit/progression/test_frontend_parity.py` pins it and the three- locale files to the rulebook.-- The ledger is `<data_dir>/progression.db`, opened on the first award, never- on the boot path. Bus handlers only queue their writes, so a publisher (the- voice pipeline) never waits on the disk.+| `suit` | captain | field armour 6, command coat 16, dress whites 26, admiral's coat 42 |+| `destination` | captain | gas giant 5, crimson nebula 10, ice moon 15, twin suns 20, event horizon 25, aurora world 30, galactic core 40 (equal to `space/destinations.ts`) |+| `decoration` | captain · agents | service ribbon 8 · 3, commendation 18 · 16, star medal 36 · 32, legion of merit 47 · 44 |++The suit the captain wears is the finest open one unless chosen at the+quartermaster or in the service record ("finest open", the duty suit, or an+open suit; kept per browser profile). The helm sets the destination. Agent+looks (`LOOK_UNLOCKS`) stay open from level 1.++## 5. Surfaces++- **Rank card** under the deck card: insignia, rank, level and the XP bar; a+ click opens the service record.+- **Name plates**: the rank after every android's name.+- **Service record** (`ServiceRecord.tsx`): Record (rank, level, XP still+ missing, next promotion, what opens next, the ship's log of recent awards),+ Ranks (the whole ladder by tier, held bright, the current framed, the ones+ ahead dim with the XP still missing), Rewards (suits and destinations with+ their levels), How to earn (every rule in plain words), Crew (every agent's+ rank, best first). The rank wall and the display cases in the Hall of+ Honour open it too.+- **Promotion ceremony** (`PromotionCeremony.tsx`): for the captain and the+ companion a centred card — the old insignia steps aside, the new one is laid+ on, the rank, the level and what it opened; a quiet toast for an android.+ Reduced motion keeps the information and drops the motion. Promotions while+ the Verse was closed are told once.++## 6. Contracts++- `GET /api/progression` returns the subjects, the pet, recent awards, the+ curve, the rules, the rewards, the looks and the ranks (`id`, `level`,+ `tier`).+- `POST /api/progression/actions` takes `{action, ref}`; `deck_discovered`+ and `warp_jump` refs are checked against the decks and the destinations.+- `ProgressionAwarded` (bus → WebSocket) carries `subject_id`, `subject_kind`,+ `xp_source`, `xp`, `total_xp`, `level`, `previous_level`, `title`,+ `unlocked`.+- The ledger is `<data_dir>/progression.db`, opened on the first award.diff --git a/docs/agent-society/mars-runtime.md b/docs/agent-society/mars-runtime.mdindex fc671176a6..ba93b99e5b 100644--- a/docs/agent-society/mars-runtime.md+++ b/docs/agent-society/mars-runtime.md@@ -1,7 +1,7 @@# Mars runtime referenceStatus: development reference, not the completed colony. Since 2026-09-28-**Agents > Map** opens the agent office ([office-map.md](office-map.md)) instead+**Agents > Map** opens the Dodaios Verse starship ([starship-verse.md](starship-verse.md)) insteadof Mars; this page documents the Mars code and backend contracts, which remainin the tree. No older URL restores a previous world. The Agents workspace and communications-stationcontrols remain separate from rendering. Final character/rover art, playerdiff --git a/docs/agent-society/office-map.md b/docs/agent-society/office-map.mddeleted file mode 100644index 147604427d..0000000000--- a/docs/agent-society/office-map.md+++ /dev/null@@ -1,1086 +0,0 @@-# Agent office map (Jarvis Verse)--Product name: **Jarvis Verse** (since 2026-09-30). The interface calls the-whole map, the Map tab and the IDE side-panel tab "Jarvis Verse"; the code keeps-its `office` identifiers, and rooms and floors inside it keep their own names.--Status: **team campus (2026-10-12).** The agents floor was rebuilt from the-2026-09-28 prototype: one studio per team instead of provider departments, a-larger plan with an atrium and commons, stations that are the objects-themselves, team-aware behaviour and the Level Hall on its own floor (§5g–§5i).-Sections 2–5 describe the engine and the rooms the rebuild kept; where they-disagree with §5g–§5i, the later sections hold.-It replaces the Mars colony as the renderer behind **Agents > Jarvis Verse**. The Mars-code, its backend contracts and the communications station remain in the tree-and reachable from the Agents workspace; only the map surface changed.--Per [game-art-pipeline.md](game-art-pipeline.md) §3 this runtime scene is the-reference for the office direction. Do not roll its style out to other asset-families or replace figures before the maintainer approves it.--Code: `dodaios/ui/web/frontend/src/components/society/office/`.--## 1. Why an office--The previous worlds (pixel island, Mars colony) were large, navigable places-that cost a lot of authored art and backend navigation to show one thing: what-the agents are doing. The office answers that question in one screen. Every-agent has a desk, departments group them, and a status ring, a monitor face and-a name pill show the run state. It is a projection of the roster only: the map-never moves an agent, starts work or invents activity (world-behaviour-manual-§1 still holds).--## 2. Style guide--| Aspect | Rule |-|---|---|-| Genre | Stylised "toy office" diorama: chunky low-poly 3D, not anime, not pixel art, not realistic. |-| Characters | Chibi proportions (big head, short body), dot eyes, flat matte colours, no textures. Seated at desks; the stored figure recipe is kept, agents without one get a stable chibi look. |-| 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 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 is a floor of the same tower (§5j). |-| 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). |-| HUD | Theme-token cards over the canvas, so light and dark mode both work: one floor card (name and who is doing what), the level card, the minimap, a small icon toolbar and one prompt (§5g). The diorama itself keeps one palette in both modes. |--## 3. Technology decision--**Three.js through React Three Fiber, in the existing frontend.** This beat the-runner-up (a Blender-authored scene exported as GLB) because the office look is-built from boxes, cylinders and rounded boxes: code builds it in milliseconds,-it adapts to any roster size, and it needs no asset pipeline. Blender stays the-tool for anything organic later (new character bases, special props), following-the game-art pipeline. No engine change (Unity, Godot, Babylon) is warranted:-the renderer is already Three.js inside the WebView, the figures and their-animation clips (`sit`, `work`, `idle`, `walk`, …) already exist, and every OS-target runs WebGL.--## 4. Floor plan and data model--The plans are pure and tested. `officeLayout.ts` holds the shared vocabulary-(types, footprints, desk and wall helpers) and the coding floor's plan;-`buildOfficeLayout(agents, { variant, teams })` hands the agents floor to-`campusLayout.ts`. The Level Hall (`hallFloorLayout.ts`) and the arcade-(`arcade/arcadeFloorLayout.ts`) have floors of their own.--- **Agents floor: a team campus** (§5h). North strip: focus booths, lead- office, team room, wardrobe, library. Middle: one studio per team, shoulder- to shoulder in rows of four, two either side of the boulevard. South strip:- café, lobby with the elevator, break room.-- **Coding floor:** north strip Mission Control, team room, server room;- departments = IDE workspaces, two columns, at least four (spare ones are- "Open space"), at most six (the rest fold into "Other"); south strip lobby- and break room.-- **Spawn point (both working floors):** a round pad with a terminal. On the- agents floor it stands in the atrium, where the two boulevards cross; on the- coding floor on the crossing of the centre aisle and the cross aisle nearest- the floor's middle. `layout.arrival` (south of the terminal) is where anyone- new to the floor appears.-- **Furniture** has fixed footprints (`FURNITURE_SIZE`) shared by renderer and- navigation; **spots** are hangout places with pose and facing; **checkpoints**- are action places; **obstacles** are every solid footprint.-- Seating is by arrival (`createdMs`, then id), so a refetch never re-seats anyone.--## 5. Behaviour, player and interaction--- **Navigation** (`officeNav.ts`): a 0.2 m occupancy grid, A* with line-of-sight- smoothing, and a final snap onto seats that sit inside a furniture footprint.-- **Agents** (`officeBehavior.ts`, `OfficeAgents.tsx`): working → seated at their- own screen; waiting → standing at the desk, waving; paused → napping on a- couch; idle → a weighted day that, on the agents floor, happens mostly in and- around the agent's own team studio and only sometimes at the shared places- (§5i). A running round of a team and a message from one agent to another are- shown as they happen (§5i). Places are reserved so nobody sits or stands on- anybody. All of it is client-side, deterministic per agent, costs no tokens- and never starts or stops work. Reduced motion places agents without walking.- Agents created while the office is open appear on the spawn pad in a column- of light and walk to their desk.-- **The person's character** (`OfficePlayer.tsx`, `playerProfile.ts`): WASD /- arrows (camera-relative, Shift runs) or click the floor to walk; a click- draws the route as dots to a ring at the destination. E interacts with the- nearest agent or station. The character walks round people and furniture- and never comes to rest inside anything solid (§5i). Name and body are- chosen in the wardrobe and stored per browser profile (not roster data).-- **Camera** (`OfficeCameraRig.tsx`): one orbit camera that glides after the- character; zoom out and it is the overview. Everything stays clickable from- afar, so walking is optional. A right-drag pan or a fly-to stops following;- moving resumes it. Inside a walled room the walls between camera and- character drop to a kerb (§5i).-- **Stations** (`stations.ts`, `StationObjects.tsx`, `OfficePanels.tsx`): every- action place is an object of the room, one station per job. Spawn terminal →- a new Jarvis agent (the app's create dialog; a host without one, like the IDE- side panel, creates at once); reception desk → the directory (agents, places,- controls, settings); team board → teams (the existing chat groups); a team- studio's board → that team; wardrobe mirror → your look; the lead's desk →- talk to the lead; coffee bar → call free agents for a coffee break (visual- only). §5g has the details.-- **Agent panel:** open chat, walk there, call over, show on map, add to a new team.--## 5a. Figures, pets and live monitors (2026-09-28, round 2)--- **Toy figures** (`ToyFigure.tsx`, `toyFigureModel.ts`): every agent and the- person are procedural toy characters — big round- head, dot eyes, smile, T-shirt, trousers, chunky sneakers, eight hair/hat- styles. Colours come from the stored figure recipe; hair from a stable hash- (the person picks it in the wardrobe). Poses are pure and tested: the hips- land exactly on each seat height (chair 0.52, couch 0.56, meeting 0.50,- beanbag 0.42) and nothing reaches more than 0.16 m behind the seat centre,- so figures no longer clip through backrests. Chairs sit 0.62 m from the desk- centre and keyboards at the desk edge so the short arms reach them.- The agent creator still shows the older rigged figures; switching it to the- toy style is the rollout step after the maintainer approves this look.-- **Pets**: each agent's symbol (the profile companion) follows it at about a- fifth of its height, reusing `AgentFollower`; the lead is drawn as the- person's own pet (see *Jarvis is the person's pet* below).-- **Accessories** (`companion/accessories.ts`): a symbol can wear one item per- slot, chosen in the agent profile's Appearance tab or the companion editor- and stored as `companion.accessories` in the avatar JSON. The set is ten- finished pieces (suit, tuxedo, lab coat, coder hoodie, crown, top hat, cap,- headphones, sunglasses, cigar); clothing starts just below the eyes with- sloped shoulders so the face stays free, and the hoodie's hood frames the head.- `scripts/art/companion_accessories.py` writes one catalog of 3D primitives- (`accessories.json`); the flat symbol draws their front projection and- `scripts/art/build_companion_accessories.py` (background Blender) builds the- same parts into `assets/society/companions/accessories.glb`, so the profile- picture and the map companion always match. Clothing is clipped to each- silhouette; unknown ids from a newer build are skipped, never rejected.-- **Live monitors** (`LiveMonitors.tsx`, `useDeskChats.ts`, `deskChat.ts`): an- agent seated at its own desk shows the tail of its chat (user lines, replies,- running tools) on its monitor, refreshed by jittered polling of the existing- session endpoint for seated agents only (at most six reads at once, the- longest unread first, so every monitor of a full floor gets its turn; each- read has an eight-second timeout and the ticks do not wait for it). Clicking the- screen dives the camera into it and then opens that agent's chat.- Follow-up: a `limit` query on the session endpoint, so long chats are not- fetched whole.-- **Pace**: the person walks at 2.0 m/s and sprints at 4.4 m/s (Shift).- Working agents stay at their screen even when called.--## 5b. Coding floor (2026-09-29)--A second floor for the coding agents that run in the Agentic IDE's terminal-panes. It shares the office's engine, style and controls; only the people and-the floor plan differ.--- **Elevator**: the reception elevator is a checkpoint on every floor. Its- call button opens the floor picker (see §5e; before the arcade floor it- simply went up or down). The ride is a short door-like fade, and- the person steps out at the elevator of the other floor. The floor survives- a remount of the stage.-- **Floor plan** (`buildOfficeLayout(agents, { variant: "coding" })`): one- department per IDE workspace; no lead office and no wardrobe (a quiet zone- takes their place, built from existing furniture); reception with the- elevator and the break room stay. The agents office layout is unchanged.-- **Spawn point** (2026-09-30): the coding floor's spawn point replaces the old- lobby kiosk. Its panel is Mission Control's launcher (CLI, workspace, how- many, optional first task, through the IDE's own `POST /terminals`); every new- pane appears on the pad and walks to its desk. `SpawnPoint.tsx` builds pad,- terminal and fittings in each floor's own materials (oak, bronze and a mint- glow with the brass ghost downstairs; walnut, brass and amber with a brass- `>_` upstairs); two gyroscope rings turn round the floor token.-- **Jarvis follows**: on the coding floor Jarvis flies (or walks) in "follow"- mode beside and behind the person with a smoothed lag and never inside a- wall, including in the elevator. In the agents office it keeps its- lead-office behaviour.-- **Jarvis is the person's pet** (2026-10-02): Jarvis appears as the pet- chosen in Settings → My Pets (`docs/pets.md`), in 3D, not always as Gigi.- `companion/petCompanions.ts` maps a pet to its companion:- Gigi keeps its hover model; the seven other built-ins have authored Blender- models (`scripts/art/build_pet_companions.py`, study- `art/studies/dodaios-pet-companions`, one GLB per pet under- `assets/society/companions/pets/`) and a gait of their own: Ember the- dragon flies with beating wings, Miso the cat trots, Cocoa the puppy trots- with flopping ears and a wagging tail, Bolt the battery- waddles, Brew the teapot hops with a rattling lid, Mochi bounces and Shelly- the snail crawls. Pets that fly hover at head height with Gigi's halo and- sparkles; pets on the floor (`gigiFlight.ts` `ground` mode) walk right- behind the person's feet, take floor routes (`findPath`) on errands instead- of flying over desks, and carry their nameplate low. Limbs move by- `companion/petRig.ts`, phased by ground covered so feet do not slide;- reduced motion stops every gait. A pet the person drew becomes a voxel- figure extruded from its own idle frames (`voxelPet.ts`), facing the camera- and floating low. The stage feeds the choice through- `companion/companionPetStore.ts`, so a change in My Pets swaps the- companion live.-- **Pane to character** (`codingFloor.ts`): every running coding-agent pane- (Claude Code, Codex and the other agent CLIs; not plain shells, not archived- panes) is one character. Its id is `pane:<workspace>:<history id or key>`,- and its look (figure and palette) is random but stable, hashed from the- pane's history id. Name comes from the pane's short title, department from- its workspace.-- **States**: working, starting or pending → sits at its computer; asking →- waits at its desk and waves; idle, done or exited → walks around and hangs- out in the break room; an error keeps the agent at its desk. The exact- mapping lives in `codingFloor.ts` and its tests.-- **Live monitors** (`TerminalMonitors.tsx`, `usePaneScreens.ts`,- `terminalScreen.ts`): an agent seated at its desk shows its terminal live —- dark background, monospace text, the last rows that fit, a cursor block and a- title bar with its name and state dot. Screens come from the read-only- `GET /api/agentic-ide/screens?pane=<workspace>:<key>` feed (at most eight- panes per call; it never resizes, attaches to or writes into a terminal).- Only seated agents near the camera are polled (six at most), on a jittered- 1.2–2 s schedule that pauses while the stage is asleep, and a monitor- redraws only when its screen changed. Idle or absent agents show a dim- screensaver.-- **Open session**: clicking a monitor (or E at the agent → "Open session")- dives the camera into the screen and then opens the Agentic IDE with that- pane focused (`codingNavigate.ts`).-- **IDE side-panel tab**: the coding floor is also the "Office" tab of the- Agentic IDE's side panel (`components/agentic/sidePanel/OfficeTab.tsx`),- added from the panel's "+" menu or its closed-panel rail. It lazy-loads the- stage in a compact layout on the coding floor, inside its own error boundary,- so a failed scene stays inside the tab. Bringing the tab forward widens a- narrow panel to 520 px once; the user can drag it back. There a monitor click- focuses the pane in the grid right next to it, and the office's "open the- ledger" action brings the Agents tab forward.-- **Its own look** (`CodingFloorLook.tsx`, `CODING_SCENE` / `CODING_STUDIOS`- in `officePalette.ts`): same plan as the agents office, none of its- surfaces. A violet night instead of navy, a fine terrazzo floor instead of- warm planks, and a glowing cyan rim under the slab edge. Every workspace- department is furnished as a studio of its own — carpet pattern (grid,- stripes, checker, dots, diagonal, zigzag) with a border, a painted sign wall,- and desk and chair colours — cycled by the department's index. All of it is- flat or outside the railing, so navigation is unchanged.--## 5c. Lead office as an executive suite (2026-09-29)--The lead office is the one room that breaks the plain toy-office palette on-purpose, so the boss's room reads as the most precious place on the floor-(`LeadSuite.tsx`, colours in `LEAD_SUITE`):--- **Shell:** smoked-oak chevron floor, the same steel-and-glass walls as- every room, a door sign lettered in bronze. Since 2026-10-12 the suite's- palette is the campus's own a tone deeper (smoked oak, bronze, cognac- leather, a slate rug; see 5h), so where this section says walnut, brass,- oxblood or navy, read those.-- **Feature wall (north, 2.9 m):** walnut slats around a backlit black-glass- star emblem, two lit bookcases with books, trophies and vases, warm LED coves.-- **Executive desk:** 2.4 m walnut desk with a brass edge, three monitors, a- banker's lamp, a star plaque on the visitor side and a high-back oxblood- leather chair. Seat distance and height match every other desk, so the- seating and figure-pose contracts are unchanged. A second lead gets a- partner desk; there is never an empty lead desk.-- **Furnishing:** navy rug with a gold border and medallion, two tan club- armchairs for visitors, a bar cabinet and a chesterfield lounge with a glass- coffee table along the west wall (fronts towards the camera), a floor globe,- two floor lamps and palms. Two warm point lights make the room glow.-- **Sit at the desk (2026-09-29):** the executive chair is solid, so nobody walks- through it. Walk up and press E, or click the chair, to sit (`leadSeat.ts`);- any movement stands the character up. Clicking the monitors dives into them- and opens the lead agent in the agents view, like any agent's desk screen.-- **Office dog (`OfficeDog.tsx`, `dogLife.ts`, `dogProps.tsx`):** a black-and-tan- rottweiler figure with jointed legs, head, ears, tail and tongue. It has baskets in- the lead office, the team room and the break room and lives in the room of its- current basket: sleeps, roams, sniffs, sits, lies down. Now and then it walks (never- jumps) to another basket. Pet it with E or a click: it sits, wags, shows hearts and- follows the person inside its room for 30 s. Easter egg: the treat jar beside the- break room's coffee bar hands out a bone; give it to the dog and it begs, catches- it, spins twice in the air with gold sparks and chews it in its basket.-- Every piece stays inside its `FURNITURE_SIZE` footprint (props test) and the- navigation tests still reach every seat, spot and checkpoint.--Awaiting the maintainer's visual review like the rest of the office.--## 5d. Contemporary look (2026-09-29)--The maintainer rejected the first look as a 1990s office and asked for a-genuinely modern one. The shared kit (`OfficeFurniture.tsx`,-`DeskInstances.tsx`), the floors and room surfaces (`OfficeScene.tsx`,-`OfficeRooms.tsx`) and the palette (`officePalette.ts`) were restyled as in §2;-the coding floor keeps its own terrazzo, night and studios, now in the same-contemporary kit with tone-on-tone patterns. Seat height, desk height, monitor-screen position and every footprint are unchanged, so poses, live screens and-navigation work as before. Still in the earlier style and waiting on the-maintainer's review of this reference before they follow: the lead suite, the-reception desk, the team room table and chairs, the lockers and-mirror, the coffee bar, the water cooler and the arcade.--## 5e. Arcade floor (2026-10-02)--A third floor on top of the building: a retro arcade hall with ten playable-cabinets. No agents work here; it is a place for the person (and their pet,-which follows like on the coding floor).--- **Elevator**: pressing the call button (click, or E at the doors) opens a- floor picker (`ElevatorPanel.tsx`) that lists all four floors top first;- a click, Enter on the focused floor or the floor's number key (0 agents,- 1 coding, 2 arcade, 3 Level Hall) rides there, Escape closes it. The call button shows- up, down or both arrows depending on the floor (`callDirection`).-- **Floor plan** (`arcade/arcadeFloorLayout.ts`, `buildArcadeLayout()`),- reworked 2026-10-02 after the maintainer found the first open hall- confusing: it now reads like the floors below. North strip: three walled- game rooms (Classics: Pixel Raiders, Maze Muncher, City Defense, Paddle- Duel; Puzzle corner: Block Drop, Neon Snake, Brick Breaker; Action zone:- Asteroid Run, Desert Dash, Road Hopper), cabinets on each back wall facing- the door. Middle: the open hall (pinballs, air hockey, dance floor, floor- logo). South strip: the foyer with the elevator and token machines, the- prize shop (counter, claw machines) and the snack bar. The doors of north- and south rooms face each other on three lanes that stay clear. Cabinets- are furniture of kind `retroCabinet` with the id `cabinet-<gameId>`; the- person plays standing 0.85 m in front of one (`OfficePlayer`- nearest-interactable, E opens it). Tests prove every play spot, counter- and room is reachable from the elevator and that the lanes stay free.-- **Look** (`arcade/ArcadeHall.tsx`, `ArcadeHallProps.tsx`,- `arcadeHallLook.ts`, `arcadeScreens.ts`): smoked-glass walls with a neon- cap in each room's colour (never hidden or popping away at any camera- angle; frames, glass and neon are three merged meshes), a lit name board- over every door, each room's own floor and neon floor logo, a calm- blacklight carpet in the hall. One shadow light plus hemisphere and- ambient; neon is self-lit. Cabinets show two-frame attract screens- flipped by a texture offset. The first version's live title-screen- preview froze the frame for 0.2-0.6 s whenever the person walked up to a- cabinet and was removed; frames at a cabinet now take 2-11 ms in a dev- build (measured with `window.__officeGl.info` and timed `__officeStep`).-- **Games** (`arcade/games/*.ts`, contract in `arcade/retroGame.ts`, registry- in `arcade/arcadeGames.ts`): Neon Snake, Brick Breaker, Paddle Duel, Block- Drop, Maze Muncher, Desert Dash, Pixel Raiders, Road Hopper and City- Defense are original Canvas 2D games (pure state + fixed 60 Hz step, no- assets, no ROMs), code-split and loaded on first play. Asteroid Run, the- break room's 3D game, has a cabinet here too.-- **Cabinet overlay** (`arcade/RetroArcadeOverlay.tsx`): a modal at the- cabinet with marquee, crisp integer scaling, start / pause (P, blur) /- game over, best score per game in localStorage, keyboard, gamepad, mouse- where a game aims with it, and a touch pad on coarse pointers. Escape or E- leaves.--## 5f. Levels (2026-10-03, ranks 2026-10-05)--The person, their pet and every agent level up from real work: finished-Jarvis turns, agent results, quests, missions, new agents, plus small metered-actions in the Verse (daily visit, floors, the office dog, arcade rounds, team-meetings, walks with the pet). Levels climb a military rank ladder from-private to a five-star general. A level card sits under the floor title,-every name plate wears a rank chip, `L` opens the Level Hall screen, and a-promotion plays a gold ring and a rising insignia plate in the world plus the-promotion card on screen. Figures wear their insignia on the sleeves or-shoulder boards, and the person their unlocked uniform, cap and decorations.-The whole contract lives in [level-system.md](level-system.md).--The Level Hall is the levels' own floor, the top one of the building (floor-3 in the elevator, `hallFloorLayout.ts`): a small foyer where the person steps-out of the elevator, and behind its door the hall, 9.2 m wide and 34 m deep.-No agents work there; the person's pet comes along. Visiting it is not yet-paid as a discovered floor: the server's list of floors does not know it, so-the map does not report it. It is dressed as a hall of honour: cream and charcoal marble underfoot, walnut and brass, a red-runner up the middle. The rank wall in the north holds all 24 insignia in a-walnut-framed velvet shadow box (held ranks struck in metal, the current one-framed in brass, the ones ahead as pewter silhouettes) above a brass plaque-with the person's rank, level, XP and next promotion; the studio dais stands-in front of it. Display cases line the runner, one per uniform piece (lowest-unlock in the south): a mannequin in the uniform with the person's own-insignia, a cap on a velvet head form, or the decoration on a slanted velvet-board — the same geometry the figures wear. Unlocked cases are lit, locked-ones stay dim behind smoked glass; a brass plaque names the piece and its-rank, and a click opens it on the promotion road. The framed service guide-stands at the runner's start. Its two checkpoints, the dais (`studio`) and the-guide (`levels`), open the Level Hall screen (level-system.md §6).--## 5g. Stations, HUD and name plates (2026-10-12)--Stations used to be floating tokens over gold floor rings with a label pill-each, and every one opened a narrow side card. They are now the objects-themselves, and what they open is the app's own surface.--- **A station is an object** (`stations.ts`, pure and tested). Every checkpoint- and every team studio's board is bound to the piece of the room that stands- for it, by furniture kind nearest to the checkpoint: spawn terminal,- reception desk, team board, dressing mirror, coffee bar, elevator, Mission- Control's wall, the Level Hall's dais and guide, and the lead's desks (their- `desk:<id>` groups). Nothing floats over the floor and nothing is painted on- it at rest.-- **Showing that it can be used** (`StationObjects.tsx`, `stationRim.ts`): an- invisible click target the size of the object keeps every station usable from- the overview, so walking stays optional. While the person stands at it,- points at it or has it open, the object wears a thin blue rim on its own- silhouette: each of its meshes gets a shell pushed out along the normals and- drawn back faces only. The rim fades in and out; reduced motion switches it.- The lead desk's target is its visitor-side front panel, so the chair and the- monitors keep their own clicks.-- **One prompt** (`OfficeHud.tsx`): bottom centre, a key cap, the action and- the object's name ("E · Create an agent · Spawn point"). It names what the- character stands at, or, with "Click" in place of the key, what the pointer- rests on from afar. It is a real button.-- **Keyboard and screen readers**: the toolbar's Places button opens a card- that lists every station of the floor as real buttons (open it, or walk- there), the rooms' places first and the team studios under "Teams", each- under its team's name (the studio of agents without a team is "Without a- team"). Arrow keys move through the rows, right and left reach a row's- "walk there", Home and End jump; arrow down on the button opens the card- on its first row. Resting on a row lights its object in the world. The- card is opaque, as tall as its list down to the stage's lower edge (capped- at 680 px), and fades at its lower edge while there is more to scroll. The reception's Places tab is the same list.-- **Focus**: closing a dialog (Escape, its close button) hands focus to the- map's canvas host, so the walking keys answer at once; a docked panel does- the same on Escape.-- **What a station opens** (`OfficePanels.tsx`, `StationSheet.tsx`):-- | Station | Opens |- |---|---|- | Spawn terminal (agents floor) | The camera dives into its screen, then the app's create-agent dialog opens. Agents are created only here. |- | Spawn terminal (coding floor) | Mission Control's launcher, as a dialog. |- | Reception desk | The directory: agents (show on the map, open, the agents view), places, the controls guide, settings. `H` opens it on the controls from anywhere and closes it again. |- | Team board (team room) | Teams: members with their state, meet at the table, the team's real chat, rename, members, delete, new team. |- | A team studio's board | The same sheet on that studio's team (`{ kind: "team", id: <Studio.board.id> }`). Its "Meet at the board" gathers the team right there, on the standing places in front of the board (`boardSeats`, `TeamMeeting.boardId`); the meeting card then counts who is "at the board" and offers "Go to the board". The board of agents without a team offers to make them one. |- | The free plot's stand | The same sheet, opened on the new-team form ("Start a team here"). The stand is the furniture piece whose id starts with `team-stand` (`TEAM_STAND_ID`); it selects `{ kind: "team", id: <its id> }`. |- | Wardrobe mirror | The look editor, docked at the side so the character stays in view and can keep walking. |- | Lead's desk | Selects the lead (the walkie-talkie panel). |- | Coffee bar | Calls the free agents to the lounge; using it again sends them back. The answer is one line in the HUD. |- | Elevator, Mission Control, Level Hall | As before: the floor picker, Mission Control, the Level Hall screen. |-- The teams sheet does one job at a time: the new-team form replaces the- list, its member list scrolls on its own (search from seven agents up) and- its buttons stay pinned to the sheet's lower edge.- Dialogs are built like every other dialog of the app (same scrim, surface,- header and type scale, the shared button, input, tabs and switch). A team- sent to the table closes the sheet so the person sees it gather; the- gathering then shows as a small card under the level card, which also lets- the team go when its time is up.-- **Live means a real round** (`teamStatus.ts`, pure and tested): "Meet" is a- gathering on the map only — members walk over, nothing is posted to the- team and no agent starts work. The card says so ("Launch crew · called to- the table", "Send them back", no live dot), the team's row and the team- room's board mark it with a plain "Called". The green "Live" mark, on the- row and on the board, comes only from the backend's running round- (teamwork's `TeamRound.running`).-- **HUD**: top left the floor card (name, and one line of working / waiting /- idle) and the level card; top right the minimap with a five-button icon- toolbar beside it (follow me, overview, places, the floor's list, help);- bottom centre the prompt. The compass bar, the six text buttons and the- permanent controls line are gone: the wardrobe and the Level Hall are places,- `L` and the level card open the Level Hall. First-time visitors see the four- essential controls once in a card they dismiss; that is remembered per- browser profile (`officeSettings.ts`, `hintsSeen`) and the reception's- settings bring it back. In the IDE side panel the toolbar is a column in the- corner.-- **Name plates** (`namePlate.ts`, pure and tested): a dot from afar, the whole- plate within 10.5 m of the camera or 4.6 m of the person, for the agent the- pointer or keyboard focus rests on, and for the selected one. A plate closes- again only beyond 12.5 m / 6 m, so it does not flicker at the threshold. Dot- and plate share one grid cell, so nothing moves when one takes over from the- other; the plate's button stays in the tab order while it shows a dot.-- **Plates in a crowd** (`plateCrowd.ts`, pure and tested): a plate is wider- than the figure under it, so people standing together would stack their- plates. Every frame the plates that want to open report where they would- sit on screen and are seated in order: the selected or pointed-at agent- (always), whoever speaks in a team round (with room kept free above the- plate for its speech bubble), plates that are already open, then the- nearest to the person. A plate that would cover a seated one, or the- person's own plate, stays a dot. Opening needs 12 px of clear space,- staying open only 2 px, so a plate at the edge of another does not flicker.- The seating is kept per stage (keyed by its scene, released when its last- plate unmounts), so two offices awake at once never seat each other's plates.-- **In-world labels stay under the HUD**: the viewport is one stacking- context, so no plate or bubble can lie over a HUD card.-- **Faces in lists** (`AgentFace.tsx`: directory, team rows, member lists,- member picker) are drawn without the run state: a working agent's symbol- would turn into its three thinking dots, which in a list reads as a picture- still loading. The state dot and word beside the face say it. Every face- sits on a neutral tile from theme tokens with a hairline in the text colour- round the symbol's own outline, so a white symbol stays readable on a light- dialog and a black one on a dark dialog.--## 5h. Team campus and the building (2026-10-12)--The maintainer found the agents floor far too small and built round model-providers instead of teams. It is now a campus whose unit is the team: a-street of team rooms round an atrium, with commons people use in between.--- **Teams are studios.** A team is a society chat group (`teams` option, fed- from `useSocietyChatGroups` in the stage). Every team has a studio; agents- without a team share the pool studio, which always comes first. An agent in- several teams sits in the oldest one (ties by id); lead-tier agents keep the- lead office; a team whose members are unknown still has its (empty) studio.- `planStudios` decides who sits where, `layout.studios` describes each- studio (team, seated members, board, huddle places, centre) and- `Department.teamId` links its desks.-- **A team's lead sits at the head of its studio.** The roster names a lead- per team (`lead_agent_id` of the chat group, `OfficeTeamInput.leadId`). A- lead who is a member the roster knows, and who does not sit in the lead- office, takes the head desk: the first desk of the bench nearest the name- wall (`dept.desks[0]`). It changes places with the earliest arrival, who- would sit there; everyone else keeps arrival order. So naming a lead- moves two people and changing one at most three (old lead back to its own- place, new lead to the head, the earliest arrival to the new lead's- place); the studio's size and everyone outside the team stay as they are.- Leading a team comes before "the oldest team" for an agent in several and- before the seat cap; an agent named lead of two teams sits with the older- one. `Studio.leadId` is that seated lead and null in every other case (no- lead, not a member, unknown, in the lead office): never guessed.- `leadDesks(layout)` lists the desks. The lead's place is marked- (`leadMark` in deskKit.ts, drawn as instances by `DeskDressing`): a deep- red shell on the back of its chair with a bronze cap along the top edge- and a pad on the seat in the same red (one red in every studio, because- the studio's own chairs already wear the team's colour; a test holds it- clear of every studio's fabric, panel and rug), a chair mat in the team's colour- on the floor under it, and a name stand on the desk's front right corner- whose plate, in the team's colour, leans back towards the camera. The chair is what the south-east camera sees first- and it stays when the lead is at the board; the mat is what reads from- the overview. `leadMark.test.tsx` puts the mark through the real cameras- at 1600 x 900: in the follow view the shell covers about 43 x 45 px and- the plate 15 x 12 px, in the overview the mat at least 11 px each way,- with no monitor, screen, chair, sitter or pendant in front. The plan is- rebuilt when a lead is named or changed, and by nothing else new.-- **A studio is a room** (`studioShape`, one cell: 11 m wide). At its back a- name wall capped in the team's colour, the team's name on the west half and- the studio board in front of the east half with four to seven huddle places- south of it. Low felt-and-glass screens close both sides (two studios- shoulder to shoulder share the one between them). The front is planted,- with a 4.8 m entrance in its middle. Inside: the desks — one free desk to- grow into, whole facing pairs, spread evenly over as few benches as hold- them (two members: four desks; twelve: fourteen) — a storage cabinet under- the name, a sofa by the entrance and a standing table opposite, each with- its spots; a rug in the team's colour and a slim pendant light over every- desk row (five centimetres wide, 2.75 m up, on two wires from the ceiling- line, a soft pool of light on the floor below). Nothing overhead is wide- enough to stand between the camera and the people at the desks. Only the- desks grow with the team, so a team of three still has a furnished room.- Twelve colours, so a full campus never repeats one. A studio seats up to- 32; the newest members of a larger team sit in the pool, and a pool of more- than 32 opens a second pool studio.-- **The plan** is four cells wide at every size (51.8 m between the window- strips: four cells, the boulevard and a 1.4 m promenade along each window)- and grows southwards by a row of studios whenever a row is full, up to- three rows (twelve studios; later teams fold into the pool). Along both- windows the promenade leaves 2.35 m to walk between the benches and- planters at the glass and the outer studios' screens. The- boulevard (5 m) runs on the floor's axis from the lobby to the team room's- door; streets between rows are 3.6 m. The main boulevard (9 m) crosses in- the gap between two blocks nearest the floor's middle, and at the crossing- lies the atrium. Every route from the lobby to a studio or a north room- passes over it. Rooms, studios and commons take about 70 % of the plan.- Sizes including the window strip: 55.0 m x 47.0 m for one row (five agents- without a team, or fifteen in three teams), 55.0 m x 81.2 m for forty- agents in eight teams. The floor it replaces measured 24.4 m x 38.2 m plus- the Level Hall's wing.-- **The atrium** is the campus's heart: the spawn point on a pale stone disc- inside a bronze ring, a flight of step seating on either side facing it, a- large tree behind each, and a ring of light over it. The step seating has- dark risers under pale oak treads that nose out over them; the lowest tier- is plainly a seat (a linen pad and a back cushion per place, where people- sit) and loose cushions in the studios' colours lie on the tiers above.- The ring is a light fitting: a steel band the size of the disc, 2.9 m up,- whose inner face is a warm lamp, hung on six rods from the ceiling line.- The lobby's name stands on an arch against the back of the reception desk- (`Room.arch`), not at the atrium's rim.-- **Commons** are named places with spots, so idle people go there: the café- beside the lobby (kitchen run, island, standing tables, sofas), the library- in the north-east corner (bookcases, reading chairs, a sofa on a rug), the- focus booths in the north-west corner (three booths a person walks into, a- sofa, a standing table), and in a cell without a studio the free plot or a- garden court (a lawn, one large tree, two olives, two benches). The free- plot is the first empty cell, the next team's place: the bare floor taped- out with dashed marking tape, its lettering on the floor, a stack of moving- crates and a plant at the back, and at the street side the team stand- (furniture kind `teamStand`, id `team-stand`, one per plan while a plot- exists), where a new team is started.-- **Stations** stand in front of what the person uses: the spawn terminal in- the atrium, the reception desk (the one directory and help station; the- agent-board totem and the reception's own create station are gone), the- team board, the wardrobe mirror, the lead's desk, the coffee bar, the- elevator, and the free plot's team stand.-- **Fittings and planting are data** (`agentsAmbience.ts`, `layout.ambience`):- screens, cabinets, sofas, standing tables, booths, step seating, the- kitchen, benches, planters, crates, olive trees and large trees are items with a- footprint, each an obstacle and a few entries of instanced meshes- (`CampusFittings.tsx`, `AgentsFloorAmbience.tsx`). Planting is a few- deliberate groups of two kinds of tree, not rows. `layout.zones` names the- flat areas (boulevard, plaza, atrium, plot, garden, booths, library, café)- for the ground (`CampusGround.tsx`) and the maps.-- **Maps:** the minimap and the full map paint the paved boulevards, the- atrium, the commons' carpets, the free plot, trees, fittings and every- studio's name wall. The full map's sheet takes the plan's shape, names- each studio on the street behind its wall (shrunk or cut to the studio's- width, clear of the people inside) and each commons along its south edge;- the pool is "The Pool". The minimap zooms out to 90 m.-- **The building** (`BuildingShell.tsx`, agents floor and Level Hall): the- tower's dark body under the slab, and on the floor's far sides a 3.4 m- 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 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.-- **The sky pad and the courier** (`skyPad.ts`, `SkyPadStructure.tsx`,- `SkyCourier.tsx`, agents floor only): the main boulevard runs on through a- doorway in the east window wall (the balustrade has the same gap) as a 5 m- bridge to a round landing deck of 12 m radius, at floor level, inside the- city's empty plaza. The deck is graphite with a gold landing circle,- chevrons and a touchdown cross, a breathing cyan light round its rim, glass- rails, four light masts (glowing lamps, not light sources) and steel struts- back into the tower. The courier- stands on it: a chrome and gold starship authored in Blender- (`art/studies/sky-pad-courier-study/source/build_courier.py`, three levels- of detail exported as glTF into `src/assets/society/courier/`), scaled to- about 22 m beside the 1.3 m figures and centred on the deck. A lens hull- with a crisp blade edge and needle points, chrome back and charcoal belly- split by a gold edge trim, inlaid panel seams and belly vents, a bridge- with a framed visor, slim pods with flush gold bands, recessed glowing- nozzles and stabilisers round long tail spikes, swept wings, keel and- dorsal fins, gold nose pinstripes and red, green and strobing white- navigation lights. The bridge and the deck are walkable- (the navigation grid reaches beyond `layout.floor` for them, an idle wander- never does), the courier is solid, and the full map, the minimap and the- overview frame the pad too.-- **Boarding and flying:** the ship is a station (`ship`, beside its hatch).- E there, or a click on the ship once the person stands there, boards it (a- click from afar walks over first, as at the elevator). The flight- (`courierFlight.ts`) is a rigid body with thrust, lift, pitch, yaw and roll:- *arcade* assist (the default) is made for fun: it flies where the nose- points, turns fast, climbs and dives as steeply as the pilot likes, its- lift thrusters push straight up or down at up to 30 m/s whatever the- attitude, and it banks into turns and levels its wings (never its nose);- *simulation* is Newtonian with momentum and drift. Cruise 85 m/s, boost- to 170 m/s on a charge that drains and refills, brake. A click into the- view captures the mouse for *mouse aim*: moving it moves a ring (where the- pilot aims), a dot marks where the nose points, and the ship keeps- turning onto the ring by itself whether or not the mouse is still moving;- the chase camera looks along the aim, and the turn and pitch keys move the- ring too (Escape lets the mouse go). Where the host refuses to capture the- mouse (an unfocused window, an embedded view), the visible cursor steers- instead: its distance from the middle of the view sets how fast the ring- turns, and a cursor resting off the middle keeps turning. Every tower, the Dodaios tower with its floor, the pad, the- street level and the singularity's core are solid (`courierWorld.ts`):- the ship bounces off in sub-steps no longer than 1.5 m (no tunnelling at- full boost), its shield flashes and the camera shakes. Past the city's- edge or above 420 m it is turned back gently. The landing assist flies to- a hover point over the pad, turns to the pad's heading and sets the ship- down with its gear out; any stick input hands control back. The gear comes- down by itself below 14 m over the deck. On the pad, E (or F, or the HUD's- button) steps out beside the hatch and the office camera takes over again.-- **Cameras:** a chase camera behind and above with smoothing, pulled in- short of any tower between it and the ship; a cockpit view from the- canopy. Wider field of view while boosting.-- **Effects and sound:** engine flames and an engine light that grow with- the throttle, glowing exhaust rings, contrails at high speed, a fresnel- shield on impact, dust blown across the deck when landing or lifting off.- The engine sound is synthesised with Web Audio (no audio files), placed at- the ship and heard from the camera (HRTF panning), pitch-shifted by the- relative speed (Doppler), muffled in the cockpit, with a thud on impact.- With reduced motion the flames, dust and camera shake stay calm. Not- built: a heat-haze distortion and a bloom/lens/motion-blur post-process- (the renderer has no post-processing pass; glow comes from emissive and- additive materials).-- **Controls** (defaults; rebindable, kept per browser):-- | Action | Keys | Gamepad |- | --- | --- | --- |- | Throttle up / down | W / S | right / left trigger |- | Turn left / right | A / D (or the mouse aim) | left stick x |- | Nose up / down | ↑ / ↓ (or the mouse aim) | left stick y |- | Roll left / right | Q / E, ← / → | right stick x |- | Rise / sink | Space / C or Ctrl | right stick y |- | Boost / brake | Shift / X | A / B |- | Flight assist | T | Back |- | Camera | V | Y |- | Landing assist | L | X |- | Step out (landed) | E or F | Start |- | Help / settings | H / Esc | — |-- The settings (Esc or the HUD's button) switch the assist and the camera,- invert pitch, set the engine volume and rebind any action by pressing a- key; "Reset keys" restores the defaults. The flight HUD shows speed,- height over the deck (or the street level), throttle, boost charge, the- assist and camera, the landing assist, and stepping out once landed. While- the courier flies, the office's own H, L and M keys and the walking keys- rest. The reception's controls guide lists the courier's default keys.-- **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- frosted band for every wall. The rooms' floors come from that family- (`CAMPUS_ROOM_FLOORS`, agents floor only): the break room lies on the open- floor's plank oak, the lobby on the window band's limestone, the wardrobe- on a terrazzo of the same stone with oak chips, the team room on the focus- booths' slate felt, and the lead office on the same oak a tone deeper,- laid as a chevron. The lead suite stays the richest room but in the- family: smoked oak, bronze, cognac leather and a slate rug (`LEAD_SUITE`),- behind the same glazing as every room. The team room's timber is the- campus's oak, and the rooms' small metal details are the same bronze.-- **Cost** (2026-10-12, counted without a GPU as visible meshes plus the- shadow-casting ones again for the shadow pass; a browser adds one merged- mesh per textured material):- - The agents floor's furniture, room signs, studio walls and meeting chairs- never change once built, so they are drawn merged (`StaticBatch.tsx`):- parts whose material is only a colour share one material per finish and- carry the colour in their vertices, textured and glowing parts merge per- material, parts smaller than a hand's width cast no shadow. A station's- prop is merged within its own group, so its rim still finds it. The- static floor is 441 / 452 / 507 draw calls for 5 / 15 / 40 people (it was- about 2450 piece by piece for 15) and 0.48 / 0.60 / 0.92 million- triangles over both passes.- - Planting, studio fittings, commons, desks and the city are instanced:- another studio adds no draw call for its furniture, another tree none.- Grass blades are eight-sided spindles and olive foliage twenty-sided- clusters (planting was the largest triangle count on the floor). A crown- is a few large clusters (fourteen on a large tree, eleven on an olive),- and two of its three leaf tones throw its shadow.- - A glass wall run is three meshes whatever its length.- - A figure is 19 meshes (13 casting, 32 draw calls) and about 31 thousand- triangles over both passes: its rigid head and torso and each half of an- arm (shoulder cap, sleeve and upper arm; forearm, cuff, hand and thumb)- are merged in the frame of their joint, so every pose moves them as- before, and its spheres have fewer segments. An arm's merged half casts- as one, so the figure's shadow keeps its arms. The merged parts are baked- again only when the look or what is worn changes by content- (`contentKey`): the level store's minute-by-minute re-read hands out new- JSX for the same regalia, and that bakes nothing. It was 41 meshes (28- casting) and 43 thousand triangles in a single pass. The legs stay- parts of their own: shoe and sole differ in finish, so merging them- would save nothing.- - Rounded boxes have one bevel segment, the task chair's tubes and bevels- fewer segments; small things on desks cast no shadow.- - The sun's shadow map is 4096 px on this floor, so shadows keep their- detail over the longer plan.- - A studio's lettering shows a name the person typed, so its texture is- never cached by its text: the wall owns it (`ownedCanvasTexture`) and- disposes it when the team is renamed or deleted. The session-long- texture cache only holds keys from fixed sets (kinds, palette entries,- a locale's own strings).--## 5i. Team life, teamwork and movement (2026-10-12)--The maintainer asked for teams that visibly work together, mechanics that-hold up, and agents that behave well in the larger world. The rule that-governs all of it: the floor shows what is real. Run state, a team's round-and a message between two agents come from the roster, the team's meeting and-the board; idle life is seeded choreography; nothing else is ever staged.--**Agents belong somewhere** (`officeBehavior.ts`, `officeTeams.ts`). The state-rules are unchanged: working sits at its own screen, waiting stands at its-desk, paused rests. An idle agent with a studio picks its next activity from-a weighted table (`TEAM_IDLE_WEIGHTS`, `POOL_IDLE_WEIGHTS`):--| Idle choice | Team member | Agent without a team |-|---|---|---|-| Sit at its own desk (40–90 s) | 30 | 20 |-| Look in on a studio mate who sits at their desk | 14 | — |-| Stand at the studio board | 12 | — |-| Stroll between its studio's benches | 12 | 10 |-| A hangout place round the corner of the studio | 12 | 10 |-| Look in on a working colleague | — | 8 |-| A trip to a shared place anywhere on the floor | 14 | 40 |-| A stroll within 12 m of the studio | 6 | 12 |--Four in five of a team member's idle choices keep it at home; an agent in-the pool studio uses the shared places far more. A trip earns a long stay-(below), so the weights are tuned by the clock: simulated, a team member-spends about two thirds of its idle time in and around its studio and 16 %-walking; an agent without a team a little over half. A trip picks among all-free shared places, weighted by what the place is (couch 22, coffee 18,-window 12, cooler 8, arcade 8, books 7, beanbag 8, team table 4, team board-3) and by how far from the studio it lies: at the trip's reach a place is-half as likely as one next door, at twice the reach a fifth. The reach is-10 m with up to six agents on the floor and grows to 20 m at thirty, so a-handful of agents on a large campus keep to their neighbourhood and the-commons near it, and nobody crosses the campus for a window when there is a-coffee round the corner. The same home activity is never taken twice in a-row. Standing at the studio board and looking in on a studio mate are idle-life, and the name plate says so ("In the studio"); "At the team board" is-shown only for a gathering that is real, a running round or a meeting the-person called there. A visitor stands in the gap between the colleague's chair and the next-one (out of the aisle behind the chairs and out of the way the colleague-gets up) and watches: the talking pose is kept for exchanges that really-happened. Every standing place beside a desk and at a board is reserved-through the same book as the spots. A stroll ends on open ground (floor a-body's width to every side), so nobody stops for a rest in a doorway. A floor-without studios (the coding floor) keeps its plain idle day.--Long ways are walked briskly (1.35 m/s up to 9 m of route left, rising to-2.1 m/s at 26 m), and an agent that got work hurries to its screen (2.1 m/s-on anything but the last steps). Measured along real routes from the lobby-to a desk, corners and getting up included, an agent averages 1.45–1.6 m/s.-A stay lasts at least 3.2 times as long as the walk to it would take at-walking pace, up to 150 s. Simulated over twenty minutes with-60 idle agents, about one agent in six is on the move at any moment.--**Real teamwork** (`teamwork.ts`, `useTeamRounds.ts`). Two things are shown,-because they are what the app can see:--- *A round of a team.* A team's meeting is read from- `GET /api/society/chat-groups/{id}/meeting` (running, transcript, the room's- next speaker); that a round opened or settled and each line said in it also- arrive on the socket (`SocietyRoomChanged`, `SocietyMessageSent` with a- `meeting:<group>:…` room id). While a round runs, its idle members walk to- their studio board and stand there in loose arcs (2.2 m, 3.3 m and 4.4 m- from the board, every place more than a metre from the next), the arc- nearest the board first; when it settles they return to their desks. They- take no place within 1.25 m of the person's character, and when the person- walks up to one of them (closer than 0.95 m) it moves to another place in- the arcs. A working member stays at its screen, with one exception that is- the round itself: the member contributing right now (the room's next- speaker) reads "working" and stands at the board in the talking pose, with- a thought bubble until its line is written. A line said in the round- appears over its speaker in its own words for up to nine seconds, and gives- way the moment the next member has the word: only one member of a team- carries a bubble at a time, and a listener at the board shows none of its- own. A member of the team that sits in another studio comes to the board- of the team whose round it is. Waiting and paused members stay where their- state puts them. The person's own call still outranks a round. A meeting- the person starts at a studio's own board uses the same arcs:- `boardSeats(layout, studio, members)` gives every member its place,- and `startMeeting` holds them there as it holds a team at the team room's- table.-- *A message from one agent to another.* `SocietyMessageSent` without a room,- between two roster agents other than the lead (ASSIGN, SAY, QUERY, ANSWER,- PROPOSE). The sender's bubble shows "To <name>: <text>"; once the sender is- idle (within 90 s) it walks to a place beside the receiver's chair, or to- where the receiver stands, and stays eight seconds. A working sender never- leaves its screen. The lead's own messages remain its pet's errands.--Reads are scheduled, jittered (2.4–3.6 s between ticks), capped at four at-once and silent while the stage sleeps. The ticks do not wait for the reads:-each is folded in when its answer comes, is given up after eight seconds and-aborted when the poller stops, so a request that hangs holds nothing back.-There is one poller for the whole app: when two floors are awake at once-(the Agents view and the IDE's side panel), one of them reads and the other-takes over when it sleeps. What is read: running rounds every tick, a team the-roster shows in a room every six seconds, a team whose board is near the-camera every eighteen, and the sweep. The sweep makes the floor independent-of the socket: every team is read once after the stage wakes (two a tick)-and again about once a minute, so a round that was already running when the-Verse was opened, or whose event was missed, is found. A round that fails to-read five times in a row is no longer shown as running.--A team can have a lead (`lead_agent_id` of its chat group, `Studio.leadId` on-the floor). The floor shows that and invents nothing more: the studio board-lists the lead first and names it ("Lead: <name>"), and in a gathering at the-board (a running round, or a meeting the person called there) the lead stands-at the centre of the front arc when it is among those gathering; the others-leave that place free while any other is. A working lead stays at its screen-like anyone, an idle lead lives the same idle day as its team, and a team-without a lead is planned and drawn exactly as before.--Not shown, because the app cannot see it: when a line was said (the meeting's-messages carry no time), a task shared by several agents, and whether a-hand-off was accepted.--**Studio boards** (`StudioBoards.tsx`, `studioBoardContent.ts`). Each board's-face shows the team's name, its members with their real run state (the-speaker marked), and the newest lines of the team's chat, or says honestly-that nothing has been said, that the chat is still being read or cannot be-read right now, or that the pool has no team chat. A face is a canvas texture on the board's own paper-sheet, created the first time the camera comes within 60 m and redrawn only-when its content changed. The three boards nearest the camera (within 30 m)-are live. The faces take no pointer events; the board's station does.--**Movement** (`officeMotion.ts`, `officeWalk.ts`). One controller walks every-agent and the person's click-to-move:--- Every step is checked against the floor and against the other bodies; the- candidates are the steered direction, straight at the waypoint, then a slide- past whatever is in the way, right before left. When none is free the figure- waits. Bodies keep 0.62 m between their centres.-- A figure turns before it walks (it slows as soon as it faces more than- about 30° off its way, down to a crawl of 8 % of its pace), faces where it- moves, and lands exactly on its last waypoint. Leaving a seat it waits for- whoever stands in its way and leaves on the free side.-- The route is recomputed when steering carried the figure off it, and when- the floor plan changes under a walk (a team was created or deleted). A plan- survives a rebuilt floor only if its place still exists there; otherwise the- agent plans again, and a target the new plan walls off is reported instead- of walked at.-- A figure that makes less than 0.4 m of progress in 1.5 s takes a detour- planned round the bodies near it. After two detours that did not help, or- when a walk overruns three times its expected duration plus eight seconds,- the walk ends. Within 3 m of its target the figure is placed: on its- reserved seat, or on free ground at the target, never on top of anybody.- Further away it gives the walk up and its agent plans again from where it- stands: nobody is moved across the floor. The one exception is a place the- agent's real state demands (its screen while it works, the board while its- round runs): after two walks given up in a row it is placed there. The- person's own character always just stops.-- Blocked beside someone who stands on the place it was heading for, a figure- stops there: that is an arrival.--**Camera and character** (`OfficeCameraRig.tsx`, `officeCamera.ts`,-`wallCutaway.ts`, `OfficePlayer.tsx`). While the character stands in a walled-room, the sides of that room the camera looks in through drop to 12 % of-their height and rise again when the character leaves or the camera turns;-the rule is by side, so nothing flickers while the character walks about-inside. The rig moves any object tagged `userData.officeWall`. The overview-is fitted to the viewport: the look-at point is moved until the plan sits in-the middle of the view (seen at an angle, the near corner looms larger than-the far one), and the camera comes as close as the plan allows, so the plan-spans 85 % of whichever axis binds — the height in a wide window, the width-in the IDE's narrow panel. The zoom limit grows with the floor so the wheel-can always reach that view. A wheel notch zooms 12 % of the way up close and up to 35 % from-90 m out, so the overview of a large campus comes down to a studio in about-five notches while the last metres stay fine. Following is exponential (the-same motion at any frame rate); resumed more than 12 m from the character,-the view glides over in 0.6 s instead of snapping, and after the overview it-also glides back to the distance the person walked at (15 m when there was-none), unless the person zoomed by hand meanwhile. A remembered view (after-a monitor dive, or from the last visit) is checked against the current floor-plan: one that looks at a place the floor no longer has starts from the-character instead, and a camera that would stand inside a wall backs out-along its line of sight. A click-to-move target on free floor is the target-itself. A click on a bench desk, its chair or whoever sits there resolves to-a standing place at that desk (in the gap beside the chair, where a visiting-colleague would stand, else behind it), and anything else solid or occupied-to the nearest free floor beside it, 0.75 m from everybody: the character-never ends up on a chair, in a desk or inside a figure. Sitting down stays-its own action (the executive chair, Mission Control's chair). The person's-pet follows on free floor that is nobody's, 0.5 m from every agent. A long-click-to-move route is-jogged (up to the sprint pace of 4.4 m/s with more than 22 m to go) and ends-in a walk over the last 7 m; and a character left standing in a solid cell-by a rebuilt floor plan is put on the nearest free ground.--**Dev handles** (development builds only):--- `__officeLife.walkers()` — one row per agent: `team`, `studio`, `role`- (its part in a running round: none, gather, speaker, busy), `plan`, `phase`,- `target`, `spot`, `with`, `at`, `remainingM`, `stuckS` (seconds without- progress on the current walk), `walkS` and `speed` (seconds walked and- average m/s along the route on the current walk, by the frame time the- walker was really given), and counters since it mounted: `replans`- (detours), `rescues` (placements), `blocked` (walks given up), `repaths`- (route repairs), `near` (arrivals beside an occupied place), `lost`- (targets a new floor plan walled off). `__officeLife.walker(id)` is one- row, `__officeLife.stuck()` the rows with a detour, a placement or a walk- given up.-- `__officeLife.teamwork()` — rounds by team (`running`, `speakerId`,- `members`, `lines`, `spoke`) and the messages still to be walked over;- `__officeLife.store` is the store itself, so a round or a message can be- set by hand; `__officeLife.boards()` lists the teams whose board is live.-- Measuring speeds: while the frame loop runs, `__officeStep(frames, dtMs)`- renders `frames` frames but each gets the real time since the one before,- not `dtMs`; distance over `frames x dtMs` is therefore not a speed. Read- `speed` from the handle instead.-- `__officeCamera.cut()` — the walls lowered right now; `.walls()` how many- wall objects are tagged; `.limits()` this floor's zoom limits.--## 5j. Coding floor as a tech campus floor (2026-10-14)--Two looks were rejected on the same day: a sci-fi "Foundry deck" (reactor,-drones, sky beams) as no office at all, and the studio look of §5b moved into-the tower as "as boring as before". The maintainer asked for a floor built the-way large technology companies build theirs. The floor plan stays (rooms,-stations, desk slots, the 6.4 m concourse); everything on it is new:--- **Zones by material** (`CodingFloorLook.tsx`): polished pale concrete with- saw-cut joints is the ground; the concourse is a terrazzo main street with- brass strips; every workspace is a team neighbourhood on an island of- white-oak planks.-- **Team neighbourhoods**: a living moss wall in a white-oak frame on the- north edge carries the team's name on an oak header with a stripe of the- team's colour (`CODING_TEAMS`), over a planter with trailing plants.-- **Long shared tables** (`CodingTables.tsx`): each bench of desk slots is one- continuous white-oak table on dark steel A-frames with a low felt screen in- the team's colour down its spine; every seat keeps its monitor (the live- terminal is drawn where it was), keyboard and a task chair in the team's felt.-- **Along the glass** (`codingAmbience.ts`): per outer neighbourhood a glass- phone booth lined in the team's felt and a planter trough, either side of the- window spot; tree planters at the cross aisles.-- **Main street**: a grove in the middle of every row — a tall tree in a round- planter ringed by an oak bench — and the terrazzo medallion round the spawn- terminal (`CodingPlaza.tsx`).-- **Busy lights** (`DeskBusyLights.tsx`): a lamp on every occupied desk in the- pane's state (green working, amber blinking when it waits, red failed, grey idle).-- The floor stands in the tower like the agents floor (`BuildingShell`).--## 6. Plan--1. First map (done 2026-09-28).-2. Walkable prototype (done 2026-09-28): rooms, checkpoints, agent life, own character.-3. **Review:** the maintainer plays it and gives feedback on look, camera, rooms and actions.-4. Polish: typing animation while working, speech bubbles for "waiting for you",- door animations, agents greeting the person, sound.-5. Scale: instanced chairs/props beyond desks, measured frame times on a laptop- GPU and a low-end integrated GPU, macOS/Linux WebViews.--## 7. Verification so far--- Unit tests: layout (grouping, stable seating, no overlap, camera framing),- navigation (every seat, spot and checkpoint reachable from the elevator for- 0/10/40 agents; paths never cross obstacles), motion, behaviour (state rules,- exclusive spots, determinism), props (every kind renders inside its footprint).-- Team campus (2026-10-12), unit tests: team grouping (several teams, an- agent in two, unknown members, leads, the studio cap), studio sizing, stable- seating, a studio's enclosure and entrance, the furnished share of the- plan, no two solid things in one place, free doorways and streets, every- seat, spot, station and studio board reachable for zero, one, three and- eight teams and teams of two and twelve, the route over the main- boulevard, the Level Hall's floor and its elevator stop, the map painting- and sheet, and a mount of the whole dressing without a GPU (mesh counts,- bounds). The first plan was checked in a browser by the orchestrator and- reworked into this one, which the orchestrator checked too. The third- round (the receded city, pendants instead of baffles, the atrium's ring,- the step seating, the rooms' materials, the promenade and the furnished- 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.-- Sky pad and courier (2026-10-14): `courierFlight.test.ts` holds the pad- (outside the slab on the boulevard's line, walkable from the floor to the- hatch, the courier solid, no idle wander onto it, the `ship` checkpoint on- the agents floor only), the collision world, the flight (lift-off, arcade- holding the nose and levelling, simulation drifting, boost and charge, no- passing through a tower at full boost, the autopilot landing from out over- the city, handing back on input) and the controls (keys and pad into one- input, dead zone, rebinding and its storage). `CampusScene.test.tsx` mounts- the pad structure and the east doorway. Checked in Chrome against the dev- build: walking out to the pad, boarding, chase and cockpit views over the- city, the landing assist starting, stepping out.-- 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 dodaios/progression/service.py and holds it equal to the- client's `METERED_FLOORS` and the elevator's `OFFICE_FLOORS`; a world- action the server refuses is logged (`reportWorldAction`).-- Team life and movement (2026-10-12), unit and component tests; a browser- run on a scripted roster confirmed the live board, the gathering, the wall- cutaway, the route marker and stuck recovery. Tested: the idle weights and- that a team member's day stays at home; trips staying near on a five-agent- floor; exclusive places; a round gathering its free members in arcs with a- metre between them, the speaker, the return to the desks, making room for- the person; a round found by reading alone; a message walked over; the- reducers behind rounds and messages and which meetings are read when; the- board's content; a long diagonal walk across a 60-agent campus (on the- floor all the way, no gliding, exact arrival); two walkers swapping places- through a door and in a 1.6 m aisle without touching; a studio built on a- walker's route; detour, placement, a walk given up and the walk budget; the- wall cutaway by side; the overview holding every corner of small and large- floors in wide and portrait viewports; the wheel's reach, the follow- distance after the overview and a remembered view on a rebuilt floor; the- click-to-move pace; a click on an occupied bench seat, a desk top and an- empty chair ending beside them. A mounted floor of 40 agents (a quarter working, one- team round) simulated for ten minutes kept every pair of bodies 0.62 m- apart, with 17 detours, no placement and no walk given up.-- Runtime (Chrome, dev build, live roster of ten agents): walking by click and- by keyboard, camera follow and overview, nearby prompt and E, agent panel,- "call over". Desks are instanced; the full floor measured ~730 draw calls and- ~18 ms per frame on the development machine.-- Runtime: checked in Chrome against the live roster (ten agents, one lead)- through a temporary dev preview: rendering, click on figure and on pill.-- Not yet measured: frame time and device coverage; macOS/Linux WebViews.diff --git a/docs/pets.md b/docs/pets.mdindex b04d09fddb..603c9500c2 100644--- a/docs/pets.md+++ b/docs/pets.md@@ -52,11 +52,11 @@ one click.what was asked, the start of the answer (see *Cards*).- **The pet "None"** (`pet_id = "none"`) shows the control strip and thecards without a figure.-- **In the Jarvis Verse.** The chosen pet is also Jarvis in the office map:- a 3D version of it walks, crawls, hops or flies behind the person's- character (`docs/agent-society/office-map.md`, *Jarvis is the person's- pet*). A pet the person drew becomes a voxel figure cut from its idle- frames.+- **In the Dodaios Verse.** The chosen pet is also Jarvis aboard the+ starship: a 3D version of it flies at the captain's shoulder or walks+ behind the captain on the deck (`docs/agent-society/starship-verse.md`,+ *The captain and the companion*). A pet the person drew becomes a voxel+ figure cut from its idle frames.- **Worn by an agent.** In an agent's look dialog (*Companion → Look →Pet*) any pet from My Pets can replace the agent's shape. It is stored as`companion.pet` in the agent's avatar JSON (`dodaios/society/companion.py`,diff --git a/dodaios/progression/__init__.py b/dodaios/progression/__init__.pyindex 6ff55879d7..1b85151d17 100644--- a/dodaios/progression/__init__.py+++ b/dodaios/progression/__init__.py@@ -1,4 +1,4 @@-"""The Jarvis Verse level system: XP, levels, titles and cosmetic rewards.+"""The Dodaios Verse level system: XP, levels, ranks and the rewards they open.``rules`` is the pure rulebook, ``store`` the SQLite ledger and ``service``the bus listener that pays XP for real achievements. Contract:diff --git a/dodaios/progression/rules.py b/dodaios/progression/rules.pyindex 1a5e596ed4..9cbca6c196 100644--- a/dodaios/progression/rules.py+++ b/dodaios/progression/rules.py@@ -1,25 +1,27 @@-"""The Jarvis Verse level system's rulebook: pure tables, no I/O.+"""The Dodaios Verse level system's rulebook: pure tables, no I/O.-Three kinds of subject level up:+The Verse is a starship. Three kinds of subject serve aboard and level up:-* ``person`` — the person at the keyboard (one subject, id ``person``);-* ``agent`` — every Jarvis agent on the society roster (``agent:<agent_id>``);-* ``pet`` — the person's pet from My Pets, which IS Jarvis in the Verse- (``pet:<pet_id>``; each pet keeps its own level, the active one earns).+* ``person`` — the captain, the person at the keyboard (one subject, id ``person``);+* ``agent`` — every Jarvis agent on the society roster, an android of the crew+ (``agent:<agent_id>``);+* ``pet`` — the person's pet from My Pets, the ship's companion, which IS+ Jarvis in the Verse (``pet:<pet_id>``; each pet keeps its own level, the+ active one earns).XP only ever comes from a rule in :data:`RULES`. A rule names its source, thesubject kind it pays, a fixed amount, an optional cooldown and an optionaldaily cap. Server rules are read off real bus events (a finished turn, a-finished task); world rules are small actions inside the Verse that the client+finished task); world rules are small actions aboard the ship that the clientreports and the server still meters. Nothing here calls a model — thesystem works with any single key and costs no tokens (AP-21).The level curve is front-loaded the way long-running progression usually is:level 2 arrives within the first few actions, level 10 after about a week of-ordinary use, level 50 after several months. Levels climb a military rank-ladder (:data:`RANKS`): a promotion every two or three levels, from private-to the five-star general at the cap, and promotions unlock real uniform-pieces (:data:`REWARDS`). ``docs/agent-society/level-system.md`` is the readable+ordinary use, level 50 after several months. Levels climb a naval rank ladder+(:data:`RANKS`) from cadet to admiral, and levels open the captain's suits,+the destinations the helm can set course for, and decorations+(:data:`REWARDS`). ``docs/agent-society/level-system.md`` is the readableversion of this file; the parity test pins the frontend's copy of the ids."""@@ -105,33 +107,32 @@ class XpRule:cooldown_s: int = 0#: Most XP one subject can earn from this rule per local day (0 = no cap).daily_cap: int = 0- #: True: at most one award per ``ref`` ever (a floor is discovered once).+ #: True: at most one award per ``ref`` ever (a deck is discovered once).once_per_ref: bool = FalseRULES: Final[tuple[XpRule, ...]] = (- # The person: talking to Jarvis, giving the team work, growing the team.+ # The captain: talking to Jarvis, giving the crew work, growing the crew.XpRule("chat_turn", "person", 5, "server", daily_cap=100),XpRule("voice_turn", "person", 5, "server", daily_cap=100),XpRule("quest_posted", "person", 15, "server", daily_cap=75),XpRule("quest_completed", "person", 20, "server"),XpRule("agent_hired", "person", 50, "server"),XpRule("mission_completed", "person", 30, "server", daily_cap=150),- # The person, inside the Verse.+ # The captain, aboard the ship.XpRule("daily_visit", "person", 25, "world", once_per_ref=True),- XpRule("floor_discovered", "person", 20, "world", once_per_ref=True),- XpRule("dog_petted", "person", 3, "world", cooldown_s=60, daily_cap=30),- XpRule("dog_treat", "person", 10, "world", cooldown_s=300, daily_cap=30),- XpRule("arcade_round", "person", 8, "world", cooldown_s=45, daily_cap=80),- XpRule("arcade_record", "person", 15, "world", cooldown_s=45, daily_cap=60),- XpRule("team_meeting", "person", 10, "world", cooldown_s=600, daily_cap=40),- # Agents: finished work is what counts.+ XpRule("deck_discovered", "person", 20, "world", once_per_ref=True),+ XpRule("holodeck_round", "person", 8, "world", cooldown_s=45, daily_cap=80),+ XpRule("holodeck_record", "person", 15, "world", cooldown_s=45, daily_cap=60),+ XpRule("team_briefing", "person", 10, "world", cooldown_s=600, daily_cap=40),+ XpRule("warp_jump", "person", 5, "world", cooldown_s=600, daily_cap=30),+ # The crew: finished work is what counts.XpRule("task_done", "agent", 40, "server"),XpRule("task_blocked", "agent", 8, "server", daily_cap=40),XpRule("quest_done", "agent", 60, "server"),XpRule("answered_teammate", "agent", 5, "server", daily_cap=50),# The pet is Jarvis: every answer and every hand-off it makes, and the- # walks it takes beside the person.+ # walks it takes beside the captain.XpRule("jarvis_answered", "pet", 4, "server", daily_cap=120),XpRule("delegated", "pet", 10, "server", daily_cap=100),XpRule("walk_together", "pet", 3, "world", cooldown_s=20, daily_cap=60),@@ -145,47 +146,43 @@ WORLD_ACTIONS: Final[frozenset[str]] = frozenset(r.source for r in RULES if r.tr# ------------------------------------------------------------------ ranks-#: The rank ladder every subject climbs, lowest first: (first level, rank id,-#: pay grade). The person, every agent and the pet share it, so a rank means-#: the same thing on every name plate. Enlisted grades come first, then the-#: commissioned grades up to the five-star general at the cap. The frontend-#: draws each rank's insignia and translates ``society.level.title.<id>``.-RANKS: Final[tuple[tuple[int, str, str], ...]] = (- (1, "private", "E-1"),- (2, "private_second_class", "E-2"),- (4, "private_first_class", "E-3"),- (6, "specialist", "E-4"),- (8, "corporal", "E-4"),- (10, "sergeant", "E-5"),- (12, "staff_sergeant", "E-6"),- (14, "sergeant_first_class", "E-7"),- (16, "master_sergeant", "E-8"),- (18, "first_sergeant", "E-8"),- (20, "sergeant_major", "E-9"),- (22, "command_sergeant_major", "E-9"),- (24, "sergeant_major_of_the_army", "E-9"),- (26, "second_lieutenant", "O-1"),- (28, "first_lieutenant", "O-2"),- (30, "captain", "O-3"),- (32, "major", "O-4"),- (34, "lieutenant_colonel", "O-5"),- (36, "colonel", "O-6"),- (38, "brigadier_general", "O-7"),- (41, "major_general", "O-8"),- (44, "lieutenant_general", "O-9"),- (47, "general", "O-10"),- (50, "general_of_the_army", "O-11"),+RankTier = Literal["enlisted", "warrant", "officer", "flag"]+RANK_TIERS: Final[tuple[RankTier, ...]] = ("enlisted", "warrant", "officer", "flag")++#: The rank ladder everyone aboard climbs, lowest first: (first level, rank+#: id, tier). The captain, every android and the pet share it, so a rank means+#: the same thing on every name plate. The frontend's copy is+#: ``starship/levels/ranks.ts`` (with the insignia's pips); its names are+#: ``ship.rank.<id>``.+RANKS: Final[tuple[tuple[int, str, RankTier], ...]] = (+ (1, "cadet", "enlisted"),+ (3, "crewman", "enlisted"),+ (5, "specialist", "enlisted"),+ (7, "petty_officer", "enlisted"),+ (10, "chief_petty_officer", "enlisted"),+ (13, "warrant_officer", "warrant"),+ (16, "ensign", "officer"),+ (19, "lieutenant_junior_grade", "officer"),+ (22, "lieutenant", "officer"),+ (26, "lieutenant_commander", "officer"),+ (30, "commander", "officer"),+ (34, "captain", "officer"),+ (38, "commodore", "flag"),+ (42, "rear_admiral", "flag"),+ (46, "vice_admiral", "flag"),+ (50, "admiral", "flag"),)# ------------------------------------------------------------------ rewards-Slot = Literal["uniform", "headwear", "decoration"]-SLOTS: Final[tuple[Slot, ...]] = ("uniform", "headwear", "decoration")+Slot = Literal["suit", "destination", "decoration"]+SLOTS: Final[tuple[Slot, ...]] = ("suit", "destination", "decoration")@dataclass(frozen=True, slots=True)class Reward:+ #: ``<slot>_<name>``; a destination's name is the helm's destination id.reward_id: strslot: Slot#: The level each subject kind unlocks it at; ``None`` = not for that kind.@@ -197,25 +194,43 @@ class Reward:return {"person": self.person, "agent": self.agent, "pet": self.pet}[kind]-#: Real uniform pieces, each unlocking on a promotion. Agents keep the outfit-#: their owner dressed them in, so they earn decorations only; the pet has no-#: body to dress and shows its rank on its name plate.+#: What a level opens. The captain earns suits for their figure, destinations+#: for the helm and decorations; androids keep the look their owner gave them+#: and earn decorations only; the pet wears its rank on its name plate.REWARDS: Final[tuple[Reward, ...]] = (- Reward("uniform_service_shirt", "uniform", person=4, agent=None, pet=None),- Reward("uniform_field_jacket", "uniform", person=10, agent=None, pet=None),- Reward("uniform_service_greens", "uniform", person=20, agent=None, pet=None),- Reward("uniform_dress_blues", "uniform", person=26, agent=None, pet=None),- Reward("uniform_mess_dress", "uniform", person=41, agent=None, pet=None),- Reward("headwear_patrol_cap", "headwear", person=6, agent=None, pet=None),- Reward("headwear_garrison_cap", "headwear", person=14, agent=None, pet=None),- Reward("headwear_beret", "headwear", person=24, agent=None, pet=None),- Reward("headwear_service_cap", "headwear", person=32, agent=None, pet=None),- Reward("decoration_ribbon_bar", "decoration", person=8, agent=3, pet=None),- Reward("decoration_ribbon_rack", "decoration", person=18, agent=16, pet=None),- Reward("decoration_aiguillette", "decoration", person=36, agent=32, pet=None),- Reward("decoration_medals", "decoration", person=47, agent=44, pet=None),+ Reward("suit_field_armor", "suit", person=6, agent=None, pet=None),+ Reward("suit_command_coat", "suit", person=16, agent=None, pet=None),+ Reward("suit_dress_whites", "suit", person=26, agent=None, pet=None),+ Reward("suit_admiral_coat", "suit", person=42, agent=None, pet=None),+ Reward("destination_gas_giant", "destination", person=5, agent=None, pet=None),+ Reward("destination_crimson_nebula", "destination", person=10, agent=None, pet=None),+ Reward("destination_ice_moon", "destination", person=15, agent=None, pet=None),+ Reward("destination_twin_suns", "destination", person=20, agent=None, pet=None),+ Reward("destination_event_horizon", "destination", person=25, agent=None, pet=None),+ Reward("destination_aurora_world", "destination", person=30, agent=None, pet=None),+ Reward("destination_galactic_core", "destination", person=40, agent=None, pet=None),+ Reward("decoration_service_ribbon", "decoration", person=8, agent=3, pet=None),+ Reward("decoration_commendation", "decoration", person=18, agent=16, pet=None),+ Reward("decoration_star_medal", "decoration", person=36, agent=32, pet=None),+ Reward("decoration_legion_of_merit", "decoration", person=47, agent=44, pet=None),)+#: Where the ship starts; every other destination is a ``destination`` reward.+HOME_DESTINATION: Final[str] = "home"++#: Every destination the helm knows, home first (a ``warp_jump`` names one).+DESTINATION_IDS: Final[tuple[str, ...]] = (HOME_DESTINATION,) + tuple(+ r.reward_id.removeprefix("destination_") for r in REWARDS if r.slot == "destination"+)+++def destination_level(destination_id: str) -> int:+ """The captain's level a destination opens at (home is open from the start)."""+ for reward in REWARDS:+ if reward.slot == "destination" and reward.reward_id == f"destination_{destination_id}":+ return reward.person or 1+ return 1+def unlocked_rewards(kind: SubjectKind, level: int) -> list[Reward]:return [r for r in REWARDS if (at := r.level_for(kind)) is not None and level >= at]diff --git a/dodaios/progression/service.py b/dodaios/progression/service.pyindex bf57cb6506..804620e676 100644--- a/dodaios/progression/service.py+++ b/dodaios/progression/service.py@@ -3,10 +3,12 @@The service listens to the core ``EventBus`` for the handful of events thatmean "something was achieved" (a finished Jarvis turn, a finished agent task,a completed quest) and maps each to one or two rules of-:mod:`dodaios.progression.rules`. The Verse reports its own small world-actions (petting the dog, an arcade round) through-:meth:`ProgressionService.report_action`; the server still applies every-cooldown and cap, so a client can never award itself XP.+:mod:`dodaios.progression.rules`. The ship reports its own small world+actions (a deck discovered, a holodeck round, a warp jump) through+:meth:`ProgressionService.report_action`. Those are the client's word: the+server applies every cooldown and daily cap and checks every reference (a+known deck, a destination the captain's rank has opened), so a client can at+most collect the few capped XP a day that playing would have paid.Every handler is an observer: a failure is logged and swallowed, neverraised into the bus (AP-18), and the database is opened on the first award,@@ -17,17 +19,21 @@ from __future__ import annotationsimport asyncioimport logging+import timefrom collections.abc import Callablefrom datetime import datetimefrom pathlib import Pathfrom typing import Anyfrom .rules import (+ DESTINATION_IDS,LEAD_AGENT_ID,PERSON_ID,RULES_BY_SOURCE,WORLD_ACTIONS,agent_subject,+ destination_level,+ level_for_xp,looks_between,pet_subject,progress_for_xp,@@ -39,8 +45,8 @@ from .store import Award, ProgressionStorelog = logging.getLogger(__name__)-#: The floors of the Verse a ``floor_discovered`` report may name.-VERSE_FLOORS = frozenset({"agents", "coding", "arcade", "hall"})+#: The decks of the ship a ``deck_discovered`` report may name.+VERSE_DECKS = frozenset({"bridge", "ops", "engineering", "holodeck", "honors"})class UnknownAction(ValueError):@@ -56,7 +62,8 @@ class ProgressionService:pet_id: Callable[[], str] | None = None,clock: Callable[[], int] | None = None,) -> None:- self.store = ProgressionStore(db_path, clock=clock)+ self._clock = clock or (lambda: int(time.time() * 1000))+ self.store = ProgressionStore(db_path, clock=self._clock)self._bus = busself._pet_id = pet_id or (lambda: "gigi")self._attached = False@@ -170,21 +177,36 @@ class ProgressionService:# ------------------------------------------------------------ world actionsasync def report_action(self, action: str, *, ref: str = "") -> Award | None:- """A small action inside the Verse, reported by the client."""+ """A small action aboard the ship, reported by the client."""if action not in WORLD_ACTIONS:raise UnknownAction(action)rule = RULES_BY_SOURCE[action]if action == "daily_visit":# The server's own calendar day, whatever the client sent.ref = datetime.now().astimezone().date().isoformat()- elif action == "floor_discovered":- if ref not in VERSE_FLOORS:- raise UnknownAction(f"floor_discovered:{ref}")+ elif action == "deck_discovered":+ if ref not in VERSE_DECKS:+ raise UnknownAction(f"deck_discovered:{ref}")+ elif action == "warp_jump":+ if ref not in DESTINATION_IDS:+ raise UnknownAction(f"warp_jump:{ref}")+ # Only a destination the captain's rank has opened can be reached.+ if await asyncio.to_thread(self._person_level) < destination_level(ref):+ raise UnknownAction(f"warp_jump:{ref}:locked")+ # Jumps repeat (the cooldown and cap meter them); the ledger keeps+ # where each one went, made unique so it never reads as a replay.+ ref = f"{ref}@{self._clock()}"else:ref = ""subject = PERSON_ID if rule.kind == "person" else pet_subject(self.current_pet())return await self.award(subject, action, ref=ref)+ def _person_level(self) -> int:+ for row in self.store.subjects():+ if row.get("subject_id") == PERSON_ID:+ return level_for_xp(int(row.get("xp", 0)))+ return 1+async def note_agent_hired(self, agent_id: str) -> None:if agent_id and agent_id != LEAD_AGENT_ID:self._later((PERSON_ID, "agent_hired", f"agent:{agent_id}"))@@ -230,8 +252,12 @@ class ProgressionService:agent_id = str(getattr(event, "agent_id", "") or "")if not agent_id or agent_id == LEAD_AGENT_ID or agent_id in {"user", "scheduler"}:return+ ref = str(getattr(event, "event_id", "") or "")+ # Without an id a replayed result could not be told apart, and task_done has no cap.+ if not ref:+ returnsource = "task_done" if getattr(event, "status", "") == "done" else "task_blocked"- self._later((agent_subject(agent_id), source, str(getattr(event, "event_id", ""))))+ self._later((agent_subject(agent_id), source, ref))async def _on_message(self, event: Any) -> None:kind = str(getattr(event, "msg_type", ""))@@ -246,6 +272,8 @@ class ProgressionService:if getattr(event, "status", "") != "approved":returnmission = str(getattr(event, "mission_id", "") or "")+ if not mission:+ returnself._later((PERSON_ID, "mission_completed", mission))# ------------------------------------------------------------ readsdiff --git a/dodaios/ui/web/dist/assets/AgenticIdeView-Bt33lg7d.css b/dodaios/ui/web/dist/assets/AgenticIdeView-Bt33lg7d.cssnew file mode 100644index 0000000000..e977bfa7f5--- /dev/null+++ b/dodaios/ui/web/dist/assets/AgenticIdeView-Bt33lg7d.css@@ -0,0 +1,32 @@+/**+ * Copyright (c) 2014 The xterm.js authors. All rights reserved.+ * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)+ * https://github.com/chjj/term.js+ * @license MIT+ *+ * Permission is hereby granted, free of charge, to any person obtaining a copy+ * of this software and associated documentation files (the "Software"), to deal+ * in the Software without restriction, including without limitation the rights+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+ * copies of the Software, and to permit persons to whom the Software is+ * furnished to do so, subject to the following conditions:+ *+ * The above copyright notice and this permission notice shall be included in+ * all copies or substantial portions of the Software.+ *+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN+ * THE SOFTWARE.+ *+ * Originally forked from (with the author's permission):+ * Fabrice Bellard's javascript vt100 for jslinux:+ * http://bellard.org/jslinux/+ * Copyright (c) 2011 Fabrice Bellard+ * The original design remains. The terminal itself+ * has been extended to include xterm CSI codes, among+ * other features.+ */.xterm{cursor:text;position:relative;-moz-user-select:none;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm .xterm-scroll-area{visibility:hidden}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::-moz-selection{color:transparent}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{-webkit-user-select:text;-moz-user-select:text;user-select:text;white-space:pre}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{-webkit-text-decoration:double underline;text-decoration:double underline}.xterm-underline-3{-webkit-text-decoration:wavy underline;text-decoration:wavy underline}.xterm-underline-4{-webkit-text-decoration:dotted underline;text-decoration:dotted underline}.xterm-underline-5{-webkit-text-decoration:dashed underline;text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{-webkit-text-decoration:overline double underline;text-decoration:overline double underline}.xterm-overline.xterm-underline-3{-webkit-text-decoration:overline wavy underline;text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{-webkit-text-decoration:overline dotted underline;text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{-webkit-text-decoration:overline dashed underline;text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}@font-face{font-family:codicon;font-display:block;src:url(/assets/codicon-BSYL95uZ.ttf?0a3cacc32b1287fa99b52a31880127dd) format("truetype")}.codicon[class*=codicon-]{font: 16px/1 codicon;display:inline-block;text-decoration:none;text-rendering:auto;text-align:center;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-moz-user-select:none;user-select:none;-webkit-user-select:none;-ms-user-select:none}@keyframes codicon-spin{to{transform:rotate(360deg)}}.codicon-sync.codicon-modifier-spin,.codicon-loading.codicon-modifier-spin,.codicon-gear.codicon-modifier-spin{animation:codicon-spin 1.5s steps(30) infinite}.codicon-modifier-disabled{opacity:.5}.codicon-modifier-hidden{opacity:0}.codicon-loading{animation-duration:1s!important;animation-timing-function:cubic-bezier(.53,.21,.29,.67)!important}.codicon-add:before{content:""}.codicon-plus:before{content:""}.codicon-gist-new:before{content:""}.codicon-repo-create:before{content:""}.codicon-lightbulb:before{content:""}.codicon-light-bulb:before{content:""}.codicon-repo:before{content:""}.codicon-repo-delete:before{content:""}.codicon-gist-fork:before{content:""}.codicon-repo-forked:before{content:""}.codicon-git-pull-request:before{content:""}.codicon-git-pull-request-abandoned:before{content:""}.codicon-record-keys:before{content:""}.codicon-keyboard:before{content:""}.codicon-tag:before{content:""}.codicon-git-pull-request-label:before{content:""}.codicon-tag-add:before{content:""}.codicon-tag-remove:before{content:""}.codicon-person:before{content:""}.codicon-person-follow:before{content:""}.codicon-person-outline:before{content:""}.codicon-person-filled:before{content:""}.codicon-git-branch:before{content:""}.codicon-git-branch-create:before{content:""}.codicon-git-branch-delete:before{content:""}.codicon-source-control:before{content:""}.codicon-mirror:before{content:""}.codicon-mirror-public:before{content:""}.codicon-star:before{content:""}.codicon-star-add:before{content:""}.codicon-star-delete:before{content:""}.codicon-star-empty:before{content:""}.codicon-comment:before{content:""}.codicon-comment-add:before{content:""}.codicon-alert:before{content:""}.codicon-warning:before{content:""}.codicon-search:before{content:""}.codicon-search-save:before{content:""}.codicon-log-out:before{content:""}.codicon-sign-out:before{content:""}.codicon-log-in:before{content:""}.codicon-sign-in:before{content:""}.codicon-eye:before{content:""}.codicon-eye-unwatch:before{content:""}.codicon-eye-watch:before{content:""}.codicon-circle-filled:before{content:""}.codicon-primitive-dot:before{content:""}.codicon-close-dirty:before{content:""}.codicon-debug-breakpoint:before{content:""}.codicon-debug-breakpoint-disabled:before{content:""}.codicon-debug-hint:before{content:""}.codicon-terminal-decoration-success:before{content:""}.codicon-primitive-square:before{content:""}.codicon-edit:before{content:""}.codicon-pencil:before{content:""}.codicon-info:before{content:""}.codicon-issue-opened:before{content:""}.codicon-gist-private:before{content:""}.codicon-git-fork-private:before{content:""}.codicon-lock:before{content:""}.codicon-mirror-private:before{content:""}.codicon-close:before{content:""}.codicon-remove-close:before{content:""}.codicon-x:before{content:""}.codicon-repo-sync:before{content:""}.codicon-sync:before{content:""}.codicon-clone:before{content:""}.codicon-desktop-download:before{content:""}.codicon-beaker:before{content:""}.codicon-microscope:before{content:""}.codicon-vm:before{content:""}.codicon-device-desktop:before{content:""}.codicon-file:before{content:""}.codicon-file-text:before{content:""}.codicon-more:before{content:""}.codicon-ellipsis:before{content:""}.codicon-kebab-horizontal:before{content:""}.codicon-mail-reply:before{content:""}.codicon-reply:before{content:""}.codicon-organization:before{content:""}.codicon-organization-filled:before{content:""}.codicon-organization-outline:before{content:""}.codicon-new-file:before{content:""}.codicon-file-add:before{content:""}.codicon-new-folder:before{content:""}.codicon-file-directory-create:before{content:""}.codicon-trash:before{content:""}.codicon-trashcan:before{content:""}.codicon-history:before{content:""}.codicon-clock:before{content:""}.codicon-folder:before{content:""}.codicon-file-directory:before{content:""}.codicon-symbol-folder:before{content:""}.codicon-logo-github:before{content:""}.codicon-mark-github:before{content:""}.codicon-github:before{content:""}.codicon-terminal:before{content:""}.codicon-console:before{content:""}.codicon-repl:before{content:""}.codicon-zap:before{content:""}.codicon-symbol-event:before{content:""}.codicon-error:before{content:""}.codicon-stop:before{content:""}.codicon-variable:before{content:""}.codicon-symbol-variable:before{content:""}.codicon-array:before{content:""}.codicon-symbol-array:before{content:""}.codicon-symbol-module:before{content:""}.codicon-symbol-package:before{content:""}.codicon-symbol-namespace:before{content:""}.codicon-symbol-object:before{content:""}.codicon-symbol-method:before{content:""}.codicon-symbol-function:before{content:""}.codicon-symbol-constructor:before{content:""}.codicon-symbol-boolean:before{content:""}.codicon-symbol-null:before{content:""}.codicon-symbol-numeric:before{content:""}.codicon-symbol-number:before{content:""}.codicon-symbol-structure:before{content:""}.codicon-symbol-struct:before{content:""}.codicon-symbol-parameter:before{content:""}.codicon-symbol-type-parameter:before{content:""}.codicon-symbol-key:before{content:""}.codicon-symbol-text:before{content:""}.codicon-symbol-reference:before{content:""}.codicon-go-to-file:before{content:""}.codicon-symbol-enum:before{content:""}.codicon-symbol-value:before{content:""}.codicon-symbol-ruler:before{content:""}.codicon-symbol-unit:before{content:""}.codicon-activate-breakpoints:before{content:""}.codicon-archive:before{content:""}.codicon-arrow-both:before{content:""}.codicon-arrow-down:before{content:""}.codicon-arrow-left:before{content:""}.codicon-arrow-right:before{content:""}.codicon-arrow-small-down:before{content:""}.codicon-arrow-small-left:before{content:""}.codicon-arrow-small-right:before{content:""}.codicon-arrow-small-up:before{content:""}.codicon-arrow-up:before{content:""}.codicon-bell:before{content:""}.codicon-bold:before{content:""}.codicon-book:before{content:""}.codicon-bookmark:before{content:""}.codicon-debug-breakpoint-conditional-unverified:before{content:""}.codicon-debug-breakpoint-conditional:before{content:""}.codicon-debug-breakpoint-conditional-disabled:before{content:""}.codicon-debug-breakpoint-data-unverified:before{content:""}.codicon-debug-breakpoint-data:before{content:""}.codicon-debug-breakpoint-data-disabled:before{content:""}.codicon-debug-breakpoint-log-unverified:before{content:""}.codicon-debug-breakpoint-log:before{content:""}.codicon-debug-breakpoint-log-disabled:before{content:""}.codicon-briefcase:before{content:""}.codicon-broadcast:before{content:""}.codicon-browser:before{content:""}.codicon-bug:before{content:""}.codicon-calendar:before{content:""}.codicon-case-sensitive:before{content:""}.codicon-check:before{content:""}.codicon-checklist:before{content:""}.codicon-chevron-down:before{content:""}.codicon-chevron-left:before{content:""}.codicon-chevron-right:before{content:""}.codicon-chevron-up:before{content:""}.codicon-chrome-close:before{content:""}.codicon-chrome-maximize:before{content:""}.codicon-chrome-minimize:before{content:""}.codicon-chrome-restore:before{content:""}.codicon-circle-outline:before{content:""}.codicon-circle:before{content:""}.codicon-debug-breakpoint-unverified:before{content:""}.codicon-terminal-decoration-incomplete:before{content:""}.codicon-circle-slash:before{content:""}.codicon-circuit-board:before{content:""}.codicon-clear-all:before{content:""}.codicon-clippy:before{content:""}.codicon-close-all:before{content:""}.codicon-cloud-download:before{content:""}.codicon-cloud-upload:before{content:""}.codicon-code:before{content:""}.codicon-collapse-all:before{content:""}.codicon-color-mode:before{content:""}.codicon-comment-discussion:before{content:""}.codicon-credit-card:before{content:""}.codicon-dash:before{content:""}.codicon-dashboard:before{content:""}.codicon-database:before{content:""}.codicon-debug-continue:before{content:""}.codicon-debug-disconnect:before{content:""}.codicon-debug-pause:before{content:""}.codicon-debug-restart:before{content:""}.codicon-debug-start:before{content:""}.codicon-debug-step-into:before{content:""}.codicon-debug-step-out:before{content:""}.codicon-debug-step-over:before{content:""}.codicon-debug-stop:before{content:""}.codicon-debug:before{content:""}.codicon-device-camera-video:before{content:""}.codicon-device-camera:before{content:""}.codicon-device-mobile:before{content:""}.codicon-diff-added:before{content:""}.codicon-diff-ignored:before{content:""}.codicon-diff-modified:before{content:""}.codicon-diff-removed:before{content:""}.codicon-diff-renamed:before{content:""}.codicon-diff:before{content:""}.codicon-diff-sidebyside:before{content:""}.codicon-discard:before{content:""}.codicon-editor-layout:before{content:""}.codicon-empty-window:before{content:""}.codicon-exclude:before{content:""}.codicon-extensions:before{content:""}.codicon-eye-closed:before{content:""}.codicon-file-binary:before{content:""}.codicon-file-code:before{content:""}.codicon-file-media:before{content:""}.codicon-file-pdf:before{content:""}.codicon-file-submodule:before{content:""}.codicon-file-symlink-directory:before{content:""}.codicon-file-symlink-file:before{content:""}.codicon-file-zip:before{content:""}.codicon-files:before{content:""}.codicon-filter:before{content:""}.codicon-flame:before{content:""}.codicon-fold-down:before{content:""}.codicon-fold-up:before{content:""}.codicon-fold:before{content:""}.codicon-folder-active:before{content:""}.codicon-folder-opened:before{content:""}.codicon-gear:before{content:""}.codicon-gift:before{content:""}.codicon-gist-secret:before{content:""}.codicon-gist:before{content:""}.codicon-git-commit:before{content:""}.codicon-git-compare:before{content:""}.codicon-compare-changes:before{content:""}.codicon-git-merge:before{content:""}.codicon-github-action:before{content:""}.codicon-github-alt:before{content:""}.codicon-globe:before{content:""}.codicon-grabber:before{content:""}.codicon-graph:before{content:""}.codicon-gripper:before{content:""}.codicon-heart:before{content:""}.codicon-home:before{content:""}.codicon-horizontal-rule:before{content:""}.codicon-hubot:before{content:""}.codicon-inbox:before{content:""}.codicon-issue-reopened:before{content:""}.codicon-issues:before{content:""}.codicon-italic:before{content:""}.codicon-jersey:before{content:""}.codicon-json:before{content:""}.codicon-kebab-vertical:before{content:""}.codicon-key:before{content:""}.codicon-law:before{content:""}.codicon-lightbulb-autofix:before{content:""}.codicon-link-external:before{content:""}.codicon-link:before{content:""}.codicon-list-ordered:before{content:""}.codicon-list-unordered:before{content:""}.codicon-live-share:before{content:""}.codicon-loading:before{content:""}.codicon-location:before{content:""}.codicon-mail-read:before{content:""}.codicon-mail:before{content:""}.codicon-markdown:before{content:""}.codicon-megaphone:before{content:""}.codicon-mention:before{content:""}.codicon-milestone:before{content:""}.codicon-git-pull-request-milestone:before{content:""}.codicon-mortar-board:before{content:""}.codicon-move:before{content:""}.codicon-multiple-windows:before{content:""}.codicon-mute:before{content:""}.codicon-no-newline:before{content:""}.codicon-note:before{content:""}.codicon-octoface:before{content:""}.codicon-open-preview:before{content:""}.codicon-package:before{content:""}.codicon-paintcan:before{content:""}.codicon-pin:before{content:""}.codicon-play:before{content:""}.codicon-run:before{content:""}.codicon-plug:before{content:""}.codicon-preserve-case:before{content:""}.codicon-preview:before{content:""}.codicon-project:before{content:""}.codicon-pulse:before{content:""}.codicon-question:before{content:""}.codicon-quote:before{content:""}.codicon-radio-tower:before{content:""}.codicon-reactions:before{content:""}.codicon-references:before{content:""}.codicon-refresh:before{content:""}.codicon-regex:before{content:""}.codicon-remote-explorer:before{content:""}.codicon-remote:before{content:""}.codicon-remove:before{content:""}.codicon-replace-all:before{content:""}.codicon-replace:before{content:""}.codicon-repo-clone:before{content:""}.codicon-repo-force-push:before{content:""}.codicon-repo-pull:before{content:""}.codicon-repo-push:before{content:""}.codicon-report:before{content:""}.codicon-request-changes:before{content:""}.codicon-rocket:before{content:""}.codicon-root-folder-opened:before{content:""}.codicon-root-folder:before{content:""}.codicon-rss:before{content:""}.codicon-ruby:before{content:""}.codicon-save-all:before{content:""}.codicon-save-as:before{content:""}.codicon-save:before{content:""}.codicon-screen-full:before{content:""}.codicon-screen-normal:before{content:""}.codicon-search-stop:before{content:""}.codicon-server:before{content:""}.codicon-settings-gear:before{content:""}.codicon-settings:before{content:""}.codicon-shield:before{content:""}.codicon-smiley:before{content:""}.codicon-sort-precedence:before{content:""}.codicon-split-horizontal:before{content:""}.codicon-split-vertical:before{content:""}.codicon-squirrel:before{content:""}.codicon-star-full:before{content:""}.codicon-star-half:before{content:""}.codicon-symbol-class:before{content:""}.codicon-symbol-color:before{content:""}.codicon-symbol-constant:before{content:""}.codicon-symbol-enum-member:before{content:""}.codicon-symbol-field:before{content:""}.codicon-symbol-file:before{content:""}.codicon-symbol-interface:before{content:""}.codicon-symbol-keyword:before{content:""}.codicon-symbol-misc:before{content:""}.codicon-symbol-operator:before{content:""}.codicon-symbol-property:before{content:""}.codicon-wrench:before{content:""}.codicon-wrench-subaction:before{content:""}.codicon-symbol-snippet:before{content:""}.codicon-tasklist:before{content:""}.codicon-telescope:before{content:""}.codicon-text-size:before{content:""}.codicon-three-bars:before{content:""}.codicon-thumbsdown:before{content:""}.codicon-thumbsup:before{content:""}.codicon-tools:before{content:""}.codicon-triangle-down:before{content:""}.codicon-triangle-left:before{content:""}.codicon-triangle-right:before{content:""}.codicon-triangle-up:before{content:""}.codicon-twitter:before{content:""}.codicon-unfold:before{content:""}.codicon-unlock:before{content:""}.codicon-unmute:before{content:""}.codicon-unverified:before{content:""}.codicon-verified:before{content:""}.codicon-versions:before{content:""}.codicon-vm-active:before{content:""}.codicon-vm-outline:before{content:""}.codicon-vm-running:before{content:""}.codicon-watch:before{content:""}.codicon-whitespace:before{content:""}.codicon-whole-word:before{content:""}.codicon-window:before{content:""}.codicon-word-wrap:before{content:""}.codicon-zoom-in:before{content:""}.codicon-zoom-out:before{content:""}.codicon-list-filter:before{content:""}.codicon-list-flat:before{content:""}.codicon-list-selection:before{content:""}.codicon-selection:before{content:""}.codicon-list-tree:before{content:""}.codicon-debug-breakpoint-function-unverified:before{content:""}.codicon-debug-breakpoint-function:before{content:""}.codicon-debug-breakpoint-function-disabled:before{content:""}.codicon-debug-stackframe-active:before{content:""}.codicon-circle-small-filled:before{content:""}.codicon-debug-stackframe-dot:before{content:""}.codicon-terminal-decoration-mark:before{content:""}.codicon-debug-stackframe:before{content:""}.codicon-debug-stackframe-focused:before{content:""}.codicon-debug-breakpoint-unsupported:before{content:""}.codicon-symbol-string:before{content:""}.codicon-debug-reverse-continue:before{content:""}.codicon-debug-step-back:before{content:""}.codicon-debug-restart-frame:before{content:""}.codicon-debug-alt:before{content:""}.codicon-call-incoming:before{content:""}.codicon-call-outgoing:before{content:""}.codicon-menu:before{content:""}.codicon-expand-all:before{content:""}.codicon-feedback:before{content:""}.codicon-git-pull-request-reviewer:before{content:""}.codicon-group-by-ref-type:before{content:""}.codicon-ungroup-by-ref-type:before{content:""}.codicon-account:before{content:""}.codicon-git-pull-request-assignee:before{content:""}.codicon-bell-dot:before{content:""}.codicon-debug-console:before{content:""}.codicon-library:before{content:""}.codicon-output:before{content:""}.codicon-run-all:before{content:""}.codicon-sync-ignored:before{content:""}.codicon-pinned:before{content:""}.codicon-github-inverted:before{content:""}.codicon-server-process:before{content:""}.codicon-server-environment:before{content:""}.codicon-pass:before{content:""}.codicon-issue-closed:before{content:""}.codicon-stop-circle:before{content:""}.codicon-play-circle:before{content:""}.codicon-record:before{content:""}.codicon-debug-alt-small:before{content:""}.codicon-vm-connect:before{content:""}.codicon-cloud:before{content:""}.codicon-merge:before{content:""}.codicon-export:before{content:""}.codicon-graph-left:before{content:""}.codicon-magnet:before{content:""}.codicon-notebook:before{content:""}.codicon-redo:before{content:""}.codicon-check-all:before{content:""}.codicon-pinned-dirty:before{content:""}.codicon-pass-filled:before{content:""}.codicon-circle-large-filled:before{content:""}.codicon-circle-large:before{content:""}.codicon-circle-large-outline:before{content:""}.codicon-combine:before{content:""}.codicon-gather:before{content:""}.codicon-table:before{content:""}.codicon-variable-group:before{content:""}.codicon-type-hierarchy:before{content:""}.codicon-type-hierarchy-sub:before{content:""}.codicon-type-hierarchy-super:before{content:""}.codicon-git-pull-request-create:before{content:""}.codicon-run-above:before{content:""}.codicon-run-below:before{content:""}.codicon-notebook-template:before{content:""}.codicon-debug-rerun:before{content:""}.codicon-workspace-trusted:before{content:""}.codicon-workspace-untrusted:before{content:""}.codicon-workspace-unknown:before{content:""}.codicon-terminal-cmd:before{content:""}.codicon-terminal-debian:before{content:""}.codicon-terminal-linux:before{content:""}.codicon-terminal-powershell:before{content:""}.codicon-terminal-tmux:before{content:""}.codicon-terminal-ubuntu:before{content:""}.codicon-terminal-bash:before{content:""}.codicon-arrow-swap:before{content:""}.codicon-copy:before{content:""}.codicon-person-add:before{content:""}.codicon-filter-filled:before{content:""}.codicon-wand:before{content:""}.codicon-debug-line-by-line:before{content:""}.codicon-inspect:before{content:""}.codicon-layers:before{content:""}.codicon-layers-dot:before{content:""}.codicon-layers-active:before{content:""}.codicon-compass:before{content:""}.codicon-compass-dot:before{content:""}.codicon-compass-active:before{content:""}.codicon-azure:before{content:""}.codicon-issue-draft:before{content:""}.codicon-git-pull-request-closed:before{content:""}.codicon-git-pull-request-draft:before{content:""}.codicon-debug-all:before{content:""}.codicon-debug-coverage:before{content:""}.codicon-run-errors:before{content:""}.codicon-folder-library:before{content:""}.codicon-debug-continue-small:before{content:""}.codicon-beaker-stop:before{content:""}.codicon-graph-line:before{content:""}.codicon-graph-scatter:before{content:""}.codicon-pie-chart:before{content:""}.codicon-bracket:before{content:""}.codicon-bracket-dot:before{content:""}.codicon-bracket-error:before{content:""}.codicon-lock-small:before{content:""}.codicon-azure-devops:before{content:""}.codicon-verified-filled:before{content:""}.codicon-newline:before{content:""}.codicon-layout:before{content:""}.codicon-layout-activitybar-left:before{content:""}.codicon-layout-activitybar-right:before{content:""}.codicon-layout-panel-left:before{content:""}.codicon-layout-panel-center:before{content:""}.codicon-layout-panel-justify:before{content:""}.codicon-layout-panel-right:before{content:""}.codicon-layout-panel:before{content:""}.codicon-layout-sidebar-left:before{content:""}.codicon-layout-sidebar-right:before{content:""}.codicon-layout-statusbar:before{content:""}.codicon-layout-menubar:before{content:""}.codicon-layout-centered:before{content:""}.codicon-target:before{content:""}.codicon-indent:before{content:""}.codicon-record-small:before{content:""}.codicon-error-small:before{content:""}.codicon-terminal-decoration-error:before{content:""}.codicon-arrow-circle-down:before{content:""}.codicon-arrow-circle-left:before{content:""}.codicon-arrow-circle-right:before{content:""}.codicon-arrow-circle-up:before{content:""}.codicon-layout-sidebar-right-off:before{content:""}.codicon-layout-panel-off:before{content:""}.codicon-layout-sidebar-left-off:before{content:""}.codicon-blank:before{content:""}.codicon-heart-filled:before{content:""}.codicon-map:before{content:""}.codicon-map-horizontal:before{content:""}.codicon-fold-horizontal:before{content:""}.codicon-map-filled:before{content:""}.codicon-map-horizontal-filled:before{content:""}.codicon-fold-horizontal-filled:before{content:""}.codicon-circle-small:before{content:""}.codicon-bell-slash:before{content:""}.codicon-bell-slash-dot:before{content:""}.codicon-comment-unresolved:before{content:""}.codicon-git-pull-request-go-to-changes:before{content:""}.codicon-git-pull-request-new-changes:before{content:""}.codicon-search-fuzzy:before{content:""}.codicon-comment-draft:before{content:""}.codicon-send:before{content:""}.codicon-sparkle:before{content:""}.codicon-insert:before{content:""}.codicon-mic:before{content:""}.codicon-thumbsdown-filled:before{content:""}.codicon-thumbsup-filled:before{content:""}.codicon-coffee:before{content:""}.codicon-snake:before{content:""}.codicon-game:before{content:""}.codicon-vr:before{content:""}.codicon-chip:before{content:""}.codicon-piano:before{content:""}.codicon-music:before{content:""}.codicon-mic-filled:before{content:""}.codicon-repo-fetch:before{content:""}.codicon-copilot:before{content:""}.codicon-lightbulb-sparkle:before{content:""}.codicon-robot:before{content:""}.codicon-sparkle-filled:before{content:""}.codicon-diff-single:before{content:""}.codicon-diff-multiple:before{content:""}.codicon-surround-with:before{content:""}.codicon-share:before{content:""}.codicon-git-stash:before{content:""}.codicon-git-stash-apply:before{content:""}.codicon-git-stash-pop:before{content:""}.codicon-vscode:before{content:""}.codicon-vscode-insiders:before{content:""}.codicon-code-oss:before{content:""}.codicon-run-coverage:before{content:""}.codicon-run-all-coverage:before{content:""}.codicon-coverage:before{content:""}.codicon-github-project:before{content:""}.codicon-map-vertical:before{content:""}.codicon-fold-vertical:before{content:""}.codicon-map-vertical-filled:before{content:""}.codicon-fold-vertical-filled:before{content:""}.codicon-go-to-search:before{content:""}.codicon-percentage:before{content:""}.codicon-sort-percentage:before{content:""}.codicon-attach:before{content:""}.codicon-go-to-editing-session:before{content:""}.codicon-edit-session:before{content:""}.codicon-code-review:before{content:""}.codicon-copilot-warning:before{content:""}.codicon-python:before{content:""}.codicon-copilot-large:before{content:""}.codicon-copilot-warning-large:before{content:""}.codicon-keyboard-tab:before{content:""}.codicon-copilot-blocked:before{content:""}.codicon-copilot-not-connected:before{content:""}.codicon-flag:before{content:""}.codicon-lightbulb-empty:before{content:""}.codicon-symbol-method-arrow:before{content:""}.codicon-copilot-unavailable:before{content:""}.codicon-repo-pinned:before{content:""}.codicon-keyboard-tab-above:before{content:""}.codicon-keyboard-tab-below:before{content:""}.codicon-git-pull-request-done:before{content:""}.codicon-mcp:before{content:""}.codicon-extensions-large:before{content:""}.codicon-layout-panel-dock:before{content:""}.codicon-layout-sidebar-left-dock:before{content:""}.codicon-layout-sidebar-right-dock:before{content:""}.codicon-copilot-in-progress:before{content:""}.codicon-copilot-error:before{content:""}.codicon-copilot-success:before{content:""}.codicon-chat-sparkle:before{content:""}.codicon-search-sparkle:before{content:""}.codicon-edit-sparkle:before{content:""}.codicon-copilot-snooze:before{content:""}.codicon-send-to-remote-agent:before{content:""}.codicon-comment-discussion-sparkle:before{content:""}.codicon-chat-sparkle-warning:before{content:""}.codicon-chat-sparkle-error:before{content:""}.codicon-git-fetch:before{content:""}@font-face{font-family:scm-codicon;font-display:block;src:url(/assets/codicon-BSYL95uZ.ttf) format("truetype")}.scm-root,.scm-portal{--scm-bg: #f8f8f8;--scm-fg: #3b3b3b;--scm-title-fg: #3b3b3b;--scm-desc-fg: #717171;--scm-border: #e5e5e5;--scm-input-bg: #ffffff;--scm-input-border: #cecece;--scm-input-placeholder: #767676;--scm-focus: #005fb8;--scm-button-bg: #005fb8;--scm-button-hover: #0258a8;--scm-button-fg: #ffffff;--scm-button-separator: rgba(255, 255, 255, .4);--scm-badge-bg: #005fb8;--scm-badge-fg: #ffffff;--scm-hover: #f2f2f2;--scm-selection: #e8e8e8;--scm-selection-focus: #e8e8e8;--scm-toolbar-hover: rgba(184, 184, 184, .31);--scm-icon: #3b3b3b;--scm-progress: #005fb8;--scm-menu-bg: #ffffff;--scm-menu-fg: #3b3b3b;--scm-menu-border: #cecece;--scm-menu-selection: #005fb8;--scm-menu-selection-fg: #ffffff;--scm-menu-separator: #cecece;--scm-error-bg: #f2dede;--scm-error-border: #be1100;--scm-modified: #895503;--scm-added: #587c0c;--scm-untracked: #007100;--scm-deleted: #ad0707;--scm-renamed: #007100;--scm-conflict: #ad0707;--scm-ignored: #8e8e90;--scm-ref-local: #005fb8;--scm-ref-remote: #652d90;--scm-ref-base: #ea5c00;--scm-ref-fg: #ffffff;--scm-lane-0: #ffb000;--scm-lane-1: #dc267f;--scm-lane-2: #994f00;--scm-lane-3: #40b0a6;--scm-lane-4: #b66dff;font-family:-apple-system,BlinkMacSystemFont,Segoe WPC,Segoe UI,Ubuntu,Droid Sans,sans-serif;font-size:13px;line-height:22px;color:var(--scm-fg);background:var(--scm-bg)}.dark .scm-root,.dark .scm-portal{--scm-bg: #181818;--scm-fg: #cccccc;--scm-title-fg: #cccccc;--scm-desc-fg: #9d9d9d;--scm-border: #2b2b2b;--scm-input-bg: #313131;--scm-input-border: #3c3c3c;--scm-input-placeholder: #989898;--scm-focus: #0078d4;--scm-button-bg: #0078d4;--scm-button-hover: #026ec1;--scm-button-fg: #ffffff;--scm-badge-bg: #0078d4;--scm-badge-fg: #ffffff;--scm-hover: #2a2d2e;--scm-selection: #37373d;--scm-selection-focus: #04395e;--scm-toolbar-hover: rgba(90, 93, 94, .31);--scm-icon: #cccccc;--scm-progress: #0078d4;--scm-menu-bg: #1f1f1f;--scm-menu-fg: #cccccc;--scm-menu-border: #454545;--scm-menu-selection: #0078d4;--scm-menu-separator: #454545;--scm-error-bg: #5a1d1d;--scm-error-border: #be1100;--scm-modified: #e2c08d;--scm-added: #81b88b;--scm-untracked: #73c991;--scm-deleted: #c74e39;--scm-renamed: #73c991;--scm-conflict: #e4676b;--scm-ignored: #8c8c8c;--scm-ref-local: #0078d4;--scm-ref-remote: #b180d7;--scm-ref-base: #ea5c00}.scm-portal{font-family:-apple-system,BlinkMacSystemFont,Segoe WPC,Segoe UI,Ubuntu,Droid Sans,sans-serif;font-size:13px}.scm-root .codicon,.scm-portal .codicon{font-family:scm-codicon!important;font-size:16px;line-height:16px}.scm-row:hover{background:var(--scm-hover)}.scm-row[aria-selected=true]{background:var(--scm-selection)}.scm-list:focus-within .scm-row[aria-selected=true]{background:var(--scm-selection-focus)}.scm-list:focus .scm-row[data-focused=true]{outline:1px solid var(--scm-focus);outline-offset:-1px}.scm-row .scm-actions{display:none}.scm-row:hover .scm-actions,.scm-row[aria-selected=true] .scm-actions,.scm-row[data-focused=true] .scm-actions{display:flex}.scm-view .scm-view-actions{display:none}.scm-view:hover .scm-view-actions,.scm-view:focus-within .scm-view-actions{display:flex}.scm-action{display:inline-flex;width:22px;height:22px;align-items:center;justify-content:center;border-radius:5px;color:var(--scm-icon);background:transparent;flex-shrink:0}.scm-action:hover{background:var(--scm-toolbar-hover)}.scm-action:disabled{opacity:.4;background:transparent}.scm-action:focus-visible{outline:1px solid var(--scm-focus);outline-offset:-1px}.scm-input{background:var(--scm-input-bg);border:1px solid var(--scm-input-border);color:var(--scm-fg);border-radius:2px}.scm-input::-moz-placeholder{color:var(--scm-input-placeholder)}.scm-input::placeholder{color:var(--scm-input-placeholder)}.scm-input:focus{outline:1px solid var(--scm-focus);outline-offset:-1px;border-color:var(--scm-focus)}.scm-button{background:var(--scm-button-bg);color:var(--scm-button-fg)}.scm-button:hover:not(:disabled){background:var(--scm-button-hover)}.scm-button:disabled{opacity:.4}.scm-button:focus-visible{outline:1px solid var(--scm-focus);outline-offset:2px}.scm-badge{display:inline-block;min-width:18px;height:18px;padding:3px 6px;border-radius:11px;font-size:11px;line-height:12px;font-weight:400;text-align:center;box-sizing:border-box;background:var(--scm-badge-bg);color:var(--scm-badge-fg)}.scm-progress{position:absolute;top:0;height:2px;width:2%;background:var(--scm-progress);animation:scm-progress 4s linear infinite}@media(prefers-reduced-motion:reduce){.scm-progress{animation:none;width:100%;opacity:.6}}@keyframes scm-progress{0%{transform:translate(0) scaleX(1);left:0}to{left:100%}}.scm-tone-M,.scm-tone-T{color:var(--scm-modified)}.scm-tone-A{color:var(--scm-added)}.scm-tone-U{color:var(--scm-untracked)}.scm-tone-D{color:var(--scm-deleted)}.scm-tone-R,.scm-tone-C{color:var(--scm-renamed)}.scm-tone-\!{color:var(--scm-conflict)}.scm-tone-I{color:var(--scm-ignored)}diff --git a/dodaios/ui/web/dist/assets/ArcadeCabinet-twip27TL.css b/dodaios/ui/web/dist/assets/ArcadeCabinet-twip27TL.cssnew file mode 100644index 0000000000..3056d81aff--- /dev/null+++ b/dodaios/ui/web/dist/assets/ArcadeCabinet-twip27TL.css@@ -0,0 +1 @@+.office-arcade-backdrop{position:absolute;top:0;right:0;bottom:0;left:0;z-index:70;display:flex;align-items:center;justify-content:center;padding:16px;background:hsl(var(--background) / .6)}.office-arcade{width:min(1100px,100%,calc((100vh - 80px) * 16 / 9));outline:none}.office-arcade-screen{position:relative;width:100%;aspect-ratio:16 / 9;border-radius:14px;overflow:hidden;background:#0b0a14;border:1px solid hsl(var(--border));box-shadow:0 18px 60px #00000073}.office-arcade-screen canvas{display:block}.office-arcade-fallback{position:absolute;top:0;right:0;bottom:0;left:0;display:flex;align-items:center;justify-content:center;margin:0;color:#c9d4ff;font-size:13px}.office-arcade-hud{position:absolute;left:18px;top:14px;pointer-events:none;color:#e6ebff;font-size:12px;font-weight:600;letter-spacing:.08em;text-transform:uppercase;font-variant-numeric:tabular-nums;text-shadow:0 1px 3px rgb(0 0 0 / .8)}.office-arcade-hud-line{display:flex;align-items:center;gap:6px;flex-wrap:wrap}.office-arcade-shields{display:inline-flex;gap:3px;vertical-align:middle}.office-arcade-shields i{width:8px;height:8px;transform:rotate(45deg);background:#e6ebff}.office-arcade-shields i[data-on=false]{background:transparent;box-shadow:inset 0 0 0 1px #e6ebff59}.office-arcade-missiles{display:inline-flex;gap:3px;vertical-align:middle}.office-arcade-missiles i{width:0;height:0;border-left:4px solid transparent;border-right:4px solid transparent;border-bottom:9px solid #ff6b57}.office-arcade-missiles i[data-on=false]{border-bottom-color:#ff6b5740}.office-arcade-screen canvas{cursor:crosshair}.office-arcade-boost-label[data-active=true]{color:#7dd3fc}.office-arcade-rapid{color:#facc15}.office-arcade-bar{width:130px;height:4px;margin-top:6px;border-radius:2px;background:#ffffff1f;overflow:hidden}.office-arcade-bar i{display:block;height:100%;background:#facc15;transition:width .08s linear}.office-arcade-hud-sub{margin-top:6px;font-size:10px;color:#e6ebffa6}.office-arcade-keys{position:absolute;left:0;right:0;bottom:10px;margin:0;text-align:center;pointer-events:none;font-size:10px;font-weight:600;letter-spacing:.14em;text-transform:uppercase;color:#e6ebff8c}.office-arcade-close{position:absolute;right:10px;top:8px;border:0;background:#ffffff14;color:#e6ebff;width:28px;height:28px;border-radius:8px;font-size:18px;line-height:1;cursor:pointer}.office-arcade-close:hover{background:#ffffff29}.office-arcade-close:focus-visible,.office-arcade-message:focus-visible{outline:2px solid hsl(var(--ring));outline-offset:2px}.office-arcade-message{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);display:flex;flex-direction:column;align-items:center;gap:8px;max-width:80%;border:1px solid rgb(250 204 21 / .6);border-radius:12px;padding:16px 26px;background:#0b0a14c7;color:#facc15;cursor:pointer;text-align:center;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px)}.office-arcade-message strong{font-size:26px;letter-spacing:.12em;text-transform:uppercase;color:#e6ebff}.office-arcade-message span{font-size:13px;font-weight:600;letter-spacing:.06em}@media(max-width:600px){.office-arcade-hud{left:10px;top:8px;font-size:10px}.office-arcade-message strong{font-size:18px}}diff --git a/dodaios/ui/web/dist/assets/OfficeStage-C1haD6xM.css b/dodaios/ui/web/dist/assets/OfficeStage-C1haD6xM.cssdeleted file mode 100644index 548d94e0a7..0000000000--- a/dodaios/ui/web/dist/assets/OfficeStage-C1haD6xM.css+++ /dev/null@@ -1 +0,0 @@-.office-pane{position:absolute;z-index:36;display:flex;flex-direction:column;min-width:0;min-height:0;overflow:hidden;border:1px solid var(--pane-edge);border-radius:12px;background:var(--pane-ground);color:var(--pane-ink);box-shadow:0 24px 60px #00000073,0 4px 14px #00000038;-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);animation:office-pane-in .16s ease-out}.office-pane[data-appearance=light]{box-shadow:0 24px 60px #14120a3d,0 4px 14px #14120a1f}.office-pane:focus{outline:none}.office-pane:focus-visible{outline:2px solid hsl(var(--ring));outline-offset:2px}.office-pane[data-gesture]{-webkit-user-select:none;-moz-user-select:none;user-select:none}@keyframes office-pane-in{0%{opacity:0;transform:translateY(6px)}}@media(prefers-reduced-motion:reduce){.office-pane{animation:none}}.office-pane-head{position:relative;display:flex;flex:none;align-items:center;gap:8px;height:36px;min-height:36px;padding:0 4px 0 12px;border-bottom:1px solid var(--pane-rule);background:color-mix(in srgb,var(--pane-float) 45%,transparent);cursor:grab;-webkit-user-select:none;-moz-user-select:none;user-select:none;touch-action:none}.office-pane[data-gesture=move] .office-pane-head{cursor:grabbing}.office-pane-dot{flex:none;width:7px;height:7px;border-radius:50%}.office-pane-head h2{flex:0 1 auto;min-width:0;margin:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px;font-weight:500;color:var(--pane-ink)}.office-pane-meta{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px;color:var(--pane-ink-muted)}.office-pane-actions{display:flex;flex:none;align-items:center;gap:1px}.office-pane-actions button{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;padding:0;border:0;border-radius:6px;background:none;color:var(--pane-ink-muted);cursor:pointer}.office-pane-actions button svg{width:15px;height:15px}.office-pane-actions button:hover:not(:disabled){background:var(--pane-chip);color:var(--pane-ink)}.office-pane-actions button:focus-visible{outline:1px solid var(--pane-ink);outline-offset:-1px}.office-pane-actions button:disabled{opacity:.35;cursor:default}.office-pane-actions button[data-danger]:hover:not(:disabled),.office-pane-actions button[data-danger][aria-pressed=true]{color:var(--pane-fault)}.office-pane-actions button[data-danger][aria-pressed=true]{background:var(--pane-chip)}.office-pane-sep{width:1px;height:16px;margin:0 3px;background:var(--pane-rule)}.office-pane-term{position:relative;flex:1 1 0;min-height:0}.office-pane-term>*{position:absolute;top:0;right:0;bottom:0;left:0}.office-pane-status{position:absolute;z-index:2;left:12px;right:12px;bottom:10px;margin:0;padding:6px 10px;border:1px solid var(--pane-rule);border-radius:8px;background:var(--pane-float);box-shadow:0 6px 18px #00000038;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px;color:var(--pane-ink-muted);cursor:pointer}.office-pane-status[data-tone=ok]{color:var(--pane-ok)}.office-pane-status[data-tone=error]{color:var(--pane-fault);white-space:normal}.office-pane-grip{position:absolute;z-index:3;touch-action:none}.office-pane-grip[data-edge=n]{top:0;left:12px;right:12px;height:4px;cursor:ns-resize}.office-pane-grip[data-edge=s]{bottom:0;left:12px;right:12px;height:4px;cursor:ns-resize}.office-pane-grip[data-edge=e]{right:0;top:12px;bottom:12px;width:4px;cursor:ew-resize}.office-pane-grip[data-edge=w]{left:0;top:12px;bottom:12px;width:4px;cursor:ew-resize}.office-pane-grip[data-edge=nw]{top:0;left:0;width:12px;height:12px;cursor:nwse-resize}.office-pane-grip[data-edge=ne]{top:0;right:0;width:12px;height:12px;cursor:nesw-resize}.office-pane-grip[data-edge=sw]{bottom:0;left:0;width:14px;height:14px;cursor:nesw-resize}.office-pane-grip[data-edge=se]{bottom:0;right:0;width:16px;height:16px;cursor:nwse-resize}.office-pane-grip[data-edge=se]:after{content:"";position:absolute;right:4px;bottom:4px;width:8px;height:8px;opacity:.55;background:linear-gradient(135deg,transparent 0 45%,var(--pane-ink-faint) 45% 55%,transparent 55% 70%,var(--pane-ink-faint) 70% 80%,transparent 80%)}.office-pane:hover .office-pane-grip[data-edge=se]:after{opacity:.9}.office-pane[data-style=minimal]{border-radius:0}.office-pane[data-style=minimal] .office-pane-head{height:28px;min-height:28px;padding:0 2px 0 10px;gap:7px}.office-pane[data-style=minimal] .office-pane-head h2{font-size:12px}.office-pane[data-style=minimal] .office-pane-actions button{width:24px;height:24px;border-radius:0}.office-pane[data-style=minimal] .office-pane-actions button svg{width:14px;height:14px}.office-pane[data-style=minimal] .office-pane-status{border-radius:0}.office-pane[data-style=minimal]:focus-within{border-color:var(--pane-focus)}.office-pane[data-style=minimal]:focus-within:after{content:"";position:absolute;top:0;right:0;bottom:0;left:0;z-index:4;pointer-events:none;box-shadow:inset 0 0 0 1px var(--pane-focus)}.office-pane[data-style=minimal]:focus-within .office-pane-head h2{color:var(--pane-focus);font-weight:600}.office-pane[data-style=minimal]:focus-visible{outline:none}.office-pane-screen{position:relative;flex:1 1 clamp(200px,38vh,420px);min-height:110px;margin:0 12px;cursor:zoom-in}.office-pane-screen pre{position:absolute;top:8px;right:0;bottom:0;left:0;margin:0;overflow:hidden;display:flex;flex-direction:column;justify-content:flex-end;color:var(--pane-ink);white-space:pre;text-shadow:none;font-variant-ligatures:none}.office-pane-screen pre>div{overflow:hidden}.office-pane-cursor{background:var(--pane-caret);color:var(--pane-ground)}.office-pane-empty{position:absolute;top:0;right:0;bottom:0;left:0;display:flex;align-items:center;justify-content:center;margin:0;font-size:12px;color:var(--pane-ink-faint)}.office-mission-screen{width:100%;height:100%;overflow:hidden;background:hsl(var(--background));color:hsl(var(--foreground));border-radius:6px}.office-mission-screen>*{height:100%}.office-ide-monitor{display:flex;height:100%;color:hsl(var(--foreground))}.office-ide-side{flex:none;width:220px;padding:10px 8px;overflow:hidden}.office-ide-side-title{height:32px;padding:0 8px;font-size:14px;font-weight:600;line-height:32px}.office-ide-project{display:flex;align-items:center;gap:8px;margin-top:8px;padding:5px 8px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;font-size:13px;font-weight:500}.office-ide-project svg{flex:none;width:15px;height:15px;color:hsl(var(--muted-foreground))}.office-ide-ws{display:flex;align-items:center;gap:8px;margin-top:1px;padding:5px 8px 5px 22px;border-radius:6px;font-size:13px;color:hsl(var(--muted-foreground))}.office-ide-ws[data-active]{background:hsl(var(--muted));color:hsl(var(--foreground))}.office-ide-ws i{flex:none;width:6px;height:6px;border-radius:50%}.office-ide-ws span{flex:1;min-width:0;overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.office-ide-ws b{flex:none;font-size:12px;font-weight:400;color:hsl(var(--muted-foreground))}.office-ide-grid{display:grid;flex:1;min-width:0;min-height:0;gap:6px;padding:6px 6px 6px 0}.office-ide-tile{display:flex;flex-direction:column;min-width:0;min-height:0;overflow:hidden;border:1px solid var(--pane-rule);border-radius:8px;background:var(--pane-ground);color:var(--pane-ink)}.office-ide-screen{flex:1 1 auto;min-height:0;margin:0 10px 6px;cursor:inherit}.office-ide-empty{margin:auto;font-size:14px;color:hsl(var(--muted-foreground))}.office-viewport[data-first-person] .office-plate:not(.office-seat-prompt),.office-viewport[data-first-person] .office-bubble,.office-viewport[data-first-person] .office-checkpoint,.office-viewport[data-first-person] .office-call-pill{visibility:hidden}.courier-hud{position:absolute;z-index:40;left:50%;bottom:16px;transform:translate(-50%);display:flex;flex-wrap:wrap;align-items:center;gap:10px 16px;padding:10px 14px;max-width:calc(100% - 28px);font-size:12px}.courier-speed{position:relative;display:flex;align-items:baseline;gap:4px;min-width:92px}.courier-speed strong{font-size:28px;font-weight:700;font-variant-numeric:tabular-nums;line-height:1}.courier-speed span{color:hsl(var(--muted-foreground))}.courier-speed-arc{position:absolute;left:0;right:0;bottom:-5px;height:3px;border-radius:2px;background:linear-gradient(90deg,hsl(var(--primary)) calc(var(--share) * 100%),hsl(var(--border)) 0)}.courier-readouts{display:flex;flex-direction:column;gap:4px;min-width:150px}.courier-readouts strong{font-variant-numeric:tabular-nums}.courier-meter{display:grid;grid-template-columns:62px 1fr;align-items:center;gap:6px;color:hsl(var(--muted-foreground))}.courier-meter i{display:block;height:5px;border-radius:3px;background:hsl(var(--secondary));overflow:hidden}.courier-meter b{display:block;height:100%;background:hsl(var(--primary));transition:width .12s linear}.courier-actions{display:flex;flex-wrap:wrap;gap:6px;align-items:center}.courier-status{color:hsl(var(--muted-foreground))}.courier-primary{background:hsl(var(--primary));color:hsl(var(--primary-foreground));border-color:transparent}.courier-hud .office-hint{flex-basis:100%}.courier-help{position:absolute;z-index:40;right:14px;bottom:16px;width:min(300px,calc(100% - 28px));max-height:calc(100% - 120px);overflow:auto;padding:12px 14px;font-size:12px}.courier-help dl{display:flex;flex-direction:column;gap:4px;margin:8px 0}.courier-help dl>div{display:flex;justify-content:space-between;gap:12px}.courier-help dt{color:hsl(var(--muted-foreground))}.courier-help dd{margin:0}.courier-help kbd{font:inherit;font-size:11px;padding:1px 6px;border:1px solid hsl(var(--border));border-radius:5px;background:hsl(var(--background))}.courier-settings{position:absolute;z-index:50;left:50%;top:50%;transform:translate(-50%,-50%);width:min(420px,calc(100% - 28px));max-height:calc(100% - 40px);overflow:auto;display:flex;flex-direction:column;gap:10px;padding:14px 16px;font-size:13px}.courier-settings-head{display:flex;justify-content:space-between;align-items:center}.courier-settings-row{display:flex;flex-wrap:wrap;align-items:center;gap:8px}.courier-settings-row input[type=range]{flex:1;accent-color:hsl(var(--primary))}.courier-settings-row input[type=checkbox]{accent-color:hsl(var(--primary))}.courier-bindings{display:grid;grid-template-columns:1fr;gap:4px}.courier-binding{display:flex;justify-content:space-between;align-items:center;gap:10px}.courier-binding span{color:hsl(var(--muted-foreground))}@media(max-width:600px){.courier-hud{bottom:10px;gap:8px}.courier-help{display:none}}.courier-aim,.courier-nose{position:absolute;z-index:39;pointer-events:none;opacity:0;transform:translate(-50%,-50%)}.courier-aim{width:34px;height:34px;border-radius:50%;border:2px solid hsl(var(--primary) / .9);box-shadow:0 0 0 1px hsl(var(--background) / .6)}.courier-aim:before,.courier-aim:after{content:"";position:absolute;left:50%;top:50%;background:hsl(var(--primary) / .9);transform:translate(-50%,-50%)}.courier-aim:before{width:2px;height:8px}.courier-aim:after{width:8px;height:2px}.courier-nose{width:10px;height:10px;border-radius:50%;background:hsl(var(--foreground) / .85);box-shadow:0 0 0 2px hsl(var(--background) / .6)}.office-bubble{position:absolute;left:0;bottom:10px;transform:translate(-50%);transform-origin:center bottom;width:-moz-max-content;width:max-content;max-width:240px;padding:7px 11px;border-radius:14px;background:#fffdf7;color:#1c1917;border:1.5px solid #1c1917;box-shadow:0 3px 10px #00000059;font-size:12px;line-height:1.35;font-weight:600;font-family:inherit;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;user-select:none;animation:office-bubble-pop .22s cubic-bezier(.2,1.4,.5,1) both}.office-bubble p{margin:0;display:-webkit-box;-webkit-line-clamp:5;-webkit-box-orient:vertical;overflow:hidden;overflow-wrap:anywhere}.office-bubble-tail{position:absolute;left:50%;bottom:-8px;width:12px;height:12px;margin-left:-6px;background:inherit;border-right:1.5px solid #1c1917;border-bottom:1.5px solid #1c1917;transform:rotate(45deg) skew(8deg,8deg);border-bottom-right-radius:3px}.office-bubble[data-kind=thought]{border-radius:18px;background:#f1f5ff;border-style:dashed;border-color:#475569;color:#334155;font-weight:500;font-style:italic;max-width:200px}.office-bubble-puffs i{position:absolute;left:50%;border-radius:50%;background:#f1f5ff;border:1.5px dashed #475569}.office-bubble-puffs i:nth-child(1){width:10px;height:10px;bottom:-13px;margin-left:-9px}.office-bubble-puffs i:nth-child(2){width:6px;height:6px;bottom:-21px;margin-left:-3px}.office-bubble[data-kind=ask]{background:#fff4d6;border-color:#b45309;color:#451a03}.office-bubble[data-kind=ask] .office-bubble-tail{border-color:#b45309}.office-bubble[data-kind=ask] p:before{content:"?";display:inline-flex;align-items:center;justify-content:center;width:16px;height:16px;margin-right:6px;border-radius:50%;background:#f59e0b;color:#1c1917;font-size:11px;font-weight:800;font-style:normal;vertical-align:-2px}.office-bubble[data-kind=error]{background:#fff1f2;border-color:#be123c;color:#4c0519}.office-bubble[data-kind=error] .office-bubble-tail{border-color:#be123c}.office-bubble-dots{display:inline-flex;gap:3px;margin-left:6px;vertical-align:middle}.office-bubble-dots i{width:4px;height:4px;border-radius:50%;background:currentColor;opacity:.35;animation:office-bubble-dot 1.2s infinite ease-in-out}.office-bubble-dots i:nth-child(2){animation-delay:.2s}.office-bubble-dots i:nth-child(3){animation-delay:.4s}@keyframes office-bubble-dot{0%,80%,to{opacity:.25;transform:translateY(0)}40%{opacity:1;transform:translateY(-2px)}}@keyframes office-bubble-pop{0%{opacity:0;margin-bottom:-6px}to{opacity:1;margin-bottom:0}}@media(prefers-reduced-motion:reduce){.office-bubble,.office-bubble-dots i{animation:none}.office-bubble-dots i{opacity:.7}}.office-bubble-memory{display:flex;align-items:center;gap:5px;margin-top:5px;padding-top:5px;border-top:1px dashed #94a3b8;color:#334155;font-size:11px;font-style:normal;font-weight:600;line-height:1.3}.office-bubble-memory:first-child{margin-top:0;padding-top:0;border-top:0}.office-bubble-memory svg{flex:none;width:12px;height:12px}.office-bubble-memory-text{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.office-bubble-memory[data-phase=pending] svg{animation:office-bubble-spin 1s linear infinite}.office-bubble-memory[data-phase=saved]{color:#15803d}.office-bubble-memory[data-phase=failed]{color:#be123c}@keyframes office-bubble-spin{to{transform:rotate(360deg)}}@media(prefers-reduced-motion:reduce){.office-bubble-memory[data-phase=pending] svg{animation:none}}.office-talk{gap:0}.office-talk-head{display:flex;align-items:center;gap:10px;padding:10px 10px 8px 12px;border-bottom:1px solid hsl(var(--border))}.office-talk-avatar{display:inline-flex;flex:none;align-items:center;justify-content:center;width:32px;height:32px;color:#fff;font-size:14px;font-weight:800;clip-path:polygon(25% 3%,75% 3%,100% 50%,75% 97%,25% 97%,0 50%)}.office-talk-who{flex:1;min-width:0}.office-talk-who h2{margin:0;font-size:14px;font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.office-talk-who span{display:flex;align-items:center;gap:6px;margin-top:2px;font-size:11px;color:hsl(var(--muted-foreground));overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.office-talk-log{list-style:none;margin:0;padding:10px 12px;display:flex;flex-direction:column;gap:6px;flex:1 1 auto;min-height:56px;max-height:260px;overflow:auto;font-size:12px;line-height:1.45}.office-talk-empty{margin:auto 0;color:hsl(var(--muted-foreground));text-align:center;font-size:12px}.office-talk-msg{display:flex}.office-talk-msg p{margin:0;max-width:88%;padding:6px 10px;border-radius:12px;white-space:pre-wrap;overflow-wrap:anywhere}.office-talk-msg[data-from=you]{justify-content:flex-end}.office-talk-msg[data-from=you] p{background:hsl(var(--primary));color:hsl(var(--primary-foreground));border-bottom-right-radius:4px}.office-talk-msg[data-from=agent] p{background:hsl(var(--secondary));color:hsl(var(--foreground));border-bottom-left-radius:4px}.office-talk-msg[data-live] p{color:hsl(var(--muted-foreground));font-style:italic}.office-talk-msg[data-from=error] p{background:hsl(var(--destructive) / .12);color:hsl(var(--destructive))}.office-talk-alert{display:flex;flex-wrap:wrap;align-items:center;gap:6px;margin:0 12px 8px;padding:6px 9px;border-radius:9px;font-size:12px;background:hsl(var(--warning) / .15);color:hsl(var(--foreground))}.office-talk-error{margin:0 12px 6px;font-size:11px;color:hsl(var(--destructive))}.office-talk-composer{display:flex;align-items:flex-end;gap:6px;margin:0 10px;padding:5px;border:1px solid hsl(var(--border-strong, var(--border)));border-radius:14px;background:hsl(var(--background));transition:box-shadow .15s,border-color .15s}.office-talk-composer:focus-within{box-shadow:0 0 0 2px hsl(var(--ring) / .5)}.office-talk-composer[data-listening]{border-color:hsl(var(--success));box-shadow:0 0 0 3px hsl(var(--success) / .25)}.office-talk-composer textarea{flex:1;min-width:0;min-height:34px;max-height:120px;resize:none;border:0;padding:8px 4px;background:transparent;color:hsl(var(--foreground));font:inherit;font-size:13px;line-height:1.35;field-sizing:content}.office-talk-composer textarea:focus{outline:none}.office-talk-composer textarea::-moz-placeholder{color:hsl(var(--muted-foreground))}.office-talk-composer textarea::placeholder{color:hsl(var(--muted-foreground))}.office-talk-mic,.office-talk-send{display:inline-flex;flex:none;align-items:center;justify-content:center;width:34px;height:34px;border:0;border-radius:10px;cursor:pointer;touch-action:none}.office-talk-mic svg,.office-talk-send svg{width:17px;height:17px}.office-talk-mic{background:hsl(var(--secondary));color:hsl(var(--foreground))}.office-talk-mic:hover:not(:disabled){background:hsl(var(--secondary) / .7)}.office-talk-mic[aria-pressed=true]{background:hsl(var(--success));color:hsl(var(--background));animation:office-talk-live 1.4s ease-in-out infinite}.office-talk-send{background:hsl(var(--primary));color:hsl(var(--primary-foreground))}.office-talk-send[data-stop]{background:hsl(var(--secondary));color:hsl(var(--foreground))}.office-talk-send[data-stop] svg{width:13px;height:13px}.office-talk-mic:disabled,.office-talk-send:disabled{opacity:.45;cursor:not-allowed}.office-talk-mic:focus-visible,.office-talk-send:focus-visible,.office-talk-tools button:focus-visible{outline:2px solid hsl(var(--ring));outline-offset:2px}@keyframes office-talk-live{0%,to{box-shadow:0 0 hsl(var(--success) / .45)}50%{box-shadow:0 0 0 6px hsl(var(--success) / 0)}}.office-talk-status{margin:5px 14px 0;min-height:16px;font-size:11px;color:hsl(var(--muted-foreground));overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.office-talk-status[data-listening]{color:hsl(var(--success));font-weight:600}.office-talk-tools{display:grid;grid-template-columns:repeat(5,1fr);gap:2px;margin:8px 6px;padding-top:6px;border-top:1px solid hsl(var(--border))}.office-talk-tools button{display:flex;flex-direction:column;align-items:center;gap:3px;min-width:0;padding:6px 2px;border:0;border-radius:9px;background:none;color:hsl(var(--muted-foreground));font-size:10px;font-weight:600;cursor:pointer}.office-talk-tools button svg{width:16px;height:16px}.office-talk-tools button span{max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.office-talk-tools button:hover:not(:disabled){background:hsl(var(--secondary));color:hsl(var(--foreground))}.office-talk-tools button[aria-pressed=true]{color:hsl(var(--primary));background:hsl(var(--secondary))}.office-talk-tools button:disabled{opacity:.4;cursor:not-allowed}.office-talk-note{margin:0 14px 10px}@media(prefers-reduced-motion:reduce){.office-talk-mic[aria-pressed=true]{animation:none}}.wardrobe-section{display:flex;flex-direction:column;gap:5px}.wardrobe-row{display:flex;flex-wrap:wrap;gap:5px}.wardrobe-outfits{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:5px;width:100%}.wardrobe-outfit{display:flex;align-items:center;gap:7px;min-width:0;border:1px solid hsl(var(--border));border-radius:9px;padding:5px 8px;background:hsl(var(--background));color:hsl(var(--foreground));font-size:11px;text-align:left;cursor:pointer}.wardrobe-outfit i{flex:none;width:16px;height:16px;border-radius:5px;box-shadow:inset 0 0 0 1px hsl(var(--foreground) / .18)}.wardrobe-outfit:hover:not([aria-pressed=true]){background:hsl(var(--secondary))}.wardrobe-outfit[aria-pressed=true]{border-color:hsl(var(--ring));background:hsl(var(--secondary));font-weight:600}.wardrobe-swatch{width:22px;height:22px;border-radius:999px;border:0;padding:0;cursor:pointer;box-shadow:inset 0 0 0 1px hsl(var(--foreground) / .2)}.wardrobe-swatch[aria-pressed=true]{outline:2px solid hsl(var(--ring));outline-offset:2px}.wardrobe-outfit:focus-visible,.wardrobe-swatch:focus-visible{outline:2px solid hsl(var(--ring));outline-offset:2px}.wardrobe-chip-name{display:inline-block;max-width:110px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;vertical-align:bottom}.wardrobe-preview{height:240px;flex:none;border-radius:10px;background:hsl(var(--secondary) / .6);overflow:hidden}.office-face{display:inline-flex;flex:none;align-items:center;justify-content:center;border-radius:50%;background:hsl(var(--surface-raised));box-shadow:inset 0 0 0 1px hsl(var(--border-strong) / .7)}.office-face>*{filter:drop-shadow(0 0 .5px hsl(var(--foreground) / .55)) drop-shadow(0 0 .5px hsl(var(--foreground) / .35))}.office-key{display:inline-flex;align-items:center;justify-content:center;min-width:22px;height:22px;padding:0 6px;border-radius:6px;border:1px solid hsl(var(--border));box-shadow:inset 0 -2px hsl(var(--border));background:hsl(var(--background));color:hsl(var(--foreground));font-family:inherit;font-size:11px;font-weight:600;line-height:1;white-space:nowrap}.office-key[data-mouse]{box-shadow:none;border-radius:999px;padding:0 9px;font-weight:500;background:hsl(var(--secondary));color:hsl(var(--muted-foreground))}.office-keys{display:flex;flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:4px}.office-keys-alt{display:inline-flex;align-items:center;gap:3px}.office-keys-or{margin:0 3px 0 1px;font-size:11px;color:hsl(var(--muted-foreground))}.office-keys-plus{font-size:11px;color:hsl(var(--muted-foreground))}.team-card[data-called]{border-color:hsl(var(--border-strong));box-shadow:inset 3px 0 hsl(var(--border-strong))}.team-card[data-live]{border-color:hsl(var(--success) / .7);box-shadow:inset 3px 0 hsl(var(--success))}.team-live-mark{flex:none;display:inline-flex;align-items:center;gap:5px;padding:1px 8px;border-radius:999px;background:hsl(var(--success) / .12);color:hsl(var(--success));font-size:11px;font-weight:600}.team-live-mark i{width:6px;height:6px;border-radius:50%;background:hsl(var(--success))}.team-stack{display:inline-flex;align-items:center;padding-left:6px}.team-face{position:relative;display:inline-flex;margin-left:-6px;border-radius:50%;box-shadow:0 0 0 2px hsl(var(--background))}.team-face .office-dot{position:absolute;right:-1px;bottom:-1px;width:9px;height:9px;box-shadow:0 0 0 2px hsl(var(--background))}.team-face .office-dot[data-state=paused]{background:hsl(var(--background));box-shadow:0 0 0 2px hsl(var(--background)),inset 0 0 0 1.5px hsl(var(--muted-foreground))}.team-face-more{width:32px;height:32px;font-size:11px;font-weight:600;color:hsl(var(--muted-foreground));box-shadow:0 0 0 2px hsl(var(--background)),inset 0 0 0 1px hsl(var(--border-strong) / .7)}.team-picker-list{max-height:min(22rem,max(8rem,calc(90dvh - 29rem)))}.team-footer{position:sticky;bottom:0;z-index:1;display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin:0 -1.25rem -1.25rem;padding:12px 1.25rem;border-top:1px solid hsl(var(--border));background:hsl(var(--background))}.team-meeting{display:flex;flex-direction:column;gap:4px;padding:12px 14px;border-radius:12px;border:1px solid hsl(var(--border-strong));background:hsl(var(--secondary) / .6)}.team-meeting[data-compact]{width:100%;padding:9px 11px;border-color:hsl(var(--border));background:hsl(var(--popover) / .92)}.team-meeting-title{display:flex;align-items:center;gap:8px;margin:0;font-size:13px;font-weight:600;overflow-wrap:anywhere}.team-meeting-line{margin:0;font-size:12px;color:hsl(var(--muted-foreground))}.office-mc-chips button{padding:4px 10px;border:1px solid hsl(var(--border));border-radius:999px;background:hsl(var(--background));color:hsl(var(--foreground));font-size:11px;font-weight:600;cursor:pointer}.office-mc-chips button:hover:not(:disabled){background:hsl(var(--secondary))}.office-mc-chips button:disabled{opacity:.45;cursor:not-allowed}.office-mc-chips button[aria-pressed=true]{border-color:hsl(var(--primary));background:hsl(var(--primary));color:hsl(var(--primary-foreground));text-shadow:none}.office-mc-chips button:focus-visible,.office-mc-tabs button:focus-visible{outline:2px solid hsl(var(--ring));outline-offset:2px}.office-talk-status[data-tone=ok]{color:hsl(var(--success))}.office-talk-status[data-tone=error]{color:hsl(var(--destructive));white-space:normal}.office-cmd-check{display:inline-flex;align-items:center;gap:6px;flex:none;font-size:11px;color:hsl(var(--muted-foreground));cursor:pointer}.office-cmd-check input{accent-color:hsl(var(--primary))}.office-mc{display:flex;flex-direction:column;gap:14px;max-width:520px}.office-mc-heading{margin:0 0 10px;font-size:13px;font-weight:600;color:hsl(var(--foreground));letter-spacing:0}.office-mc-more{border-top:1px solid hsl(var(--border));padding-top:12px}.office-mc-more>summary{cursor:pointer;list-style:none;display:flex;align-items:center;justify-content:space-between;margin:0}.office-mc-more>summary::-webkit-details-marker{display:none}.office-mc-more>summary:after{content:"";width:7px;height:7px;border-right:1.5px solid hsl(var(--muted-foreground));border-bottom:1.5px solid hsl(var(--muted-foreground));transform:rotate(45deg);transition:transform .15s;margin-right:3px}.office-mc-more[open]>summary{margin-bottom:10px}.office-mc-more[open]>summary:after{transform:rotate(-135deg)}.office-mc-block{display:flex;flex-direction:column;gap:10px}.office-mc-note{margin:0;font-size:12px;line-height:1.45;color:hsl(var(--muted-foreground))}.office-mc-note[data-tone=ok]{color:hsl(var(--success))}.office-mc-empty{display:flex;flex-direction:column;gap:10px;font-size:12px;color:hsl(var(--muted-foreground))}.office-mc-empty p{margin:0}.office-mc-agents{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:6px}.office-mc-agents button{display:flex;align-items:center;gap:8px;min-width:0;padding:6px 8px;border:1px solid hsl(var(--border));border-radius:10px;background:hsl(var(--background));color:hsl(var(--foreground));font:inherit;font-size:12px;font-weight:500;text-align:left;cursor:pointer;transition:border-color .12s,background .12s}.office-mc-agents button span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.office-mc-agents button:hover:not(:disabled){background:hsl(var(--secondary))}.office-mc-agents button[aria-checked=true]{border-color:hsl(var(--foreground));box-shadow:inset 0 0 0 1px hsl(var(--foreground))}.office-mc-agents button:disabled{opacity:.5;cursor:not-allowed}.office-mc-row{display:flex;align-items:center;justify-content:space-between;gap:10px;font-size:12px;color:hsl(var(--muted-foreground))}.office-mc-row .office-mc-select{flex:0 1 60%;width:auto;min-width:0}.office-mc-row input{flex:0 1 60%;min-width:0;padding:6px 8px;border:1px solid hsl(var(--border));border-radius:8px;background:hsl(var(--background));color:hsl(var(--foreground));font:inherit;font-size:12px}.office-mc-row input::-moz-placeholder{color:hsl(var(--muted-foreground))}.office-mc-row input::placeholder{color:hsl(var(--muted-foreground))}.office-mc-task{width:100%;min-height:44px;resize:vertical;padding:9px 10px;border:1px solid hsl(var(--border));border-radius:10px;background:hsl(var(--background));color:hsl(var(--foreground));font:inherit;font-size:13px;line-height:1.4}.office-mc-task::-moz-placeholder{color:hsl(var(--muted-foreground))}.office-mc-task::placeholder{color:hsl(var(--muted-foreground))}.office-mc-go{display:flex;align-items:center;gap:8px}.office-mc-stepper{display:inline-flex;align-items:center;border:1px solid hsl(var(--border));border-radius:10px;overflow:hidden;flex:none}.office-mc-stepper button{display:inline-flex;align-items:center;justify-content:center;width:30px;height:34px;border:0;background:none;color:hsl(var(--foreground));cursor:pointer}.office-mc-stepper button svg{width:14px;height:14px}.office-mc-stepper button:hover:not(:disabled){background:hsl(var(--secondary))}.office-mc-stepper button:disabled{opacity:.35;cursor:not-allowed}.office-mc-stepper output{min-width:22px;text-align:center;font-size:13px;font-weight:600;font-variant-numeric:tabular-nums}.office-mc-primary,.office-mc-secondary{flex:1;height:36px;padding:0 14px;border-radius:10px;font:inherit;font-size:13px;font-weight:600;cursor:pointer;transition:opacity .12s,background .12s}.office-mc-primary{border:0;background:hsl(var(--foreground));color:hsl(var(--background));text-shadow:none}.office-mc-primary:hover:not(:disabled){opacity:.88}.office-mc-secondary{border:1px solid hsl(var(--border));background:hsl(var(--background));color:hsl(var(--foreground));flex:0 1 auto}.office-mc-secondary:hover:not(:disabled){background:hsl(var(--secondary))}.office-mc-primary:disabled,.office-mc-secondary:disabled{opacity:.4;cursor:not-allowed}.office-mc-link{align-self:flex-start;padding:0;border:0;background:none;color:hsl(var(--muted-foreground));font:inherit;font-size:12px;text-decoration:underline;text-underline-offset:2px;cursor:pointer}.office-mc-link:hover{color:hsl(var(--foreground))}.office-mc button:focus-visible,.office-mc select:focus-visible,.office-mc input:focus-visible,.office-mc textarea:focus-visible,.office-mc summary:focus-visible{outline:2px solid hsl(var(--ring));outline-offset:2px}.office-mc-dropzone{position:relative}.office-mc-drophint{position:absolute;top:-6px;right:-6px;bottom:-6px;left:-6px;display:flex;align-items:center;justify-content:center;padding:16px;border:1.5px dashed hsl(var(--ring));border-radius:12px;background:hsl(var(--background) / .9);color:hsl(var(--foreground));font-size:13px;font-weight:600;text-align:center;pointer-events:none}.office-mc-tools{display:flex;align-items:center;justify-content:space-between;gap:10px}.office-mc-attach{display:inline-flex;align-items:center;gap:5px;text-decoration:none}.office-mc-attach svg{width:13px;height:13px}.office-mc-attach:disabled{opacity:.45;cursor:not-allowed}.office-mc-files{list-style:none;margin:0;padding:0;display:flex;flex-wrap:wrap;gap:6px}.office-mc-files li{display:inline-flex;align-items:center;gap:2px;max-width:100%;min-width:0;padding:2px 3px 2px 9px;border:1px solid hsl(var(--border));border-radius:999px;background:hsl(var(--secondary) / .6);color:hsl(var(--foreground));font-size:11px}.office-mc-files span{max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.office-mc-files button{display:inline-flex;align-items:center;justify-content:center;flex:none;width:18px;height:18px;padding:0;border:0;border-radius:50%;background:none;color:hsl(var(--muted-foreground));cursor:pointer}.office-mc-files button:hover:not(:disabled){background:hsl(var(--secondary));color:hsl(var(--foreground))}.office-mc-files button:disabled{opacity:.45;cursor:not-allowed}.office-mc-files button svg{width:12px;height:12px}.office-mc-log{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:5px;font-size:12px;color:hsl(var(--foreground))}.office-mc-log li{display:flex;align-items:baseline;gap:8px;line-height:1.4}.office-mc-log li i{flex:none;width:7px;height:7px;border-radius:50%;background:hsl(var(--muted-foreground));transform:translateY(-1px)}.office-mc-log li[data-tone=busy]{color:hsl(var(--muted-foreground))}.office-mc-log li[data-tone=busy] i{animation:office-mc-pulse 1.2s ease-in-out infinite}.office-mc-log li[data-tone=ok] i{background:hsl(var(--success))}.office-mc-log li[data-tone=warn] i{background:hsl(var(--warning))}.office-mc-log li[data-tone=error]{color:hsl(var(--destructive))}.office-mc-log li[data-tone=error] i{background:hsl(var(--destructive))}@keyframes office-mc-pulse{50%{opacity:.3}}@media(prefers-reduced-motion:reduce){.office-mc-log li i{animation:none!important}}.office-mc-fleet{list-style:none;margin:0;padding:0;max-height:180px;overflow:auto;display:flex;flex-direction:column}.office-mc-fleet label{display:flex;align-items:center;gap:9px;padding:6px 2px;border-bottom:1px solid hsl(var(--border) / .6);cursor:pointer;font-size:12px;min-width:0}.office-mc-fleet li:last-child label{border-bottom:0}.office-mc-fleet input{accent-color:hsl(var(--foreground));flex:none}.office-mc-fleet-name{flex:1;min-width:0;font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.office-mc-fleet-state{display:inline-flex;align-items:center;gap:6px;flex:none;color:hsl(var(--muted-foreground))}.office-arcade-backdrop{position:absolute;top:0;right:0;bottom:0;left:0;z-index:70;display:flex;align-items:center;justify-content:center;padding:16px;background:hsl(var(--background) / .6)}.office-arcade{width:min(1100px,100%,calc((100vh - 80px) * 16 / 9));outline:none}.office-arcade-screen{position:relative;width:100%;aspect-ratio:16 / 9;border-radius:14px;overflow:hidden;background:#0b0a14;border:1px solid hsl(var(--border));box-shadow:0 18px 60px #00000073}.office-arcade-screen canvas{display:block}.office-arcade-fallback{position:absolute;top:0;right:0;bottom:0;left:0;display:flex;align-items:center;justify-content:center;margin:0;color:#c9d4ff;font-size:13px}.office-arcade-hud{position:absolute;left:18px;top:14px;pointer-events:none;color:#e6ebff;font-size:12px;font-weight:600;letter-spacing:.08em;text-transform:uppercase;font-variant-numeric:tabular-nums;text-shadow:0 1px 3px rgb(0 0 0 / .8)}.office-arcade-hud-line{display:flex;align-items:center;gap:6px;flex-wrap:wrap}.office-arcade-shields{display:inline-flex;gap:3px;vertical-align:middle}.office-arcade-shields i{width:8px;height:8px;transform:rotate(45deg);background:#e6ebff}.office-arcade-shields i[data-on=false]{background:transparent;box-shadow:inset 0 0 0 1px #e6ebff59}.office-arcade-missiles{display:inline-flex;gap:3px;vertical-align:middle}.office-arcade-missiles i{width:0;height:0;border-left:4px solid transparent;border-right:4px solid transparent;border-bottom:9px solid #ff6b57}.office-arcade-missiles i[data-on=false]{border-bottom-color:#ff6b5740}.office-arcade-screen canvas{cursor:crosshair}.office-arcade-boost-label[data-active=true]{color:#7dd3fc}.office-arcade-rapid{color:#facc15}.office-arcade-bar{width:130px;height:4px;margin-top:6px;border-radius:2px;background:#ffffff1f;overflow:hidden}.office-arcade-bar i{display:block;height:100%;background:#facc15;transition:width .08s linear}.office-arcade-hud-sub{margin-top:6px;font-size:10px;color:#e6ebffa6}.office-arcade-keys{position:absolute;left:0;right:0;bottom:10px;margin:0;text-align:center;pointer-events:none;font-size:10px;font-weight:600;letter-spacing:.14em;text-transform:uppercase;color:#e6ebff8c}.office-arcade-close{position:absolute;right:10px;top:8px;border:0;background:#ffffff14;color:#e6ebff;width:28px;height:28px;border-radius:8px;font-size:18px;line-height:1;cursor:pointer}.office-arcade-close:hover{background:#ffffff29}.office-arcade-close:focus-visible,.office-arcade-message:focus-visible{outline:2px solid hsl(var(--ring));outline-offset:2px}.office-arcade-message{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);display:flex;flex-direction:column;align-items:center;gap:8px;max-width:80%;border:1px solid rgb(250 204 21 / .6);border-radius:12px;padding:16px 26px;background:#0b0a14c7;color:#facc15;cursor:pointer;text-align:center;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px)}.office-arcade-message strong{font-size:26px;letter-spacing:.12em;text-transform:uppercase;color:#e6ebff}.office-arcade-message span{font-size:13px;font-weight:600;letter-spacing:.06em}@media(max-width:600px){.office-arcade-hud{left:10px;top:8px;font-size:10px}.office-arcade-message strong{font-size:18px}}.office-stage{position:relative;width:100%;min-width:0;height:100%;min-height:0;overflow:hidden;background:#0b1024}.office-viewport{position:absolute;top:0;right:0;bottom:0;left:0;touch-action:none;isolation:isolate}.office-viewport:focus-visible{outline:2px solid hsl(var(--ring));outline-offset:-2px}.office-fallback{display:flex;align-items:center;justify-content:center;height:100%;padding:24px;font-size:13px;color:hsl(var(--muted-foreground));background:hsl(var(--background))}.office-hud{position:absolute;z-index:30}.office-hud-left{left:14px;top:14px;display:flex;flex-direction:column;align-items:flex-start;gap:8px;max-width:min(320px,calc(100% - 430px))}.office-card{border:1px solid hsl(var(--border));border-radius:12px;background:hsl(var(--popover) / .92);color:hsl(var(--popover-foreground));box-shadow:0 4px 18px #00000040;-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px)}.office-title{display:flex;flex-direction:column;gap:3px;max-width:100%;padding:8px 12px;font-size:14px}.office-title strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.office-title>span{font-size:11px;color:hsl(var(--muted-foreground))}.office-states{display:flex;flex-wrap:wrap;gap:2px 10px}.office-states span{display:inline-flex;align-items:center;gap:5px;white-space:nowrap}.office-states i{width:7px;height:7px;border-radius:50%;background:hsl(var(--muted-foreground))}.office-states [data-tone=working] i{background:hsl(var(--success))}.office-states [data-tone=waiting] i{background:hsl(var(--warning))}.office-states [data-tone=paused] i{background:transparent;box-shadow:inset 0 0 0 1.5px hsl(var(--muted-foreground))}.office-note{margin:0;padding:6px 10px;font-size:11px;color:hsl(var(--muted-foreground))}.office-tools-dock{right:226px;top:14px;bottom:16px;z-index:32;display:flex;flex-direction:column;align-items:flex-end;gap:9px;pointer-events:none}.office-tools-dock>*{pointer-events:auto}.office-tools{flex:none;display:flex;gap:2px;padding:3px;border:1px solid hsl(var(--border));border-radius:11px;background:hsl(var(--popover) / .92);color:hsl(var(--popover-foreground));box-shadow:0 4px 18px #00000040;-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px)}.office-tool{position:relative;display:inline-flex;align-items:center;justify-content:center;width:30px;height:30px;padding:0;border:0;border-radius:8px;background:none;color:inherit;cursor:pointer}.office-tool svg{width:16px;height:16px}.office-tool:hover{background:hsl(var(--secondary))}.office-tool[aria-pressed=true],.office-tool[aria-expanded=true]{background:hsl(var(--secondary));color:hsl(var(--foreground));box-shadow:inset 0 0 0 1px hsl(var(--border))}.office-tool:focus-visible{outline:2px solid hsl(var(--ring));outline-offset:1px}.office-tool[data-tip]:hover:after,.office-tool[data-tip]:focus-visible:after{content:attr(data-tip);position:absolute;top:calc(100% + 9px);left:50%;transform:translate(-50%);z-index:2;padding:4px 8px;border-radius:7px;border:1px solid hsl(var(--border));background:hsl(var(--popover));color:hsl(var(--popover-foreground));font-size:11px;font-weight:500;line-height:1.3;white-space:nowrap;pointer-events:none;box-shadow:0 4px 14px #00000038}.office-tools>.office-tool:last-child[data-tip]:after{left:auto;right:0;transform:none}.office-places-card{position:relative;flex:0 1 auto;display:flex;flex-direction:column;min-height:0;width:min(320px,calc(100vw - 28px));max-height:680px;overflow:hidden;border:1px solid hsl(var(--border));border-radius:12px;background:hsl(var(--popover));color:hsl(var(--popover-foreground));box-shadow:0 10px 30px #00000052}.office-places-scroll{flex:1 1 auto;min-height:0;overflow-y:auto;overscroll-behavior:contain;padding:6px;scrollbar-gutter:stable}.office-places-card[data-more]:after{content:"";position:absolute;left:0;right:0;bottom:0;height:30px;border-radius:0 0 11px 11px;background:linear-gradient(hsl(var(--popover) / 0),hsl(var(--popover)));pointer-events:none}@media(max-width:760px){.office-tools-dock{right:14px;top:262px}.office-hud-left{max-width:min(320px,calc(100% - 254px))}}@media(max-height:520px),(max-width:600px){.office-tools-dock{right:14px;top:14px}.office-hud-left{max-width:calc(100% - 218px)}}.office-stage.office-stage-compact .office-tools-dock{right:8px;top:8px;bottom:8px;flex-direction:row-reverse;align-items:flex-start}.office-stage.office-stage-compact .office-tools{flex-direction:column}.office-stage.office-stage-compact .office-hud-left{max-width:calc(100% - 62px)}.office-stage.office-stage-compact .office-tool[data-tip]:after{top:50%;left:auto;right:calc(100% + 9px);transform:translateY(-50%)}.office-stage.office-stage-compact .office-places-card{width:min(280px,calc(100vw - 80px));max-height:min(680px,100%)}.office-hud-bottom{left:50%;bottom:16px;transform:translate(-50%);display:flex;flex-direction:column;align-items:center;gap:8px;width:-moz-max-content;width:max-content;max-width:calc(100% - 28px);pointer-events:none}.office-hud-bottom>*{pointer-events:auto;max-width:100%}.office-hud-bottom>[role=status]:empty{display:none}.office-prompt{display:inline-flex;align-items:center;gap:8px;padding:6px 13px 6px 6px;border-radius:10px;border:1px solid hsl(var(--border));background:hsl(var(--popover) / .94);color:hsl(var(--popover-foreground));font:inherit;font-size:13px;cursor:pointer;box-shadow:0 6px 20px #0000004d;-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px)}.office-prompt b{font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.office-prompt span{color:hsl(var(--muted-foreground));white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.office-prompt[data-compact]{text-align:left}.office-prompt[data-compact] b{white-space:normal;overflow:visible;text-overflow:clip;overflow-wrap:anywhere}.office-prompt[data-compact] .office-key{flex:none}.office-prompt:hover{background:hsl(var(--popover))}.office-prompt:focus-visible{outline:2px solid hsl(var(--ring));outline-offset:2px}.office-notice{margin:0;padding:6px 12px;font-size:12px}.office-hints{display:flex;align-items:center;gap:14px;padding:8px 8px 8px 14px}.office-hints ul{display:flex;flex-wrap:wrap;gap:6px 16px;margin:0;padding:0;list-style:none}.office-hints li{display:inline-flex;align-items:center;gap:7px;font-size:12px;color:hsl(var(--muted-foreground));white-space:nowrap}.office-hints-dismiss{flex:none;padding:5px 11px;border:1px solid hsl(var(--border));border-radius:8px;background:hsl(var(--background));color:hsl(var(--foreground));font:inherit;font-size:12px;font-weight:500;cursor:pointer}.office-hints-dismiss:hover{background:hsl(var(--secondary))}.office-hints-dismiss:focus-visible{outline:2px solid hsl(var(--ring));outline-offset:2px}@media(max-width:700px){.office-hints{flex-direction:column;align-items:stretch;padding:10px}}.office-plate-wrap{display:inline-grid;place-items:center;pointer-events:none}.office-plate-wrap>*{grid-area:1 / 1}.office-plate-dot{position:relative;width:9px;height:9px;border-radius:50%;background:#94a3b8;box-shadow:0 0 0 2px #181a20cc;pointer-events:auto;cursor:pointer;transition:opacity .18s ease}.office-plate-dot:after{content:"";position:absolute;top:-7px;right:-7px;bottom:-7px;left:-7px;border-radius:50%}.office-plate-wrap[data-state=working] .office-plate-dot{background:#4ade80}.office-plate-wrap[data-state=waiting] .office-plate-dot{background:#fbbf24}.office-plate-wrap[data-state=paused] .office-plate-dot{background:#181a20cc;box-shadow:0 0 0 2px #181a20cc,inset 0 0 0 1.5px #94a3b8}.office-plate-wrap .office-plate{transition:opacity .18s ease}.office-plate-wrap[data-detail=dot] .office-plate{opacity:0;pointer-events:none}.office-plate-wrap[data-detail=full] .office-plate{pointer-events:auto}.office-plate-wrap[data-detail=full] .office-plate-dot{opacity:0;pointer-events:none}@media(prefers-reduced-motion:reduce){.office-plate-dot,.office-plate-wrap .office-plate{transition:none}}.office-plate{transform-origin:center bottom;display:inline-flex;align-items:center;gap:5px;padding:2px 8px 2px 2px;border:0;border-radius:999px;background:#181a20d6;color:#f8fafc;cursor:pointer;font-family:inherit;white-space:nowrap;-webkit-user-select:none;-moz-user-select:none;user-select:none;box-shadow:0 2px 8px #00000059}.office-plate:hover{background:#242730f2}.office-plate-name{max-width:16em;overflow:hidden;text-overflow:ellipsis;font-size:12px;font-weight:600}.office-plate-badge{display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;font-size:10px;font-weight:800;color:#fff;clip-path:polygon(25% 3%,75% 3%,100% 50%,75% 97%,25% 97%,0 50%)}.office-plate-state{display:inline-flex;align-items:center;gap:4px;font-size:10px;font-weight:500;color:#cbd5e1}.office-plate-state em{font-style:normal}.office-plate-state i{width:7px;height:7px;border-radius:50%;background:#94a3b8}.office-plate[data-state=working] .office-plate-state i{background:#4ade80;box-shadow:0 0 6px #4ade80}.office-plate[data-state=waiting] .office-plate-state i{background:#fbbf24}.office-plate:focus-visible{outline:2px solid #93c5fd;outline-offset:2px}.office-plate[data-selected]{box-shadow:0 0 0 2px #93c5fd,0 2px 8px #00000059}.office-plate-player{cursor:default;background:#3a2c0ce6;box-shadow:0 0 0 1.5px #f5b83d,0 2px 8px #00000059}.office-plate[data-pane]{align-items:flex-start;gap:6px;padding:4px 10px 4px 4px;border-radius:12px;text-align:left}.office-plate[data-pane] .office-plate-badge{flex:none;margin-top:1px}.office-plate-logo{display:inline-flex;flex:none;align-items:center;justify-content:center;width:20px;height:20px;margin-top:1px;border-radius:6px;background:#ffffff14}.office-plate-logo[data-ground=dark]{background:#111318}.office-plate-logo i{display:block;width:14px;height:14px;background:#f8fafc;-webkit-mask-repeat:no-repeat;mask-repeat:no-repeat;-webkit-mask-position:center;mask-position:center;-webkit-mask-size:contain;mask-size:contain}.office-plate-logo img{display:block;width:14px;height:14px;-o-object-fit:contain;object-fit:contain}.office-plate-text{display:flex;flex-direction:column;align-items:flex-start;gap:1px;min-width:0;line-height:1.25}.office-plate[data-pane] .office-plate-name{max-width:13em}.office-plate-line{display:inline-flex;align-items:center;gap:6px;max-width:17em}.office-plate-result{min-width:0;overflow:hidden;text-overflow:ellipsis;font-size:11px;font-weight:600;color:#e2e8f0}.office-plate-line .office-plate-state{flex:none}.office-plate[data-pane][data-open]{width:-moz-max-content;width:max-content;max-width:min(22em,calc(100vw - 32px));background:#181a20f5}.office-plate[data-pane][data-open] .office-plate-name,.office-plate[data-pane][data-open] .office-plate-result{max-width:min(20em,100%);white-space:normal;overflow:visible;overflow-wrap:anywhere;text-overflow:clip}.office-plate[data-pane][data-open] .office-plate-line{max-width:100%;flex-wrap:wrap}.office-seat-prompt{padding:4px 12px 4px 4px;gap:7px;font-size:12px;font-weight:500;cursor:default}.office-seat-prompt kbd{display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;border-radius:6px;background:#f8fafc;color:#181a20;font-family:inherit;font-size:11px;font-weight:700}.office-viewport[data-first-person] .office-plate-dot{visibility:hidden}.office-panel-slot{position:absolute;z-index:35;right:14px;top:258px;width:min(340px,calc(100% - 28px));max-height:calc(100% - 276px);display:flex}.office-panel-slot[data-tall]{top:14px;width:min(360px,calc(100% - 28px));max-height:calc(100% - 28px)}.office-panel{display:flex;flex-direction:column;width:100%;min-height:0;overflow:hidden}.office-panel:focus{outline:none}.office-panel:focus-visible{outline:2px solid hsl(var(--ring));outline-offset:2px}.office-panel-body{display:flex;flex-direction:column;gap:12px;padding:14px 16px 16px;overflow:auto;font-size:13px;line-height:1.45}.office-panel-body p{margin:0}.office-icon-button{border:0;background:none;color:hsl(var(--muted-foreground));font-size:18px;line-height:1;cursor:pointer;padding:0 4px;border-radius:6px}.office-icon-button:hover{color:hsl(var(--foreground));background:hsl(var(--secondary))}.office-icon-button:focus-visible{outline:2px solid hsl(var(--ring));outline-offset:1px;color:hsl(var(--foreground))}.office-link{border:0;background:none;padding:0;color:hsl(var(--primary));font-size:12px;cursor:pointer;text-decoration:underline;text-underline-offset:2px}.office-link:focus-visible,.office-chip:focus-visible{outline:2px solid hsl(var(--ring));outline-offset:2px}.office-dot{display:inline-block;flex:none;width:8px;height:8px;border-radius:50%;background:hsl(var(--muted-foreground))}.office-dot[data-state=working]{background:hsl(var(--success))}.office-dot[data-state=waiting]{background:hsl(var(--warning))}.office-dot[data-state=paused]{background:transparent;box-shadow:inset 0 0 0 1.5px hsl(var(--muted-foreground))}.office-subhead{margin:0;font-size:12px;font-weight:600;color:hsl(var(--muted-foreground))}.office-chip{border:1px solid hsl(var(--border));border-radius:999px;padding:3px 10px;background:hsl(var(--background));color:hsl(var(--foreground));font-size:12px;cursor:pointer}.office-chip:hover:not([aria-pressed=true]){background:hsl(var(--secondary))}.office-chip[aria-pressed=true]{background:hsl(var(--primary));color:hsl(var(--primary-foreground));border-color:transparent}.office-hint{margin:0;font-size:12px;color:hsl(var(--muted-foreground))}.office-error{color:hsl(var(--destructive))}.office-success{color:hsl(var(--foreground))}@media(max-width:760px){.office-panel-slot{top:14px;max-height:calc(100% - 80px)}}@media(max-height:520px){.office-panel-slot{top:60px;max-height:calc(100% - 100px)}}@media(max-width:600px){.office-panel-slot,.office-panel-slot[data-tall]{top:auto;bottom:12px;max-height:55%}}.office-dive-fade{position:absolute;top:0;right:0;bottom:0;left:0;z-index:60;pointer-events:none;background:hsl(var(--background));opacity:0;animation:office-dive-fade 1.4s ease-in forwards}@keyframes office-dive-fade{0%,72%{opacity:0}to{opacity:1}}@media(prefers-reduced-motion:reduce){.office-dive-fade{animation:none}}.office-real-chat{width:100%;height:100%;overflow:hidden;background:hsl(var(--background));color:hsl(var(--foreground));border-radius:6px}.office-minimap{right:14px;top:14px;display:flex;flex-direction:column;gap:4px;-webkit-user-select:none;-moz-user-select:none;user-select:none}.office-minimap-map{position:relative;overflow:hidden;border-radius:14px;border:2px solid hsl(var(--popover) / .92);background:#121833;box-shadow:0 0 0 1px hsl(var(--border)),0 6px 22px #00000059}.office-minimap-map:after{content:"";position:absolute;top:0;right:0;bottom:0;left:0;border-radius:12px;pointer-events:none;box-shadow:inset 0 0 18px 4px #00000061,inset 0 0 0 1px #ffffff1f}.office-minimap-canvas{display:block;cursor:crosshair;touch-action:manipulation}.office-minimap-north{position:absolute;z-index:1;top:3px;left:50%;transform:translate(-50%);min-width:16px;padding:0 4px;border-radius:999px;background:hsl(var(--popover) / .92);color:hsl(var(--popover-foreground));font-size:10px;font-weight:800;line-height:15px;text-align:center;pointer-events:none;box-shadow:0 1px 4px #0000004d}.office-minimap-tooltip{position:absolute;z-index:2;transform:translateY(-100%);padding:2px 7px;border-radius:6px;border:1px solid hsl(var(--border));background:hsl(var(--popover));color:hsl(var(--popover-foreground));font-size:11px;font-weight:600;white-space:nowrap;max-width:160px;overflow:hidden;text-overflow:ellipsis;pointer-events:none;box-shadow:0 2px 8px #0003}.office-minimap-tooltip[data-side=left]{transform:translate(-100%,-100%)}.office-minimap-bar{display:flex;align-items:center;gap:4px;padding:2px;border:1px solid hsl(var(--border));border-radius:10px;background:hsl(var(--popover) / .92);color:hsl(var(--popover-foreground));-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);box-shadow:0 2px 10px #0003}.office-minimap-btn{display:inline-flex;align-items:center;justify-content:center;gap:4px;height:22px;min-width:22px;padding:0 5px;border:0;border-radius:7px;background:none;color:hsl(var(--popover-foreground));font-size:11px;font-weight:600;cursor:pointer}.office-minimap-btn:hover:not(:disabled){background:hsl(var(--secondary))}.office-minimap-btn:disabled{opacity:.4;cursor:default}.office-minimap-btn:focus-visible{outline:2px solid hsl(var(--ring));outline-offset:1px}.office-minimap-zoom{min-width:34px;text-align:center;font-size:10px;font-variant-numeric:tabular-nums;color:hsl(var(--muted-foreground))}.office-minimap-open{margin-left:auto;padding:0 8px;border:1px solid hsl(var(--border))}.office-compass{left:50%;top:8px;transform:translate(-50%);width:min(440px,calc(100% - 720px));height:34px;border:1px solid hsl(var(--border));border-radius:10px;background:hsl(var(--popover) / .88);box-shadow:0 4px 16px #00000040;-webkit-backdrop-filter:blur(6px);backdrop-filter:blur(6px);pointer-events:none}.office-compass-canvas{display:block;width:100%;height:100%;-webkit-mask-image:linear-gradient(90deg,transparent,#000 14%,#000 86%,transparent);mask-image:linear-gradient(90deg,transparent,#000 14%,#000 86%,transparent)}.office-compass-readout{position:absolute;top:100%;left:50%;transform:translate(-50%,3px);padding:0 6px;border-radius:6px;border:1px solid hsl(var(--border));background:hsl(var(--popover) / .92);color:hsl(var(--popover-foreground));font-size:10px;font-weight:700;line-height:16px;font-variant-numeric:tabular-nums}.office-compass-readout:empty{display:none}.office-fullmap-backdrop{position:absolute;top:0;right:0;bottom:0;left:0;z-index:60;display:flex;align-items:center;justify-content:center;padding:3%;background:hsl(var(--background) / .55);-webkit-backdrop-filter:blur(3px);backdrop-filter:blur(3px)}.office-fullmap{display:flex;flex-direction:column;width:100%;height:100%;max-width:1200px;min-height:0;overflow:hidden}.office-fullmap:focus{outline:none}.office-fullmap-head{display:flex;align-items:center;gap:12px;padding:8px 10px 8px 14px;border-bottom:1px solid hsl(var(--border))}.office-fullmap-heading{display:flex;flex-direction:column;min-width:0}.office-fullmap-heading h2{margin:0;font-size:14px;font-weight:700}.office-fullmap-heading span{font-size:11px;color:hsl(var(--muted-foreground))}.office-fullmap-readout{margin-left:auto;font-size:12px;font-weight:600;font-variant-numeric:tabular-nums;color:hsl(var(--muted-foreground));white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.office-fullmap-close{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px}.office-fullmap-body{position:relative;flex:1;min-height:0;overflow:hidden;background:hsl(var(--muted))}.office-fullmap-canvas{display:block;cursor:crosshair}.office-fullmap-axis{position:absolute;transform:translate(-50%,-50%);font-size:11px;font-weight:800;color:hsl(var(--foreground));pointer-events:none}@media(max-width:960px){.office-compass{display:none}}@media(max-height:520px),(max-width:600px){.office-minimap{display:none}}@media(prefers-reduced-motion:reduce){.office-fullmap-backdrop{-webkit-backdrop-filter:none;backdrop-filter:none}}.office-doors{position:absolute;top:0;right:0;bottom:0;left:0;z-index:62;pointer-events:none;overflow:hidden}.office-doors-leaf{position:absolute;top:0;bottom:0;width:50%;background:repeating-linear-gradient(90deg,rgb(255 255 255 / .05) 0 1px,transparent 1px 3px),linear-gradient(90deg,#969ca4,#c4c8ce 50%,#9ca2a9);transition:transform .64s cubic-bezier(.45,0,.2,1)}.office-doors-leaf[data-side=left]{left:0;transform:translate(-101%);box-shadow:inset -3px 0 #2f3338,inset -18px 0 26px -16px #00000080}.office-doors-leaf[data-side=right]{right:0;transform:translate(101%);box-shadow:inset 3px 0 #2f3338,inset 18px 0 26px -16px #00000080}.office-doors[data-phase=closing] .office-doors-leaf,.office-doors[data-phase=closed] .office-doors-leaf{transform:translate(0)}.office-doors[data-phase=closing] .office-doors-leaf{animation:office-doors-close .64s cubic-bezier(.45,0,.2,1)}@keyframes office-doors-close{0%{transform:translate(var(--office-door-from, 0))}}.office-doors[data-phase=closing] .office-doors-leaf[data-side=left]{--office-door-from:-101%}.office-doors[data-phase=closing] .office-doors-leaf[data-side=right]{--office-door-from:101%}@media(prefers-reduced-motion:reduce){.office-doors-leaf{transition:none;animation:none!important}}.office-call-pill{display:inline-flex;flex-direction:column;align-items:center;gap:1px;padding:4px 10px;border-radius:10px;background:#181a20db;color:#f8fafc;white-space:nowrap;-webkit-user-select:none;-moz-user-select:none;user-select:none;pointer-events:none;box-shadow:0 2px 8px #00000059}.office-call-pill b{font-size:12px;font-weight:700}.office-call-pill small{font-size:10px;color:#f5b83d;font-weight:600}.office-facts{display:grid;grid-template-columns:auto 1fr;gap:3px 10px;margin:0}.office-facts dt{color:hsl(var(--muted-foreground));font-size:11px}.office-facts dd{margin:0;min-width:0;overflow-wrap:anywhere}.office-facts-quote{display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden;font-style:italic}.office-dot[data-dot=error]{background:hsl(var(--destructive))}.office-stage-compact .office-hud-left{left:8px;top:8px;gap:5px;max-width:calc(100% - 16px)}.office-stage-compact .office-title{padding:5px 9px;font-size:12px}.office-stage-compact .office-counts{gap:8px;padding:4px 9px;font-size:11px;flex-wrap:wrap}.office-stage-compact .office-hud-right{right:8px;top:auto;bottom:8px;flex-direction:row;flex-wrap:wrap;justify-content:flex-end;max-width:calc(100% - 16px)}.office-stage-compact .office-button{padding:4px 8px;font-size:11px}.office-stage-compact .office-panel-slot{top:auto;bottom:48px;right:8px;width:calc(100% - 16px);max-height:62%}.office-stage-compact .office-prompt{bottom:48px;max-width:calc(100% - 16px);font-size:12px}.office-stage-compact .office-note{font-size:11px}.office-lift-backdrop{position:absolute;top:0;right:0;bottom:0;left:0;z-index:64;display:flex;align-items:center;justify-content:center;padding:16px;background:#08090c52}.office-lift{position:relative;width:min(230px,100%);padding:18px 18px 14px;border-radius:10px;background:radial-gradient(circle,#6a7078 0 1.7px,transparent 2.3px) left 4px top 4px / 14px 14px no-repeat,radial-gradient(circle,#6a7078 0 1.7px,transparent 2.3px) right 4px top 4px / 14px 14px no-repeat,radial-gradient(circle,#6a7078 0 1.7px,transparent 2.3px) left 4px bottom 4px / 14px 14px no-repeat,radial-gradient(circle,#6a7078 0 1.7px,transparent 2.3px) right 4px bottom 4px / 14px 14px no-repeat,repeating-linear-gradient(90deg,rgb(255 255 255 / .05) 0 1px,transparent 1px 3px),linear-gradient(180deg,#d5d9de,#aeb4bb);box-shadow:0 18px 48px #00000073,inset 0 1px #ffffffb3,inset 0 0 0 1px #00000029;animation:office-lift-in .2s cubic-bezier(.2,.8,.2,1)}@keyframes office-lift-in{0%{opacity:0;transform:translateY(8px)}}.office-lift-close{position:absolute;top:8px;right:8px;width:24px;height:24px;border:0;border-radius:6px;background:transparent;color:#4a4f56;font-size:17px;line-height:1;cursor:pointer}.office-lift-close:hover{background:#00000014}.office-lift-close:focus-visible{outline:2px solid #2f7fb0;outline-offset:1px}.office-lift-display{display:flex;align-items:center;justify-content:center;gap:8px;width:96px;height:46px;margin:0 auto 16px;border-radius:5px;background:linear-gradient(180deg,#121316,#050506);box-shadow:inset 0 0 0 1px #ffffff12,0 1px #fff9;color:#ff8a1f;font-family:Pixelify Sans,ui-monospace,monospace;font-weight:600;line-height:1}.office-lift-display b{font-size:30px;text-shadow:0 0 8px rgb(255 138 31 / .7)}.office-lift-arrow{width:16px;height:16px;opacity:.16;transition:opacity .16s ease}.office-lift-arrow[data-dir]{opacity:1;filter:drop-shadow(0 0 4px rgb(255 138 31 / .7))}.office-lift-arrow[data-dir=down]{transform:rotate(180deg)}.office-lift-rows{display:flex;flex-direction:column;gap:10px}.office-lift-row{display:flex;align-items:center;gap:14px;width:100%;padding:2px 4px;border:0;border-radius:28px;background:transparent;color:inherit;text-align:left;cursor:pointer}.office-lift-row:focus-visible{outline:none}.office-lift-row:focus-visible .office-lift-button{box-shadow:0 2px 4px #00000061,inset 0 -1px 2px #00000040,0 0 0 3px #2f7fb0}.office-lift-row:disabled{cursor:default}.office-lift-button{position:relative;flex:none;width:46px;height:46px;border-radius:50%;background:radial-gradient(circle at 35% 30%,#fdfdfd,#b6bcc3 55%,#737980);box-shadow:0 2px 4px #00000061,inset 0 -1px 2px #00000040;transition:transform 90ms ease}.office-lift-button span{position:absolute;top:6px;right:6px;bottom:6px;left:6px;display:grid;place-items:center;border-radius:50%;background:radial-gradient(circle at 50% 38%,#e3e6ea,#b3b9c0);color:#40454c;font-family:Inter Variable,Inter,system-ui,sans-serif;font-size:16px;font-weight:650;text-shadow:0 1px 0 rgb(255 255 255 / .65);box-shadow:inset 0 1px 2px #00000040,0 0 0 2px transparent;transition:box-shadow .18s ease,color .18s ease,background .14s ease}.office-lift-row:enabled:hover .office-lift-button span{background:radial-gradient(circle at 50% 38%,#eef0f3,#c0c6cc)}.office-lift-row:enabled:active .office-lift-button{transform:scale(.95)}.office-lift-row[data-lit] .office-lift-button span{color:#1f6f96;box-shadow:inset 0 1px 2px #0003,0 0 0 2px #8fd8ff,0 0 12px #8fd8fff2}.office-lift-label{font-size:13px;font-weight:600;color:#30353b;text-shadow:0 1px 0 rgb(255 255 255 / .55)}.office-lift-row[data-here] .office-lift-label{color:#6b7179}.office-lift-row:disabled:not([data-here]):not([data-lit]){opacity:.55}.office-lift-keys{margin:14px 0 0;text-align:center;font-size:10px;color:#5c626a;text-shadow:0 1px 0 rgb(255 255 255 / .45)}.office-lift[data-reduced],.office-lift[data-reduced] *{animation:none!important;transition:none!important}@media(prefers-reduced-motion:reduce){.office-lift,.office-lift *{animation:none!important;transition:none!important}}.hall-layer{position:absolute;top:0;right:0;bottom:0;left:0;z-index:50;display:flex;align-items:center;justify-content:center;padding:16px;background:#080a146b;-webkit-backdrop-filter:blur(3px);backdrop-filter:blur(3px)}.hall{--h-bg:#fbfaf6;--h-panel:#ffffff;--h-sunken:#f2efe7;--h-sunken-2:#e9e4d8;--h-line:#e5e0d4;--h-line-strong:#cfc7b5;--h-ink:#151a2b;--h-ink-2:#3a3f52;--h-muted:#76726a;--h-navy:#1b2444;--h-navy-2:#26325c;--h-gold:#b08a35;--h-gold-ink:#8a6a22;--h-gold-soft:#f4ecd6;--h-ok:#2d7a4b;--h-ok-soft:#e3f1e8;--h-focus:#2f5bd3;display:flex;flex-direction:column;width:min(1200px,100%);height:min(860px,100%);overflow:hidden;border:1px solid var(--h-line);border-radius:18px;background:var(--h-bg);color:var(--h-ink);box-shadow:0 30px 80px #080a1459,0 0 0 1px #fff9 inset;color-scheme:light;animation:hall-in .28s cubic-bezier(.2,.9,.3,1) both}.hall:focus{outline:none}@keyframes hall-in{0%{opacity:0;transform:translateY(12px) scale(.985)}to{opacity:1;transform:none}}.hall-head{display:flex;align-items:center;gap:14px;padding:18px 20px 12px 22px;background:var(--h-panel)}.hall-brand{display:flex;align-items:center;gap:13px;flex:1;min-width:0}.hall-brand-mark{display:inline-flex;flex:none;align-items:center;justify-content:center;width:42px;height:42px;border-radius:11px;color:#e5c574;background:linear-gradient(180deg,var(--h-navy-2),var(--h-navy));box-shadow:inset 0 0 0 1px #c9a24ab3,0 4px 12px #1b244440}.hall-brand h2{margin:0;font-size:19px;font-weight:800;letter-spacing:-.015em;color:var(--h-ink)}.hall-brand small{display:block;margin-top:2px;font-size:12.5px;color:var(--h-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.hall-subject{display:inline-flex;flex:none;gap:2px;padding:3px;border-radius:10px;background:var(--h-sunken);box-shadow:inset 0 0 0 1px var(--h-line)}.hall-subject button{border:0;border-radius:8px;padding:6px 14px;background:none;color:var(--h-muted);font:inherit;font-size:12.5px;font-weight:700;cursor:pointer}.hall-subject button[aria-checked=true]{background:var(--h-panel);color:var(--h-ink);box-shadow:0 1px 3px #151a2b1f,0 0 0 1px var(--h-line)}.hall-subject button:focus-visible,.hall-close:focus-visible,.hall-tab:focus-visible{outline:2px solid var(--h-focus);outline-offset:1px}.hall-close{display:inline-flex;flex:none;align-items:center;justify-content:center;width:36px;height:36px;border:0;border-radius:10px;background:none;color:var(--h-muted);cursor:pointer}.hall-close:hover{background:var(--h-sunken);color:var(--h-ink)}.hall-tabs{display:flex;gap:4px;padding:0 16px;background:var(--h-panel);border-bottom:1px solid var(--h-line);overflow-x:auto;scrollbar-width:none}.hall-tab{display:inline-flex;flex:none;align-items:center;gap:7px;padding:11px 12px 10px;border:0;border-bottom:2px solid transparent;background:none;color:var(--h-muted);font:inherit;font-size:13.5px;font-weight:650;cursor:pointer}.hall-tab:hover{color:var(--h-ink)}.hall-tab[aria-selected=true]{color:var(--h-ink);border-bottom-color:var(--h-gold)}.hall-tab[aria-selected=true] svg{color:var(--h-gold)}.hall-body{flex:1;min-height:0;overflow:auto;padding:22px;font-size:13px}.hall-foot{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;padding:10px 22px 12px;border-top:1px solid var(--h-line);background:var(--h-panel);font-size:12px;color:var(--h-muted)}.hall-sound{display:inline-flex;align-items:center;gap:7px;color:var(--h-ink-2);cursor:pointer}.hall-sound input{accent-color:var(--h-navy)}.hall-section{display:flex;flex-direction:column;gap:10px;min-width:0}.hall-section>header{display:flex;align-items:baseline;justify-content:space-between;gap:10px}.hall-section h3,.hall-rank-tier h3{margin:0;font-size:11px;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:var(--h-muted)}.hall-link{border:0;padding:0;background:none;color:var(--h-gold-ink);font:inherit;font-size:12.5px;font-weight:700;cursor:pointer}.hall-link:hover{text-decoration:underline}.hall-lead{margin:0;font-size:14px;line-height:1.5;color:var(--h-ink-2)}.hall-hint{margin:0;font-size:12px;line-height:1.5;color:var(--h-muted)}.hall-empty{margin:0;padding:24px;text-align:center;color:var(--h-muted)}.hall-button{border:1px solid var(--h-line-strong);border-radius:10px;padding:8px 14px;background:var(--h-panel);color:var(--h-ink);font:inherit;font-size:13px;font-weight:700;cursor:pointer;white-space:nowrap}.hall-button:hover{background:var(--h-sunken)}.hall-button:focus-visible,.hall-card:focus-visible,.hall-item:focus-visible,.hall-slot:focus-visible,.hall-road-step:focus-visible,.hall-promotion:focus-visible{outline:2px solid var(--h-focus);outline-offset:2px}.hall-button-primary{align-self:flex-start;border-color:var(--h-navy);background:var(--h-navy);color:#f6ecd2;padding:10px 18px;box-shadow:0 4px 12px #1b244438}.hall-button-primary:hover{background:var(--h-navy-2)}.hall-rank-tag{display:inline-flex;align-items:center;gap:5px;padding:2px 8px 2px 4px;border-radius:6px;background:var(--h-sunken);box-shadow:inset 0 0 0 1px var(--h-line);color:var(--h-ink-2);font-size:11px;font-weight:700;white-space:nowrap}.hall-rank-tag svg{display:block}.hall-lock{position:absolute;top:10px;right:10px;color:var(--h-muted)}.hall .level-bar{background:var(--h-sunken-2)}.hall .level-bar-fill{background:linear-gradient(90deg,#a07a2a,#d6b25e)}.hall .level-bar-gain{background:#f0dda8;box-shadow:none}.hall .level-ring-track{stroke:var(--h-sunken-2)}.hall .level-ring-fill{stroke:var(--h-gold)}.hall .level-reward-icon{border-radius:9px}.hall-hero{display:flex;align-items:center;gap:24px;padding:20px 24px;border:1px solid var(--h-line);border-radius:16px;background:linear-gradient(180deg,var(--h-panel),var(--h-bg));box-shadow:0 1px 2px #151a2b0d}.hall-hero[data-compact]{gap:14px;padding:10px 14px}.hall-hero-body{display:flex;flex-direction:column;gap:7px;flex:1;min-width:0}.hall-hero-name{font-size:13px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;color:var(--h-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.hall-hero-title{display:inline-flex;align-items:baseline;gap:10px;font-size:26px;font-weight:800;letter-spacing:-.02em;color:var(--h-ink)}.hall-hero-title small{padding:2px 7px;border-radius:6px;background:var(--h-gold-soft);color:var(--h-gold-ink);font-size:11.5px;font-weight:800;letter-spacing:.06em}.hall-hero[data-compact] .hall-hero-name{font-size:11px}.hall-hero[data-compact] .hall-hero-title{font-size:16px}.hall-hero .level-bar{height:8px;margin-top:2px}.hall-hero[data-compact] .level-bar{height:6px}.hall-hero-xp{display:flex;align-items:baseline;gap:12px;flex-wrap:wrap;font-size:13px;font-variant-numeric:tabular-nums;color:var(--h-ink)}.hall-hero-xp span{color:var(--h-muted)}.hall-hero[data-compact] .hall-hero-xp{font-size:11.5px}.hall-hero-meta{display:flex;gap:18px;flex-wrap:wrap;font-size:12px;color:var(--h-muted)}.hall-hero .level-ring b{font-size:12px;line-height:17px;bottom:-7px}.hall-hero[data-compact] .level-ring b{font-size:10px;line-height:14px;bottom:-5px}.hall-overview{display:grid;grid-template-columns:minmax(0,1.3fr) minmax(0,1fr);gap:22px;align-items:start}.hall-overview>.hall-hero,.hall-overview>.hall-wide{grid-column:1 / -1}.hall-cards{display:grid;grid-template-columns:1fr;gap:8px}.hall-card{position:relative;display:flex;align-items:center;gap:14px;width:100%;padding:10px 36px 10px 10px;border:1px solid var(--h-line);border-radius:12px;background:var(--h-panel);color:inherit;font:inherit;text-align:left;cursor:pointer;transition:border-color .12s,box-shadow .12s,transform .12s}.hall-card:hover{border-color:var(--h-line-strong);box-shadow:0 4px 14px #151a2b14;transform:translateY(-1px)}.hall-card-text{display:flex;flex-direction:column;gap:4px;min-width:0}.hall-card-text strong{font-size:14px;color:var(--h-ink)}.hall-card-meta{display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:11.5px;color:var(--h-muted)}.hall-card-state{font-size:11.5px;color:var(--h-muted);font-variant-numeric:tabular-nums}.hall-card-state[data-open]{color:var(--h-ok);font-weight:700}.hall-rules{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:6px 10px;margin:0;padding:0;list-style:none}.hall-overview .hall-rules{grid-template-columns:1fr}.hall-rule{display:flex;align-items:flex-start;gap:10px;padding:9px 11px;border:1px solid var(--h-line);border-radius:10px;background:var(--h-panel)}.hall-rule-xp{flex:none;min-width:42px;padding:2px 6px;border-radius:6px;background:var(--h-gold-soft);color:var(--h-gold-ink);font-size:12px;font-weight:800;text-align:center;font-variant-numeric:tabular-nums}.hall-rule-text{display:flex;flex-direction:column;gap:2px;font-size:13px;color:var(--h-ink)}.hall-rule-text em{font-style:normal;font-size:11px;color:var(--h-muted)}.hall-promotion{display:flex;align-items:center;gap:18px;width:100%;padding:16px 18px;border:1px solid var(--h-line);border-radius:14px;background:var(--h-panel);color:inherit;font:inherit;text-align:left;cursor:pointer;box-shadow:0 1px 2px #151a2b0d}.hall-promotion:hover{border-color:var(--h-gold)}.hall-promotion>svg{padding:8px;border-radius:12px;background:var(--h-sunken);box-sizing:content-box}.hall-promotion>span{display:flex;flex-direction:column;gap:4px;min-width:0}.hall-promotion strong{font-size:18px;letter-spacing:-.01em;color:var(--h-ink)}.hall-promotion em{font-style:normal;font-size:12px;color:var(--h-muted)}.hall-promotion-xp{font-size:12.5px;font-weight:800;color:var(--h-gold-ink);font-variant-numeric:tabular-nums}.hall-stage{position:relative;min-height:460px;overflow:hidden;border-radius:16px;color:var(--h-ink);background:radial-gradient(70% 55% at 50% 38%,#fff,#f3f0e9 55%,#e4dfd3);box-shadow:inset 0 0 0 1px var(--h-line)}.hall-stage:after{content:"";position:absolute;left:0;right:0;bottom:0;height:30%;background:linear-gradient(180deg,transparent,rgb(214 206 189 / .35));pointer-events:none}.hall-stage-small{min-height:380px}.hall-preview{position:absolute;top:0;right:0;bottom:0;left:0;z-index:1;cursor:grab;touch-action:none}.hall-preview:active{cursor:grabbing}.hall-preview-note{position:absolute;left:12px;right:12px;top:50%;margin:0;padding:6px 10px;border-radius:10px;background:#ffffffe6;color:var(--h-ink);font-size:12px;text-align:center;pointer-events:none}.hall-preview-fallback{position:absolute;top:0;right:0;bottom:0;left:0;display:flex;align-items:center;justify-content:center;margin:0;padding:20px;text-align:center;color:var(--h-muted)}.hall-stage-top{position:absolute;z-index:2;top:12px;left:12px;right:12px;pointer-events:none}.hall-stage .hall-hero{border-color:#ffffffe6;background:#ffffffd1;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);box-shadow:0 6px 18px #151a2b14}.hall-stage-bottom{position:absolute;z-index:2;left:12px;right:12px;bottom:14px;display:flex;flex-direction:column;align-items:center;gap:8px;pointer-events:none}.hall-stage-bottom>*{pointer-events:auto}.hall-stage-hint{font-size:11px;color:var(--h-muted);pointer-events:none!important}.hall-plate{display:inline-flex;align-items:center;gap:8px;padding:4px 6px 4px 12px;border-radius:9px;background:var(--h-navy);color:#f6ecd2;font-size:13px;font-weight:700;box-shadow:0 4px 12px #1b244440}.hall-plate .level-chip{height:22px;font-size:12px;padding:0 7px 0 4px}.hall-tryon{display:flex;align-items:center;gap:12px;max-width:100%;padding:8px 8px 8px 10px;border:1px solid var(--h-gold);border-radius:12px;background:var(--h-panel);color:var(--h-ink);box-shadow:0 8px 24px #151a2b24}.hall-tryon>span:nth-child(2){display:flex;flex-direction:column;gap:1px;min-width:0}.hall-tryon strong{font-size:13px}.hall-tryon em{font-style:normal;font-size:11.5px;color:var(--h-muted)}.hall-tryon-badge{flex:none;padding:3px 8px;border-radius:6px;background:var(--h-gold-soft);color:var(--h-gold-ink);font-size:10px;font-weight:900;letter-spacing:.1em;text-transform:uppercase}.hall-tryon .hall-button{font-size:12px;padding:6px 10px}.hall-stage-rank{position:absolute;z-index:2;right:14px;top:14px;display:flex;flex-direction:column;align-items:center;gap:4px;padding:10px 12px 8px;border-radius:12px;background:#ffffffd9;box-shadow:0 6px 18px #151a2b1a;pointer-events:none}.hall-stage-rank span{font-size:10.5px;font-weight:800;letter-spacing:.06em;color:var(--h-gold-ink)}.hall-studio{display:grid;grid-template-columns:minmax(320px,1fr) minmax(0,1.05fr);gap:22px;align-items:start}.hall-studio .hall-stage{position:sticky;top:0;height:min(580px,calc(100vh - 260px));min-height:420px}.hall-detail .hall-stage{height:420px;min-height:0}.hall-wardrobe{display:flex;flex-direction:column;gap:14px;min-width:0}.hall-slots{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;padding:4px;border-radius:14px;background:var(--h-sunken);box-shadow:inset 0 0 0 1px var(--h-line)}.hall-slot{display:flex;align-items:center;gap:10px;padding:8px 10px;border:0;border-radius:10px;background:none;color:var(--h-muted);font:inherit;font-size:13px;font-weight:750;text-align:left;cursor:pointer}.hall-slot:hover{color:var(--h-ink)}.hall-slot[aria-selected=true]{background:var(--h-panel);color:var(--h-ink);box-shadow:0 1px 3px #151a2b1f,0 0 0 1px var(--h-line)}.hall-slot-empty{flex:none;width:34px;height:34px;border:1.5px dashed var(--h-line-strong);border-radius:9px}.hall-items{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:10px}.hall-item{position:relative;display:flex;flex-direction:column;align-items:center;gap:7px;padding:16px 10px 12px;border:1px solid var(--h-line);border-radius:14px;background:var(--h-panel);color:var(--h-ink);font:inherit;text-align:center;cursor:pointer;transition:border-color .12s,box-shadow .12s,transform .12s}.hall-item:hover{border-color:var(--h-line-strong);box-shadow:0 6px 16px #151a2b14;transform:translateY(-2px)}.hall-item[aria-pressed=true]{border-color:var(--h-navy);box-shadow:0 0 0 2px var(--h-navy),0 6px 16px #1b244424}.hall-item strong{font-size:13px;line-height:1.25}.hall-item em{font-style:normal;font-size:11px;color:var(--h-muted);font-variant-numeric:tabular-nums}.hall-item em[data-open]{color:var(--h-ok);font-weight:700}.hall-item-tile{display:inline-flex;align-items:center;justify-content:center;width:58px;height:58px;border-radius:10px;background:var(--h-sunken);color:var(--h-muted);box-shadow:inset 0 0 0 1px var(--h-line)}.hall-item-check{position:absolute;top:8px;left:8px;display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;border-radius:6px;background:var(--h-navy);color:#f6ecd2}.hall-insignia-card{display:flex;flex-direction:column;align-items:center;gap:12px;padding:40px 24px;border:1px solid var(--h-line);border-radius:16px;background:var(--h-panel);text-align:center}.hall-insignia-card strong{font-size:22px;letter-spacing:-.01em}.hall-rewards{display:flex;flex-direction:column;gap:16px}.hall-road{display:flex;align-items:center;margin:0;padding:30px 4px 12px;list-style:none;overflow-x:auto;scroll-snap-type:x proximity}.hall-road>li{position:relative;display:flex;flex:none;align-items:center;scroll-snap-align:center}.hall-road-step{position:relative;display:flex;flex-direction:column;align-items:center;gap:8px;min-width:112px;padding:12px;border:1px solid var(--h-line);border-radius:14px;background:var(--h-panel);color:var(--h-ink);font:inherit;cursor:pointer;transition:transform .12s,box-shadow .12s,border-color .12s}.hall-road-step:hover{border-color:var(--h-line-strong)}.hall-road>li[data-done] .hall-road-step{border-top:3px solid var(--h-gold)}.hall-road-step[aria-pressed=true]{transform:translateY(-3px);border-color:var(--h-navy);box-shadow:0 0 0 2px var(--h-navy),0 10px 22px #151a2b1f}.hall-road-level{font-size:12px;font-weight:800;letter-spacing:.04em;color:var(--h-muted);font-variant-numeric:tabular-nums}.hall-road-icons{display:flex;align-items:center;gap:6px;min-height:34px}.hall-road-title{max-width:130px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11.5px;font-weight:750;color:var(--h-ink)}.hall-road-step .hall-lock{top:7px;right:7px}.hall-road-link{width:24px;height:2px;background:var(--h-line-strong)}.hall-road>li[data-done] .hall-road-link{background:var(--h-gold)}.hall-road-here{position:absolute;top:-26px;left:0;padding:2px 9px;border-radius:6px;background:var(--h-navy);color:#f6ecd2;font-size:10.5px;font-weight:800;white-space:nowrap}.hall-detail{display:grid;grid-template-columns:minmax(300px,1.1fr) minmax(0,1fr);gap:22px;align-items:stretch}.hall-detail-info{display:flex;flex-direction:column;justify-content:center;gap:14px;min-width:0;padding:8px 4px}.hall-detail-info p{margin:0;color:var(--h-muted);line-height:1.5}.hall-detail-kicker{font-size:11px;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:var(--h-muted)}.hall-detail-kicker[data-open]{color:var(--h-ok)}.hall-detail-rank{display:flex;align-items:center;gap:18px;padding:16px 18px;border:1px solid var(--h-line);border-radius:14px;background:var(--h-panel)}.hall-detail-rank>svg{padding:6px;border-radius:12px;background:var(--h-sunken);box-sizing:content-box}.hall-detail-rank[data-tier=general]>svg{background:#111216}.hall-detail-rank>span{display:flex;flex-direction:column;gap:4px}.hall-detail-rank strong{font-size:24px;font-weight:800;letter-spacing:-.02em}.hall-detail-rank em{font-style:normal;font-size:12.5px;color:var(--h-muted)}.hall-detail-pick{display:flex;gap:6px;flex-wrap:wrap}.hall-detail-pick button{display:inline-flex;align-items:center;gap:6px;padding:4px 10px 4px 4px;border:1px solid var(--h-line);border-radius:10px;background:var(--h-panel);color:var(--h-ink);font:inherit;font-size:12px;font-weight:700;cursor:pointer}.hall-detail-pick button[aria-pressed=true]{border-color:var(--h-navy);box-shadow:0 0 0 1px var(--h-navy)}.hall-detail-piece{display:flex;align-items:flex-start;gap:14px;padding:14px;border:1px solid var(--h-line);border-radius:14px;background:var(--h-panel)}.hall-detail-piece h3{margin:0 0 3px;font-size:16px;font-weight:800;color:var(--h-ink)}.hall-detail-piece p{margin:6px 0 0;font-size:12.5px}.hall-detail-missing{font-size:15px;font-weight:800;color:var(--h-gold-ink)!important}.hall-detail-worn{align-self:flex-start;padding:6px 12px;border-radius:8px;background:var(--h-ok-soft);color:var(--h-ok);font-size:12.5px;font-weight:800}.hall-ranks{display:flex;flex-direction:column;gap:22px}.hall-rank-summary{display:flex;align-items:center;gap:18px;padding:16px 20px;border:1px solid var(--h-line);border-radius:14px;background:var(--h-panel)}.hall-rank-summary>div{display:flex;flex-direction:column;gap:6px;flex:1;min-width:0}.hall-rank-summary strong{font-size:15px}.hall-rank-summary .hall-rank-track{position:relative;height:6px;border-radius:3px;background:var(--h-sunken-2);overflow:hidden}.hall-rank-summary .hall-rank-track i{position:absolute;inset:0 auto 0 0;border-radius:inherit;background:linear-gradient(90deg,#a07a2a,#d6b25e)}.hall-rank-tier{display:flex;flex-direction:column;gap:10px}.hall-rank-tier h3{display:flex;align-items:center;gap:10px}.hall-rank-tier h3:after{content:"";flex:1;height:1px;background:var(--h-line)}.hall-rank-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:10px;margin:0;padding:0;list-style:none}.hall-rank-cell{position:relative;display:flex;flex-direction:column;align-items:center;gap:5px;padding:12px 10px;border:1px solid var(--h-line);border-radius:14px;background:var(--h-panel);text-align:center}.hall-rank-cell[data-current]{border-color:var(--h-gold);box-shadow:0 0 0 2px var(--h-gold),0 10px 22px #b08a352e}.hall-rank-art{position:relative;display:flex;align-items:center;justify-content:center;width:100%;height:96px;border-radius:10px;background:radial-gradient(80% 80% at 50% 35%,#ffffff,var(--h-sunken));box-shadow:inset 0 0 0 1px var(--h-line)}.hall-rank-tier[data-tier=general] .hall-rank-art{background:radial-gradient(80% 80% at 50% 35%,#2a2c33,#111216);box-shadow:inset 0 0 0 1px #c9a24a66}.hall-rank-none{position:absolute;inset:auto 6px 8px;font-size:10px;color:var(--h-muted)}.hall-rank-cell strong{font-size:12.5px;line-height:1.25;color:var(--h-ink)}.hall-rank-cell:not([data-reached]) strong{color:var(--h-muted)}.hall-rank-grade{padding:1px 7px;border-radius:5px;background:var(--h-gold-soft);color:var(--h-gold-ink);font-size:10.5px;font-weight:800;letter-spacing:.06em}.hall-rank-cell:not([data-reached]) .hall-rank-grade{background:var(--h-sunken);color:var(--h-muted)}.hall-rank-cell em{font-style:normal;font-size:10.5px;color:var(--h-muted);font-variant-numeric:tabular-nums}.hall-rank-now{position:absolute;top:-9px;left:50%;transform:translate(-50%);padding:2px 9px;border-radius:6px;background:var(--h-navy);color:#f6ecd2;font-size:10px;font-weight:800;white-space:nowrap}.hall-guide{display:flex;flex-direction:column;gap:22px}.hall-steps{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin:0;padding:0;list-style:none}.hall-steps>li{display:flex;flex-direction:column;gap:7px;padding:18px;border:1px solid var(--h-line);border-radius:14px;background:var(--h-panel)}.hall-steps strong{font-size:15px}.hall-steps p{margin:0;color:var(--h-muted);line-height:1.5}.hall-step-n{display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:8px;background:var(--h-navy);color:#f6ecd2;font-size:14px;font-weight:900}.hall-costs{display:flex;flex-direction:column;gap:2px;margin:4px 0 0;padding:0;list-style:none;font-size:12px;color:var(--h-ink-2);font-variant-numeric:tabular-nums}.hall-rule-group h4{margin:2px 0 8px;font-size:13px;font-weight:800;color:var(--h-ink)}.hall-guide-section{padding-top:4px}.hall-team{display:flex;flex-direction:column;gap:12px}.hall-ranking{display:flex;flex-direction:column;gap:6px;margin:0;padding:0;list-style:none}.hall-ranking li{display:flex;align-items:center;gap:12px;padding:10px 12px;border:1px solid var(--h-line);border-radius:12px;background:var(--h-panel)}.hall-rank{width:24px;text-align:center;font-size:13px;font-weight:800;color:var(--h-muted)}.hall-ranking li[data-podium="1"] .hall-rank{color:var(--h-gold-ink)}.hall-rank-body{display:flex;flex-direction:column;gap:6px;flex:1;min-width:0}.hall-rank-body em{font-style:normal;font-size:11.5px;color:var(--h-muted)}.hall-rank-next{display:flex;align-items:center;gap:6px;font-size:11.5px;color:var(--h-muted)}.hall-looks{display:grid;grid-template-columns:repeat(auto-fill,minmax(104px,1fr));gap:8px;margin:0;padding:0;list-style:none}.hall-looks li{display:flex;flex-direction:column;align-items:center;gap:4px;padding:12px 8px 10px;border:1px solid var(--h-line);border-radius:12px;background:var(--h-panel);text-align:center}.hall-looks strong{font-size:12px;line-height:1.2}.hall-looks em{font-style:normal;font-size:11px;color:var(--h-muted)}.hall-rank-xp{font-size:12px;color:var(--h-muted);font-variant-numeric:tabular-nums;white-space:nowrap}@media(max-width:860px){.hall-overview,.hall-studio,.hall-detail{grid-template-columns:1fr}.hall-studio .hall-stage{min-height:380px}.hall-steps{grid-template-columns:1fr}.hall-brand small{display:none}}@media(max-width:520px){.hall-layer{padding:0}.hall{border-radius:0;height:100%}.hall-hero{flex-direction:column;align-items:flex-start}.hall-slots{grid-template-columns:1fr}}@media(prefers-reduced-motion:reduce){.hall,.hall-card,.hall-item,.hall-road-step{animation:none;transition:none}.hall-card:hover,.hall-item:hover,.hall-road-step[aria-pressed=true]{transform:none}}.level-hud{display:flex;align-items:center;gap:10px;padding:8px 12px 8px 8px;min-width:236px;max-width:300px;text-align:left;font:inherit;color:hsl(var(--popover-foreground));cursor:pointer}.level-hud:hover{background:hsl(var(--secondary) / .92)}.level-hud:focus-visible{outline:2px solid hsl(var(--ring));outline-offset:2px}.level-hud[data-compact]{min-width:0;padding:5px 10px 5px 5px}.level-hud-body{display:flex;flex-direction:column;gap:4px;min-width:0;flex:1}.level-hud-name{display:flex;align-items:baseline;gap:6px;min-width:0}.level-hud-name strong{font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.level-hud-name em{font-style:normal;font-size:11px;font-weight:600;color:hsl(var(--warning));white-space:nowrap}.level-hud-xp{font-size:10.5px;color:hsl(var(--muted-foreground));font-variant-numeric:tabular-nums}.level-hud-pet{display:flex;flex-direction:column;gap:3px;margin-top:2px;padding-top:5px;border-top:1px solid hsl(var(--border));font-size:11px;color:hsl(var(--muted-foreground))}.level-ring{position:relative;display:inline-flex;flex:none;align-items:center;justify-content:center}.level-ring-gauge{position:absolute;top:0;right:0;bottom:0;left:0}.level-ring-track{fill:none;stroke:hsl(var(--border));stroke-width:3}.level-ring-fill{fill:none;stroke-width:3;stroke-linecap:round;stroke:#d9ab47;transition:stroke-dasharray .7s cubic-bezier(.2,.8,.2,1)}.level-ring[data-kind=pet] .level-ring-fill{stroke:#2dd4bf}.level-ring[data-kind=agent] .level-ring-fill{stroke:#4ade80}.level-ring-medal{fill:#141b33;stroke:#c9a24a;stroke-width:1}.level-ring[data-tier=general] .level-ring-medal{fill:#0d0e12;stroke:#e0b955;stroke-width:1.6}.level-ring-insignia{position:relative;filter:drop-shadow(0 1px 1px rgb(0 0 0 / .45))}.level-ring b{position:absolute;left:50%;bottom:-5px;transform:translate(-50%);min-width:18px;padding:0 5px;border-radius:6px;background:#141b33;box-shadow:inset 0 0 0 1px #c9a24a;color:#f6e7bd;font-size:10px;line-height:14px;font-weight:800;text-align:center;font-variant-numeric:tabular-nums}.level-bar{position:relative;display:block;height:6px;border-radius:999px;overflow:hidden;background:hsl(var(--muted))}.level-bar i{position:absolute;left:0;top:0;bottom:0;border-radius:inherit}.level-bar-gain{background:#fff1b8;box-shadow:0 0 8px #ffd25e;transition:width .15s ease-out}.level-bar-fill{background:linear-gradient(90deg,#f0a92b,#ffd25e);transition:width .65s cubic-bezier(.2,.8,.2,1)}.level-bar[data-kind=pet] .level-bar-fill{background:linear-gradient(90deg,#14b8a6,#5eead4)}.level-bar[data-kind=pet] .level-bar-gain{background:#ccfbf1;box-shadow:0 0 8px #5eead4}.level-bar[data-kind=agent] .level-bar-fill{background:linear-gradient(90deg,#22c55e,#86efac)}.level-bar[data-kind=agent] .level-bar-gain{background:#dcfce7;box-shadow:0 0 8px #86efac}.level-chip{display:inline-flex;flex:none;align-items:center;gap:3px;height:18px;padding:0 5px 0 3px;border-radius:5px;background:#141b33;box-shadow:inset 0 0 0 1px #b8913c;color:#f6e7bd;font-size:10px;font-variant-numeric:tabular-nums}.level-chip b{font-weight:800}.level-chip[data-tier=officer]{box-shadow:inset 0 0 0 1px #d9dde3}.level-chip[data-tier=general]{background:#0d0e12;box-shadow:inset 0 0 0 1.5px #e0b955}.level-chip-insignia{display:block}.office-plate .level-chip{margin-left:1px}.level-toasts{position:absolute;z-index:38;left:14px;bottom:14px;display:flex;flex-direction:column;gap:6px;max-width:min(320px,calc(100% - 28px))}.level-toast{display:flex;align-items:center;gap:9px;padding:8px 12px 8px 9px;border:1px solid hsl(var(--border));border-radius:12px;background:hsl(var(--popover) / .95);color:hsl(var(--popover-foreground));font:inherit;text-align:left;cursor:pointer;box-shadow:0 6px 20px #00000040;animation:level-toast-in .45s cubic-bezier(.2,1.4,.4,1) both}.level-toast span{display:flex;flex-direction:column;gap:1px;min-width:0}.level-toast strong{font-size:12px}.level-toast em{font-style:normal;font-size:11px;color:hsl(var(--muted-foreground))}.level-toast .level-toast-looks{margin-top:5px;gap:4px}.level-toast .level-toast-look{flex-direction:row;align-items:center;gap:7px;font-size:11.5px;font-weight:600;color:hsl(var(--primary))}@keyframes level-toast-in{0%{opacity:0;transform:translate(-24px) scale(.96)}to{opacity:1;transform:none}}.promo-tag{display:inline-flex;align-items:center;gap:9px;padding:6px 14px 6px 8px;border-radius:8px;background:#10162cf0;box-shadow:inset 0 0 0 1px #c9a24a,0 8px 22px #00000059;color:#f6e7bd;white-space:nowrap;pointer-events:none;animation-name:promo-tag;animation-timing-function:cubic-bezier(.2,.7,.2,1);animation-fill-mode:both}.promo-tag>span{display:flex;flex-direction:column;gap:1px}.promo-tag small{font-size:9.5px;font-weight:700;letter-spacing:.18em;text-transform:uppercase;color:#d9ab47}.promo-tag b{font-size:14px;font-weight:800;letter-spacing:.01em}@keyframes promo-tag{0%{opacity:0;transform:translateY(14px)}12%{opacity:1;transform:translateY(0)}82%{opacity:1;transform:translateY(-8px)}to{opacity:0;transform:translateY(-14px)}}.level-xp-pop{display:inline-block;font-size:13px;font-weight:800;color:#ffe58a;text-shadow:0 1px 0 #6b4a00,0 0 8px rgb(255 210 94 / .8);white-space:nowrap;pointer-events:none;animation:level-xp 1.6s ease-out both}.level-xp-pop[data-kind=pet]{color:#99f6e4;text-shadow:0 1px 0 #0f4f47,0 0 8px rgb(94 234 212 / .8)}.level-xp-pop[data-kind=agent]{color:#bbf7d0;text-shadow:0 1px 0 #14532d,0 0 8px rgb(134 239 172 / .8)}@keyframes level-xp{0%{opacity:0;transform:translateY(8px) scale(.7)}15%{opacity:1;transform:translateY(0) scale(1.1)}30%{transform:scale(1)}to{opacity:0;transform:translateY(-34px)}}.level-banner-layer{position:absolute;top:0;right:0;bottom:0;left:0;z-index:55;display:flex;align-items:center;justify-content:center;pointer-events:none;background:radial-gradient(60% 55% at 50% 50%,rgb(6 9 20 / .45),transparent 75%)}.promo{position:relative;pointer-events:auto;display:flex;flex-direction:column;align-items:center;gap:2px;min-width:320px;max-width:min(440px,calc(100% - 32px));padding:26px 40px 24px;border:0;border-radius:14px;font:inherit;color:#f3ead2;cursor:pointer;background:linear-gradient(180deg,#1b2445,#111833 60%,#0c1229);box-shadow:0 0 0 1px #c9a24a,0 30px 70px #0000008c;animation:promo-in .45s cubic-bezier(.2,.8,.2,1) both}.promo[data-tier=general]{background:linear-gradient(180deg,#17181f,#0d0e13);box-shadow:0 0 0 1.5px #e0b955,0 30px 70px #0009}.promo:focus-visible{outline:2px solid #f3ead2;outline-offset:4px}.promo-rule{position:absolute;top:6px;right:6px;bottom:6px;left:6px;border:1px solid rgb(201 162 74 / .55);border-radius:9px;pointer-events:none}.promo>:not(.promo-rule){position:relative}.promo-away{font-size:11px;font-weight:600;color:#c9b88f;margin-bottom:4px}.promo-kicker{font-size:12px;font-weight:800;letter-spacing:.42em;padding-left:.42em;text-transform:uppercase;color:#d9ab47;animation:promo-kicker .6s .1s cubic-bezier(.2,.8,.2,1) both}.promo-who{font-size:13px;font-weight:600;color:#c9c2ad;animation:promo-rise .4s .2s ease-out both}.promo-stage{position:relative;display:flex;align-items:center;justify-content:center;height:138px;margin:10px 0 6px}.promo-new{display:flex;filter:drop-shadow(0 6px 14px rgb(0 0 0 / .5));animation:promo-glint .9s 1.45s ease-out both}.promo:not([data-promoted]) .promo-new{animation:promo-rise .5s .25s ease-out both,promo-glint .9s .9s ease-out both}.promo-old{position:absolute;display:flex;animation:promo-old 1.1s .35s cubic-bezier(.4,0,.2,1) both}.promo-new .rank-part{animation:promo-part .32s calc(.75s + var(--i) * 70ms) cubic-bezier(.2,.9,.3,1.15) both;transform-box:fill-box;transform-origin:center}.promo-rank{font-size:24px;font-weight:800;letter-spacing:.01em;color:#fff6dc;text-align:center;animation:promo-rise .45s 1.15s ease-out both}.promo:not([data-promoted]) .promo-rank{animation-delay:.45s}.promo-grade{display:inline-flex;align-items:center;gap:8px;font-size:12px;font-weight:700;letter-spacing:.08em;color:#c9b88f;animation:promo-rise .45s 1.25s ease-out both}.promo:not([data-promoted]) .promo-grade{animation-delay:.55s}.promo-dot{width:3px;height:3px;border-radius:50%;background:#c9a24a}.promo-level{display:inline-flex;align-items:center;gap:4px}.promo-number{display:inline-grid;height:16px;overflow:hidden;font-variant-numeric:tabular-nums;color:#f3ead2}.promo-number>span{grid-area:1 / 1;text-align:center}.promo-number-old{animation:promo-roll-out .4s 1.5s ease-in both}.promo-number-new{animation:promo-roll-in .45s 1.6s cubic-bezier(.2,.9,.3,1.1) both}.promo:not([data-promoted]) .promo-number-old{animation-delay:.7s}.promo:not([data-promoted]) .promo-number-new{animation-delay:.8s}.promo-next{margin-top:8px;font-size:12px;color:#a9a28d;animation:promo-rise .4s 1s ease-out both}.promo-rewards{display:flex;flex-direction:column;align-items:stretch;gap:6px;width:100%;margin-top:16px;padding-top:14px;border-top:1px solid rgb(201 162 74 / .3)}.promo-unlocked{font-size:10px;font-weight:700;letter-spacing:.24em;text-transform:uppercase;color:#d9ab47;text-align:center;animation:promo-rise .4s 1.6s ease-out both}.promo-reward{display:flex;align-items:center;gap:12px;padding:5px 12px 5px 5px;border-radius:10px;background:#ffffff0d;box-shadow:inset 0 0 0 1px #c9a24a40;font-size:13px;font-weight:700;text-align:left;animation:promo-rise .45s ease-out both}.promo-hint{margin-top:2px;font-size:11px;color:#a9a28d;text-align:center;animation:promo-rise .4s 2.1s ease-out both}@keyframes promo-in{0%{opacity:0;transform:translateY(12px) scale(.97)}to{opacity:1;transform:none}}@keyframes promo-kicker{0%{opacity:0;letter-spacing:.8em}to{opacity:1;letter-spacing:.42em}}@keyframes promo-rise{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:none}}@keyframes promo-old{0%{opacity:0;transform:scale(.9)}20%{opacity:1;transform:none}55%{opacity:1;transform:none}to{opacity:0;transform:translate(-120px) scale(.7)}}@keyframes promo-part{0%{opacity:0;transform:translateY(-10px) scale(1.12)}to{opacity:1;transform:none}}@keyframes promo-glint{0%{filter:drop-shadow(0 6px 14px rgb(0 0 0 / .5)) brightness(1)}35%{filter:drop-shadow(0 6px 14px rgb(0 0 0 / .5)) drop-shadow(0 0 14px rgb(255 214 120 / .55)) brightness(1.35)}to{filter:drop-shadow(0 6px 14px rgb(0 0 0 / .5)) brightness(1)}}@keyframes promo-roll-out{to{opacity:0;transform:translateY(-16px)}}@keyframes promo-roll-in{0%{opacity:0;transform:translateY(16px)}to{opacity:1;transform:none}}.level-reward-icon{display:inline-flex;flex:none;align-items:center;justify-content:center}.level-reward-icon svg{display:block}.level-panel-layer{position:absolute;top:0;right:0;bottom:0;left:0;z-index:50;display:flex;align-items:center;justify-content:center;padding:16px;background:#00000040}.level-panel{display:flex;flex-direction:column;width:min(680px,100%);max-height:min(720px,100%);overflow:hidden}.level-panel:focus{outline:none}.level-panel-head{display:flex;align-items:center;gap:12px;padding:12px 14px 8px;border-bottom:1px solid hsl(var(--border))}.level-panel-head h2{margin:0;font-size:15px;font-weight:800}.level-tabs{display:flex;gap:4px;flex:1;flex-wrap:wrap}.level-tab{border:1px solid transparent;border-radius:8px;padding:4px 10px;background:none;color:hsl(var(--muted-foreground));font:inherit;font-size:12px;font-weight:600;cursor:pointer}.level-tab:hover{background:hsl(var(--secondary));color:hsl(var(--foreground))}.level-tab[aria-selected=true]{background:hsl(var(--secondary));color:hsl(var(--foreground));border-color:hsl(var(--border))}.level-tab:focus-visible{outline:2px solid hsl(var(--ring));outline-offset:1px}.level-panel-body{display:flex;flex-direction:column;gap:14px;padding:12px 14px 14px;overflow:auto;font-size:12px}.level-panel-foot{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;padding:8px 14px 10px;border-top:1px solid hsl(var(--border))}.level-sound{display:inline-flex;align-items:center;gap:6px;font-size:12px;cursor:pointer}.level-sound input{accent-color:hsl(var(--primary))}.level-subject{display:flex;align-items:center;gap:12px}.level-subject>div{display:flex;flex-direction:column;gap:4px;flex:1;min-width:0}.level-subject strong{font-size:15px}.level-subject em{font-style:normal;font-size:12px;font-weight:700;color:hsl(var(--warning))}.level-subject-xp{font-size:11px;color:hsl(var(--muted-foreground));font-variant-numeric:tabular-nums}.level-section h3{margin:0 0 6px;font-size:11px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;color:hsl(var(--muted-foreground))}.level-slots{display:flex;flex-direction:column;gap:8px}.level-slot{display:grid;grid-template-columns:64px 1fr;gap:8px;align-items:start}.level-slot-name{padding-top:4px;font-weight:600}.level-wear-chip{display:inline-flex;align-items:center;gap:5px;padding-left:4px}.level-wear-chip:disabled{opacity:.55;cursor:not-allowed}.level-wear-chip small{font-size:10px;color:hsl(var(--muted-foreground))}.level-track{display:flex;gap:8px;margin:0;padding:2px 2px 8px;list-style:none;overflow-x:auto;scroll-snap-type:x proximity}.level-track li{flex:none;display:flex;flex-direction:column;gap:6px;min-width:118px;max-width:150px;padding:8px;border:1px solid hsl(var(--border));border-radius:12px;background:hsl(var(--background));scroll-snap-align:center}.level-track li[data-done]{border-color:hsl(var(--warning) / .55);background:hsl(var(--warning) / .08)}.level-track li[data-next]{border-color:hsl(var(--primary));box-shadow:0 0 0 2px hsl(var(--primary) / .25)}.level-track-at{font-size:11px;font-weight:800}.level-track-items{display:flex;flex-direction:column;gap:5px}.level-track-item{display:flex;align-items:center;gap:6px;font-size:11px;line-height:1.25}.level-track-title{align-self:flex-start;padding:2px 7px;border-radius:999px;background:hsl(var(--secondary));font-size:10.5px;font-weight:700}.level-rules{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:4px 12px;margin:0;padding:0;list-style:none}.level-rules li{display:flex;align-items:flex-start;gap:8px;padding:5px 6px;border-radius:8px}.level-rules li:hover{background:hsl(var(--secondary) / .6)}.level-rule-xp{flex:none;min-width:34px;padding:1px 5px;border-radius:6px;background:hsl(var(--warning) / .16);color:hsl(var(--foreground));font-size:11px;font-weight:800;text-align:center;font-variant-numeric:tabular-nums}.level-rule-text{display:flex;flex-direction:column;gap:1px}.level-rule-text em{font-style:normal;font-size:10.5px;color:hsl(var(--muted-foreground))}.level-agents{display:flex;flex-direction:column;gap:4px;margin:0;padding:0;list-style:none}.level-agents li{display:flex;align-items:center;gap:8px;padding:5px 6px;border-radius:8px}.level-agents li:hover{background:hsl(var(--secondary) / .6)}.level-agent-rank{width:18px;text-align:right;font-size:11px;font-weight:700;color:hsl(var(--muted-foreground))}.level-agent-body{display:flex;flex-direction:column;gap:4px;flex:1;min-width:0}.level-agent-body em{font-style:normal;font-size:11px;color:hsl(var(--muted-foreground))}@media(max-width:600px){.level-hud{min-width:0}.level-slot{grid-template-columns:1fr}.promo{min-width:0;padding:22px 20px 20px}.promo-rank{font-size:20px}}@media(prefers-reduced-motion:reduce){.promo,.promo *,.level-toast,.promo-tag,.level-xp-pop{animation-duration:.01ms!important;animation-delay:0s!important}.promo-old,.promo-number-old{display:none}.level-bar i,.level-ring-fill{transition:none}}diff --git a/dodaios/ui/web/dist/assets/antigravity-8EbLmxw8.svg b/dodaios/ui/web/dist/assets/antigravity-_lOIeRhP.svgsimilarity index 100%rename from dodaios/ui/web/dist/assets/antigravity-8EbLmxw8.svgrename to dodaios/ui/web/dist/assets/antigravity-_lOIeRhP.svgdiff --git a/dodaios/ui/web/dist/assets/blockDrop-fHu-vbt1.js b/dodaios/ui/web/dist/assets/blockDrop-fHu-vbt1.jsnew file mode 100644index 0000000000..2c113a2c0f--- /dev/null+++ b/dodaios/ui/web/dist/assets/blockDrop-fHu-vbt1.js@@ -0,0 +1 @@+import{s as F,d as U,a as I,b as j,e as Q}from"./games2Kit-CD5FIutl.js";import"./retroGame-jKwLP3oJ.js";const k=10,m=22,w=2,W=.17,z=.05,K=.5,x=15,q=.3,ee=.035,le=[0,100,300,500,800],H=0,L=1,N=2,oe=3,Se=4,me=5,te=6,E=7,ie=[[0,1,1,1,2,1,3,1],[0,0,1,0,0,1,1,1],[1,0,0,1,1,1,2,1],[1,0,2,0,0,1,1,1],[0,0,1,0,1,1,2,1],[0,0,0,1,1,1,2,1],[2,0,0,1,1,1,2,1]],re=[4,2,3,3,3,3,3],A=ie.map((e,l)=>{const o=re[l],t=[Int8Array.from(e)];for(let r=1;r<4;r+=1){const c=t[r-1],p=new Int8Array(8);for(let i=0;i<4;i+=1)p[i*2]=l===L?c[i*2]:o-1-c[i*2+1],p[i*2+1]=l===L?c[i*2+1]:c[i*2];t.push(p)}return t}),fe=[0,0,-1,0,1,0,0,-1,-1,-1,1,-1],ne=[0,0,-1,0,1,0,-2,0,2,0,0,-1,0,-2],Z=200,B=236,n=11,y=8,f=8,u=128,S=64,v=["#4fd8ff","#ffd84a","#b06bff","#5dea6a","#ff5a6e","#4a7dff","#ff9a3d"],ae="#5b6177";function J(e){const l=Math.min(20,Math.max(1,e));return Math.pow(.8-(l-1)*.007,l-1)}function b(e,l,o,t,r){const c=A[l][o];for(let p=0;p<4;p+=1){const i=t+c[p*2],T=r+c[p*2+1];if(i<0||i>=k||T<0||T>=m||e.cells[T*k+i]!==0)return!1}return!0}function X(e,l){for(;e.queue.length<E;){const o=e.bag;for(let t=0;t<E;t+=1)o[t]=t;for(let t=E-1;t>0;t-=1){const r=Math.floor(l()*(t+1)),c=o[t];o[t]=o[r],o[r]=c}for(let t=0;t<E;t+=1)e.queue.push(o[t])}}function _(e,l){const o=e.queue.shift()??N;if(X(e,l),e.piece=o,e.rot=0,e.px=o===L?4:3,e.py=1,e.gravityTimer=0,e.lockTimer=0,e.lockResets=0,e.lowestRow=e.py,!b(e,o,0,e.px,e.py)){e.active=!1,e.over=!0;return}e.active=!0}function ce(e){const l={cells:new Uint8Array(k*m),active:!1,piece:0,rot:0,px:0,py:0,queue:[],bag:[0,0,0,0,0,0,0],gravityTimer:0,lockTimer:0,lockResets:0,lowestRow:0,shiftDir:0,shiftTimer:0,clearing:0,clearRows:[],score:0,lines:0,level:1,over:!1,ticks:0,sparks:F(90),kick:0,popupValue:0,popupRow:0,popupTime:0,levelGlow:0};return X(l,e),_(l,e),l}function M(e){return!b(e,e.piece,e.rot,e.px,e.py+1)}function V(e,l){(l||M(e))&&e.lockResets<x&&(e.lockTimer=0,e.lockResets+=1)}function C(e,l){if(!b(e,e.piece,e.rot,e.px+l,e.py))return!1;const o=M(e);return e.px+=l,V(e,o),!0}function pe(e){if(e.piece===L)return!0;const l=(e.rot+1)%4,o=e.piece===H?ne:fe,t=M(e);for(let r=0;r<o.length;r+=2){const c=e.px+o[r],p=e.py+o[r+1];if(b(e,e.piece,l,c,p))return e.rot=l,e.px=c,e.py=p,V(e,t),!0}return!1}function Y(e){let l=0;for(;b(e,e.piece,e.rot,e.px,e.py+l+1);)l+=1;return l}function G(e,l){const o=A[e.piece][e.rot];let t=!0;for(let i=0;i<4;i+=1){const T=e.py+o[i*2+1];e.cells[T*k+e.px+o[i*2]]=e.piece+1,T>=w&&(t=!1)}if(e.active=!1,t){e.over=!0;return}e.clearRows.length=0;for(let i=0;i<m;i+=1){let T=!0;for(let a=0;a<k;a+=1)if(e.cells[i*k+a]===0){T=!1;break}T&&e.clearRows.push(i)}const r=e.clearRows.length;if(r===0){_(e,l);return}const c=le[r]*e.level;e.score+=c,e.lines+=r;const p=Math.max(e.level,1+Math.floor(e.lines/10));p>e.level&&(e.levelGlow=1),e.level=p,e.clearing=q,e.popupValue=c,e.popupRow=e.clearRows[0],e.popupTime=1.1;for(let i=0;i<r;i+=1){const T=f+(e.clearRows[i]-w)*n+n/2;for(let a=0;a<12;a+=1){const h=y+l()*k*n;Q(e.sparks,h,T,(l()-.5)*90,-30-l()*90,.4+l()*.4,r===4?3:2,r===4?v[Math.floor(l()*E)]:"#ffffff")}}}function ue(e){let l=m-1;for(let o=m-1;o>=0;o-=1)e.clearRows.includes(o)||(l!==o&&e.cells.copyWithin(l*k,o*k,o*k+k),l-=1);for(;l>=0;l-=1)e.cells.fill(0,l*k,l*k+k);e.clearRows.length=0}function he(e,l,o){if(l.pressed.left)e.shiftDir=-1,e.shiftTimer=0,C(e,-1);else if(l.pressed.right)e.shiftDir=1,e.shiftTimer=0,C(e,1);else if(e.shiftDir===-1&&!l.left||e.shiftDir===1&&!l.right)e.shiftDir=e.shiftDir===-1?l.right?1:0:l.left?-1:0,e.shiftTimer=0;else if(e.shiftDir!==0)for(e.shiftTimer+=o;e.shiftTimer>=W;){if(!C(e,e.shiftDir)){e.shiftTimer=W;break}e.shiftTimer-=z}}function Te(e,l,o,t){if(e.ticks+=1,j(e.sparks,o,160),e.kick=Math.max(0,e.kick-o),e.popupTime=Math.max(0,e.popupTime-o),e.levelGlow=Math.max(0,e.levelGlow-o*.8),e.over)return;if(e.clearing>0){e.clearing-=o,e.clearing<=0&&(e.clearing=0,ue(e),_(e,t));return}if(!e.active&&(_(e,t),!e.active))return;if((l.pressed.up||l.pressed.a)&&pe(e),he(e,l,o),l.pressed.b){const p=Y(e);e.py+=p,e.score+=p*2,e.kick=.12,G(e,t);return}const r=l.down,c=r?Math.min(J(e.level),ee):J(e.level);for(e.gravityTimer+=o;e.gravityTimer>=c;){if(!b(e,e.piece,e.rot,e.px,e.py+1)){e.gravityTimer=0;break}e.gravityTimer-=c,e.py+=1,r&&(e.score+=1),e.py>e.lowestRow&&(e.lowestRow=e.py,e.lockResets=0,e.lockTimer=0)}M(e)&&(e.lockTimer+=o,e.lockTimer>=K-1e-9&&G(e,t))}function d(e,l,o,t,r){e.fillStyle=r,e.fillRect(l,o,t,t),e.fillStyle="rgba(255,255,255,0.38)",e.fillRect(l,o,t,1),e.fillRect(l,o,1,t),e.fillStyle="rgba(0,0,0,0.35)",e.fillRect(l,o+t-1,t,1),e.fillRect(l+t-1,o,1,t),t>=8&&(e.fillStyle="rgba(255,255,255,0.55)",e.fillRect(l+2,o+2,2,2))}function D(e,l,o,t,r){const c=A[l][0];let p=9,i=-9,T=9,a=-9;for(let g=0;g<4;g+=1)p=Math.min(p,c[g*2]),i=Math.max(i,c[g*2]),T=Math.min(T,c[g*2+1]),a=Math.max(a,c[g*2+1]);const h=Math.round(o-(i-p+1)*r/2),R=Math.round(t-(a-T+1)*r/2);for(let g=0;g<4;g+=1)d(e,h+(c[g*2]-p)*r,R+(c[g*2+1]-T)*r,r-1,v[l])}function s(e,l,o,t,r){e.fillStyle="#0b1433",e.fillRect(l,o,t,r),e.strokeStyle="#2a4a8f",e.lineWidth=1,e.strokeRect(l+.5,o+.5,t-1,r-1)}const O=["J.........","JJJ....LOO","ZZTT.LLLOO","SZZT.ITTTS","SSZT.IJTSS","OOTT.IJJJS"],ke={I:0,O:1,T:2,S:3,Z:4,J:5,L:6};function Re(e,l,o){const t=k*n,r=(m-w)*n;e.fillStyle="#070c1f",e.fillRect(y,f,t,r),e.fillStyle="rgba(124,196,255,0.06)";for(let i=1;i<k;i+=1)e.fillRect(y+i*n,f,1,r);for(let i=1;i<m-w;i+=1)e.fillRect(y,f+i*n,t,1);if(e.strokeStyle=l.levelGlow>0?`rgba(124,196,255,${.45+l.levelGlow*.55})`:"rgba(63,162,255,0.45)",e.lineWidth=l.levelGlow>0?2:1,e.strokeRect(y-1.5,f-1.5,t+3,r+3),o.idle&&l.ticks===0){const i=m-O.length;for(let a=0;a<O.length;a+=1)for(let h=0;h<k;h+=1){const R=O[a][h];R!=="."&&d(e,y+h*n,f+(i+a-w)*n,n-1,v[ke[R]])}const T=o.reduced?0:Math.round(Math.sin(o.time*2)*3);for(let a=0;a<4;a+=1)d(e,y+4*n,f+(7+a)*n+T,n-1,v[H]);e.strokeStyle="rgba(79,216,255,0.35)";for(let a=0;a<4;a+=1)e.strokeRect(y+4*n+.5,f+(i+2+a-w)*n+.5,n-2,n-2);return}const p=l.clearing>0?1-l.clearing/q:0;for(let i=w;i<m;i+=1){const T=l.clearing>0&&l.clearRows.includes(i);for(let a=0;a<k;a+=1){const h=l.cells[i*k+a];if(h===0)continue;const R=y+a*n,g=f+(i-w)*n;if(T){if(o.reduced)e.globalAlpha=1-p,d(e,R,g,n-1,v[h-1]),e.globalAlpha=1;else{const P=Math.max(1,Math.round((n-1)*(1-p))),$=p*(k/2+1);e.fillStyle=Math.abs(a+.5-k/2)<$?"#ffffff":v[h-1],e.fillRect(R,g+Math.round((n-1-P)/2),n-1,P)}continue}d(e,R,g,n-1,l.over?ae:v[h-1])}}if(l.active&&!l.over){const i=A[l.piece][l.rot],T=l.py+Y(l);e.strokeStyle=v[l.piece],e.globalAlpha=.45,e.lineWidth=1;for(let h=0;h<4;h+=1){const R=T+i[h*2+1];R<w||e.strokeRect(y+(l.px+i[h*2])*n+.5,f+(R-w)*n+.5,n-2,n-2)}e.globalAlpha=1;const a=M(l)?Math.min(1,l.lockTimer/K):0;for(let h=0;h<4;h+=1){const R=l.py+i[h*2+1];R<w||(d(e,y+(l.px+i[h*2])*n,f+(R-w)*n,n-1,v[l.piece]),a>0&&(e.fillStyle=`rgba(7,12,31,${a*.35})`,e.fillRect(y+(l.px+i[h*2])*n,f+(R-w)*n,n-1,n-1)))}}l.over&&(e.fillStyle="rgba(7,12,31,0.45)",e.fillRect(y,f,t,r))}function ge(e,l,o){const t=o.idle&&l.ticks===0;s(e,u,f,S,46),e.fillStyle="#7cc4ff",e.beginPath(),e.moveTo(u+4,f+4),e.lineTo(u+10,f+4),e.lineTo(u+7,f+8),e.closePath(),e.fill(),D(e,t?N:l.queue[0],u+S/2,f+25,10),s(e,u,f+50,31,30),s(e,u+33,f+50,31,30),D(e,t?te:l.queue[1],u+15.5,f+65,6),D(e,t?oe:l.queue[2],u+48.5,f+65,6),s(e,u,f+88,S,26),I(e,l.score,u+S-5,f+94,14,"#ffffff","right",600),s(e,u,f+120,S,20),e.strokeStyle="#ffd84a",e.lineWidth=2,e.beginPath(),e.moveTo(u+5,f+131),e.lineTo(u+9,f+127),e.lineTo(u+13,f+131),e.moveTo(u+5,f+135),e.lineTo(u+9,f+131),e.lineTo(u+13,f+135),e.stroke(),I(e,l.level,u+S-5,f+124,12,"#ffd84a","right"),s(e,u,f+144,S,20),e.fillStyle="#5dea6a";for(let r=0;r<3;r+=1)e.fillRect(u+5,f+149+r*4,9,2);I(e,l.lines,u+S-5,f+148,12,"#5dea6a","right"),s(e,u,f+170,S,8),e.fillStyle="#3fa2ff",e.fillRect(u+2,f+172,Math.round((S-4)*(l.lines%10/10)),4);for(let r=0;r<4;r+=1)d(e,u+8+r*13,f+200,11,v[(r+2)%E]),r%2===0&&d(e,u+8+r*13,f+188,11,v[(r+5)%E])}function ye(e,l,o){if(e.fillStyle="#050916",e.fillRect(0,0,Z,B),e.save(),!o.reduced&&l.kick>0&&e.translate(0,Math.round(l.kick/.12*2)),Re(e,l,o),U(e,l.sparks),l.popupTime>0&&l.popupValue>0&&!l.over){const t=o.reduced?0:(1.1-l.popupTime)*14;e.globalAlpha=Math.min(1,l.popupTime*2),I(e,`+${l.popupValue}`,y+k*n/2,f+(l.popupRow-w)*n-10-t,12,"#ffffff","center",600),e.globalAlpha=1}e.restore(),ge(e,l,o)}const de={id:"block-drop",width:Z,height:B,create:e=>ce(e),step:(e,l,o,t)=>Te(e,l,o,t),draw:(e,l,o)=>ye(e,l,o),status:e=>({score:e.score,level:e.level,over:e.over})};export{z as ARR,q as CLEAR_TIME,k as COLS,W as DAS,B as HEIGHT,w as HIDDEN,le as LINE_SCORES,K as LOCK_DELAY,x as MAX_LOCK_RESETS,E as PIECE_COUNT,H as PIECE_I,me as PIECE_J,te as PIECE_L,L as PIECE_O,oe as PIECE_S,N as PIECE_T,Se as PIECE_Z,m as ROWS,A as SHAPES,Z as WIDTH,ce as createBlockDrop,de as default,ye as drawBlockDrop,Y as dropDistance,b as fits,J as gravityInterval,_ as spawnPiece,Te as stepBlockDrop,pe as tryRotate,C as tryShift};diff --git a/dodaios/ui/web/dist/assets/chatLibraryApi-CvqmhVQf.js b/dodaios/ui/web/dist/assets/chatLibraryApi-CvqmhVQf.jsdeleted file mode 100644index 6ecf25b341..0000000000--- a/dodaios/ui/web/dist/assets/chatLibraryApi-CvqmhVQf.js+++ /dev/null@@ -1 +0,0 @@-const a="/api/chat-library";class c extends Error{constructor(t,e){super(t),this.status=e,this.name="ChatLibraryError"}}async function n(o,t){const e=await fetch(`${a}${o}`,{headers:t!=null&&t.body?{"Content-Type":"application/json"}:void 0,...t});if(!e.ok){let s=e.statusText;try{const r=await e.json();r&&typeof r.detail=="string"&&(s=r.detail)}catch{}throw new c(s,e.status)}if(e.status!==204)return await e.json()}async function d(o,t){return n("/projects",{method:"POST",body:JSON.stringify({path:o,name:t})})}async function i(o,t){return n(`/projects/${encodeURIComponent(o)}`,{method:"PATCH",body:JSON.stringify(t)})}async function y(o){return(await n(`/projects/${encodeURIComponent(o)}`,{method:"DELETE"})).removed}async function p(o){return(await n(`/projects/${encodeURIComponent(o)}/reveal`,{method:"POST"})).opened}function u(o){return n(`/projects/${encodeURIComponent(o)}/launchers`)}async function f(o,t){return(await n(`/projects/${encodeURIComponent(o)}/open-in`,{method:"POST",body:JSON.stringify({target:t})})).opened}async function h(o){return(await n("/projects/order",{method:"PUT",body:JSON.stringify({project_ids:o})})).projects}export{c as C,f as a,p as b,y as d,u as f,d as o,i as p,h as r};diff --git a/dodaios/ui/web/dist/assets/courier-lod0-DXskDcZz.glb b/dodaios/ui/web/dist/assets/courier-lod0-DXskDcZz.glbdeleted file mode 100644index 1d980f2841..0000000000Binary files a/dodaios/ui/web/dist/assets/courier-lod0-DXskDcZz.glb and /dev/null differdiff --git a/dodaios/ui/web/dist/assets/courier-lod1-CHc5IA82.glb b/dodaios/ui/web/dist/assets/courier-lod1-CHc5IA82.glbdeleted file mode 100644index a7bf26f596..0000000000Binary files a/dodaios/ui/web/dist/assets/courier-lod1-CHc5IA82.glb and /dev/null differdiff --git a/dodaios/ui/web/dist/assets/courier-lod2-CCGTtqFE.glb b/dodaios/ui/web/dist/assets/courier-lod2-CCGTtqFE.glbdeleted file mode 100644index e851287000..0000000000Binary files a/dodaios/ui/web/dist/assets/courier-lod2-CCGTtqFE.glb and /dev/null differdiff --git a/dodaios/ui/web/dist/assets/desertDash-DagbbBDf.js b/dodaios/ui/web/dist/assets/desertDash-DagbbBDf.jsnew file mode 100644index 0000000000..a82162937c--- /dev/null+++ b/dodaios/ui/web/dist/assets/desertDash-DagbbBDf.js@@ -0,0 +1 @@+import{R as m}from"./retroGame-jKwLP3oJ.js";import{s as F,d as X,m as D,a as z,b as Q,e as U,h as R}from"./games2Kit-CD5FIutl.js";const c=320,v=180,d=150,S=36,C=400,Y=1150,B=2300,I=220,Z=5200,$=.1,N=160,q=440,x=3.2,ee=10,le=.18,te=150,A={x0:5,x1:15,h:17},O={x0:3,x1:20,h:9},p=[{w:9,hx0:1,hx1:8,bottom:0,top:17,bird:!1,duck:!1,minScore:0,minSpeed:0,weight:4},{w:11,hx0:1,hx1:10,bottom:0,top:27,bird:!1,duck:!1,minScore:0,minSpeed:0,weight:3},{w:20,hx0:1,hx1:19,bottom:0,top:17,bird:!1,duck:!1,minScore:60,minSpeed:0,weight:2},{w:22,hx0:1,hx1:21,bottom:0,top:27,bird:!1,duck:!1,minScore:200,minSpeed:220,weight:2},{w:31,hx0:1,hx1:30,bottom:0,top:17,bird:!1,duck:!1,minScore:400,minSpeed:260,weight:1},{w:16,hx0:2,hx1:14,bottom:3,top:11,bird:!0,duck:!1,minScore:300,minSpeed:0,weight:2},{w:16,hx0:2,hx1:14,bottom:12,top:20,bird:!0,duck:!0,minScore:300,minSpeed:0,weight:2}],k=(()=>{const e=[];let t=0,l=C;for(let o=0;o<400&&(l-=(l>0?Y:B)*m,t+=l*m,!(t<=0));o+=1)e.push(t);return e})(),oe=(k.length+1)*m,ke=Math.max(...k);function ie(e){let t=-1,l=-1;for(let o=0;o<k.length;o+=1)k[o]>e&&(t<0&&(t=o),l=o);return t<0?null:{rise:(t+1)*m,fall:(l+1)*m}}function fe(e,t){if(e.duck)return O.h<e.bottom;const l=ie(e.top);if(!l)return!1;const o=(e.hx1-e.hx0+A.x1-A.x0)/t;return l.fall-l.rise>=o+m*2}function ne(e){return e*(oe+le)}function ae(e){return Math.min(q,N+x*e)}function re(e){const t=new Float32Array(96);for(let o=0;o<48;o+=1)t[o*2]=e()*c,t[o*2+1]=e()*95;const l=[];for(let o=0;o<8;o+=1)l.push({active:!1,kind:0,x:0});return{y:0,vy:0,onGround:!0,ducking:!1,jumpHeld:!1,jumpBuffer:0,speed:N,distance:0,time:0,score:0,over:!1,obstacles:l,nextGap:c*.6,milestone:0,milestoneGlow:0,dustTimer:0,sparks:F(40),stars:t,ticks:0}}function se(e,t){let l=0;for(let i=0;i<p.length;i+=1)_(p[i],e)&&(l+=p[i].weight);let o=t()*l;for(let i=0;i<p.length;i+=1)if(_(p[i],e)&&(o-=p[i].weight,o<0))return i;return 0}function _(e,t){return t.score>=e.minScore&&t.speed>=e.minSpeed&&fe(e,t.speed)}function ue(e,t){let l=null;for(const s of e.obstacles)if(!s.active){l=s;break}const o=se(e,t),i=ne(e.speed)*(1+t()*.9)+t()*40;return l&&(l.active=!0,l.kind=o,l.x=c+4+Math.min(0,e.nextGap)),e.nextGap=p[o].w+i,i}function ce(e){return e.ducking?O:A}function de(e,t){const l=p[t.kind],o=ce(e),i=S+o.x0,s=S+o.x1,a=t.x+l.hx0,f=t.x+l.hx1;return s>a&&i<f&&e.y+o.h>l.bottom&&e.y<l.top}function j(e,t,l){for(let o=0;o<t;o+=1)U(e.sparks,S+6+l()*6,d-1,-e.speed*.3-l()*30,-10-l()*30,.25+l()*.25,2,"#e8c896")}function he(e,t,l,o){if(e.ticks+=1,Q(e.sparks,l,90),e.over)return;e.time+=l,e.speed=ae(e.time),e.distance+=e.speed*l,e.score=Math.floor(e.distance/ee),e.milestoneGlow=Math.max(0,e.milestoneGlow-l),e.score>=e.milestone+500&&(e.milestone+=500,e.milestoneGlow=1);const i=t.pressed.a||t.pressed.up,s=t.a||t.up;if(i?e.jumpBuffer=$:e.jumpBuffer=Math.max(0,e.jumpBuffer-l),e.onGround&&(e.jumpBuffer>0?(e.onGround=!1,e.ducking=!1,e.vy=C,e.jumpHeld=s,e.jumpBuffer=0):e.ducking=t.down),!e.onGround){e.jumpHeld&&!s&&(e.jumpHeld=!1,e.vy>I&&(e.vy=I));const f=t.down?Z:e.vy>0&&e.jumpHeld?Y:B;e.vy-=f*l,e.y+=e.vy*l,e.y<=0&&(e.y=0,e.vy=0,e.onGround=!0,e.jumpHeld=!1,e.ducking=t.down,j(e,5,o))}e.dustTimer-=l,e.onGround&&e.dustTimer<=0&&(e.dustTimer=.09,j(e,1,o));const a=e.speed*l;for(const f of e.obstacles)f.active&&(f.x-=a,f.x+p[f.kind].w<-4&&(f.active=!1));e.nextGap-=a,e.nextGap<=0&&ue(e,o);for(const f of e.obstacles)if(f.active&&de(e,f)){e.over=!0;for(let n=0;n<14;n+=1){const u=o()*Math.PI*2,M=30+o()*70;U(e.sparks,S+10,d-e.y-10,Math.cos(u)*M,Math.sin(u)*M-30,.4+o()*.4,2,"#ff9a3d")}return}}const w=(e,t,l,o,i,s,a)=>({skyTop:R(e),skyBottom:R(t),far:R(l),near:R(o),ground:R(i),detail:R(s),cactus:R(a)}),y=w("#6ec6ff","#ffe9b8","#e9b97a","#d99a55","#f0c27b","#b8844a","#2f8f4e"),L=w("#4b3a78","#ff8a5c","#b8705a","#8f4f43","#c98a5e","#7a4a3a","#2a6a48"),E=w("#070b24","#1d2457","#2b2f5c","#222650","#3a3a66","#262850","#2a6a5a"),pe=R("#ffffff"),Re=R("#ffd23f"),K=w("#3f6fb8","#ffb8a0","#c99a8a","#a8766a","#d8a888","#8a6a5a","#2a7a52"),g=[[0,y],[.24,y],[.34,L],[.44,E],[.68,E],[.78,K],[.88,y],[1,y]];function me(e){let t=0;for(;t<g.length-2&&e>=g[t+1][0];)t+=1;const[l,o]=g[t],[i,s]=g[t+1],a=i>l?(e-l)/(i-l):0,f=a*a*(3-2*a),n=u=>u===E?1:u===L?.45:u===K?.35:0;return{a:o,b:s,k:f,night:n(o)+(n(s)-n(o))*f}}function H(e,t,l,o,i,s){e.fillStyle=s,e.beginPath(),e.moveTo(0,d);for(let a=0;a<=c;a+=8){const f=a+t,n=l-(Math.sin(f*i)*o+Math.sin(f*i*2.7+1.3)*o*.35);e.lineTo(a,n)}e.lineTo(c,d),e.closePath(),e.fill()}function h(e,t,l,o,i){const s=d-o,a=Math.max(3,Math.round(l*.4)),f=Math.round(t+(l-a)/2);e.fillStyle=i,e.fillRect(f,s+1,a,o-1),e.fillRect(f+1,s,a-2,1);const n=s+Math.round(o*.35);e.fillRect(Math.round(t),n+2,f-Math.round(t),2),e.fillRect(Math.round(t),n-2,2,5),e.fillRect(f+a,n+5,Math.round(t+l)-f-a,2),e.fillRect(Math.round(t+l)-2,n+1,2,6),e.fillStyle="rgba(255,255,255,0.18)",e.fillRect(f+1,s+2,1,o-4)}function be(e,t,l,o,i,s){const a=p[t];if(a.bird){const f=d-a.top,n=s?0:Math.floor(i*8)%2;e.fillStyle="#5a3a2a",e.fillRect(Math.round(l+4),Math.round(f+3),9,4),e.fillRect(Math.round(l+1),Math.round(f+2),4,3),e.fillStyle="#ffb000",e.fillRect(Math.round(l-1),Math.round(f+3),2,1),e.fillStyle="#5a3a2a",e.fillRect(Math.round(l+13),Math.round(f+4),3,2),n===0?e.fillRect(Math.round(l+6),Math.round(f-2),4,5):e.fillRect(Math.round(l+6),Math.round(f+6),4,4),e.fillStyle="#ffffff",e.fillRect(Math.round(l+2),Math.round(f+3),1,1);return}switch(t){case 0:h(e,l,9,18,o);break;case 1:h(e,l,11,28,o);break;case 2:h(e,l,9,18,o),h(e,l+11,9,15,o);break;case 3:h(e,l,11,28,o),h(e,l+13,9,18,o);break;default:h(e,l,9,16,o),h(e,l+11,9,18,o),h(e,l+22,9,14,o)}}function Se(e,t,l,o){const i=S,s="#ff9a3d",a="#ffe6c0",f="#2a1a0a";if(t.ducking&&t.onGround&&!o){const u=d-11;e.fillStyle=s,e.fillRect(i-3,u+3,6,3),e.fillRect(i+2,u+3,14,6),e.fillRect(i+14,u+1,8,6),e.fillRect(i+11,u,5,2),e.fillStyle=a,e.fillRect(i-3,u+3,2,2),e.fillRect(i+20,u+4,3,2),e.fillRect(i+6,u+7,8,2),e.fillStyle=f,e.fillRect(i+18,u+3,1,1),e.fillRect(i+23,u+4,1,1),e.fillStyle=s,e.fillRect(i+4+l*2,u+9,2,2),e.fillRect(i+12-l*2,u+9,2,2);return}const n=d-20-Math.round(t.y);e.fillStyle=s,e.fillRect(i,n+8,5,4),e.fillRect(i+4,n+8,9,7),e.fillRect(i+8,n+2,8,7),e.fillRect(i+9,n-2,2,4),e.fillRect(i+13,n-2,2,4),e.fillStyle=a,e.fillRect(i,n+8,2,3),e.fillRect(i+7,n+11,5,3),e.fillRect(i+14,n+5,3,3),e.fillRect(i+10,n-1,1,2),e.fillRect(i+14,n-1,1,2),e.fillStyle=f,e.fillRect(i+17,n+5,1,1),o?(e.fillRect(i+11,n+3,1,1),e.fillRect(i+13,n+3,1,1),e.fillRect(i+12,n+4,1,1),e.fillRect(i+11,n+5,1,1),e.fillRect(i+13,n+5,1,1)):e.fillRect(i+12,n+4,1,2),e.fillStyle=s,t.onGround?(e.fillRect(i+5,n+15,2,l===0?5:3),e.fillRect(i+10,n+15,2,l===0?3:5)):(e.fillRect(i+5,n+15,2,3),e.fillRect(i+10,n+15,2,3))}function Me(e,t,l){const o=l.idle&&t.ticks===0,i=o?l.reduced?0:l.time*24:t.distance,s=(t.time/te%1+1)%1,a=me(s),f=r=>D(r(a.a),r(a.b),a.k),n=e.createLinearGradient(0,0,0,d);if(n.addColorStop(0,f(r=>r.skyTop)),n.addColorStop(1,f(r=>r.skyBottom)),e.fillStyle=n,e.fillRect(0,0,c,v),a.night>.05){e.fillStyle="#ffffff";for(let r=0;r<t.stars.length;r+=2){const b=l.reduced?1:.6+.4*Math.sin(l.time*2+r);e.globalAlpha=a.night*b*.9;const T=((t.stars[r]-i*.02)%c+c)%c;e.fillRect(Math.round(T),Math.round(t.stars[r+1]),1,1)}e.globalAlpha=1}const u=1-a.night;u>.02&&(e.globalAlpha=u,e.fillStyle="#fff4c2",e.beginPath(),e.arc(250,36+a.night*70,14,0,Math.PI*2),e.fill(),e.globalAlpha=1),a.night>.02&&(e.globalAlpha=a.night,e.fillStyle="#f2f0ff",e.beginPath(),e.arc(70,34,9,0,Math.PI*2),e.fill(),e.fillStyle=f(r=>r.skyTop),e.beginPath(),e.arc(74,31,8,0,Math.PI*2),e.fill(),e.globalAlpha=1),H(e,i*.12,112,9,.011,f(r=>r.far)),H(e,i*.35,132,7,.02,f(r=>r.near)),e.fillStyle=f(r=>r.ground),e.fillRect(0,d,c,v-d);const M=f(r=>r.detail);e.fillStyle=M,e.fillRect(0,d,c,1);const P=Math.floor(i/13);for(let r=P;r<P+Math.ceil(c/13)+2;r+=1){const b=(Math.imul(r,2654435761)>>>0)/4294967296,T=Math.round(r*13-i+b*9),W=d+3+Math.floor(b*24);e.fillRect(T,W,b>.7?3:1,1)}const G=f(r=>r.cactus);if(o)h(e,170,11,28,G),h(e,250,9,18,G);else for(const r of t.obstacles)r.active&&be(e,r.kind,r.x,G,l.time,l.reduced);const J=o?l.reduced?0:Math.floor(l.time*8)%2:Math.floor(t.distance/14)%2;Se(e,t,J,t.over),X(e,t.sparks);const V=t.milestoneGlow>0?D(pe,Re,t.milestoneGlow):"#ffffff";e.fillStyle="rgba(0,0,0,0.25)",e.fillRect(c-52,4,48,13),z(e,String(t.score).padStart(5,"0"),c-7,5,10,V,"right",600)}const we={id:"desert-dash",width:c,height:v,create:e=>re(e),step:(e,t,l,o)=>he(e,t,l,o),draw:(e,t,l)=>Me(e,t,l),status:e=>({score:e.score,over:e.over})};export{oe as AIRTIME,O as DUCK_HIT,B as GRAVITY,Y as GRAVITY_HELD,v as HEIGHT,ke as JUMP_APEX,I as JUMP_CUT,C as JUMP_SPEED,p as KINDS,q as MAX_SPEED,le as REACTION,S as RUNNER_X,x as SPEED_RAMP,A as STAND_HIT,N as START_SPEED,c as WIDTH,fe as clearable,de as collides,re as createDesert,we as default,Me as drawDesert,ie as jumpWindow,ne as minGap,se as pickKind,ue as spawnObstacle,ae as speedAt,he as stepDesert};diff --git a/dodaios/ui/web/dist/assets/fly-BBgZ4Q4B.svg b/dodaios/ui/web/dist/assets/fly-C4H8YhO_.svgsimilarity index 100%rename from dodaios/ui/web/dist/assets/fly-BBgZ4Q4B.svgrename to dodaios/ui/web/dist/assets/fly-C4H8YhO_.svgdiff --git a/dodaios/ui/web/dist/assets/games2Kit-CD5FIutl.js b/dodaios/ui/web/dist/assets/games2Kit-CD5FIutl.jsnew file mode 100644index 0000000000..a30aa478d4--- /dev/null+++ b/dodaios/ui/web/dist/assets/games2Kit-CD5FIutl.js@@ -0,0 +1 @@+import{r as u}from"./retroGame-jKwLP3oJ.js";function g(t){const n=[];for(let o=0;o<t;o+=1)n.push({x:0,y:0,vx:0,vy:0,life:0,max:1,size:1,color:"#ffffff"});return n}function m(t,n,o,e,i,l,r,a){if(t.length===0)return;let f=t[0];for(let h=0;h<t.length;h+=1){const s=t[h];if(s.life<=0){f=s;break}s.life<f.life&&(f=s)}f.x=n,f.y=o,f.vx=e,f.vy=i,f.life=l,f.max=l,f.size=r,f.color=a}function x(t,n,o){for(let e=0;e<t.length;e+=1){const i=t[e];i.life<=0||(i.life-=n,i.vy+=o*n,i.x+=i.vx*n,i.y+=i.vy*n)}}function y(t,n){for(let o=0;o<n.length;o+=1){const e=n[o];if(e.life<=0)continue;t.globalAlpha=Math.max(0,Math.min(1,e.life/e.max)),t.fillStyle=e.color;const i=e.size/2;t.fillRect(Math.round(e.x-i),Math.round(e.y-i),e.size,e.size)}t.globalAlpha=1}function M(t,n,o,e,i,l,r="left",a=400){t.font=u(i,a),t.textAlign=r,t.textBaseline="top",t.fillStyle=l,t.fillText(typeof n=="number"?String(Math.floor(n)):n,o,e)}function p(t){const n=parseInt(t.slice(1),16);return[n>>16&255,n>>8&255,n&255]}function b(t,n,o){const e=Math.max(0,Math.min(1,o)),i=Math.round(t[0]+(n[0]-t[0])*e),l=Math.round(t[1]+(n[1]-t[1])*e),r=Math.round(t[2]+(n[2]-t[2])*e);return`rgb(${i},${l},${r})`}export{M as a,x as b,y as d,m as e,p as h,b as m,g as s};diff --git a/dodaios/ui/web/dist/assets/granola-CIlE1D1h.svg b/dodaios/ui/web/dist/assets/granola-CYNYNSF5.svgsimilarity index 100%rename from dodaios/ui/web/dist/assets/granola-CIlE1D1h.svgrename to dodaios/ui/web/dist/assets/granola-CYNYNSF5.svgdiff --git a/dodaios/ui/web/dist/assets/ideChat-CFbL2ovg.css b/dodaios/ui/web/dist/assets/ideChat-CFbL2ovg.cssdeleted file mode 100644index 43d99cd904..0000000000--- a/dodaios/ui/web/dist/assets/ideChat-CFbL2ovg.css+++ /dev/null@@ -1,32 +0,0 @@-/**- * Copyright (c) 2014 The xterm.js authors. All rights reserved.- * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)- * https://github.com/chjj/term.js- * @license MIT- *- * Permission is hereby granted, free of charge, to any person obtaining a copy- * of this software and associated documentation files (the "Software"), to deal- * in the Software without restriction, including without limitation the rights- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell- * copies of the Software, and to permit persons to whom the Software is- * furnished to do so, subject to the following conditions:- *- * The above copyright notice and this permission notice shall be included in- * all copies or substantial portions of the Software.- *- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN- * THE SOFTWARE.- *- * Originally forked from (with the author's permission):- * Fabrice Bellard's javascript vt100 for jslinux:- * http://bellard.org/jslinux/- * Copyright (c) 2011 Fabrice Bellard- * The original design remains. The terminal itself- * has been extended to include xterm CSI codes, among- * other features.- */.xterm{cursor:text;position:relative;-moz-user-select:none;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:none}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm .xterm-scroll-area{visibility:hidden}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm.xterm-cursor-pointer,.xterm .xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) *::-moz-selection{color:transparent}.xterm .xterm-accessibility-tree:not(.debug) *::selection{color:transparent}.xterm .xterm-accessibility-tree{-webkit-user-select:text;-moz-user-select:text;user-select:text;white-space:pre}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{-webkit-text-decoration:double underline;text-decoration:double underline}.xterm-underline-3{-webkit-text-decoration:wavy underline;text-decoration:wavy underline}.xterm-underline-4{-webkit-text-decoration:dotted underline;text-decoration:dotted underline}.xterm-underline-5{-webkit-text-decoration:dashed underline;text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{-webkit-text-decoration:overline double underline;text-decoration:overline double underline}.xterm-overline.xterm-underline-3{-webkit-text-decoration:overline wavy underline;text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{-webkit-text-decoration:overline dotted underline;text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{-webkit-text-decoration:overline dashed underline;text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}diff --git a/dodaios/ui/web/dist/assets/intercom-Dh0L0ym2.svg b/dodaios/ui/web/dist/assets/intercom-DfEJASO4.svgsimilarity index 100%rename from dodaios/ui/web/dist/assets/intercom-Dh0L0ym2.svgrename to dodaios/ui/web/dist/assets/intercom-DfEJASO4.svgdiff --git a/dodaios/ui/web/dist/assets/kubernetes-DGGHM7xL.svg b/dodaios/ui/web/dist/assets/kubernetes-BTaq8_2V.svgsimilarity index 100%rename from dodaios/ui/web/dist/assets/kubernetes-DGGHM7xL.svgrename to dodaios/ui/web/dist/assets/kubernetes-BTaq8_2V.svgdiff --git a/dodaios/ui/web/dist/assets/mazeMuncher-1LHzEuy-.js b/dodaios/ui/web/dist/assets/mazeMuncher-1LHzEuy-.jsnew file mode 100644index 0000000000..1bc05812de--- /dev/null+++ b/dodaios/ui/web/dist/assets/mazeMuncher-1LHzEuy-.js@@ -0,0 +1 @@+import{s as le,d as de,a as W,b as he,e as se}from"./games2Kit-CD5FIutl.js";import"./retroGame-jKwLP3oJ.js";const D=["#####################","#.........#.........#","#o##.####.#.####.##o#","#...................#","#.##.#.#######.#.##.#","#....#....#....#....#","####.####.#.####.####","####.#.........#.####","####.#.###-###.#.####","T......#PPPPP#......T","####.#.#######.#.####","####.#.........#.####","####.#.#######.#.####","#.........#.........#","#.##.####.#.####.##.#","#o.#...... ......#.o#","##.#.#.#######.#.#.##","#....#....#....#....#","#.#######.#.#######.#","#...................#","#####################"],s=21,y=21,S=0,T=1,N=2,V=3,v=-1,E=[0,-1,0,1],b=[-1,0,1,0],X=[N,V,S,T],ue=10,ce=15,p=10,I=7,te=9,Me=[10,10,9,11],L=10,C=11,Te=9,pe=10,ye=50,j=[200,400,800,1600],q=[100,300,500,700,1e3,2e3,3e3,5e3],ge=3,oe=1.6,k=1.4,ie=2,me=.5,Pe=9,J=[7,20,7,20,5,20,5,1/0],ve=[0,1,5,9],Se=[0,0,25,50],K=[19,1,20,0],Q=[-2,-2,22,22],P=1e-6;function we(e,n){if(n<0||n>=y)return"#";const t=(e%s+s)%s;return D[n][t]}function Ie(e,n){const t=we(e,n);return t!=="#"&&t!=="P"&&t!=="-"}function _(e,n){return Ie(Math.round(e.x)+E[n],Math.round(e.y)+b[n])}function Ee(e){return Math.abs(e.x-Math.round(e.x))<P&&Math.abs(e.y-Math.round(e.y))<P}function Re(e){e.x<-.5?e.x+=s:e.x>s-.5&&(e.x-=s)}function re(e){return Math.min(1.3,1+(e-1)*.06)}function _e(e){return Math.max(1.5,7-(e-1)*1.1)}function ae(e){let n=0;for(let t=0;t<y;t+=1)for(let o=0;o<s;o+=1){const a=D[t][o],i=a==="."?1:a==="o"?2:0;e.dots[t*s+o]=i,i&&(n+=1)}e.dotsLeft=n,e.totalDots=n,e.bonusShown=0,e.bonusTimer=0}function Z(e){const n=e.player;n.x=ue,n.y=ce,n.dir=v,n.want=T,n.chew=0;for(const t of e.bugs)t.frightened=!1,t.index===0?(t.x=p,t.y=I,t.dir=T,t.mode="active"):(t.x=Me[t.index],t.y=te,t.dir=S,t.mode="pen");e.modeIndex=0,e.modeTimer=0,e.frightTimer=0,e.chain=0,e.eatPause=0,e.roundTime=0,e.dotsThisRound=0,e.bonusTimer=0,e.phase="ready",e.phaseTimer=oe}function ke(){const e={dots:new Uint8Array(s*y),dotsLeft:0,totalDots:0,player:{x:0,y:0,dir:v,want:T,chew:0},bugs:[0,1,2,3].map(n=>({index:n,x:0,y:0,dir:S,mode:"pen",frightened:!1})),score:0,lives:ge,level:1,over:!1,phase:"ready",phaseTimer:oe,modeIndex:0,modeTimer:0,frightTimer:0,chain:0,eatPause:0,roundTime:0,dotsThisRound:0,bonusTimer:0,bonusShown:0,popups:[0,1,2].map(()=>({x:0,y:0,value:0,time:0})),sparks:le(48),ticks:0};return ae(e),Z(e),e}function be(e){return e.modeIndex%2===0}function Oe(e,n,t){if(n.mode==="eaten"){t.x=p,t.y=I;return}const o=e.player,a=Math.round(o.x),i=Math.round(o.y),f=o.dir>=0?o.dir:o.want>=0?o.want:T;if(be(e)){t.x=K[n.index],t.y=Q[n.index];return}switch(n.index){case 0:t.x=a,t.y=i;return;case 1:t.x=a+E[f]*4,t.y=i+b[f]*4;return;case 2:{const r=a+E[f]*2,l=i+b[f]*2,d=e.bugs[0];t.x=r*2-Math.round(d.x),t.y=l*2-Math.round(d.y);return}default:{const r=n.x-o.x,l=n.y-o.y;r*r+l*l>64?(t.x=a,t.y=i):(t.x=K[3],t.y=Q[3])}}}const H={x:0,y:0};function De(e,n,t){if(n.mode==="eaten"&&Math.round(n.x)===p&&Math.round(n.y)===I)return v;const o=n.dir>=0?X[n.dir]:v;let a=0;for(let d=0;d<4;d+=1)d!==o&&_(n,d)&&(a+=1);if(a===0)return o>=0&&_(n,o)?o:v;if(n.frightened){let d=Math.floor(t()*a);for(let M=0;M<4;M+=1)if(!(M===o||!_(n,M))){if(d===0)return M;d-=1}}Oe(e,n,H);let i=v,f=1/0;const r=Math.round(n.x),l=Math.round(n.y);for(let d=0;d<4;d+=1){if(d===o||!_(n,d))continue;const M=r+E[d]-H.x,u=l+b[d]-H.y,c=M*M+u*u;c<f&&(f=c,i=d)}return i}function Ne(e){return e.want>=0&&_(e,e.want)?e.want:e.dir>=0&&_(e,e.dir)?e.dir:v}function F(e,n,t,o,a){let i=0;for(let f=0;t>P&&f<8;f+=1){if(Ee(n)){n.x=Math.round(n.x),n.y=Math.round(n.y);const A=o?De(e,o,a):Ne(n);if(A<0)return o||(n.dir=v),i;n.dir=A}const r=E[n.dir]!==0,l=E[n.dir]+b[n.dir],d=r?n.x:n.y,M=l>0?Math.floor(d+P)+1:Math.ceil(d-P)-1,u=Math.abs(M-d),c=Math.min(t,u);r?n.x=u-c<P?M:n.x+l*c:n.y=u-c<P?M:n.y+l*c,t-=c,i+=c,Re(n)}return i}function z(e,n,t,o){const a=n-e.x,i=t-e.y,f=Math.hypot(a,i);return f<=o?(e.x=n,e.y=t,!0):(e.x+=a/f*o,e.y+=i/f*o,Math.abs(a)>Math.abs(i)?e.dir=a<0?T:V:e.dir=i<0?S:N,!1)}function Ae(e){return Math.round(e.y)===Te&&(e.x<3.5||e.x>s-4.5)}function fe(e,n,t,o){let a=e.popups[0];for(const i of e.popups)i.time<a.time&&(a=i);a.x=n,a.y=t,a.value=o,a.time=1}function B(e,n,t,o,a,i){for(let f=0;f<a;f+=1){const r=i()*Math.PI*2,l=20+i()*50;se(e.sparks,g(n),m(t),Math.cos(r)*l,Math.sin(r)*l,.35+i()*.35,2,o)}}function x(e,n){return n===S?e.up:n===T?e.left:n===N?e.down:e.right}function Le(e,n){const t=n.pressed;if(t.up)e.want=S;else if(t.left)e.want=T;else if(t.down)e.want=N;else if(t.right)e.want=V;else if(e.want>=0&&!x(n,e.want)){for(let o=0;o<4;o+=1)if(x(n,o)){e.want=o;break}}e.dir>=0&&e.want===X[e.dir]&&(e.dir=e.want)}function Ce(e,n){const t=e.player,o=(Math.round(t.x)%s+s)%s,a=Math.round(t.y),i=a*s+o,f=e.dots[i];if(f!==0){if(e.dots[i]=0,e.dotsLeft-=1,e.dotsThisRound+=1,f===2){e.score+=ye,e.frightTimer=_e(e.level),e.chain=0;for(const l of e.bugs)l.mode==="active"&&(l.frightened=!0,l.dir>=0&&(l.dir=X[l.dir]));B(e,o,a,"#ffd23f",10,n)}else e.score+=pe;const r=e.totalDots-e.dotsLeft;e.bonusShown<2&&r>=Math.floor(e.totalDots*(e.bonusShown===0?.3:.7))&&(e.bonusShown+=1,e.bonusTimer=Pe),e.dotsLeft===0&&(e.phase="clear",e.phaseTimer=ie)}if(e.bonusTimer>0&&Math.abs(t.x-L)<.6&&Math.abs(t.y-C)<.6){const r=q[Math.min(e.level-1,q.length-1)];e.score+=r,e.bonusTimer=0,fe(e,L,C,r),B(e,L,C,U(e.level),12,n)}}function Ye(e,n,t,o){const a=re(e.level);switch(n.mode){case"pen":(e.roundTime>=ve[n.index]/a||e.dotsThisRound>=Se[n.index])&&(n.mode="leaving");return;case"leaving":{const i=3.5*t;if(Math.abs(n.x-p)>P){z(n,p,n.y,i);return}z(n,p,I,i)&&(n.mode="active",n.dir=T,n.frightened=!1);return}case"entering":z(n,p,te,6*t)&&(n.mode="leaving");return;case"eaten":F(e,n,14*t,n,o),Math.abs(n.x-p)<.15&&Math.abs(n.y-I)<.15&&(n.x=p,n.y=I,n.mode="entering");return;default:{const i=Ae(n)?3.6:n.frightened?4.2:6.8*a;F(e,n,i*t,n,o)}}}function ee(e,n){const t=e.player;for(const o of e.bugs)if(o.mode==="active"&&!(Math.abs(o.x-t.x)>.6||Math.abs(o.y-t.y)>.6))if(o.frightened){const a=j[Math.min(e.chain,j.length-1)];e.chain+=1,e.score+=a,o.frightened=!1,o.mode="eaten",e.eatPause=me,fe(e,o.x,o.y,a),B(e,o.x,o.y,"#3de8ff",10,n)}else{e.lives-=1,e.phase="dying",e.phaseTimer=k;return}}function Ue(e,n,t,o){e.ticks+=1,he(e.sparks,t,0);for(const i of e.popups)i.time=Math.max(0,i.time-t);if(e.over)return;if(Le(e.player,n),e.phase!=="play"){if(e.phaseTimer-=t,e.phase==="dying"&&e.phaseTimer<k*.25&&e.phaseTimer+t>=k*.25&&B(e,e.player.x,e.player.y,"#ffd23f",16,o),e.phaseTimer>0)return;if(e.phase==="dying"){if(e.lives<=0){e.over=!0;return}Z(e)}else e.phase==="clear"?(e.level+=1,ae(e),Z(e)):e.phase="play";return}if(e.eatPause>0){e.eatPause-=t;return}if(e.roundTime+=t,e.bonusTimer>0&&(e.bonusTimer=Math.max(0,e.bonusTimer-t)),e.frightTimer>0){if(e.frightTimer-=t,e.frightTimer<=0){e.frightTimer=0;for(const i of e.bugs)i.frightened=!1}}else if(e.modeTimer+=t,e.modeTimer>=J[e.modeIndex]){e.modeTimer=0,e.modeIndex=Math.min(J.length-1,e.modeIndex+1);for(const i of e.bugs)i.mode==="active"&&i.dir>=0&&(i.dir=X[i.dir])}const a=e.player;if(a.chew+=F(e,a,7.2*re(e.level)*t,null,o),Ce(e,o),e.phase==="play"&&(ee(e,o),!(e.phase!=="play"||e.eatPause>0))){for(const i of e.bugs)Ye(e,i,t,o);ee(e,o)}}const h=10,w=14,R=s*h,Y=y*h+w*2;function g(e){return e*h+h/2}function m(e){return w+e*h+h/2}const O=(()=>{const e=[],n=(o,a)=>o<0||o>=s||a<0||a>=y||D[a][o]==="#";for(let o=0;o<y;o+=1)for(let a=0;a<s;a+=1){if(D[o][a]!=="#")continue;const i=a*h,f=w+o*h,r=i+h,l=f+h;n(a,o-1)||e.push(i,f+2,r,f+2),n(a,o+1)||e.push(i,l-2,r,l-2),n(a-1,o)||e.push(i+2,f,i+2,l),n(a+1,o)||e.push(r-2,f,r-2,l)}return e})(),Be=["#ff4d5e","#ff7ad9","#3de8ff","#ffa13d"],ne=["#ff4d5e","#ffa13d","#ffd23f","#5dea6a","#3de8ff","#4a7dff","#b06bff","#ffffff"];function U(e){return ne[Math.min(e-1,ne.length-1)]}function G(e,n,t,o,a){e.fillStyle=a,e.beginPath(),e.moveTo(n,t-o),e.lineTo(n+o,t-o*.2),e.lineTo(n,t+o),e.lineTo(n-o,t-o*.2),e.closePath(),e.fill(),e.fillStyle="rgba(255,255,255,0.6)",e.beginPath(),e.moveTo(n,t-o),e.lineTo(n+o*.4,t-o*.2),e.lineTo(n,t+o*.2),e.lineTo(n-o*.4,t-o*.2),e.closePath(),e.fill()}function $(e,n,t,o,a,i){const f=a===S?-Math.PI/2:a===T?Math.PI:a===N?Math.PI/2:0;if(e.fillStyle="#ffd23f",e.beginPath(),i>=Math.PI-.01)return;e.moveTo(n,t),e.arc(n,t,o,f+i,f+Math.PI*2-i),e.closePath(),e.fill();const r=n+Math.cos(f-Math.PI/2-.5)*o*.5,l=t+Math.sin(f-Math.PI/2-.5)*o*.5;e.fillStyle="#2b1f05",e.fillRect(Math.round(r-1),Math.round(l-1),2,2)}function Xe(e,n,t,o){const a=t.mode==="pen"&&!o.reduced?Math.sin(o.time*5+t.index*2)*1.5:0,i=g(t.x),f=m(t.y)+a,r=t.dir>=0?E[t.dir]:0,l=t.dir>=0?b[t.dir]:0;if(t.mode!=="eaten"&&t.mode!=="entering"){let d=Be[t.index];if(t.frightened){const u=n.frightTimer;if(d="#2a3cc8",u<2)if(o.reduced){const c=1-u/2;d=`rgb(${Math.round(42+180*c)},${Math.round(60+160*c)},${Math.round(200+40*c)})`}else Math.floor(u*5)%2===0&&(d="#e8ecff")}const M=o.reduced?0:Math.floor((o.time*10+t.index)%2);e.strokeStyle=d,e.lineWidth=1,e.beginPath();for(let u=-1;u<=1;u+=1){const c=i+u*3,A=(u+M)%2===0?1:0;e.moveTo(c,f+3),e.lineTo(c+(u===0?0:u),f+5+A)}if(e.moveTo(i-2,f-4),e.lineTo(i-3,f-6),e.moveTo(i+2,f-4),e.lineTo(i+3,f-6),e.stroke(),e.fillStyle=d,e.beginPath(),e.arc(i,f,4.5,Math.PI,0),e.lineTo(i+4.5,f+3),e.lineTo(i-4.5,f+3),e.closePath(),e.fill(),e.fillRect(Math.round(i-3.5),Math.round(f-7),1,1),e.fillRect(Math.round(i+2.5),Math.round(f-7),1,1),t.frightened){e.strokeStyle="#ffe0f0",e.beginPath(),e.moveTo(i-3,f+1),e.lineTo(i-1.5,f),e.lineTo(i,f+1),e.lineTo(i+1.5,f),e.lineTo(i+3,f+1),e.stroke(),e.fillStyle="#ffe0f0",e.fillRect(Math.round(i-2),Math.round(f-3),1,1),e.fillRect(Math.round(i+1),Math.round(f-3),1,1);return}}e.fillStyle="#0b0f22",e.fillRect(Math.round(i-3.5),Math.round(f-2.5),7,3),e.fillStyle="#e8fbff",e.fillRect(Math.round(i-3+r),Math.round(f-2+l*.5),2,2),e.fillRect(Math.round(i+1+r),Math.round(f-2+l*.5),2,2)}function We(e,n,t){e.fillStyle="#03040c",e.fillRect(0,0,R,Y),e.fillStyle="#0a0f3a";for(let r=0;r<y;r+=1)for(let l=0;l<s;l+=1)D[r][l]==="#"&&e.fillRect(l*h,w+r*h,h,h);let o="#3b6bff";if(n.phase==="clear"){const r=t.reduced?.6:.5+.5*Math.sin((ie-n.phaseTimer)*Math.PI*3);o=`rgb(${Math.round(59+196*r)},${Math.round(107+148*r)},255)`}e.strokeStyle=o,e.lineWidth=1,e.beginPath();for(let r=0;r<O.length;r+=4)e.moveTo(O[r]+.5,O[r+1]+.5),e.lineTo(O[r+2]+.5,O[r+3]+.5);e.stroke(),e.fillStyle="#ff7ad9",e.fillRect(p*h,w+(I+1)*h+4,h,2),e.fillStyle="#ffe6b0";const a=t.reduced?3.5:3+Math.sin(t.time*6)*.8;for(let r=0;r<y;r+=1)for(let l=0;l<s;l+=1){const d=n.dots[r*s+l];d===1?e.fillRect(l*h+4,w+r*h+4,2,2):d===2&&(e.beginPath(),e.arc(g(l),m(r),a,0,Math.PI*2),e.fill())}n.bonusTimer>0&&G(e,g(L),m(C),4,U(n.level)),e.save(),e.beginPath(),e.rect(0,w,R,y*h),e.clip();const i=n.player;if(n.phase==="dying"){const r=1-Math.max(0,n.phaseTimer-k*.25)/(k*.75);n.phaseTimer>k*.25&&$(e,g(i.x),m(i.y),4.5,S,.2+r*(Math.PI-.2))}else if(!n.over){const r=t.idle||t.reduced?t.idle&&!t.reduced?t.time*2:.25:i.chew,l=.08+Math.abs(Math.sin(r*Math.PI))*.6;$(e,g(i.x),m(i.y),4.5,i.dir>=0?i.dir:i.want>=0?i.want:T,l)}if(n.phase!=="dying"&&n.phase!=="clear")for(const r of n.bugs)Xe(e,n,r,t);e.restore(),de(e,n.sparks);for(const r of n.popups)r.time<=0||(e.globalAlpha=Math.min(1,r.time*2),W(e,r.value,g(r.x),m(r.y)-4-(t.reduced?0:(1-r.time)*6),8,"#3de8ff","center",600));e.globalAlpha=1,W(e,n.score,4,2,10,"#ffffff","left",600),G(e,R-24,7,4,U(n.level)),W(e,n.level,R-4,2,10,"#ffd23f","right");const f=n.phase==="dying"?n.lives:n.lives-1;for(let r=0;r<Math.max(0,f);r+=1)$(e,8+r*12,Y-7,4,T,.5);for(let r=0;r<Math.min(n.level,6);r+=1)G(e,R-8-r*11,Y-7,3.5,U(n.level-r));if(n.phase==="ready"&&!t.idle){e.strokeStyle="rgba(255,210,63,0.6)",e.lineWidth=1,e.beginPath();const r=t.reduced?8:7+n.phaseTimer%.8*4;e.arc(g(i.x),m(i.y),r,0,Math.PI*2),e.stroke()}}const Ge={id:"maze-muncher",width:R,height:Y,create:()=>ke(),step:(e,n,t,o)=>Ue(e,n,t,o),draw:(e,n,t)=>We(e,n,t),status:e=>({score:e.score,lives:e.lives,level:e.level,over:e.over})};export{q as BONUS_POINTS,L as BONUS_X,C as BONUS_Y,j as CHAIN_POINTS,ie as CLEAR_TIME,pe as DOT_POINTS,N as DOWN,k as DYING_TIME,p as EXIT_X,I as EXIT_Y,Y as HEIGHT,T as LEFT,D as MAZE,y as MAZE_H,s as MAZE_W,v as NONE,ye as ORB_POINTS,ue as PLAYER_START_X,ce as PLAYER_START_Y,oe as READY_TIME,V as RIGHT,ge as START_LIVES,h as TILE,S as UP,R as WIDTH,Oe as bugTarget,ke as createMaze,Ge as default,We as drawMaze,_e as frightDuration,Ie as isOpen,re as levelSpeed,Ue as stepMaze};diff --git a/dodaios/ui/web/dist/assets/neon-DXVqyv8y.svg b/dodaios/ui/web/dist/assets/neon-Buxn172S.svgsimilarity index 100%rename from dodaios/ui/web/dist/assets/neon-DXVqyv8y.svgrename to dodaios/ui/web/dist/assets/neon-Buxn172S.svgdiff --git a/dodaios/ui/web/dist/assets/obsidian-BnPNDMFS.svg b/dodaios/ui/web/dist/assets/obsidian-DoGKp-BR.svgsimilarity index 100%rename from dodaios/ui/web/dist/assets/obsidian-BnPNDMFS.svgrename to dodaios/ui/web/dist/assets/obsidian-DoGKp-BR.svgdiff --git a/dodaios/ui/web/dist/assets/onedrive-C_SGaMdu.svg b/dodaios/ui/web/dist/assets/onedrive-C6cVDewa.svgsimilarity index 100%rename from dodaios/ui/web/dist/assets/onedrive-C_SGaMdu.svgrename to dodaios/ui/web/dist/assets/onedrive-C6cVDewa.svgdiff --git a/dodaios/ui/web/dist/assets/outlook-C7JHAwlw.svg b/dodaios/ui/web/dist/assets/outlook-B-qerR2g.svgsimilarity index 100%rename from dodaios/ui/web/dist/assets/outlook-C7JHAwlw.svgrename to dodaios/ui/web/dist/assets/outlook-B-qerR2g.svgdiff --git a/dodaios/ui/web/dist/assets/paddleDuel-CYgLpa93.js b/dodaios/ui/web/dist/assets/paddleDuel-CYgLpa93.jsnew file mode 100644index 0000000000..713b20f579--- /dev/null+++ b/dodaios/ui/web/dist/assets/paddleDuel-CYgLpa93.js@@ -0,0 +1 @@+import{r as s}from"./retroGame-jKwLP3oJ.js";import{c as v,d as O,a as w,s as B,b as C,e as d}from"./games1Kit-3UfnKRah.js";const o=320,p=240,c=8,h=p-8,Y=6,u=34,T=14,g=o-14-Y,b=5,n=b/2,N=230,U=420,I=150,V=10,W=380,F=1,G=140,S=.55,A=7,m=1.1,j=2.2,y=6;function k(l){const e=l-1;return{reaction:Math.max(.07,.22-.025*e),speed:Math.min(285,118+22*e),error:Math.max(4,16-2.5*e),predicts:l>=3}}function H(l){l.ballX=o/2,l.ballY=p/2,l.vx=0,l.vy=0,l.spin=0;for(let e=0;e<y;e+=1)l.trail[e*2]=l.ballX,l.trail[e*2+1]=l.ballY}function q(){const l={playerY:p/2,playerVy:0,cpuY:p/2,cpuVy:0,cpuTarget:p/2,cpuThink:0,cpuError:0,ballX:o/2,ballY:p/2,vx:0,vy:0,spin:0,speed:I,serving:!0,serveTimer:m,serveDir:1,rally:0,playerPoints:0,cpuPoints:0,level:1,score:0,over:!1,matchPause:0,pointerTarget:null,lastPointerY:null,flashSide:0,flash:0,shake:0,time:0,trail:new Float32Array(y*2),trailHead:0,sparks:C(120)};return H(l),l}function Z(l,e){l.serving=!1,l.rally=0,l.speed=I+(l.level-1)*8,l.ballX=o/2,l.ballY=p/2+(e()-.5)*80;const a=(e()*2-1)*.45;l.vx=Math.cos(a)*l.speed*l.serveDir,l.vy=Math.sin(a)*l.speed,l.spin=0,l.cpuError=(e()*2-1)*k(l.level).error}function z(l){if(l.vx<=0)return l.ballY;const e=(g-n-l.ballX)/l.vx,a=c+n,t=h-n-a;let i=l.ballY+l.vy*e-a;const r=t*2;return i=(i%r+r)%r,i>t&&(i=r-i),i+a}function X(l,e){const a=k(l.level);if(l.cpuThink-=e,l.cpuThink<=0){l.cpuThink=a.reaction;const E=!l.serving&&l.vx>0;l.cpuTarget=E?(a.predicts?z(l):l.ballY)+l.cpuError:p/2}const t=l.serving||l.vx<=0,i=a.speed*(t?.5:1)*e,r=l.cpuY,f=l.cpuTarget-l.cpuY;Math.abs(f)>2&&(l.cpuY+=v(f,-i,i)),l.cpuY=v(l.cpuY,c+u/2,h-u/2),l.cpuVy=e>0?(l.cpuY-r)/e:0}function J(l,e,a){const t=l.playerY,i=(e.down?1:0)-(e.up?1:0);i!==0&&(l.pointerTarget=null,l.playerY+=i*N*a);const r=e.pointer;if(r&&r.y!==l.lastPointerY&&(l.pointerTarget=r.y),l.lastPointerY=r?r.y:null,i===0&&l.pointerTarget!==null){const f=U*a;l.playerY+=v(l.pointerTarget-l.playerY,-f,f)}l.playerY=v(l.playerY,c+u/2,h-u/2),l.playerVy=a>0?(l.playerY-t)/a:0}function D(l,e,a,t,i){l.rally+=1,l.speed=Math.min(W,l.speed+V);const f=v((l.ballY-a)/(u/2+n),-1,1)*F,E=e?1:-1;l.vx=Math.cos(f)*l.speed*E,l.vy=Math.sin(f)*l.speed+t*.2,l.spin=v(t/250,-1,1),l.ballX=e?T+Y+n:g-n,e&&(l.cpuError=(i()*2-1)*k(l.level).error),d(l.sparks,l.ballX,l.ballY,6+Math.min(10,l.rally),90,e?"#9aa3ff":"#ff8f6b",i,.35,2)}function K(l){const e=Math.hypot(l.vx,l.vy);if(e<1e-6)return;let a=l.vx/e,t=l.vy/e;Math.abs(a)<S&&(a=Math.sign(a||1)*S,t=Math.sign(t||1)*Math.sqrt(1-S*S)),l.vx=a*l.speed,l.vy=t*l.speed}function R(l,e,a){if(d(l.sparks,v(l.ballX,0,o),l.ballY,24,140,e?"#9aa3ff":"#ff8f6b",a,.7,2),e?(l.playerPoints+=1,l.score+=100+10*l.rally,l.flashSide=1):(l.cpuPoints+=1,l.flashSide=-1,l.shake=.3),l.flash=1,l.rally=0,l.serving=!0,l.serveTimer=m,l.serveDir=e?1:-1,H(l),l.playerPoints>=A){l.score+=1e3*l.level,l.level+=1,l.matchPause=j,l.serveDir=-1;for(let t=0;t<4;t+=1)d(l.sparks,o*(.2+t*.2),p/2,12,150,t%2?"#f5f5f0":"#9aa3ff",a,1,2)}else l.cpuPoints>=A&&(l.over=!0)}function Q(l,e,a){const t=Math.max(1,Math.ceil(Math.hypot(l.vx,l.vy)*e/2)),i=e/t;for(let r=0;r<t;r+=1){l.vy+=l.spin*G*i,l.ballX+=l.vx*i,l.ballY+=l.vy*i,l.ballY<c+n?(l.ballY=c+n,l.vy=Math.abs(l.vy),l.spin*=.5,d(l.sparks,l.ballX,c,3,50,"#f5f5f0",a,.25,1)):l.ballY>h-n&&(l.ballY=h-n,l.vy=-Math.abs(l.vy),l.spin*=.5,d(l.sparks,l.ballX,h,3,50,"#f5f5f0",a,.25,1));const f=u/2+n;if(l.vx<0&&l.ballX-n<=T+Y&&l.ballX-n>=T-2&&Math.abs(l.ballY-l.playerY)<=f?D(l,!0,l.playerY,l.playerVy,a):l.vx>0&&l.ballX+n>=g&&l.ballX+n<=g+Y+2&&Math.abs(l.ballY-l.cpuY)<=f&&D(l,!1,l.cpuY,l.cpuVy,a),l.ballX<-b*2){R(l,!1,a);return}if(l.ballX>o+b*2){R(l,!0,a);return}}}function $(l,e,a,t){if(l.time+=a,l.flash=Math.max(0,l.flash-a*2.5),l.shake=Math.max(0,l.shake-a),B(l.sparks,a,40),!l.over){if(J(l,e,a),l.matchPause>0){l.matchPause-=a,X(l,a),l.matchPause<=0&&(l.matchPause=0,l.playerPoints=0,l.cpuPoints=0,l.serving=!0,l.serveTimer=m);return}l.serving&&(l.serveTimer-=a,(l.serveTimer<=0||e.pressed.a)&&Z(l,t)),X(l,a),!l.serving&&(l.spin*=Math.pow(.5,a),K(l),Q(l,a,t),l.trailHead=(l.trailHead+1)%y,l.trail[l.trailHead*2]=l.ballX,l.trail[l.trailHead*2+1]=l.ballY)}}const _=["0","1","2","3","4","5","6","7","8","9"],M="#9aa3ff",P="#ff8f6b",x="#e8e4d8";function L(l,e,a,t){const i=Math.round(a-u/2);l.globalAlpha=.22,l.fillStyle=t,l.fillRect(e-2,i-2,Y+4,u+4),l.globalAlpha=1,l.fillRect(e,i,Y,u),l.fillStyle="#ffffff",l.fillRect(e+1,i+1,1,u-2)}function ll(l,e,a){if(l.save(),!a.reduced&&e.shake>0){const r=e.shake*6;l.translate(Math.round(Math.sin(e.time*77)*r),Math.round(Math.cos(e.time*61)*r))}l.fillStyle="#0a0b10",l.fillRect(-8,-8,o+16,p+16),!a.reduced&&e.flash>0&&e.flashSide!==0&&(l.globalAlpha=e.flash*.16,l.fillStyle=e.flashSide>0?M:P,l.fillRect(e.flashSide>0?o/2:0,0,o/2,p),l.globalAlpha=1),l.fillStyle=x,l.fillRect(0,c-2,o,2),l.fillRect(0,h,o,2),l.globalAlpha=.35;for(let r=c+4;r<h-4;r+=12)l.fillRect(o/2-1,r,2,6);l.font=s(28,600),l.textAlign="center",l.textBaseline="top",l.fillStyle=M,l.fillText(_[Math.min(9,e.playerPoints)],o/2-36,c+8),l.fillStyle=P,l.fillText(_[Math.min(9,e.cpuPoints)],o/2+36,c+8),l.globalAlpha=.6;const t=Math.min(10,e.level);for(let r=0;r<t;r+=1)l.fillRect(o/2+36-t*2+r*4,c+42,2,2);l.globalAlpha=1,L(l,T,e.playerY,M),L(l,g,e.cpuY,P);const i=e.spin>.15?M:e.spin<-.15?P:"#f5f5f0";if(!e.serving&&e.matchPause<=0){for(let r=1;r<y;r+=1){const f=(e.trailHead-r+y)%y;l.globalAlpha=.28*(1-r/y),l.fillStyle=i,l.fillRect(Math.round(e.trail[f*2]-n),Math.round(e.trail[f*2+1]-n),b,b)}l.globalAlpha=1}e.matchPause<=0&&(l.fillStyle="#f5f5f0",l.fillRect(Math.round(e.ballX-n),Math.round(e.ballY-n),b,b),e.serving&&!a.idle&&(l.strokeStyle=e.serveDir>0?M:P,l.lineWidth=1,l.beginPath(),l.arc(e.ballX,e.ballY,8,-Math.PI/2,-Math.PI/2+Math.PI*2*v(e.serveTimer/m,0,1)),l.stroke())),O(l,e.sparks),l.restore(),w(l,o,p,.1)}const rl={id:"paddle-duel",width:o,height:p,pointer:!0,create:()=>q(),step:$,draw:ll,status:l=>({score:l.score,level:l.level,over:l.over,won:!1})};export{b as BALL,h as BOTTOM,g as CPU_X,p as HEIGHT,V as HIT_SPEEDUP,j as MATCH_PAUSE,W as MAX_BALL_SPEED,u as PADDLE_H,Y as PADDLE_W,N as PLAYER_SPEED,T as PLAYER_X,m as SERVE_DELAY,I as SERVE_SPEED,c as TOP,o as WIDTH,A as WIN_POINTS,k as cpuSkill,rl as default,z as predictY,Z as serve};diff --git a/dodaios/ui/web/dist/assets/postgresql-D-vtYnT7.svg b/dodaios/ui/web/dist/assets/postgresql-CrKK9N4f.svgsimilarity index 100%rename from dodaios/ui/web/dist/assets/postgresql-D-vtYnT7.svgrename to dodaios/ui/web/dist/assets/postgresql-CrKK9N4f.svgdiff --git a/dodaios/ui/web/dist/assets/progressionApi-ju3oLA4e.js b/dodaios/ui/web/dist/assets/progressionApi-ju3oLA4e.jsdeleted file mode 100644index 2c843d123c..0000000000--- a/dodaios/ui/web/dist/assets/progressionApi-ju3oLA4e.js+++ /dev/null@@ -1 +0,0 @@-const m=["uniform","headwear","decoration"],g=["uniform_service_shirt","uniform_field_jacket","uniform_service_greens","uniform_dress_blues","uniform_mess_dress","headwear_patrol_cap","headwear_garrison_cap","headwear_beret","headwear_service_cap","decoration_ribbon_bar","decoration_ribbon_rack","decoration_aiguillette","decoration_medals"],v=["private","private_second_class","private_first_class","specialist","corporal","sergeant","staff_sergeant","sergeant_first_class","master_sergeant","first_sergeant","sergeant_major","command_sergeant_major","sergeant_major_of_the_army","second_lieutenant","first_lieutenant","captain","major","lieutenant_colonel","colonel","brigadier_general","major_general","lieutenant_general","general","general_of_the_army"],f={private:{grade:"E-1",tier:"enlisted"},private_second_class:{grade:"E-2",tier:"enlisted"},private_first_class:{grade:"E-3",tier:"enlisted"},specialist:{grade:"E-4",tier:"enlisted"},corporal:{grade:"E-4",tier:"nco"},sergeant:{grade:"E-5",tier:"nco"},staff_sergeant:{grade:"E-6",tier:"nco"},sergeant_first_class:{grade:"E-7",tier:"nco"},master_sergeant:{grade:"E-8",tier:"nco"},first_sergeant:{grade:"E-8",tier:"nco"},sergeant_major:{grade:"E-9",tier:"nco"},command_sergeant_major:{grade:"E-9",tier:"nco"},sergeant_major_of_the_army:{grade:"E-9",tier:"nco"},second_lieutenant:{grade:"O-1",tier:"officer"},first_lieutenant:{grade:"O-2",tier:"officer"},captain:{grade:"O-3",tier:"officer"},major:{grade:"O-4",tier:"officer"},lieutenant_colonel:{grade:"O-5",tier:"officer"},colonel:{grade:"O-6",tier:"officer"},brigadier_general:{grade:"O-7",tier:"general"},major_general:{grade:"O-8",tier:"general"},lieutenant_general:{grade:"O-9",tier:"general"},general:{grade:"O-10",tier:"general"},general_of_the_army:{grade:"O-11",tier:"general"}};function d(e){return typeof e=="string"&&e in f}function j(e){return d(e)?e:"private"}function k(e,r){let a="private";for(const i of e??[])r>=i.level&&d(i.title)&&(a=i.title);return a}function x(e){return e.slice(0,e.indexOf("_"))}function p(e){return typeof e=="string"&&g.includes(e)}const n=(e,r=0)=>typeof e=="number"&&Number.isFinite(e)?e:r,s=e=>typeof e=="string"?e:"",l=e=>e==="agent"||e==="pet"?e:"person";function u(e){const r=t=>Array.isArray(t)?t.filter(o=>!!o&&typeof o=="object"):[],a=e.titles&&typeof e.titles=="object"?e.titles:{},i=t=>r(a[t]).map(o=>({level:n(o.level,1),title:s(o.title)}));return{subjects:r(e.subjects).map(t=>({subjectId:s(t.subject_id),kind:l(t.kind),xp:n(t.xp),level:n(t.level,1),xpIntoLevel:n(t.xp_into_level),xpForNext:n(t.xp_for_next),title:s(t.title)})),petId:s(e.pet_id)||"gigi",recent:r(e.recent).map(t=>({seq:n(t.seq),subjectId:s(t.subject_id),kind:l(t.kind),source:s(t.source),xp:n(t.xp),levelBefore:n(t.level_before,1),levelAfter:n(t.level_after,1),tsMs:n(t.ts_ms)})),latestSeq:n(e.latest_seq),maxLevel:n(e.max_level,50),levelXp:Array.isArray(e.level_xp)?e.level_xp.map(t=>n(t)):[0],rules:r(e.rules).map(t=>({source:s(t.source),kind:l(t.kind),xp:n(t.xp),trigger:t.trigger==="world"?"world":"server",cooldownS:n(t.cooldown_s),dailyCap:n(t.daily_cap)})),rewards:r(e.rewards).filter(t=>p(t.reward_id)).map(t=>{const o=t.levels&&typeof t.levels=="object"?t.levels:{},c=_=>typeof o[_]=="number"?o[_]:null;return{rewardId:t.reward_id,slot:s(t.slot),levels:{person:c("person"),agent:c("agent"),pet:c("pet")}}}),titles:{person:i("person"),agent:i("agent"),pet:i("pet")},looks:Object.fromEntries(r(e.looks).filter(t=>s(t.look_id)).map(t=>[s(t.look_id),n(t.agent,1)]))}}function b(e){if(!e||typeof e!="object")return null;const r=e,a=s(r.subject_id);return a?{seq:n(r.seq),subjectId:a,kind:l(r.subject_kind),source:s(r.xp_source),xp:n(r.xp),totalXp:n(r.total_xp),level:n(r.level,1),previousLevel:n(r.previous_level,1),title:s(r.title),unlocked:Array.isArray(r.unlocked)?r.unlocked.filter(p):[],unlockedLooks:Array.isArray(r.unlocked_looks)?r.unlocked_looks.filter(i=>typeof i=="string"):[]}:null}async function O(e=0){const r=await fetch(`/api/progression${e>0?`?after_seq=${e}`:""}`);if(!r.ok)throw new Error(`HTTP ${r.status}`);return u(await r.json())}async function E(e,r=""){try{const a=await fetch("/api/progression/actions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,ref:r})});a.ok||console.warn("Level action refused",e,r,a.status)}catch(a){console.debug("Level action not reported",e,a)}}const h=e=>`agent:${e}`,y=e=>`pet:${e}`,A="person";export{A as P,f as R,m as S,v as T,h as a,k as b,E as c,g as d,b as e,O as f,d as i,y as p,j as r,x as s};diff --git a/dodaios/ui/web/dist/assets/retroGame-jKwLP3oJ.js b/dodaios/ui/web/dist/assets/retroGame-jKwLP3oJ.jsnew file mode 100644index 0000000000..c79db043ff--- /dev/null+++ b/dodaios/ui/web/dist/assets/retroGame-jKwLP3oJ.js@@ -0,0 +1 @@+const t=.016666666666666666,s="'Pixelify Sans', ui-monospace, monospace";function e(o,n=400){return`${n} ${o}px ${s}`}export{t as R,e as r};diff --git a/dodaios/ui/web/dist/assets/salesforce-B5hPJLMG.svg b/dodaios/ui/web/dist/assets/salesforce-DqKqehgY.svgsimilarity index 100%rename from dodaios/ui/web/dist/assets/salesforce-B5hPJLMG.svgrename to dodaios/ui/web/dist/assets/salesforce-DqKqehgY.svgdiff --git a/dodaios/ui/web/dist/assets/teams-DisLtML7.svg b/dodaios/ui/web/dist/assets/teams-DlMZ5N6j.svgsimilarity index 100%rename from dodaios/ui/web/dist/assets/teams-DisLtML7.svgrename to dodaios/ui/web/dist/assets/teams-DlMZ5N6j.svgdiff --git a/dodaios/ui/web/dist/assets/vscode-zVAWFD4C.svg b/dodaios/ui/web/dist/assets/vscode-BC_h-9TH.svgsimilarity index 100%rename from dodaios/ui/web/dist/assets/vscode-zVAWFD4C.svgrename to dodaios/ui/web/dist/assets/vscode-BC_h-9TH.svgdiff --git a/dodaios/ui/web/dist/assets/xai-DOoawZUy.js b/dodaios/ui/web/dist/assets/xai-CKxq66Rb.jssimilarity index 99%rename from dodaios/ui/web/dist/assets/xai-DOoawZUy.jsrename to dodaios/ui/web/dist/assets/xai-CKxq66Rb.jsindex 91a9c992fc..67e16a1322 100644--- a/dodaios/ui/web/dist/assets/xai-DOoawZUy.js+++ b/dodaios/ui/web/dist/assets/xai-CKxq66Rb.js@@ -1 +1 @@-const e="/assets/antigravity-8EbLmxw8.svg",a="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M6.763%2010.036c0%20.296.032.535.088.71.064.176.144.368.256.576.04.063.056.127.056.183%200%20.08-.048.16-.152.24l-.503.335a.383.383%200%200%201-.208.072c-.08%200-.16-.04-.239-.112a2.47%202.47%200%200%201-.287-.375%206.18%206.18%200%200%201-.248-.471c-.622.734-1.405%201.101-2.347%201.101-.67%200-1.205-.191-1.596-.574-.391-.384-.59-.894-.59-1.533%200-.678.239-1.23.726-1.644.487-.415%201.133-.623%201.955-.623.272%200%20.551.024.846.064.296.04.6.104.918.176v-.583c0-.607-.127-1.03-.375-1.277-.255-.248-.686-.367-1.3-.367-.28%200-.568.031-.863.103-.295.072-.583.16-.862.272a2.287%202.287%200%200%201-.28.104.488.488%200%200%201-.127.023c-.112%200-.168-.08-.168-.247v-.391c0-.128.016-.224.056-.28a.597.597%200%200%201%20.224-.167c.279-.144.614-.264%201.005-.36a4.84%204.84%200%200%201%201.246-.151c.95%200%201.644.216%202.091.647.439.43.662%201.085.662%201.963v2.586zm-3.24%201.214c.263%200%20.534-.048.822-.144.287-.096.543-.271.758-.51.128-.152.224-.32.272-.512.047-.191.08-.423.08-.694v-.335a6.66%206.66%200%200%200-.735-.136%206.02%206.02%200%200%200-.75-.048c-.535%200-.926.104-1.19.32-.263.215-.39.518-.39.917%200%20.375.095.655.295.846.191.2.47.296.838.296zm6.41.862c-.144%200-.24-.024-.304-.08-.064-.048-.12-.16-.168-.311L7.586%205.55a1.398%201.398%200%200%201-.072-.32c0-.128.064-.2.191-.2h.783c.151%200%20.255.025.31.08.065.048.113.16.16.312l1.342%205.284%201.245-5.284c.04-.16.088-.264.151-.312a.549.549%200%200%201%20.32-.08h.638c.152%200%20.256.025.32.08.063.048.12.16.151.312l1.261%205.348%201.381-5.348c.048-.16.104-.264.16-.312a.52.52%200%200%201%20.311-.08h.743c.127%200%20.2.065.2.2%200%20.04-.009.08-.017.128a1.137%201.137%200%200%201-.056.2l-1.923%206.17c-.048.16-.104.263-.168.311a.51.51%200%200%201-.303.08h-.687c-.151%200-.255-.024-.32-.08-.063-.056-.119-.16-.15-.32l-1.238-5.148-1.23%205.14c-.04.16-.087.264-.15.32-.065.056-.177.08-.32.08zm10.256.215c-.415%200-.83-.048-1.229-.143-.399-.096-.71-.2-.918-.32-.128-.071-.215-.151-.247-.223a.563.563%200%200%201-.048-.224v-.407c0-.167.064-.247.183-.247.048%200%20.096.008.144.024.048.016.12.048.2.08.271.12.566.215.878.279.319.064.63.096.95.096.502%200%20.894-.088%201.165-.264a.86.86%200%200%200%20.415-.758.777.777%200%200%200-.215-.559c-.144-.151-.416-.287-.807-.415l-1.157-.36c-.583-.183-1.014-.454-1.277-.813a1.902%201.902%200%200%201-.4-1.158c0-.335.073-.63.216-.886.144-.255.335-.479.575-.654.24-.184.51-.32.83-.415.32-.096.655-.136%201.006-.136.175%200%20.359.008.535.032.183.024.35.056.518.088.16.04.312.08.455.127.144.048.256.096.336.144a.69.69%200%200%201%20.24.2.43.43%200%200%201%20.071.263v.375c0%20.168-.064.256-.184.256a.83.83%200%200%201-.303-.096%203.652%203.652%200%200%200-1.532-.311c-.455%200-.815.071-1.062.223-.248.152-.375.383-.375.71%200%20.224.08.416.24.567.159.152.454.304.877.44l1.134.358c.574.184.99.44%201.237.767.247.327.367.702.367%201.117%200%20.343-.072.655-.207.926-.144.272-.336.511-.583.703-.248.2-.543.343-.886.447-.36.111-.734.167-1.142.167zM21.698%2016.207c-2.626%201.94-6.442%202.969-9.722%202.969-4.598%200-8.74-1.7-11.87-4.526-.247-.223-.024-.527.272-.351%203.384%201.963%207.559%203.153%2011.877%203.153%202.914%200%206.114-.607%209.06-1.852.439-.2.814.287.383.607zM22.792%2014.961c-.336-.43-2.22-.207-3.074-.103-.255.032-.295-.192-.063-.36%201.5-1.053%203.967-.75%204.254-.399.287.36-.08%202.826-1.485%204.007-.215.184-.423.088-.327-.151.32-.79%201.03-2.57.695-2.994z'/%3e%3c/svg%3e",c="data:image/svg+xml,%3csvg%20width='416'%20height='426'%20viewBox='0%200%20416%20426'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20width='415.632'%20height='425.055'%20fill='%23004E23'/%3e%3cpath%20d='M317.301%20182.114V237.681H289.766L286.153%20232.679L277.49%20220.689L271.591%20212.526L261.508%20198.571L264.557%20212.526L268.964%20232.679L270.056%20237.681L273.37%20252.833L277.49%20271.685L277.774%20272.987L282.178%20293.138L286.585%20313.292H224.406L219.999%20293.138L217.769%20282.929L215.595%20272.987L211.189%20252.833L207.877%20237.681L204.565%20252.833L200.158%20272.987L197.864%20283.481L195.754%20293.138L191.347%20313.292H129.048L133.455%20293.138L137.738%20273.533V273.53L138.143%20273.231L138.475%20272.987L158.05%20258.489L165.69%20252.833L177.957%20243.747L186.149%20237.681H98.332V182.114H157.722L158.05%20180.617L159.887%20172.221L164.291%20152.067L168.698%20131.914L173.102%20111.763H242.531L246.935%20131.914L247.858%20136.131L237.676%20143.671L226.336%20152.067L217.769%20158.413L199.123%20172.221L197.864%20173.152L185.764%20182.114H317.301Z'%20fill='%23F9F9F8'/%3e%3c/svg%3e",l="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eClaude%3c/title%3e%3cpath%20d='M4.709%2015.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0%2011.784l.055-.352.48-.321.686.06%201.52.103%202.278.158%201.652.097%202.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686%201.908%201.476%202.491%201.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97%202.97%200%2001-.104-.729L6.283.134%206.696%200l.996.134.42.364.62%201.414%201.002%202.229%201.555%203.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286%201.851-.559%202.903-.364%201.942h.212l.243-.242.985-1.306%201.652-2.064.73-.82.85-.904.547-.431h1.033l.76%201.129-.34%201.166-1.064%201.347-.881%201.142-1.264%201.7-.79%201.36.073.11.188-.02%202.856-.606%201.543-.28%201.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061%201.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093%201.068%202.006%201.81%202.509%202.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649%202.345%203.521.122%201.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674%207.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434%201.967-2.18%202.945-1.726%201.845-.414.164-.717-.37.067-.662.401-.589%202.388-3.036%201.44-1.882.93-1.086-.006-.158h-.055L4.132%2018.56l-1.13.146-.487-.456.061-.746.231-.243%201.908-1.312-.006.006z'%20fill='%23D97757'%20fill-rule='nonzero'%3e%3c/path%3e%3c/svg%3e",t="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M11.336%201.816a6.95%206.95%200%200%200-6.879%205.889%207.88%207.88%200%200%201%202.24-.412A4.855%204.855%200%200%201%2011.33%203.92a4.853%204.853%200%200%201%203.45%201.44%204.793%204.793%200%200%201%201.197%202.01%207.633%207.633%200%200%201%20.875-.067h.33a8.313%208.313%200%200%201%20.976.076%206.95%206.95%200%200%200-6.822-5.564zM6.99%208.224A6.983%206.983%200%200%200%200%2015.2a6.978%206.978%200%200%200%206.977%206.976%206.966%206.966%200%200%200%204.933-2.03%20691.43%20691.43%200%200%200%201.56-1.581l-1.488-1.488-1.55%201.582a4.86%204.86%200%200%201-3.452%201.436A4.881%204.881%200%200%201%202.104%2015.2a4.877%204.877%200%200%201%204.876-4.871%204.855%204.855%200%200%201%202.819.904l.04-.043%201.466-1.465A6.969%206.969%200%200%200%206.99%208.224zm10.04%200a6.966%206.966%200%200%200-4.936%202.047l-1.59%201.574%201.488%201.489%201.58-1.584A4.88%204.88%200%200%201%2021.9%2015.2a4.881%204.881%200%200%201-4.877%204.882%204.858%204.858%200%200%201-2.83-.914l-.045.046s-1.078%201.096-1.437%201.467a6.95%206.95%200%200%200%204.312%201.504A6.983%206.983%200%200%200%2024%2015.205a6.95%206.95%200%200%200-2.04-4.933%206.962%206.962%200%200%200-4.93-2.047z'/%3e%3c/svg%3e",s="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M12.04%200C5.408-.02.005%205.37.005%2011.992h4.638c0-4.923%204.882-8.731%2010.064-6.855a6.95%206.95%200%20014.147%204.148c1.889%205.177-1.924%2010.055-6.84%2010.064v-4.61H7.391v4.623h4.61V24c7.86%200%2013.967-7.588%2011.397-15.83-1.115-3.59-3.985-6.446-7.575-7.575A12.8%2012.8%200%200012.039%200zM7.39%2019.362H3.828v3.564H7.39zm-3.563%200v-2.978H.85v2.978z'/%3e%3c/svg%3e",o="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eElevenLabs%3c/title%3e%3cpath%20d='M5%200h5v24H5V0zM14%200h5v24h-5V0z'%3e%3c/path%3e%3c/svg%3e",v="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eGemini%3c/title%3e%3cpath%20d='M20.616%2010.835a14.147%2014.147%200%2001-4.45-3.001%2014.111%2014.111%200%2001-3.678-6.452.503.503%200%2000-.975%200%2014.134%2014.134%200%2001-3.679%206.452%2014.155%2014.155%200%2001-4.45%203.001c-.65.28-1.318.505-2.002.678a.502.502%200%20000%20.975c.684.172%201.35.397%202.002.677a14.147%2014.147%200%20014.45%203.001%2014.112%2014.112%200%20013.679%206.453.502.502%200%2000.975%200c.172-.685.397-1.351.677-2.003a14.145%2014.145%200%20013.001-4.45%2014.113%2014.113%200%20016.453-3.678.503.503%200%20000-.975%2013.245%2013.245%200%2001-2.003-.678z'%20fill='%233186FF'%3e%3c/path%3e%3cpath%20d='M20.616%2010.835a14.147%2014.147%200%2001-4.45-3.001%2014.111%2014.111%200%2001-3.678-6.452.503.503%200%2000-.975%200%2014.134%2014.134%200%2001-3.679%206.452%2014.155%2014.155%200%2001-4.45%203.001c-.65.28-1.318.505-2.002.678a.502.502%200%20000%20.975c.684.172%201.35.397%202.002.677a14.147%2014.147%200%20014.45%203.001%2014.112%2014.112%200%20013.679%206.453.502.502%200%2000.975%200c.172-.685.397-1.351.677-2.003a14.145%2014.145%200%20013.001-4.45%2014.113%2014.113%200%20016.453-3.678.503.503%200%20000-.975%2013.245%2013.245%200%2001-2.003-.678z'%20fill='url(%23lobe-icons-gemini-0-_R_0_)'%3e%3c/path%3e%3cpath%20d='M20.616%2010.835a14.147%2014.147%200%2001-4.45-3.001%2014.111%2014.111%200%2001-3.678-6.452.503.503%200%2000-.975%200%2014.134%2014.134%200%2001-3.679%206.452%2014.155%2014.155%200%2001-4.45%203.001c-.65.28-1.318.505-2.002.678a.502.502%200%20000%20.975c.684.172%201.35.397%202.002.677a14.147%2014.147%200%20014.45%203.001%2014.112%2014.112%200%20013.679%206.453.502.502%200%2000.975%200c.172-.685.397-1.351.677-2.003a14.145%2014.145%200%20013.001-4.45%2014.113%2014.113%200%20016.453-3.678.503.503%200%20000-.975%2013.245%2013.245%200%2001-2.003-.678z'%20fill='url(%23lobe-icons-gemini-1-_R_0_)'%3e%3c/path%3e%3cpath%20d='M20.616%2010.835a14.147%2014.147%200%2001-4.45-3.001%2014.111%2014.111%200%2001-3.678-6.452.503.503%200%2000-.975%200%2014.134%2014.134%200%2001-3.679%206.452%2014.155%2014.155%200%2001-4.45%203.001c-.65.28-1.318.505-2.002.678a.502.502%200%20000%20.975c.684.172%201.35.397%202.002.677a14.147%2014.147%200%20014.45%203.001%2014.112%2014.112%200%20013.679%206.453.502.502%200%2000.975%200c.172-.685.397-1.351.677-2.003a14.145%2014.145%200%20013.001-4.45%2014.113%2014.113%200%20016.453-3.678.503.503%200%20000-.975%2013.245%2013.245%200%2001-2.003-.678z'%20fill='url(%23lobe-icons-gemini-2-_R_0_)'%3e%3c/path%3e%3cdefs%3e%3clinearGradient%20gradientUnits='userSpaceOnUse'%20id='lobe-icons-gemini-0-_R_0_'%20x1='7'%20x2='11'%20y1='15.5'%20y2='12'%3e%3cstop%20stop-color='%2308B962'%3e%3c/stop%3e%3cstop%20offset='1'%20stop-color='%2308B962'%20stop-opacity='0'%3e%3c/stop%3e%3c/linearGradient%3e%3clinearGradient%20gradientUnits='userSpaceOnUse'%20id='lobe-icons-gemini-1-_R_0_'%20x1='8'%20x2='11.5'%20y1='5.5'%20y2='11'%3e%3cstop%20stop-color='%23F94543'%3e%3c/stop%3e%3cstop%20offset='1'%20stop-color='%23F94543'%20stop-opacity='0'%3e%3c/stop%3e%3c/linearGradient%3e%3clinearGradient%20gradientUnits='userSpaceOnUse'%20id='lobe-icons-gemini-2-_R_0_'%20x1='3.5'%20x2='17.5'%20y1='13.5'%20y2='12'%3e%3cstop%20stop-color='%23FABC12'%3e%3c/stop%3e%3cstop%20offset='.46'%20stop-color='%23FABC12'%20stop-opacity='0'%3e%3c/stop%3e%3c/linearGradient%3e%3c/defs%3e%3c/svg%3e",g="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eGoogleCloud%3c/title%3e%3cpath%20d='M15.961%207.327l2.086-2.086.14-.879C14.384.905%208.34%201.297%204.913%205.18A9.643%209.643%200%20002.88%208.991l.747-.105%204.172-.688.322-.33c1.856-2.038%204.994-2.312%207.137-.578l.703.037z'%20fill='%23EA4335'%3e%3c/path%3e%3cpath%20d='M21.02%208.93a9.399%209.399%200%2000-2.834-4.568L15.258%207.29a5.204%205.204%200%20011.91%204.129v.52a2.606%202.606%200%20012.607%202.605c0%201.44-1.167%202.577-2.606%202.577h-5.22l-.512.556v3.126l.513.49h5.219c3.743.03%206.802-2.952%206.83-6.695a6.778%206.778%200%2000-2.98-5.668z'%20fill='%234285F4'%3e%3c/path%3e%3cpath%20d='M6.738%2021.293h5.212v-4.172H6.738c-.371%200-.731-.08-1.069-.234l-.74.227-2.1%202.086-.183.71a6.763%206.763%200%20004.092%201.383z'%20fill='%2334A853'%3e%3c/path%3e%3cpath%20d='M6.738%207.759A6.778%206.778%200%20002.646%2019.91l3.023-3.023a2.606%202.606%200%20113.448-3.448l3.023-3.023a6.771%206.771%200%2000-5.402-2.657z'%20fill='%23FBBC05'%3e%3c/path%3e%3c/svg%3e",i="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eGroq%3c/title%3e%3cpath%20d='M12.036%202c-3.853-.035-7%203-7.036%206.781-.035%203.782%203.055%206.872%206.908%206.907h2.42v-2.566h-2.292c-2.407.028-4.38-1.866-4.408-4.23-.029-2.362%201.901-4.298%204.308-4.326h.1c2.407%200%204.358%201.915%204.365%204.278v6.305c0%202.342-1.944%204.25-4.323%204.279a4.375%204.375%200%2001-3.033-1.252l-1.851%201.818A7%207%200%200012.029%2022h.092c3.803-.056%206.858-3.083%206.879-6.816v-6.5C18.907%204.963%2015.817%202%2012.036%202z'%3e%3c/path%3e%3c/svg%3e",n="/assets/hermes-CiVWQ9gt.svg",p="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M0%200v24h24V0H0zm4.602%204.025h2.244c.509%200%20.716.215.716.717v5.64h8.883v-5.64c0-.509.215-.717.717-.717h2.229c.5%200%20.71.23.724.717v14.516c0%20.509-.215.717-.717.717h-2.23c-.51%200-.717-.215-.717-.717v-5.735H7.562v5.735c0%20.516-.215.717-.716.717H4.602c-.51%200-.717-.208-.717-.717V4.742c0-.509.207-.717.717-.717z'/%3e%3c/svg%3e",h="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M16.415%200v7.16l5.785%203.384V2.949L16.415%200ZM1.8%200v11.237h18.815L14.89%208.09l-7.457-.003V3.024L1.8%200Zm14.615%2020.894v-5.019l-7.514-.005c.007.033-5.82-3.197-5.82-3.197l19.119.091V24l-5.785-3.106ZM1.8%2013.551v7.343l5.633%202.949v-6.988L1.8%2013.551Z'/%3e%3c/svg%3e",w="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAALQAAAC0CAYAAAA9zQYyAAAACXBIWXMAAAsTAAALEwEAmpwYAAAJoklEQVR4nO2dMW9URxSF7y+AH4BxnyDXUSSXIAp3RETKNiBBERcgQcNKRIIqFg1d7MalaegSN3QgGlcuXLhysxI/YH/CRGelEasFr9m3M+/cd+cURxHg2Gfv+97xzLy588zMkqQaWJwa0A1IqkES0IJAQWBKaEFg4WtANyCpBklACwIFgSmhBYGFrwHdgKQaJAEtCBQEpoQWBBa+BnQDkmqQBLQgUBCYEloQWPga0A1IqkES0IJAQWBKaEFg4WtANyCpBklACwIFgSmhBYGFrwHdgKQaJAEtCBQEpoQWBBa+BnQDkmqQBLQgUBCYEloQWPga0A1IqkES0IJAQWBKaEFg4WtANyCpBklACwIFgSmhBYGFrwHdgKQaJAEtCBQEpoQWBBa+BnQDTen6tWvpn7dv0vH7o9l/dx8/TNu//jL7e7Y3iyG6gaa0c/dOmn65+K4+f/hvBjkAZ/u04YpuoBkBVCTzZUAv6uhwP43u36P7tmGJbiC1nsxX6ezk0yy5N29u0D+H+RfdQDPa3LiR9l69TGcnHzvDLbBNQPsDe6Mz0Fl/v3qpxLbv1pd/gVvSn48epsn56dpA56GIxtgmoFkwv3j2pAjIGobYsjrzU6sFlRhmXJXWW7d+on9OB6IbaGbJribQWbuPHtA/K1l0A82scPQB9PTLxWxow/68RNENNDMZ7AvoadtQ0w00IYxx+wR6+uWi1RUQuoHwwsajUkt1q2hyftriRJFuoAkBrHWeEHbV2cmn1nby0Q0MRthLsXP39mzLJ57U4TF01vj50yvBwcQQX9c32EeH+/Ta9Si6AbcCoBiHAtjFIQOgxN/j31fdNJTB7hPqnbu36fXsSXQDLh+CIIEXIcafAWLerwzgATP+/D1dBTrA3n/7prfx9PU2hh50A+66SS7bfA+Y8e9I5x+d5OHr9l6/XPpzkfJ9DEPGz5/Sa9yD6AbCbBrKw5AubVVI69pQT85PW9ihRzdAFaBbpYtkUfh/AXAJUODl6PBAKW0CuvNYucsDjwzxfAKXTL7Lhj0aS5sSetm68KpDDICchxIY92LiiLE1ulBKN7bWhHoceyxNN9C7/rh/byUAAG1euchLeIAbUNdaOcD3xc+tldLm4DpUEt2A622cWKGY79YGDH3tkcBEsdYj8+24RyXQDfQ6Zl4FEAwlMKyYH3L0vZa7Trf49IoblX09KoluoDetMgEE+PNfzxx3rrMKM71E+Gzs61FJdAPu+/nYk6hazQGbMdek6QZc9/O9Ozyg+4dqPCLfffyQ/rkqiG6gurougeHJ3ebNG3T/tXoS99++oX+uCqIbcJvO3jo+So+lP3/4l/6ZKohuwGU6Ax6290VhiFAS6EnM9Wi6gWrCElukddoak8PNeBNDuoFqwpCh69iZ7f0ylX7QshWv55BuoJq67lzzPPsvvRtvJ14nC92AuzTznFp7r/8qCvTo99/on6mw6AaqaOvWzyEnSqV7EUcCehjqugfC4+pGiXnBVEAPW11/Nb9z3vIvoO2qGvEvkqfJk/enZ6WB3tGkcBjq+lTNO9Clx9DbDtfb1xTdQBV17aD2DnTpVY4txys6HUU3UEVRgS69Dn093uEzdAOugPa+YafksbwT50uUHUU34Apoz0dmlX5Py7HzJcqOohuoonVOIfI6USq9wjGOeZwB3UAVrXMEgNcG0tJvAdh2euOuKboBd5Mnj2PL0uk8jTkhhOgGXC5veetWKZ3OxzHHzxDdgMtE89TmX+MNtCNnN2xB0Q242m3nbdKER9OlYZ7OOlV8NP9WEN2A6+4O5pO0LgdKTgNswFpTdAOun6ph6MHou6sF8zTu6kYW3YD7Lum+oS7xNoHpAPslC4luYBAvvOwDavidPxyyhkZxJ4NZdAODOZwFN8fuoweDS+VpO+kM0Q0M7ggtpHWJpEMiY1jU13vAR/HTOT7QtY6jzWADyFVWQpa9zLOm9p1vixXQ5MfGi8qvqcAYGOvX88Lf4fXEjHd9T50dOimgnaf0EDRqY6iRRTcw2LH0ELTndOeggC5QhNovtfSms5OPUXfULRPdwCDXpb3rrK1xc5tAtzL0mJyfRuzmFtB9HQXgSZO2YYboBiiKOJ6eCOZ2ga756mHWmHmr7WTOohugQs162FFSuDEbnQAmAR0sqbHO3ODSXBLQS4oAIIY2UcR4OeDJoUlAOz7Zs+ZGI6WyXXYd6XeUu1eneR1XYz9K8PapVEB0Ay6FDT1ewBbIJqAjgC2QTQldM7H7eBgDiNE0oDGyacjR1xgbcGNiViK58T3QvSKIrdQ14o9Xhw44JmoAcm/WmXIwS1kIsEL5zwAXX4OvxWvnlMJW45rwoZBUAxPQgkBBYEpoQWDRa0A3IKkGSUALAgWBKaEFgYWvAd2ApBokAS0IFASmhBYEFr4GdAOSapAEtCBQEJgSegYB9lDgNH50SWMfBlqZsOEIwj6L+VNDsf8iCyeI5n0ZEHoR836Ny4Svmf9/8D3y98s/Bz8TPxteIPhivNfFYohuoKgAAgAFJBnCDN5QjwGbvzHwmXCjLd4EugEsFtB4pcOQu7drnFM9un+vRdDpBoqIDZJnHb8/aumMaLqBImr5QPMf1YtnT+jXSUA7eu1EBG3H7xqnGyjWOcKGZQg6O/kUvVOGbsDNy+pb0fj5U/r1EtBLirC5sdHbu/6irIRsxl39oBtYWxo/rw718fsj+nUT0MGPxe1bo5hLeXQD4c+k8zz0uB5vgkg30OQJol40jjdBpBuodrqRHrZctJjSdAPV4dYej4uWUppuoJrwVAybdIa6y64vTc5P6ddKQC8pAvYTa7hx0eojcbqB4sJeYXbqDU17cV5yTzdQRUic+dNAtaR3sRRoHA/MvmYCesUiYDafOzyg3HaVW6Gg3B413zaV26nYKVpT4zgTQ7qBQQp7Ieb7EnFj4Mzn+Zsl9yd6/y1xdvIx0tId3UBz+tqce+eb3xDzvyW+NucefNOcW3LlZhwnnSG6AWnNGuA3Rb5Bdue61hdvjHnlbvNAqxsC2kHxJRPQgkA3QlJCC4LUSA3oBiTVIAloQaAgMCW0ILDwNaAbkFSDJKAFgYLAlNCCwMLXgG5AUg2SgBYECgJTQgsCC18DugFJNUgCWhAoCEwJLQgsfA3oBiTVIAloQaAgMCW0ILDwNaAbkFSDJKAFgYLAlNCCwMLXgG5AUg2SgBYECgJTQgsCC18DugFJNUgCWhAoCEwJLQgsfA3oBiTVIAloQaAgMCW0ILDwNaAbkFSDJKAFgYLAlNCCwMLXgG5AUg2SgBYECgL7tgb/A6oyzIW++c0FAAAAAElFTkSuQmCC",A="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M22.182%2015.499a1.7634%201.7634%200%200%201-.3536-.0358%201.8319%201.8319%200%200%201-1.2086-.8632l-.0066-.012c-.1308-.2616-.0448-.5693.2-.7162a.5236.5236%200%200%201%20.2689-.0743.5327.5327%200%200%201%20.4632.272.558.558%200%200%200%20.018.0299l.0564.0766.0757.0765a.7385.7385%200%200%200%20.3453.167.7596.7596%200%200%200%20.5954-.136.7206.7206%200%200%200%20.299-.5386.7441.7441%200%200%200-.207-.578s-1.5994-1.6612-1.6712-1.7382a1.9604%201.9604%200%200%201-.1929-.229c-.2256-.3198-.2962-.697-.2614-1.0702a1.7361%201.7361%200%200%201%20.2253-.7397s.0732-.124.0948-.1554c.0847-.1236.2515-.2834.3658-.3726a1.8813%201.8813%200%200%201%20.3069-.1844%201.7494%201.7494%200%200%201%202.2815.7041.5186.5186%200%200%201%20.0553.402.5298.5298%200%200%201-.2528.3263.5082.5082%200%200%201-.2593.0705.5283.5283%200%200%201-.46-.2706.6953.6953%200%200%200-.4656-.329.721.721%200%200%200-.5645.1269.688.688%200%200%200-.267.498.6998.6998%200%200%200%20.1905.5398l1.6351%201.6862a1.8284%201.8284%200%200%201%20.5071%201.3931c-.0465.5243-.3071.9994-.7152%201.3053a1.8425%201.8425%200%200%201-1.0984.369m-5.175-.0006a1.7608%201.7608%200%200%200%201.7585-1.7589v-3.4787a1.7587%201.7587%200%200%200-3.5173%200v3.4786a1.7608%201.7608%200%200%200%201.7587%201.7589m0-5.9342c.3777%200%20.6968.319.6968.6967v3.4786a.6977.6977%200%200%201-.6968.6968.6894.6894%200%200%201-.6968-.6968v-3.4786a.6976.6976%200%200%201%20.697-.6967m-7.8986.3224v5.0804a.5309.5309%200%200%200%201.0618%200V12.09Zm2.8802%202.0255V9.0328a.531.531%200%200%201%201.0619%200v5.0828zm1.053%202.9406v.1134a.533.533%200%200%201-1.0067.2408L9.1153%209.154v-.1212a.5261.5261%200%200%201%20.3028-.4772.5253.5253%200%200%201%20.7088.2475Zm-7.9067.6457a1.761%201.761%200%200%200%201.7586-1.7589v-3.4786a1.7587%201.7587%200%200%200-3.5173%200v3.4786a1.7609%201.7609%200%200%200%201.7587%201.7589m0-5.9342a.707.707%200%200%201%20.6968.6967v3.4786a.6968.6968%200%201%201-1.3936%200v-3.4786a.6976.6976%200%200%201%20.6968-.6967M0%2014.9111a.5791.5791%200%201%200%201.1581%200V9.0803a.5791.5791%200%200%200-1.1582%200z'/%3e%3c/svg%3e",_="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M22.006%2010.684a.15.15%200%200%200-.07-.15l-3.261-1.821a.14.14%200%200%200-.14%200l-2.771%201.69a.17.17%200%200%200-.07.13v1.451l-1.13-.74a.14.14%200%200%200-.15%200l-1.62%201-.071-1.64a.19.19%200%200%200-.07-.12l-1.65-1.09%201.51-.781a.16.16%200%200%200%20.08-.14l-.27-6.272a.16.16%200%200%200-.08-.13L8%200h-.1L2.08%201.81A.16.16%200%200%200%202%202l1.27%206.233a.22.22%200%200%200%200%20.08l1.83%201.38-1.26.6a.16.16%200%200%200-.08.17l1%204.702a.18.18%200%200%200%200%20.07L6%2016.375l-.8.49a.15.15%200%200%200-.06.16l.75%203.642a.11.11%200%200%200%200%20.07l3.002%203.221a.14.14%200%200%200%20.2%200l3.921-3.121a.16.16%200%200%200%20.06-.12l-.07-2.12%201.32%201.1a.14.14%200%200%200%20.18%200l3.142-2.511a.24.24%200%200%200%20.06-.11l.09-1.57%201%20.67a.14.14%200%200%200%20.17%200l2.571-2.001a.14.14%200%200%200%20.05-.1zm-9.623.15l.07%201.57.12%202.781-4.231%202.871-.66-4.532zm-.35-8.423l.25%205.912-5.002%202.59-.9-6.321zM3.54%208.123L2.33%202.26l3.74%202.32.931%206.203-1.58-1.2zM5%2015.055l-.88-4.261%203.281%202.74.6%204.382-1.68-1.62zm1.14%205.512l-.65-3.141%202.892%202.85.47%203.162zm3.002%203l-.49-3.33%204.001-2.871.14%203.28zm3.861-5.36v-1.081a.16.16%200%200%200-.05-.11l-1.13-.92%201-.7a.14.14%200%200%200%20.06-.12v-.261l1.39%201.06v3.211zm4.442-1.201l-2.861%202.28v-3.22l3.07-2.201zm1.29-1.21l-.9-.631.09-1.59a.11.11%200%200%200%200-.06.1.1%200%200%200%200-.05l-1.93-1.27v-1.391l3%201.89zm2.55-1.861l-2.28%201.81.26-3.06%202.431-1.681z'/%3e%3c/svg%3e",d="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eNvidia%3c/title%3e%3cpath%20d='M10.212%208.976V7.62c.127-.01.256-.017.388-.021%203.596-.117%205.957%203.184%205.957%203.184s-2.548%203.647-5.282%203.647a3.227%203.227%200%2001-1.063-.175v-4.109c1.4.174%201.681.812%202.523%202.258l1.873-1.627a4.905%204.905%200%2000-3.67-1.846%206.594%206.594%200%2000-.729.044m0-4.476v2.025c.13-.01.259-.019.388-.024%205.002-.174%208.261%204.226%208.261%204.226s-3.743%204.69-7.643%204.69c-.338%200-.675-.031-1.007-.092v1.25c.278.038.558.057.838.057%203.629%200%206.253-1.91%208.794-4.169.421.347%202.146%201.193%202.501%201.564-2.416%202.083-8.048%203.763-11.24%203.763-.308%200-.603-.02-.894-.048V19.5H24v-15H10.21zm0%209.756v1.068c-3.356-.616-4.287-4.21-4.287-4.21a7.173%207.173%200%20014.287-2.138v1.172h-.005a3.182%203.182%200%2000-2.502%201.178s.615%202.276%202.507%202.931m-5.961-3.3c1.436-1.935%203.604-3.148%205.961-3.336V6.523C5.81%206.887%202%2010.723%202%2010.723s2.158%206.427%208.21%207.015v-1.166C5.77%2016%204.25%2010.958%204.25%2010.958h-.002z'%20fill='%2374B71B'%20fill-rule='nonzero'%3e%3c/path%3e%3c/svg%3e",m="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eOllama%3c/title%3e%3cpath%20d='M7.905%201.09c.216.085.411.225.588.41.295.306.544.744.734%201.263.191.522.315%201.1.362%201.68a5.054%205.054%200%20012.049-.636l.051-.004c.87-.07%201.73.087%202.48.474.101.053.2.11.297.17.05-.569.172-1.134.36-1.644.19-.52.439-.957.733-1.264a1.67%201.67%200%2001.589-.41c.257-.1.53-.118.796-.042.401.114.745.368%201.016.737.248.337.434.769.561%201.287.23.934.27%202.163.115%203.645l.053.04.026.019c.757.576%201.284%201.397%201.563%202.35.435%201.487.216%203.155-.534%204.088l-.018.021.002.003c.417.762.67%201.567.724%202.4l.002.03c.064%201.065-.2%202.137-.814%203.19l-.007.01.01.024c.472%201.157.62%202.322.438%203.486l-.006.039a.651.651%200%2001-.747.536.648.648%200%2001-.54-.742c.167-1.033.01-2.069-.48-3.123a.643.643%200%2001.04-.617l.004-.006c.604-.924.854-1.83.8-2.72-.046-.779-.325-1.544-.8-2.273a.644.644%200%2001.18-.886l.009-.006c.243-.159.467-.565.58-1.12a4.229%204.229%200%2000-.095-1.974c-.205-.7-.58-1.284-1.105-1.683-.595-.454-1.383-.673-2.38-.61a.653.653%200%2001-.632-.371c-.314-.665-.772-1.141-1.343-1.436a3.288%203.288%200%2000-1.772-.332c-1.245.099-2.343.801-2.67%201.686a.652.652%200%2001-.61.425c-1.067.002-1.893.252-2.497.703-.522.39-.878.935-1.066%201.588a4.07%204.07%200%2000-.068%201.886c.112.558.331%201.02.582%201.269l.008.007c.212.207.257.53.109.785-.36.622-.629%201.549-.673%202.44-.05%201.018.186%201.902.719%202.536l.016.019a.643.643%200%2001.095.69c-.576%201.236-.753%202.252-.562%203.052a.652.652%200%2001-1.269.298c-.243-1.018-.078-2.184.473-3.498l.014-.035-.008-.012a4.339%204.339%200%2001-.598-1.309l-.005-.019a5.764%205.764%200%2001-.177-1.785c.044-.91.278-1.842.622-2.59l.012-.026-.002-.002c-.293-.418-.51-.953-.63-1.545l-.005-.024a5.352%205.352%200%2001.093-2.49c.262-.915.777-1.701%201.536-2.269.06-.045.123-.09.186-.132-.159-1.493-.119-2.73.112-3.67.127-.518.314-.95.562-1.287.27-.368.614-.622%201.015-.737.266-.076.54-.059.797.042zm4.116%209.09c.936%200%201.8.313%202.446.855.63.527%201.005%201.235%201.005%201.94%200%20.888-.406%201.58-1.133%202.022-.62.375-1.451.557-2.403.557-1.009%200-1.871-.259-2.493-.734-.617-.47-.963-1.13-.963-1.845%200-.707.398-1.417%201.056-1.946.668-.537%201.55-.849%202.485-.849zm0%20.896a3.07%203.07%200%2000-1.916.65c-.461.37-.722.835-.722%201.25%200%20.428.21.829.61%201.134.455.347%201.124.548%201.943.548.799%200%201.473-.147%201.932-.426.463-.28.7-.686.7-1.257%200-.423-.246-.89-.683-1.256-.484-.405-1.14-.643-1.864-.643zm.662%201.21l.004.004c.12.151.095.37-.056.49l-.292.23v.446a.375.375%200%2001-.376.373.375.375%200%2001-.376-.373v-.46l-.271-.218a.347.347%200%2001-.052-.49.353.353%200%2001.494-.051l.215.172.22-.174a.353.353%200%2001.49.051zm-5.04-1.919c.478%200%20.867.39.867.871a.87.87%200%2001-.868.871.87.87%200%2001-.867-.87.87.87%200%2001.867-.872zm8.706%200c.48%200%20.868.39.868.871a.87.87%200%2001-.868.871.87.87%200%2001-.867-.87.87.87%200%2001.867-.872zM7.44%202.3l-.003.002a.659.659%200%2000-.285.238l-.005.006c-.138.189-.258.467-.348.832-.17.692-.216%201.631-.124%202.782.43-.128.899-.208%201.404-.237l.01-.001.019-.034c.046-.082.095-.161.148-.239.123-.771.022-1.692-.253-2.444-.134-.364-.297-.65-.453-.813a.628.628%200%2000-.107-.09L7.44%202.3zm9.174.04l-.002.001a.628.628%200%2000-.107.09c-.156.163-.32.45-.453.814-.29.794-.387%201.776-.23%202.572l.058.097.008.014h.03a5.184%205.184%200%20011.466.212c.086-1.124.038-2.043-.128-2.722-.09-.365-.21-.643-.349-.832l-.004-.006a.659.659%200%2000-.285-.239h-.004z'%3e%3c/path%3e%3c/svg%3e",r="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eOpenAI%3c/title%3e%3cpath%20d='M9.205%208.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357%201.356-.523%202.117-.523%202.854%200%204.662%202.212%204.662%204.566%200%20.167%200%20.357-.024.547l-4.71-2.759a.797.797%200%2000-.856%200l-5.97%203.473zm10.609%208.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473%201.95-1.118a.433.433%200%2001.476%200l4.543%202.617c1.309.76%202.189%202.378%202.189%203.948%200%201.808-1.07%203.473-2.76%204.163zM7.802%2012.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545%201.95-4.472%204.591-4.472%201%200%201.927.333%202.712.928L8.23%205.067c-.285.166-.428.404-.428.737v6.898zM12%2015.128l-2.795-1.57v-3.33L12%208.658l2.795%201.57v3.33L12%2015.128zm1.796%207.23c-1%200-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974%201.142c.167.095.238.238.238.428v5.233c0%202.545-1.974%204.472-4.614%204.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482%204.482%200%20014.21%206.327v5.423c0%20.333.143.571.428.738l5.947%203.449-1.95%201.118a.432.432%200%2001-.476%200zm-.262%203.9c-2.688%200-4.662-2.021-4.662-4.519%200-.19.024-.38.047-.57l4.686%202.71c.286.167.571.167.856%200l5.97-3.448v2.26c0%20.19-.07.333-.237.428l-4.543%202.616c-.619.357-1.356.523-2.117.523zm5.899%202.83a5.947%205.947%200%20005.827-4.756C22.287%2018.339%2024%2015.84%2024%2013.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498%200-3.401-2.759-5.947-5.946-5.947-.642%200-1.26.095-1.88.31A5.962%205.962%200%200010.205%200a5.947%205.947%200%2000-5.827%204.757C1.713%205.447%200%207.945%200%2010.49c0%201.666.713%203.283%201.998%204.448-.119.5-.19%201-.19%201.499%200%203.401%202.759%205.946%205.946%205.946.642%200%201.26-.095%201.88-.309a5.96%205.96%200%20004.162%201.713z'%3e%3c/path%3e%3c/svg%3e",x="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eOpenClaw%3c/title%3e%3cpath%20d='M12%202.568c-6.33%200-9.495%205.275-9.495%209.495%200%204.22%203.165%208.44%206.33%209.494v2.11h2.11v-2.11s1.055.422%202.11%200v2.11h2.11v-2.11c3.165-1.055%206.33-5.274%206.33-9.494S18.33%202.568%2012%202.568z'%20fill='url(%23lobe-icons-open-claw-0-_R_0_)'%3e%3c/path%3e%3cpath%20d='M3.56%209.953C.396%208.898-.66%2011.008.396%2013.118c1.055%202.11%203.164%201.055%204.22-1.055.632-1.477%200-2.11-1.056-2.11z'%20fill='url(%23lobe-icons-open-claw-1-_R_0_)'%3e%3c/path%3e%3cpath%20d='M20.44%209.953c3.164-1.055%204.22%201.055%203.164%203.165-1.055%202.11-3.164%201.055-4.22-1.055-.632-1.477%200-2.11%201.056-2.11z'%20fill='url(%23lobe-icons-open-claw-2-_R_0_)'%3e%3c/path%3e%3cpath%20d='M5.507%201.875c.476-.285%201.036-.233%201.615.037.577.27%201.223.774%201.937%201.488a.316.316%200%2001-.447.447c-.693-.693-1.279-1.138-1.757-1.361-.475-.222-.795-.205-1.022-.069a.317.317%200%2001-.326-.542zM16.877%201.913c.58-.27%201.14-.323%201.616-.038a.317.317%200%2001-.326.542c-.227-.136-.547-.153-1.022.069-.478.223-1.064.668-1.756%201.361a.316.316%200%2011-.448-.447c.714-.714%201.36-1.218%201.936-1.487z'%20fill='%23FF4D4D'%3e%3c/path%3e%3cpath%20d='M8.835%209.109a1.266%201.266%200%20100-2.532%201.266%201.266%200%20000%202.532zM15.165%209.109a1.266%201.266%200%20100-2.532%201.266%201.266%200%20000%202.532z'%20fill='%23050810'%3e%3c/path%3e%3cpath%20d='M9.046%208.16a.527.527%200%20100-1.056.527.527%200%20000%201.055zM15.376%208.16a.527.527%200%20100-1.055.527.527%200%20000%201.054z'%20fill='%2300E5CC'%3e%3c/path%3e%3cdefs%3e%3clinearGradient%20gradientUnits='userSpaceOnUse'%20id='lobe-icons-open-claw-0-_R_0_'%20x1='-.659'%20x2='27.023'%20y1='.458'%20y2='22.855'%3e%3cstop%20stop-color='%23FF4D4D'%3e%3c/stop%3e%3cstop%20offset='1'%20stop-color='%23991B1B'%3e%3c/stop%3e%3c/linearGradient%3e%3clinearGradient%20gradientUnits='userSpaceOnUse'%20id='lobe-icons-open-claw-1-_R_0_'%20x1='0'%20x2='4.311'%20y1='9.672'%20y2='14.949'%3e%3cstop%20stop-color='%23FF4D4D'%3e%3c/stop%3e%3cstop%20offset='1'%20stop-color='%23991B1B'%3e%3c/stop%3e%3c/linearGradient%3e%3clinearGradient%20gradientUnits='userSpaceOnUse'%20id='lobe-icons-open-claw-2-_R_0_'%20x1='19.385'%20x2='24.399'%20y1='9.953'%20y2='14.462'%3e%3cstop%20stop-color='%23FF4D4D'%3e%3c/stop%3e%3cstop%20offset='1'%20stop-color='%23991B1B'%3e%3c/stop%3e%3c/linearGradient%3e%3c/defs%3e%3c/svg%3e",B="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eOpenRouter%3c/title%3e%3cpath%20d='M18.654%203.87a5.087%205.087%200%20110%2010.174L23.7%2019.09c.64.641.187%201.737-.72%201.737H8.48a8.479%208.479%200%20010-16.958h10.175zM8.479%207.26a5.087%205.087%200%20100%2010.176%205.087%205.087%200%20000-10.175z'%3e%3c/path%3e%3c/svg%3e",z="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M16.412%204.412h-8.82a7.588%207.588%200%200%200-.008%2015.176h8.828a7.588%207.588%200%200%200%200-15.176zm-.193%2012.502H7.786a4.915%204.915%200%200%201%200-9.828h8.433a4.914%204.914%200%201%201%200%209.828z'/%3e%3c/svg%3e",L="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M19.881%2010.095l2.563-4.45C23.434%207.389%2024%209.404%2024%2011.555c0%202.88-1.017%205.523-2.71%207.594h-6.62l2.04-3.541h-2.696l3.176-5.513h2.691zm-2.32-5.243L9.333%2019.14l.003.009H2.709C1.014%2017.077%200%2014.435%200%2011.555c0-2.152.57-4.17%201.561-5.918L5.855%2013.1%2010.6%204.852h6.961z'/%3e%3c/svg%3e",C="/assets/raspberrypi-CW7KYKqj.svg",b="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M8.36%202.172A1.194%201.194%200%20007.348%201.6H1.2A1.2%201.2%200%20000%202.8a1.211%201.211%200%2000.182.64l11.6%2018.4a1.206%201.206%200%20002.035%200l3.075-4.874a1.229%201.229%200%2000.182-.64%201.211%201.211%200%2000-.182-.642zm10.349%208.68a1.206%201.206%200%20002.035%200L21.8%209.178l2.017-3.2a1.211%201.211%200%2000.183-.64%201.229%201.229%200%2000-.183-.64l-1.6-2.526a1.206%201.206%200%2000-1.016-.571h-6.148a1.2%201.2%200%2000-1.201%201.2%201.143%201.143%200%2000.188.64z'/%3e%3c/svg%3e",f="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eGrok%3c/title%3e%3cpath%20d='M9.27%2015.29l7.978-5.897c.391-.29.95-.177%201.137.272.98%202.369.542%205.215-1.41%207.169-1.951%201.954-4.667%202.382-7.149%201.406l-2.711%201.257c3.889%202.661%208.611%202.003%2011.562-.953%202.341-2.344%203.066-5.539%202.388-8.42l.006.007c-.983-4.232.242-5.924%202.75-9.383.06-.082.12-.164.179-.248l-3.301%203.305v-.01L9.267%2015.292M7.623%2016.723c-2.792-2.67-2.31-6.801.071-9.184%201.761-1.763%204.647-2.483%207.166-1.425l2.705-1.25a7.808%207.808%200%2000-1.829-1A8.975%208.975%200%20005.984%205.83c-2.533%202.536-3.33%206.436-1.962%209.764%201.022%202.487-.653%204.246-2.34%206.022-.599.63-1.199%201.259-1.682%201.925l7.62-6.815'%3e%3c/path%3e%3c/svg%3e";export{f as _,b as a,C as b,L as c,z as d,B as e,x as f,r as g,m as h,d as i,_ as j,A as k,w as l,h as m,p as n,n as o,i as p,g as q,v as r,o as s,s as t,t as u,l as v,c as w,a as x,e as y};+const e="/assets/antigravity-_lOIeRhP.svg",a="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M6.763%2010.036c0%20.296.032.535.088.71.064.176.144.368.256.576.04.063.056.127.056.183%200%20.08-.048.16-.152.24l-.503.335a.383.383%200%200%201-.208.072c-.08%200-.16-.04-.239-.112a2.47%202.47%200%200%201-.287-.375%206.18%206.18%200%200%201-.248-.471c-.622.734-1.405%201.101-2.347%201.101-.67%200-1.205-.191-1.596-.574-.391-.384-.59-.894-.59-1.533%200-.678.239-1.23.726-1.644.487-.415%201.133-.623%201.955-.623.272%200%20.551.024.846.064.296.04.6.104.918.176v-.583c0-.607-.127-1.03-.375-1.277-.255-.248-.686-.367-1.3-.367-.28%200-.568.031-.863.103-.295.072-.583.16-.862.272a2.287%202.287%200%200%201-.28.104.488.488%200%200%201-.127.023c-.112%200-.168-.08-.168-.247v-.391c0-.128.016-.224.056-.28a.597.597%200%200%201%20.224-.167c.279-.144.614-.264%201.005-.36a4.84%204.84%200%200%201%201.246-.151c.95%200%201.644.216%202.091.647.439.43.662%201.085.662%201.963v2.586zm-3.24%201.214c.263%200%20.534-.048.822-.144.287-.096.543-.271.758-.51.128-.152.224-.32.272-.512.047-.191.08-.423.08-.694v-.335a6.66%206.66%200%200%200-.735-.136%206.02%206.02%200%200%200-.75-.048c-.535%200-.926.104-1.19.32-.263.215-.39.518-.39.917%200%20.375.095.655.295.846.191.2.47.296.838.296zm6.41.862c-.144%200-.24-.024-.304-.08-.064-.048-.12-.16-.168-.311L7.586%205.55a1.398%201.398%200%200%201-.072-.32c0-.128.064-.2.191-.2h.783c.151%200%20.255.025.31.08.065.048.113.16.16.312l1.342%205.284%201.245-5.284c.04-.16.088-.264.151-.312a.549.549%200%200%201%20.32-.08h.638c.152%200%20.256.025.32.08.063.048.12.16.151.312l1.261%205.348%201.381-5.348c.048-.16.104-.264.16-.312a.52.52%200%200%201%20.311-.08h.743c.127%200%20.2.065.2.2%200%20.04-.009.08-.017.128a1.137%201.137%200%200%201-.056.2l-1.923%206.17c-.048.16-.104.263-.168.311a.51.51%200%200%201-.303.08h-.687c-.151%200-.255-.024-.32-.08-.063-.056-.119-.16-.15-.32l-1.238-5.148-1.23%205.14c-.04.16-.087.264-.15.32-.065.056-.177.08-.32.08zm10.256.215c-.415%200-.83-.048-1.229-.143-.399-.096-.71-.2-.918-.32-.128-.071-.215-.151-.247-.223a.563.563%200%200%201-.048-.224v-.407c0-.167.064-.247.183-.247.048%200%20.096.008.144.024.048.016.12.048.2.08.271.12.566.215.878.279.319.064.63.096.95.096.502%200%20.894-.088%201.165-.264a.86.86%200%200%200%20.415-.758.777.777%200%200%200-.215-.559c-.144-.151-.416-.287-.807-.415l-1.157-.36c-.583-.183-1.014-.454-1.277-.813a1.902%201.902%200%200%201-.4-1.158c0-.335.073-.63.216-.886.144-.255.335-.479.575-.654.24-.184.51-.32.83-.415.32-.096.655-.136%201.006-.136.175%200%20.359.008.535.032.183.024.35.056.518.088.16.04.312.08.455.127.144.048.256.096.336.144a.69.69%200%200%201%20.24.2.43.43%200%200%201%20.071.263v.375c0%20.168-.064.256-.184.256a.83.83%200%200%201-.303-.096%203.652%203.652%200%200%200-1.532-.311c-.455%200-.815.071-1.062.223-.248.152-.375.383-.375.71%200%20.224.08.416.24.567.159.152.454.304.877.44l1.134.358c.574.184.99.44%201.237.767.247.327.367.702.367%201.117%200%20.343-.072.655-.207.926-.144.272-.336.511-.583.703-.248.2-.543.343-.886.447-.36.111-.734.167-1.142.167zM21.698%2016.207c-2.626%201.94-6.442%202.969-9.722%202.969-4.598%200-8.74-1.7-11.87-4.526-.247-.223-.024-.527.272-.351%203.384%201.963%207.559%203.153%2011.877%203.153%202.914%200%206.114-.607%209.06-1.852.439-.2.814.287.383.607zM22.792%2014.961c-.336-.43-2.22-.207-3.074-.103-.255.032-.295-.192-.063-.36%201.5-1.053%203.967-.75%204.254-.399.287.36-.08%202.826-1.485%204.007-.215.184-.423.088-.327-.151.32-.79%201.03-2.57.695-2.994z'/%3e%3c/svg%3e",c="data:image/svg+xml,%3csvg%20width='416'%20height='426'%20viewBox='0%200%20416%20426'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20width='415.632'%20height='425.055'%20fill='%23004E23'/%3e%3cpath%20d='M317.301%20182.114V237.681H289.766L286.153%20232.679L277.49%20220.689L271.591%20212.526L261.508%20198.571L264.557%20212.526L268.964%20232.679L270.056%20237.681L273.37%20252.833L277.49%20271.685L277.774%20272.987L282.178%20293.138L286.585%20313.292H224.406L219.999%20293.138L217.769%20282.929L215.595%20272.987L211.189%20252.833L207.877%20237.681L204.565%20252.833L200.158%20272.987L197.864%20283.481L195.754%20293.138L191.347%20313.292H129.048L133.455%20293.138L137.738%20273.533V273.53L138.143%20273.231L138.475%20272.987L158.05%20258.489L165.69%20252.833L177.957%20243.747L186.149%20237.681H98.332V182.114H157.722L158.05%20180.617L159.887%20172.221L164.291%20152.067L168.698%20131.914L173.102%20111.763H242.531L246.935%20131.914L247.858%20136.131L237.676%20143.671L226.336%20152.067L217.769%20158.413L199.123%20172.221L197.864%20173.152L185.764%20182.114H317.301Z'%20fill='%23F9F9F8'/%3e%3c/svg%3e",l="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eClaude%3c/title%3e%3cpath%20d='M4.709%2015.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0%2011.784l.055-.352.48-.321.686.06%201.52.103%202.278.158%201.652.097%202.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686%201.908%201.476%202.491%201.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97%202.97%200%2001-.104-.729L6.283.134%206.696%200l.996.134.42.364.62%201.414%201.002%202.229%201.555%203.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286%201.851-.559%202.903-.364%201.942h.212l.243-.242.985-1.306%201.652-2.064.73-.82.85-.904.547-.431h1.033l.76%201.129-.34%201.166-1.064%201.347-.881%201.142-1.264%201.7-.79%201.36.073.11.188-.02%202.856-.606%201.543-.28%201.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061%201.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093%201.068%202.006%201.81%202.509%202.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649%202.345%203.521.122%201.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674%207.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434%201.967-2.18%202.945-1.726%201.845-.414.164-.717-.37.067-.662.401-.589%202.388-3.036%201.44-1.882.93-1.086-.006-.158h-.055L4.132%2018.56l-1.13.146-.487-.456.061-.746.231-.243%201.908-1.312-.006.006z'%20fill='%23D97757'%20fill-rule='nonzero'%3e%3c/path%3e%3c/svg%3e",t="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M11.336%201.816a6.95%206.95%200%200%200-6.879%205.889%207.88%207.88%200%200%201%202.24-.412A4.855%204.855%200%200%201%2011.33%203.92a4.853%204.853%200%200%201%203.45%201.44%204.793%204.793%200%200%201%201.197%202.01%207.633%207.633%200%200%201%20.875-.067h.33a8.313%208.313%200%200%201%20.976.076%206.95%206.95%200%200%200-6.822-5.564zM6.99%208.224A6.983%206.983%200%200%200%200%2015.2a6.978%206.978%200%200%200%206.977%206.976%206.966%206.966%200%200%200%204.933-2.03%20691.43%20691.43%200%200%200%201.56-1.581l-1.488-1.488-1.55%201.582a4.86%204.86%200%200%201-3.452%201.436A4.881%204.881%200%200%201%202.104%2015.2a4.877%204.877%200%200%201%204.876-4.871%204.855%204.855%200%200%201%202.819.904l.04-.043%201.466-1.465A6.969%206.969%200%200%200%206.99%208.224zm10.04%200a6.966%206.966%200%200%200-4.936%202.047l-1.59%201.574%201.488%201.489%201.58-1.584A4.88%204.88%200%200%201%2021.9%2015.2a4.881%204.881%200%200%201-4.877%204.882%204.858%204.858%200%200%201-2.83-.914l-.045.046s-1.078%201.096-1.437%201.467a6.95%206.95%200%200%200%204.312%201.504A6.983%206.983%200%200%200%2024%2015.205a6.95%206.95%200%200%200-2.04-4.933%206.962%206.962%200%200%200-4.93-2.047z'/%3e%3c/svg%3e",s="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M12.04%200C5.408-.02.005%205.37.005%2011.992h4.638c0-4.923%204.882-8.731%2010.064-6.855a6.95%206.95%200%20014.147%204.148c1.889%205.177-1.924%2010.055-6.84%2010.064v-4.61H7.391v4.623h4.61V24c7.86%200%2013.967-7.588%2011.397-15.83-1.115-3.59-3.985-6.446-7.575-7.575A12.8%2012.8%200%200012.039%200zM7.39%2019.362H3.828v3.564H7.39zm-3.563%200v-2.978H.85v2.978z'/%3e%3c/svg%3e",o="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eElevenLabs%3c/title%3e%3cpath%20d='M5%200h5v24H5V0zM14%200h5v24h-5V0z'%3e%3c/path%3e%3c/svg%3e",v="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eGemini%3c/title%3e%3cpath%20d='M20.616%2010.835a14.147%2014.147%200%2001-4.45-3.001%2014.111%2014.111%200%2001-3.678-6.452.503.503%200%2000-.975%200%2014.134%2014.134%200%2001-3.679%206.452%2014.155%2014.155%200%2001-4.45%203.001c-.65.28-1.318.505-2.002.678a.502.502%200%20000%20.975c.684.172%201.35.397%202.002.677a14.147%2014.147%200%20014.45%203.001%2014.112%2014.112%200%20013.679%206.453.502.502%200%2000.975%200c.172-.685.397-1.351.677-2.003a14.145%2014.145%200%20013.001-4.45%2014.113%2014.113%200%20016.453-3.678.503.503%200%20000-.975%2013.245%2013.245%200%2001-2.003-.678z'%20fill='%233186FF'%3e%3c/path%3e%3cpath%20d='M20.616%2010.835a14.147%2014.147%200%2001-4.45-3.001%2014.111%2014.111%200%2001-3.678-6.452.503.503%200%2000-.975%200%2014.134%2014.134%200%2001-3.679%206.452%2014.155%2014.155%200%2001-4.45%203.001c-.65.28-1.318.505-2.002.678a.502.502%200%20000%20.975c.684.172%201.35.397%202.002.677a14.147%2014.147%200%20014.45%203.001%2014.112%2014.112%200%20013.679%206.453.502.502%200%2000.975%200c.172-.685.397-1.351.677-2.003a14.145%2014.145%200%20013.001-4.45%2014.113%2014.113%200%20016.453-3.678.503.503%200%20000-.975%2013.245%2013.245%200%2001-2.003-.678z'%20fill='url(%23lobe-icons-gemini-0-_R_0_)'%3e%3c/path%3e%3cpath%20d='M20.616%2010.835a14.147%2014.147%200%2001-4.45-3.001%2014.111%2014.111%200%2001-3.678-6.452.503.503%200%2000-.975%200%2014.134%2014.134%200%2001-3.679%206.452%2014.155%2014.155%200%2001-4.45%203.001c-.65.28-1.318.505-2.002.678a.502.502%200%20000%20.975c.684.172%201.35.397%202.002.677a14.147%2014.147%200%20014.45%203.001%2014.112%2014.112%200%20013.679%206.453.502.502%200%2000.975%200c.172-.685.397-1.351.677-2.003a14.145%2014.145%200%20013.001-4.45%2014.113%2014.113%200%20016.453-3.678.503.503%200%20000-.975%2013.245%2013.245%200%2001-2.003-.678z'%20fill='url(%23lobe-icons-gemini-1-_R_0_)'%3e%3c/path%3e%3cpath%20d='M20.616%2010.835a14.147%2014.147%200%2001-4.45-3.001%2014.111%2014.111%200%2001-3.678-6.452.503.503%200%2000-.975%200%2014.134%2014.134%200%2001-3.679%206.452%2014.155%2014.155%200%2001-4.45%203.001c-.65.28-1.318.505-2.002.678a.502.502%200%20000%20.975c.684.172%201.35.397%202.002.677a14.147%2014.147%200%20014.45%203.001%2014.112%2014.112%200%20013.679%206.453.502.502%200%2000.975%200c.172-.685.397-1.351.677-2.003a14.145%2014.145%200%20013.001-4.45%2014.113%2014.113%200%20016.453-3.678.503.503%200%20000-.975%2013.245%2013.245%200%2001-2.003-.678z'%20fill='url(%23lobe-icons-gemini-2-_R_0_)'%3e%3c/path%3e%3cdefs%3e%3clinearGradient%20gradientUnits='userSpaceOnUse'%20id='lobe-icons-gemini-0-_R_0_'%20x1='7'%20x2='11'%20y1='15.5'%20y2='12'%3e%3cstop%20stop-color='%2308B962'%3e%3c/stop%3e%3cstop%20offset='1'%20stop-color='%2308B962'%20stop-opacity='0'%3e%3c/stop%3e%3c/linearGradient%3e%3clinearGradient%20gradientUnits='userSpaceOnUse'%20id='lobe-icons-gemini-1-_R_0_'%20x1='8'%20x2='11.5'%20y1='5.5'%20y2='11'%3e%3cstop%20stop-color='%23F94543'%3e%3c/stop%3e%3cstop%20offset='1'%20stop-color='%23F94543'%20stop-opacity='0'%3e%3c/stop%3e%3c/linearGradient%3e%3clinearGradient%20gradientUnits='userSpaceOnUse'%20id='lobe-icons-gemini-2-_R_0_'%20x1='3.5'%20x2='17.5'%20y1='13.5'%20y2='12'%3e%3cstop%20stop-color='%23FABC12'%3e%3c/stop%3e%3cstop%20offset='.46'%20stop-color='%23FABC12'%20stop-opacity='0'%3e%3c/stop%3e%3c/linearGradient%3e%3c/defs%3e%3c/svg%3e",g="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eGoogleCloud%3c/title%3e%3cpath%20d='M15.961%207.327l2.086-2.086.14-.879C14.384.905%208.34%201.297%204.913%205.18A9.643%209.643%200%20002.88%208.991l.747-.105%204.172-.688.322-.33c1.856-2.038%204.994-2.312%207.137-.578l.703.037z'%20fill='%23EA4335'%3e%3c/path%3e%3cpath%20d='M21.02%208.93a9.399%209.399%200%2000-2.834-4.568L15.258%207.29a5.204%205.204%200%20011.91%204.129v.52a2.606%202.606%200%20012.607%202.605c0%201.44-1.167%202.577-2.606%202.577h-5.22l-.512.556v3.126l.513.49h5.219c3.743.03%206.802-2.952%206.83-6.695a6.778%206.778%200%2000-2.98-5.668z'%20fill='%234285F4'%3e%3c/path%3e%3cpath%20d='M6.738%2021.293h5.212v-4.172H6.738c-.371%200-.731-.08-1.069-.234l-.74.227-2.1%202.086-.183.71a6.763%206.763%200%20004.092%201.383z'%20fill='%2334A853'%3e%3c/path%3e%3cpath%20d='M6.738%207.759A6.778%206.778%200%20002.646%2019.91l3.023-3.023a2.606%202.606%200%20113.448-3.448l3.023-3.023a6.771%206.771%200%2000-5.402-2.657z'%20fill='%23FBBC05'%3e%3c/path%3e%3c/svg%3e",i="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eGroq%3c/title%3e%3cpath%20d='M12.036%202c-3.853-.035-7%203-7.036%206.781-.035%203.782%203.055%206.872%206.908%206.907h2.42v-2.566h-2.292c-2.407.028-4.38-1.866-4.408-4.23-.029-2.362%201.901-4.298%204.308-4.326h.1c2.407%200%204.358%201.915%204.365%204.278v6.305c0%202.342-1.944%204.25-4.323%204.279a4.375%204.375%200%2001-3.033-1.252l-1.851%201.818A7%207%200%200012.029%2022h.092c3.803-.056%206.858-3.083%206.879-6.816v-6.5C18.907%204.963%2015.817%202%2012.036%202z'%3e%3c/path%3e%3c/svg%3e",n="/assets/hermes-CiVWQ9gt.svg",p="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M0%200v24h24V0H0zm4.602%204.025h2.244c.509%200%20.716.215.716.717v5.64h8.883v-5.64c0-.509.215-.717.717-.717h2.229c.5%200%20.71.23.724.717v14.516c0%20.509-.215.717-.717.717h-2.23c-.51%200-.717-.215-.717-.717v-5.735H7.562v5.735c0%20.516-.215.717-.716.717H4.602c-.51%200-.717-.208-.717-.717V4.742c0-.509.207-.717.717-.717z'/%3e%3c/svg%3e",h="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M16.415%200v7.16l5.785%203.384V2.949L16.415%200ZM1.8%200v11.237h18.815L14.89%208.09l-7.457-.003V3.024L1.8%200Zm14.615%2020.894v-5.019l-7.514-.005c.007.033-5.82-3.197-5.82-3.197l19.119.091V24l-5.785-3.106ZM1.8%2013.551v7.343l5.633%202.949v-6.988L1.8%2013.551Z'/%3e%3c/svg%3e",w="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAALQAAAC0CAYAAAA9zQYyAAAACXBIWXMAAAsTAAALEwEAmpwYAAAJoklEQVR4nO2dMW9URxSF7y+AH4BxnyDXUSSXIAp3RETKNiBBERcgQcNKRIIqFg1d7MalaegSN3QgGlcuXLhysxI/YH/CRGelEasFr9m3M+/cd+cURxHg2Gfv+97xzLy588zMkqQaWJwa0A1IqkES0IJAQWBKaEFg4WtANyCpBklACwIFgSmhBYGFrwHdgKQaJAEtCBQEpoQWBBa+BnQDkmqQBLQgUBCYEloQWPga0A1IqkES0IJAQWBKaEFg4WtANyCpBklACwIFgSmhBYGFrwHdgKQaJAEtCBQEpoQWBBa+BnQDkmqQBLQgUBCYEloQWPga0A1IqkES0IJAQWBKaEFg4WtANyCpBklACwIFgSmhBYGFrwHdgKQaJAEtCBQEpoQWBBa+BnQDTen6tWvpn7dv0vH7o9l/dx8/TNu//jL7e7Y3iyG6gaa0c/dOmn65+K4+f/hvBjkAZ/u04YpuoBkBVCTzZUAv6uhwP43u36P7tmGJbiC1nsxX6ezk0yy5N29u0D+H+RfdQDPa3LiR9l69TGcnHzvDLbBNQPsDe6Mz0Fl/v3qpxLbv1pd/gVvSn48epsn56dpA56GIxtgmoFkwv3j2pAjIGobYsjrzU6sFlRhmXJXWW7d+on9OB6IbaGbJribQWbuPHtA/K1l0A82scPQB9PTLxWxow/68RNENNDMZ7AvoadtQ0w00IYxx+wR6+uWi1RUQuoHwwsajUkt1q2hyftriRJFuoAkBrHWeEHbV2cmn1nby0Q0MRthLsXP39mzLJ57U4TF01vj50yvBwcQQX9c32EeH+/Ta9Si6AbcCoBiHAtjFIQOgxN/j31fdNJTB7hPqnbu36fXsSXQDLh+CIIEXIcafAWLerwzgATP+/D1dBTrA3n/7prfx9PU2hh50A+66SS7bfA+Y8e9I5x+d5OHr9l6/XPpzkfJ9DEPGz5/Sa9yD6AbCbBrKw5AubVVI69pQT85PW9ihRzdAFaBbpYtkUfh/AXAJUODl6PBAKW0CuvNYucsDjwzxfAKXTL7Lhj0aS5sSetm68KpDDICchxIY92LiiLE1ulBKN7bWhHoceyxNN9C7/rh/byUAAG1euchLeIAbUNdaOcD3xc+tldLm4DpUEt2A622cWKGY79YGDH3tkcBEsdYj8+24RyXQDfQ6Zl4FEAwlMKyYH3L0vZa7Trf49IoblX09KoluoDetMgEE+PNfzxx3rrMKM71E+Gzs61FJdAPu+/nYk6hazQGbMdek6QZc9/O9Ozyg+4dqPCLfffyQ/rkqiG6gurougeHJ3ebNG3T/tXoS99++oX+uCqIbcJvO3jo+So+lP3/4l/6ZKohuwGU6Ax6290VhiFAS6EnM9Wi6gWrCElukddoak8PNeBNDuoFqwpCh69iZ7f0ylX7QshWv55BuoJq67lzzPPsvvRtvJ14nC92AuzTznFp7r/8qCvTo99/on6mw6AaqaOvWzyEnSqV7EUcCehjqugfC4+pGiXnBVEAPW11/Nb9z3vIvoO2qGvEvkqfJk/enZ6WB3tGkcBjq+lTNO9Clx9DbDtfb1xTdQBV17aD2DnTpVY4txys6HUU3UEVRgS69Dn093uEzdAOugPa+YafksbwT50uUHUU34Apoz0dmlX5Py7HzJcqOohuoonVOIfI6USq9wjGOeZwB3UAVrXMEgNcG0tJvAdh2euOuKboBd5Mnj2PL0uk8jTkhhOgGXC5veetWKZ3OxzHHzxDdgMtE89TmX+MNtCNnN2xB0Q242m3nbdKER9OlYZ7OOlV8NP9WEN2A6+4O5pO0LgdKTgNswFpTdAOun6ph6MHou6sF8zTu6kYW3YD7Lum+oS7xNoHpAPslC4luYBAvvOwDavidPxyyhkZxJ4NZdAODOZwFN8fuoweDS+VpO+kM0Q0M7ggtpHWJpEMiY1jU13vAR/HTOT7QtY6jzWADyFVWQpa9zLOm9p1vixXQ5MfGi8qvqcAYGOvX88Lf4fXEjHd9T50dOimgnaf0EDRqY6iRRTcw2LH0ELTndOeggC5QhNovtfSms5OPUXfULRPdwCDXpb3rrK1xc5tAtzL0mJyfRuzmFtB9HQXgSZO2YYboBiiKOJ6eCOZ2ga756mHWmHmr7WTOohugQs162FFSuDEbnQAmAR0sqbHO3ODSXBLQS4oAIIY2UcR4OeDJoUlAOz7Zs+ZGI6WyXXYd6XeUu1eneR1XYz9K8PapVEB0Ay6FDT1ewBbIJqAjgC2QTQldM7H7eBgDiNE0oDGyacjR1xgbcGNiViK58T3QvSKIrdQ14o9Xhw44JmoAcm/WmXIwS1kIsEL5zwAXX4OvxWvnlMJW45rwoZBUAxPQgkBBYEpoQWDRa0A3IKkGSUALAgWBKaEFgYWvAd2ApBokAS0IFASmhBYEFr4GdAOSapAEtCBQEJgSegYB9lDgNH50SWMfBlqZsOEIwj6L+VNDsf8iCyeI5n0ZEHoR836Ny4Svmf9/8D3y98s/Bz8TPxteIPhivNfFYohuoKgAAgAFJBnCDN5QjwGbvzHwmXCjLd4EugEsFtB4pcOQu7drnFM9un+vRdDpBoqIDZJnHb8/aumMaLqBImr5QPMf1YtnT+jXSUA7eu1EBG3H7xqnGyjWOcKGZQg6O/kUvVOGbsDNy+pb0fj5U/r1EtBLirC5sdHbu/6irIRsxl39oBtYWxo/rw718fsj+nUT0MGPxe1bo5hLeXQD4c+k8zz0uB5vgkg30OQJol40jjdBpBuodrqRHrZctJjSdAPV4dYej4uWUppuoJrwVAybdIa6y64vTc5P6ddKQC8pAvYTa7hx0eojcbqB4sJeYXbqDU17cV5yTzdQRUic+dNAtaR3sRRoHA/MvmYCesUiYDafOzyg3HaVW6Gg3B413zaV26nYKVpT4zgTQ7qBQQp7Ieb7EnFj4Mzn+Zsl9yd6/y1xdvIx0tId3UBz+tqce+eb3xDzvyW+NucefNOcW3LlZhwnnSG6AWnNGuA3Rb5Bdue61hdvjHnlbvNAqxsC2kHxJRPQgkA3QlJCC4LUSA3oBiTVIAloQaAgMCW0ILDwNaAbkFSDJKAFgYLAlNCCwMLXgG5AUg2SgBYECgJTQgsCC18DugFJNUgCWhAoCEwJLQgsfA3oBiTVIAloQaAgMCW0ILDwNaAbkFSDJKAFgYLAlNCCwMLXgG5AUg2SgBYECgJTQgsCC18DugFJNUgCWhAoCEwJLQgsfA3oBiTVIAloQaAgMCW0ILDwNaAbkFSDJKAFgYLAlNCCwMLXgG5AUg2SgBYECgL7tgb/A6oyzIW++c0FAAAAAElFTkSuQmCC",A="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M22.182%2015.499a1.7634%201.7634%200%200%201-.3536-.0358%201.8319%201.8319%200%200%201-1.2086-.8632l-.0066-.012c-.1308-.2616-.0448-.5693.2-.7162a.5236.5236%200%200%201%20.2689-.0743.5327.5327%200%200%201%20.4632.272.558.558%200%200%200%20.018.0299l.0564.0766.0757.0765a.7385.7385%200%200%200%20.3453.167.7596.7596%200%200%200%20.5954-.136.7206.7206%200%200%200%20.299-.5386.7441.7441%200%200%200-.207-.578s-1.5994-1.6612-1.6712-1.7382a1.9604%201.9604%200%200%201-.1929-.229c-.2256-.3198-.2962-.697-.2614-1.0702a1.7361%201.7361%200%200%201%20.2253-.7397s.0732-.124.0948-.1554c.0847-.1236.2515-.2834.3658-.3726a1.8813%201.8813%200%200%201%20.3069-.1844%201.7494%201.7494%200%200%201%202.2815.7041.5186.5186%200%200%201%20.0553.402.5298.5298%200%200%201-.2528.3263.5082.5082%200%200%201-.2593.0705.5283.5283%200%200%201-.46-.2706.6953.6953%200%200%200-.4656-.329.721.721%200%200%200-.5645.1269.688.688%200%200%200-.267.498.6998.6998%200%200%200%20.1905.5398l1.6351%201.6862a1.8284%201.8284%200%200%201%20.5071%201.3931c-.0465.5243-.3071.9994-.7152%201.3053a1.8425%201.8425%200%200%201-1.0984.369m-5.175-.0006a1.7608%201.7608%200%200%200%201.7585-1.7589v-3.4787a1.7587%201.7587%200%200%200-3.5173%200v3.4786a1.7608%201.7608%200%200%200%201.7587%201.7589m0-5.9342c.3777%200%20.6968.319.6968.6967v3.4786a.6977.6977%200%200%201-.6968.6968.6894.6894%200%200%201-.6968-.6968v-3.4786a.6976.6976%200%200%201%20.697-.6967m-7.8986.3224v5.0804a.5309.5309%200%200%200%201.0618%200V12.09Zm2.8802%202.0255V9.0328a.531.531%200%200%201%201.0619%200v5.0828zm1.053%202.9406v.1134a.533.533%200%200%201-1.0067.2408L9.1153%209.154v-.1212a.5261.5261%200%200%201%20.3028-.4772.5253.5253%200%200%201%20.7088.2475Zm-7.9067.6457a1.761%201.761%200%200%200%201.7586-1.7589v-3.4786a1.7587%201.7587%200%200%200-3.5173%200v3.4786a1.7609%201.7609%200%200%200%201.7587%201.7589m0-5.9342a.707.707%200%200%201%20.6968.6967v3.4786a.6968.6968%200%201%201-1.3936%200v-3.4786a.6976.6976%200%200%201%20.6968-.6967M0%2014.9111a.5791.5791%200%201%200%201.1581%200V9.0803a.5791.5791%200%200%200-1.1582%200z'/%3e%3c/svg%3e",_="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M22.006%2010.684a.15.15%200%200%200-.07-.15l-3.261-1.821a.14.14%200%200%200-.14%200l-2.771%201.69a.17.17%200%200%200-.07.13v1.451l-1.13-.74a.14.14%200%200%200-.15%200l-1.62%201-.071-1.64a.19.19%200%200%200-.07-.12l-1.65-1.09%201.51-.781a.16.16%200%200%200%20.08-.14l-.27-6.272a.16.16%200%200%200-.08-.13L8%200h-.1L2.08%201.81A.16.16%200%200%200%202%202l1.27%206.233a.22.22%200%200%200%200%20.08l1.83%201.38-1.26.6a.16.16%200%200%200-.08.17l1%204.702a.18.18%200%200%200%200%20.07L6%2016.375l-.8.49a.15.15%200%200%200-.06.16l.75%203.642a.11.11%200%200%200%200%20.07l3.002%203.221a.14.14%200%200%200%20.2%200l3.921-3.121a.16.16%200%200%200%20.06-.12l-.07-2.12%201.32%201.1a.14.14%200%200%200%20.18%200l3.142-2.511a.24.24%200%200%200%20.06-.11l.09-1.57%201%20.67a.14.14%200%200%200%20.17%200l2.571-2.001a.14.14%200%200%200%20.05-.1zm-9.623.15l.07%201.57.12%202.781-4.231%202.871-.66-4.532zm-.35-8.423l.25%205.912-5.002%202.59-.9-6.321zM3.54%208.123L2.33%202.26l3.74%202.32.931%206.203-1.58-1.2zM5%2015.055l-.88-4.261%203.281%202.74.6%204.382-1.68-1.62zm1.14%205.512l-.65-3.141%202.892%202.85.47%203.162zm3.002%203l-.49-3.33%204.001-2.871.14%203.28zm3.861-5.36v-1.081a.16.16%200%200%200-.05-.11l-1.13-.92%201-.7a.14.14%200%200%200%20.06-.12v-.261l1.39%201.06v3.211zm4.442-1.201l-2.861%202.28v-3.22l3.07-2.201zm1.29-1.21l-.9-.631.09-1.59a.11.11%200%200%200%200-.06.1.1%200%200%200%200-.05l-1.93-1.27v-1.391l3%201.89zm2.55-1.861l-2.28%201.81.26-3.06%202.431-1.681z'/%3e%3c/svg%3e",d="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eNvidia%3c/title%3e%3cpath%20d='M10.212%208.976V7.62c.127-.01.256-.017.388-.021%203.596-.117%205.957%203.184%205.957%203.184s-2.548%203.647-5.282%203.647a3.227%203.227%200%2001-1.063-.175v-4.109c1.4.174%201.681.812%202.523%202.258l1.873-1.627a4.905%204.905%200%2000-3.67-1.846%206.594%206.594%200%2000-.729.044m0-4.476v2.025c.13-.01.259-.019.388-.024%205.002-.174%208.261%204.226%208.261%204.226s-3.743%204.69-7.643%204.69c-.338%200-.675-.031-1.007-.092v1.25c.278.038.558.057.838.057%203.629%200%206.253-1.91%208.794-4.169.421.347%202.146%201.193%202.501%201.564-2.416%202.083-8.048%203.763-11.24%203.763-.308%200-.603-.02-.894-.048V19.5H24v-15H10.21zm0%209.756v1.068c-3.356-.616-4.287-4.21-4.287-4.21a7.173%207.173%200%20014.287-2.138v1.172h-.005a3.182%203.182%200%2000-2.502%201.178s.615%202.276%202.507%202.931m-5.961-3.3c1.436-1.935%203.604-3.148%205.961-3.336V6.523C5.81%206.887%202%2010.723%202%2010.723s2.158%206.427%208.21%207.015v-1.166C5.77%2016%204.25%2010.958%204.25%2010.958h-.002z'%20fill='%2374B71B'%20fill-rule='nonzero'%3e%3c/path%3e%3c/svg%3e",m="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eOllama%3c/title%3e%3cpath%20d='M7.905%201.09c.216.085.411.225.588.41.295.306.544.744.734%201.263.191.522.315%201.1.362%201.68a5.054%205.054%200%20012.049-.636l.051-.004c.87-.07%201.73.087%202.48.474.101.053.2.11.297.17.05-.569.172-1.134.36-1.644.19-.52.439-.957.733-1.264a1.67%201.67%200%2001.589-.41c.257-.1.53-.118.796-.042.401.114.745.368%201.016.737.248.337.434.769.561%201.287.23.934.27%202.163.115%203.645l.053.04.026.019c.757.576%201.284%201.397%201.563%202.35.435%201.487.216%203.155-.534%204.088l-.018.021.002.003c.417.762.67%201.567.724%202.4l.002.03c.064%201.065-.2%202.137-.814%203.19l-.007.01.01.024c.472%201.157.62%202.322.438%203.486l-.006.039a.651.651%200%2001-.747.536.648.648%200%2001-.54-.742c.167-1.033.01-2.069-.48-3.123a.643.643%200%2001.04-.617l.004-.006c.604-.924.854-1.83.8-2.72-.046-.779-.325-1.544-.8-2.273a.644.644%200%2001.18-.886l.009-.006c.243-.159.467-.565.58-1.12a4.229%204.229%200%2000-.095-1.974c-.205-.7-.58-1.284-1.105-1.683-.595-.454-1.383-.673-2.38-.61a.653.653%200%2001-.632-.371c-.314-.665-.772-1.141-1.343-1.436a3.288%203.288%200%2000-1.772-.332c-1.245.099-2.343.801-2.67%201.686a.652.652%200%2001-.61.425c-1.067.002-1.893.252-2.497.703-.522.39-.878.935-1.066%201.588a4.07%204.07%200%2000-.068%201.886c.112.558.331%201.02.582%201.269l.008.007c.212.207.257.53.109.785-.36.622-.629%201.549-.673%202.44-.05%201.018.186%201.902.719%202.536l.016.019a.643.643%200%2001.095.69c-.576%201.236-.753%202.252-.562%203.052a.652.652%200%2001-1.269.298c-.243-1.018-.078-2.184.473-3.498l.014-.035-.008-.012a4.339%204.339%200%2001-.598-1.309l-.005-.019a5.764%205.764%200%2001-.177-1.785c.044-.91.278-1.842.622-2.59l.012-.026-.002-.002c-.293-.418-.51-.953-.63-1.545l-.005-.024a5.352%205.352%200%2001.093-2.49c.262-.915.777-1.701%201.536-2.269.06-.045.123-.09.186-.132-.159-1.493-.119-2.73.112-3.67.127-.518.314-.95.562-1.287.27-.368.614-.622%201.015-.737.266-.076.54-.059.797.042zm4.116%209.09c.936%200%201.8.313%202.446.855.63.527%201.005%201.235%201.005%201.94%200%20.888-.406%201.58-1.133%202.022-.62.375-1.451.557-2.403.557-1.009%200-1.871-.259-2.493-.734-.617-.47-.963-1.13-.963-1.845%200-.707.398-1.417%201.056-1.946.668-.537%201.55-.849%202.485-.849zm0%20.896a3.07%203.07%200%2000-1.916.65c-.461.37-.722.835-.722%201.25%200%20.428.21.829.61%201.134.455.347%201.124.548%201.943.548.799%200%201.473-.147%201.932-.426.463-.28.7-.686.7-1.257%200-.423-.246-.89-.683-1.256-.484-.405-1.14-.643-1.864-.643zm.662%201.21l.004.004c.12.151.095.37-.056.49l-.292.23v.446a.375.375%200%2001-.376.373.375.375%200%2001-.376-.373v-.46l-.271-.218a.347.347%200%2001-.052-.49.353.353%200%2001.494-.051l.215.172.22-.174a.353.353%200%2001.49.051zm-5.04-1.919c.478%200%20.867.39.867.871a.87.87%200%2001-.868.871.87.87%200%2001-.867-.87.87.87%200%2001.867-.872zm8.706%200c.48%200%20.868.39.868.871a.87.87%200%2001-.868.871.87.87%200%2001-.867-.87.87.87%200%2001.867-.872zM7.44%202.3l-.003.002a.659.659%200%2000-.285.238l-.005.006c-.138.189-.258.467-.348.832-.17.692-.216%201.631-.124%202.782.43-.128.899-.208%201.404-.237l.01-.001.019-.034c.046-.082.095-.161.148-.239.123-.771.022-1.692-.253-2.444-.134-.364-.297-.65-.453-.813a.628.628%200%2000-.107-.09L7.44%202.3zm9.174.04l-.002.001a.628.628%200%2000-.107.09c-.156.163-.32.45-.453.814-.29.794-.387%201.776-.23%202.572l.058.097.008.014h.03a5.184%205.184%200%20011.466.212c.086-1.124.038-2.043-.128-2.722-.09-.365-.21-.643-.349-.832l-.004-.006a.659.659%200%2000-.285-.239h-.004z'%3e%3c/path%3e%3c/svg%3e",r="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eOpenAI%3c/title%3e%3cpath%20d='M9.205%208.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357%201.356-.523%202.117-.523%202.854%200%204.662%202.212%204.662%204.566%200%20.167%200%20.357-.024.547l-4.71-2.759a.797.797%200%2000-.856%200l-5.97%203.473zm10.609%208.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473%201.95-1.118a.433.433%200%2001.476%200l4.543%202.617c1.309.76%202.189%202.378%202.189%203.948%200%201.808-1.07%203.473-2.76%204.163zM7.802%2012.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545%201.95-4.472%204.591-4.472%201%200%201.927.333%202.712.928L8.23%205.067c-.285.166-.428.404-.428.737v6.898zM12%2015.128l-2.795-1.57v-3.33L12%208.658l2.795%201.57v3.33L12%2015.128zm1.796%207.23c-1%200-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974%201.142c.167.095.238.238.238.428v5.233c0%202.545-1.974%204.472-4.614%204.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482%204.482%200%20014.21%206.327v5.423c0%20.333.143.571.428.738l5.947%203.449-1.95%201.118a.432.432%200%2001-.476%200zm-.262%203.9c-2.688%200-4.662-2.021-4.662-4.519%200-.19.024-.38.047-.57l4.686%202.71c.286.167.571.167.856%200l5.97-3.448v2.26c0%20.19-.07.333-.237.428l-4.543%202.616c-.619.357-1.356.523-2.117.523zm5.899%202.83a5.947%205.947%200%20005.827-4.756C22.287%2018.339%2024%2015.84%2024%2013.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498%200-3.401-2.759-5.947-5.946-5.947-.642%200-1.26.095-1.88.31A5.962%205.962%200%200010.205%200a5.947%205.947%200%2000-5.827%204.757C1.713%205.447%200%207.945%200%2010.49c0%201.666.713%203.283%201.998%204.448-.119.5-.19%201-.19%201.499%200%203.401%202.759%205.946%205.946%205.946.642%200%201.26-.095%201.88-.309a5.96%205.96%200%20004.162%201.713z'%3e%3c/path%3e%3c/svg%3e",B="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eOpenClaw%3c/title%3e%3cpath%20d='M12%202.568c-6.33%200-9.495%205.275-9.495%209.495%200%204.22%203.165%208.44%206.33%209.494v2.11h2.11v-2.11s1.055.422%202.11%200v2.11h2.11v-2.11c3.165-1.055%206.33-5.274%206.33-9.494S18.33%202.568%2012%202.568z'%20fill='url(%23lobe-icons-open-claw-0-_R_0_)'%3e%3c/path%3e%3cpath%20d='M3.56%209.953C.396%208.898-.66%2011.008.396%2013.118c1.055%202.11%203.164%201.055%204.22-1.055.632-1.477%200-2.11-1.056-2.11z'%20fill='url(%23lobe-icons-open-claw-1-_R_0_)'%3e%3c/path%3e%3cpath%20d='M20.44%209.953c3.164-1.055%204.22%201.055%203.164%203.165-1.055%202.11-3.164%201.055-4.22-1.055-.632-1.477%200-2.11%201.056-2.11z'%20fill='url(%23lobe-icons-open-claw-2-_R_0_)'%3e%3c/path%3e%3cpath%20d='M5.507%201.875c.476-.285%201.036-.233%201.615.037.577.27%201.223.774%201.937%201.488a.316.316%200%2001-.447.447c-.693-.693-1.279-1.138-1.757-1.361-.475-.222-.795-.205-1.022-.069a.317.317%200%2001-.326-.542zM16.877%201.913c.58-.27%201.14-.323%201.616-.038a.317.317%200%2001-.326.542c-.227-.136-.547-.153-1.022.069-.478.223-1.064.668-1.756%201.361a.316.316%200%2011-.448-.447c.714-.714%201.36-1.218%201.936-1.487z'%20fill='%23FF4D4D'%3e%3c/path%3e%3cpath%20d='M8.835%209.109a1.266%201.266%200%20100-2.532%201.266%201.266%200%20000%202.532zM15.165%209.109a1.266%201.266%200%20100-2.532%201.266%201.266%200%20000%202.532z'%20fill='%23050810'%3e%3c/path%3e%3cpath%20d='M9.046%208.16a.527.527%200%20100-1.056.527.527%200%20000%201.055zM15.376%208.16a.527.527%200%20100-1.055.527.527%200%20000%201.054z'%20fill='%2300E5CC'%3e%3c/path%3e%3cdefs%3e%3clinearGradient%20gradientUnits='userSpaceOnUse'%20id='lobe-icons-open-claw-0-_R_0_'%20x1='-.659'%20x2='27.023'%20y1='.458'%20y2='22.855'%3e%3cstop%20stop-color='%23FF4D4D'%3e%3c/stop%3e%3cstop%20offset='1'%20stop-color='%23991B1B'%3e%3c/stop%3e%3c/linearGradient%3e%3clinearGradient%20gradientUnits='userSpaceOnUse'%20id='lobe-icons-open-claw-1-_R_0_'%20x1='0'%20x2='4.311'%20y1='9.672'%20y2='14.949'%3e%3cstop%20stop-color='%23FF4D4D'%3e%3c/stop%3e%3cstop%20offset='1'%20stop-color='%23991B1B'%3e%3c/stop%3e%3c/linearGradient%3e%3clinearGradient%20gradientUnits='userSpaceOnUse'%20id='lobe-icons-open-claw-2-_R_0_'%20x1='19.385'%20x2='24.399'%20y1='9.953'%20y2='14.462'%3e%3cstop%20stop-color='%23FF4D4D'%3e%3c/stop%3e%3cstop%20offset='1'%20stop-color='%23991B1B'%3e%3c/stop%3e%3c/linearGradient%3e%3c/defs%3e%3c/svg%3e",x="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eOpenRouter%3c/title%3e%3cpath%20d='M18.654%203.87a5.087%205.087%200%20110%2010.174L23.7%2019.09c.64.641.187%201.737-.72%201.737H8.48a8.479%208.479%200%20010-16.958h10.175zM8.479%207.26a5.087%205.087%200%20100%2010.176%205.087%205.087%200%20000-10.175z'%3e%3c/path%3e%3c/svg%3e",z="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M16.412%204.412h-8.82a7.588%207.588%200%200%200-.008%2015.176h8.828a7.588%207.588%200%200%200%200-15.176zm-.193%2012.502H7.786a4.915%204.915%200%200%201%200-9.828h8.433a4.914%204.914%200%201%201%200%209.828z'/%3e%3c/svg%3e",L="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M19.881%2010.095l2.563-4.45C23.434%207.389%2024%209.404%2024%2011.555c0%202.88-1.017%205.523-2.71%207.594h-6.62l2.04-3.541h-2.696l3.176-5.513h2.691zm-2.32-5.243L9.333%2019.14l.003.009H2.709C1.014%2017.077%200%2014.435%200%2011.555c0-2.152.57-4.17%201.561-5.918L5.855%2013.1%2010.6%204.852h6.961z'/%3e%3c/svg%3e",C="/assets/raspberrypi-CW7KYKqj.svg",b="data:image/svg+xml,%3csvg%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M8.36%202.172A1.194%201.194%200%20007.348%201.6H1.2A1.2%201.2%200%20000%202.8a1.211%201.211%200%2000.182.64l11.6%2018.4a1.206%201.206%200%20002.035%200l3.075-4.874a1.229%201.229%200%2000.182-.64%201.211%201.211%200%2000-.182-.642zm10.349%208.68a1.206%201.206%200%20002.035%200L21.8%209.178l2.017-3.2a1.211%201.211%200%2000.183-.64%201.229%201.229%200%2000-.183-.64l-1.6-2.526a1.206%201.206%200%2000-1.016-.571h-6.148a1.2%201.2%200%2000-1.201%201.2%201.143%201.143%200%2000.188.64z'/%3e%3c/svg%3e",f="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eGrok%3c/title%3e%3cpath%20d='M9.27%2015.29l7.978-5.897c.391-.29.95-.177%201.137.272.98%202.369.542%205.215-1.41%207.169-1.951%201.954-4.667%202.382-7.149%201.406l-2.711%201.257c3.889%202.661%208.611%202.003%2011.562-.953%202.341-2.344%203.066-5.539%202.388-8.42l.006.007c-.983-4.232.242-5.924%202.75-9.383.06-.082.12-.164.179-.248l-3.301%203.305v-.01L9.267%2015.292M7.623%2016.723c-2.792-2.67-2.31-6.801.071-9.184%201.761-1.763%204.647-2.483%207.166-1.425l2.705-1.25a7.808%207.808%200%2000-1.829-1A8.975%208.975%200%20005.984%205.83c-2.533%202.536-3.33%206.436-1.962%209.764%201.022%202.487-.653%204.246-2.34%206.022-.599.63-1.199%201.259-1.682%201.925l7.62-6.815'%3e%3c/path%3e%3c/svg%3e";export{f as _,b as a,C as b,L as c,z as d,x as e,B as f,r as g,m as h,d as i,_ as j,A as k,w as l,h as m,p as n,n as o,i as p,g as q,v as r,o as s,s as t,t as u,l as v,c as w,a as x,e as y};diff --git a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/IdeSidePanel.test.tsx b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/IdeSidePanel.test.tsxindex ec8dbc2fef..884f202552 100644--- a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/IdeSidePanel.test.tsx+++ b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/IdeSidePanel.test.tsx@@ -16,9 +16,9 @@ vi.mock("@/components/workspace/WorkspaceTerminal", () => ({}));// The real stage is a WebGL scene; the tab only owes it the right props and a place to live.-vi.mock("@/components/society/office/OfficeStage", () => ({- OfficeStage: ({ onOpenLedger, initialFloor, compact }: { onOpenLedger: () => void; initialFloor?: string; compact?: boolean }) => (- <div data-testid="office-stage" data-floor={initialFloor} data-compact={String(Boolean(compact))}>+vi.mock("@/components/society/starship/ShipStage", () => ({+ ShipStage: ({ onOpenLedger, initialDeck, compact }: { onOpenLedger: () => void; initialDeck?: string; compact?: boolean }) => (+ <div data-testid="office-stage" data-floor={initialDeck} data-compact={String(Boolean(compact))}><button type="button" onClick={onOpenLedger}>ledger</button></div>),@@ -263,7 +263,7 @@ describe("IdeSidePanel", () => {expect(screen.queryByTestId("ide-side-panel-waiting")).toBeNull();});- it("adds the Dodaios Verse tab from + and shows the coding floor in a compact stage", async () => {+ it("adds the Dodaios Verse tab from + and shows the engineering deck in a compact stage", async () => {act(() => useIdeSidePanelStore.setState({ open: true, tabs: ["agents"], active: "agents" }));render(<Harness />);fireEvent.click(screen.getByTestId("ide-side-panel-add"));@@ -275,7 +275,7 @@ describe("IdeSidePanel", () => {expect(screen.getByTestId("ide-side-panel-tab-office").getAttribute("aria-selected")).toBe("true");expect(screen.getByTestId("ide-office-tab").className).toContain("h-full");const stage = await screen.findByTestId("office-stage");- expect(stage.getAttribute("data-floor")).toBe("coding");+ expect(stage.getAttribute("data-floor")).toBe("engineering");expect(stage.getAttribute("data-compact")).toBe("true");});diff --git a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/OfficeTab.tsx b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/OfficeTab.tsxindex 929ed0bab9..b73f7393e2 100644--- a/dodaios/ui/web/frontend/src/components/agentic/sidePanel/OfficeTab.tsx+++ b/dodaios/ui/web/frontend/src/components/agentic/sidePanel/OfficeTab.tsx@@ -3,9 +3,9 @@ import { AlertTriangle, RotateCcw } from "lucide-react";import { translate, useLocaleChunk } from "@/i18n";import { useIdeSidePanelStore } from "@/store/ideSidePanel";-// The office is a WebGL scene with its own chunk: nothing of it loads until+// The ship is a WebGL scene with its own chunk: nothing of it loads until// someone opens this tab.-const OfficeStage = lazy(() => import("@/components/society/office/OfficeStage").then((m) => ({ default: m.OfficeStage })));+const ShipStage = lazy(() => import("@/components/society/starship/ShipStage").then((m) => ({ default: m.ShipStage })));/** Keeps a failed scene inside the tab instead of taking the IDE down with it. */class OfficeTabBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {@@ -39,11 +39,11 @@ class OfficeTabBoundary extends Component<{ children: ReactNode }, { failed: boo}/**- * The coding floor of the agent office, inside the IDE's side panel.+ * The ship's engineering deck, inside the IDE's side panel.*- * Every running coding-agent pane walks around here; a click on a monitor- * focuses that pane in the grid next to it. The office's "open the ledger"- * action has no ledger in the IDE, so it brings the Agents tab forward.+ * Every running coding-agent pane works at a console here; a click on its+ * screen focuses that pane in the grid next to it. The ship's "open the+ * ledger" action has no ledger in the IDE, so it brings the Agents tab forward.*/export function OfficeTab() {const ready = useLocaleChunk("society");@@ -53,7 +53,7 @@ export function OfficeTab() {<OfficeTabBoundary>{ready && (<Suspense fallback={<div className="h-full w-full animate-pulse bg-secondary" aria-hidden />}>- <OfficeStage initialFloor="coding" compact onOpenLedger={() => openTab("agents")} />+ <ShipStage initialDeck="engineering" compact onOpenLedger={() => openTab("agents")} /></Suspense>)}</OfficeTabBoundary>diff --git a/dodaios/ui/web/frontend/src/components/society/office/ArcadeCabinet.tsx b/dodaios/ui/web/frontend/src/components/society/arcade/ArcadeCabinet.tsxsimilarity index 100%rename from dodaios/ui/web/frontend/src/components/society/office/ArcadeCabinet.tsxrename to dodaios/ui/web/frontend/src/components/society/arcade/ArcadeCabinet.tsxdiff --git a/dodaios/ui/web/frontend/src/components/society/arcade/ArcadeHall.tsx b/dodaios/ui/web/frontend/src/components/society/arcade/ArcadeHall.tsxdeleted file mode 100644index f45b4e3226..0000000000--- a/dodaios/ui/web/frontend/src/components/society/arcade/ArcadeHall.tsx+++ /dev/null@@ -1,460 +0,0 @@-/**- * The arcade floor: a neon-lit arcade floating in a violet night, the top- * floor of the building. Its rooms (arcadeFloorLayout) stand behind smoked- * glass with a neon cap in each room's colour, a lit name board over every- * door, the room's own floor and a neon logo inlaid in it; the open hall in- * the middle keeps the blacklight carpet, the pinballs, the air hockey and- * the dance floor.- *- * Renders everything floor-specific; OfficeScene adds the person, the- * camera, the elevator's call button and the checkpoint marker on top.- *- * Kept cheap on purpose: one shadow-casting light plus a hemisphere and an- * ambient light (the neon comes from self-lit materials, not from lamps);- * all wall frames are one merged mesh, all glass another, all neon caps a- * third; cabinet screens flip between two baked attract frames by moving a- * texture offset, so nothing is redrawn or re-uploaded while you walk around.- */-import { useEffect, useMemo, useRef } from "react";-import { Stars } from "@react-three/drei";-import { useFrame, type ThreeEvent } from "@react-three/fiber";-import {- AdditiveBlending, BoxGeometry, Color, DoubleSide, InstancedMesh, MeshBasicMaterial, MeshStandardMaterial, Object3D, PlaneGeometry, RepeatWrapping,- type BufferGeometry, type Texture,-} from "three";-import { useT } from "@/i18n";-import { cachedCanvasTexture } from "../office/canvasMaterials";-import { Box, Railing } from "../office/OfficeFurniture";-import { FurniturePiece } from "../office/OfficeProps";-import type { Furniture, OfficeLayout, Point, Rect, Room, RoomKind, WallSegment } from "../office/officeLayout";-import { ARCADE_GAMES, gameForCabinet } from "./arcadeGames";-import { arcadeDecor, ROOM_ACCENT } from "./arcadeFloorLayout";-import { drawGlowSpot, HALL, HALL_MAT, PartKit, ROOM_FLOORS, type ArcadeRoomKind } from "./arcadeHallLook";-import { floorLogoMaterial, neonMaterial, roomBoardMaterial, setScreenFrame, type NeonSymbol } from "./arcadeScreens";--export interface ArcadeHallProps {- layout: OfficeLayout;- onFloorClick: (event: ThreeEvent<MouseEvent>) => void;- /** Furniture id of the cabinet the person stands at, or null. Its screen and floor glow brighten. */- nearCabinet: string | null;- awake: boolean;- reduced: boolean;-}--/** Height of the rooms' glass walls; the name boards sit on top of the door headers. */-const WALL_H = 2.2;-/** The name board over a door: width, height, and how far above the wall top its centre sits. */-const BOARD = { w: 2.5, h: 0.58, lift: 0.36 } as const;-/** Seconds each attract frame stays on the cabinets' screens. */-const ATTRACT_FRAME_S = 0.6;-/** Seconds between two steps of the dance pad's light chase. */-const PAD_STEP_S = 0.45;--/** Each room's neon symbol: on its glass and in its floor logo. */-const ROOM_SYMBOL: Partial<Record<RoomKind, NeonSymbol>> = {- classics: "alien", puzzle: "joystick", action: "bolt", foyer: "coin", prizes: "ticket", snack: "soda", arcade: "star",-};--const accentOf = (kind: RoomKind) => ROOM_ACCENT[kind] ?? HALL.neon.magenta;--/** A cached base texture, cloned per surface with its own repeat (the clone belongs to the caller). */-function repeated(base: Texture | null, repeatX: number, repeatY: number): Texture | null {- if (!base) return null;- const map = base.clone();- map.wrapS = map.wrapT = RepeatWrapping;- map.anisotropy = 8;- map.repeat.set(repeatX, repeatY);- map.needsUpdate = true;- return map;-}--const RIM = new MeshBasicMaterial({ color: HALL.rim, toneMapped: false });-const UNIT_BOX = new BoxGeometry(1, 1, 1);-/** The dance pad's dark frame between its lit tiles. */-const PAD_BASE = new MeshStandardMaterial({ color: "#07060d", roughness: 0.4 });-/** Smoked glass: dark enough to read as a wall, clear enough that no camera angle loses a room behind it. */-const SMOKED_GLASS = new MeshStandardMaterial({- color: "#3a3358", transparent: true, opacity: 0.3, roughness: 0.08, metalness: 0.2, side: DoubleSide, depthWrite: false,-});-const BOARD_BACK = new MeshStandardMaterial({ color: HALL.frame, roughness: 0.5, metalness: 0.3 });-const BOARD_PLANE = new PlaneGeometry(BOARD.w - 0.06, BOARD.h - 0.06);-const LOGO_PLANE = new PlaneGeometry(1, 1);--// ----------------------------------------------------------------------------// Slab and floors-// -----------------------------------------------------------------------------function floorMaterial(kind: ArcadeRoomKind, w: number, d: number): MeshStandardMaterial {- const floor = ROOM_FLOORS[kind];- const map = repeated(cachedCanvasTexture(`arcade:floor:${kind}`, 256, 256, floor.draw), w / floor.metres, d / floor.metres);- return new MeshStandardMaterial({- color: map ? "#ffffff" : HALL.carpet.base, map, roughness: floor.roughness,- // Carpets glow faintly under the "blacklight"; stone and tiles do not.- ...(map && floor.glow > 0 ? { emissive: "#ffffff", emissiveMap: map, emissiveIntensity: floor.glow } : {}),- });-}--/** The slab: a dark edge with a glowing rim, the hall's carpet over all of it (everyone walks and clicks on it), railings round it. */-function HallSlab({ layout, onFloorClick }: { layout: OfficeLayout; onFloorClick: (event: ThreeEvent<MouseEvent>) => void }) {- const { minX, maxX, minZ, maxZ } = layout.bounds;- const w = maxX - minX, d = maxZ - minZ, cx = (minX + maxX) / 2, cz = (minZ + maxZ) / 2;- const carpet = useMemo(() => floorMaterial("arcade", w, d), [w, d]);- const edge = useMemo(() => new MeshStandardMaterial({ color: HALL.slabEdge, roughness: 0.8 }), []);- useEffect(() => () => { carpet.map?.dispose(); carpet.dispose(); edge.dispose(); }, [carpet, edge]);- const glow = 0.05, inset = 0.15;- return (- <group>- <Box size={[w, 0.6, d]} position={[cx, -0.3, cz]} material={edge} cast={false} />- <mesh geometry={UNIT_BOX} material={RIM} position={[cx, -0.06, maxZ]} scale={[w + glow, glow, glow]} />- <mesh geometry={UNIT_BOX} material={RIM} position={[maxX, -0.06, cz]} scale={[glow, glow, d + glow]} />- <mesh geometry={UNIT_BOX} material={RIM} position={[cx, -0.06, minZ]} scale={[w + glow, glow, glow]} />- <mesh geometry={UNIT_BOX} material={RIM} position={[minX, -0.06, cz]} scale={[glow, glow, d + glow]} />- <mesh position={[cx, 0.001, cz]} rotation={[-Math.PI / 2, 0, 0]} material={carpet} receiveShadow onClick={onFloorClick}>- <planeGeometry args={[w, d]} />- </mesh>- <Railing from={[minX + inset, maxZ - inset]} to={[maxX - inset, maxZ - inset]} />- <Railing from={[maxX - inset, maxZ - inset]} to={[maxX - inset, minZ + inset]} />- <Railing from={[maxX - inset, minZ + inset]} to={[minX + inset, minZ + inset]} />- <Railing from={[minX + inset, minZ + inset]} to={[minX + inset, maxZ - inset]} />- </group>- );-}--/** A walled room's own floor, laid over the hall's carpet (and just as clickable). */-function RoomFloor({ room, onFloorClick }: { room: Room; onFloorClick: (event: ThreeEvent<MouseEvent>) => void }) {- const w = room.maxX - room.minX, d = room.maxZ - room.minZ;- const material = useMemo(() => (room.kind in ROOM_FLOORS ? floorMaterial(room.kind as ArcadeRoomKind, w, d) : null), [room.kind, w, d]);- useEffect(() => () => { material?.map?.dispose(); material?.dispose(); }, [material]);- if (!material) return null;- return (- <mesh position={[(room.minX + room.maxX) / 2, 0.004, (room.minZ + room.maxZ) / 2]} rotation={[-Math.PI / 2, 0, 0]}- material={material} receiveShadow onClick={onFloorClick}>- <planeGeometry args={[w, d]} />- </mesh>- );-}--// ----------------------------------------------------------------------------// Walls, door headers and name boards-// -----------------------------------------------------------------------------/** An axis-aligned box along a wall run (or across a door), `thick` deep, from y0 to y1. */-function runBox(kit: PartKit, from: Point, to: Point, thick: number, y0: number, y1: number, colour: string): void {- const length = Math.hypot(to.x - from.x, to.z - from.z);- if (length < 0.02) return;- const alongX = Math.abs(to.x - from.x) >= Math.abs(to.z - from.z);- kit.box(alongX ? [length, y1 - y0, thick] : [thick, y1 - y0, length], [(from.x + to.x) / 2, (y0 + y1) / 2, (from.z + to.z) / 2], colour);-}--/** Every door of the walled rooms as a run across its gap, with the room it belongs to. */-function doorRuns(rooms: readonly Room[]): { room: Room; from: Point; to: Point }[] {- return rooms.filter((r) => r.walled).flatMap((room) => room.doors.map((door) => {- const half = door.width / 2;- switch (door.side) {- case "north": return { room, from: { x: door.at - half, z: room.minZ }, to: { x: door.at + half, z: room.minZ } };- case "south": return { room, from: { x: door.at - half, z: room.maxZ }, to: { x: door.at + half, z: room.maxZ } };- case "west": return { room, from: { x: room.minX, z: door.at - half }, to: { x: room.minX, z: door.at + half } };- case "east": return { room, from: { x: room.maxX, z: door.at - half }, to: { x: room.maxX, z: door.at + half } };- }- }));-}--/**- * All glass walls in three draws: the dark steel frames (foot, posts, top- * rail, door headers), the smoked panes, and the neon caps in each room's colour.- */-function GlassWalls({ walls, rooms }: { walls: readonly WallSegment[]; rooms: readonly Room[] }) {- const geometries = useMemo(() => {- const frame = new PartKit(), glass = new PartKit(), neon = new PartKit();- for (const wall of walls) {- const from = { x: wall.x1, z: wall.z1 }, to = { x: wall.x2, z: wall.z2 };- const length = Math.hypot(to.x - from.x, to.z - from.z);- if (length < 0.05) continue;- runBox(frame, from, to, 0.1, 0, 0.1, HALL.frame);- runBox(glass, from, to, 0.02, 0.1, WALL_H - 0.05, "#ffffff");- runBox(frame, from, to, 0.08, WALL_H - 0.05, WALL_H, HALL.frame);- runBox(neon, from, to, 0.05, WALL_H, WALL_H + 0.025, accentOf(wall.room));- // Posts at both ends and at most every two metres between.- const posts = Math.max(2, Math.ceil(length / 2) + 1);- for (let i = 0; i < posts; i += 1) {- const k = i / (posts - 1);- const p = { x: from.x + (to.x - from.x) * k, z: from.z + (to.z - from.z) * k };- frame.box([0.06, WALL_H, 0.06], [p.x, WALL_H / 2, p.z], HALL.frame);- }- }- // Each door: a header across the top of the gap, lit underneath like an entrance.- for (const { room, from, to } of doorRuns(rooms)) {- runBox(frame, from, to, 0.1, WALL_H - 0.1, WALL_H, HALL.frame);- runBox(neon, from, to, 0.05, WALL_H - 0.125, WALL_H - 0.1, accentOf(room.kind));- }- return { frame: frame.build(), glass: glass.build(), neon: neon.build() };- }, [walls, rooms]);- useEffect(() => () => { geometries.frame.dispose(); geometries.glass.dispose(); geometries.neon.dispose(); }, [geometries]);- return (- <group>- <mesh geometry={geometries.frame} material={HALL_MAT.gloss} castShadow receiveShadow />- <mesh geometry={geometries.glass} material={SMOKED_GLASS} renderOrder={2} />- <mesh geometry={geometries.neon} material={HALL_MAT.glow} />- </group>- );-}--/** A lit name board over a room's door, readable from both sides. */-function RoomBoard({ room, label }: { room: Room; label: string }) {- const door = doorRuns([room])[0];- if (!door) return null;- const along = Math.abs(door.to.x - door.from.x) >= Math.abs(door.to.z - door.from.z);- const material = roomBoardMaterial(label, accentOf(room.kind));- return (- <group position={[(door.from.x + door.to.x) / 2, WALL_H + BOARD.lift, (door.from.z + door.to.z) / 2]} rotation={[0, along ? 0 : Math.PI / 2, 0]}>- <mesh geometry={UNIT_BOX} material={BOARD_BACK} scale={[BOARD.w, BOARD.h, 0.05]} />- <mesh geometry={BOARD_PLANE} material={material} position={[0, 0, 0.026]} />- <mesh geometry={BOARD_PLANE} material={material} position={[0, 0, -0.026]} rotation={[0, Math.PI, 0]} />- </group>- );-}--interface WallSign { symbol: NeonSymbol; x: number; z: number; y: number; size: number }--/**- * Each room's neon symbol on its glass: on the back wall beside the cabinets- * in the game rooms, on the far (south) wall in the rooms of the south strip.- */-function wallSigns(layout: OfficeLayout): WallSign[] {- const hall = layout.rooms.find((r) => r.kind === "arcade");- const signs: WallSign[] = [];- for (const room of layout.rooms) {- const symbol = ROOM_SYMBOL[room.kind];- if (!symbol || !room.walled) continue;- const north = !!hall && room.maxZ <= hall.minZ + 1e-6;- if (north) {- const cabinets = layout.furniture.filter((f) => f.kind === "retroCabinet" && f.room === room.kind);- const xs = cabinets.map((c) => c.x);- // On whichever side of the cabinet row has more room.- const left = xs.length ? Math.min(...xs) - room.minX : 0, right = xs.length ? room.maxX - Math.max(...xs) : 0;- const x = left >= right ? (room.minX + Math.min(...xs)) / 2 - 0.2 : (room.maxX + Math.max(...xs)) / 2 + 0.2;- signs.push({ symbol, x, z: room.minZ + 0.04, y: 1.45, size: 0.95 });- } else {- signs.push({ symbol, x: (room.minX + room.maxX) / 2 + 1.2, z: room.maxZ - 0.04, y: 1.45, size: 1.0 });- }- }- return signs;-}--function WallSigns({ layout }: { layout: OfficeLayout }) {- const signs = useMemo(() => wallSigns(layout), [layout]);- return (- <group>- {signs.map((sign) => (- <mesh key={`${sign.symbol}:${sign.x}`} geometry={LOGO_PLANE} material={neonMaterial(sign.symbol)} scale={[sign.size, sign.size, 1]}- position={[sign.x, sign.y, sign.z]} />- ))}- </group>- );-}--// ----------------------------------------------------------------------------// Lights-// -----------------------------------------------------------------------------function HallLights({ layout }: { layout: OfficeLayout }) {- const { minX, maxX, minZ, maxZ } = layout.bounds;- const span = Math.max(maxX - minX, maxZ - minZ);- return (- <>- <hemisphereLight args={[HALL.sky, HALL.ground, 1.05]} />- <ambientLight intensity={0.32} />- <directionalLight position={[maxX + 10, 26, maxZ + 6]} intensity={1.2} color={HALL.sun} castShadow- shadow-mapSize={[2048, 2048]} shadow-bias={-0.0004} shadow-normalBias={0.03}- shadow-camera-left={-span * 0.7} shadow-camera-right={span * 0.7}- shadow-camera-top={span * 0.7} shadow-camera-bottom={-span * 0.7} shadow-camera-far={120} />- </>- );-}--// ----------------------------------------------------------------------------// Floor decor-// -----------------------------------------------------------------------------let tableGeometry: BufferGeometry | null = null;-/** A bistro table on a chrome pedestal with three red stools round it, inside the layout's SNACK_TABLE_HALF footprint. */-function bistroTable(): BufferGeometry {- if (!tableGeometry) {- const kit = new PartKit();- kit.cylinder(0.22, 0.03, [0, 0.015, 0], HALL.chrome, { segments: 18 });- kit.cylinder(0.04, 0.7, [0, 0.38, 0], HALL.chrome, { segments: 10 });- kit.cylinder(0.37, 0.03, [0, 0.735, 0], HALL.chrome, { segments: 24 });- kit.cylinder(0.35, 0.02, [0, 0.755, 0], HALL.snack.cream, { segments: 24 });- for (let i = 0; i < 3; i += 1) {- const a = (i / 3) * Math.PI * 2 + Math.PI / 6;- const x = Math.cos(a) * 0.45, z = Math.sin(a) * 0.45;- kit.cylinder(0.13, 0.02, [x, 0.01, z], HALL.chrome, { segments: 14 });- kit.cylinder(0.022, 0.6, [x, 0.31, z], HALL.chrome, { segments: 8 });- kit.cylinder(0.16, 0.07, [x, 0.635, z], "#c0392b", { segments: 18 });- }- tableGeometry = kit.build();- }- return tableGeometry;-}--function SnackTables({ tables }: { tables: Point[] }) {- const geometry = bistroTable();- return <>{tables.map((t) => <mesh key={`${t.x}:${t.z}`} geometry={geometry} material={HALL_MAT.gloss} position={[t.x, 0, t.z]} castShadow receiveShadow />)}</>;-}--const PAD_TILES = 4;-const PAD_COLOURS = [HALL.neon.magenta, HALL.neon.cyan, HALL.neon.yellow, HALL.neon.green, HALL.neon.violet];--/** Light step `n` of the pad's chase: every third diagonal bright, the rest dimmed. */-function paintPad(mesh: InstancedMesh, bright: Color[], dim: Color[], n: number): void {- for (let r = 0; r < PAD_TILES; r += 1) {- for (let c = 0; c < PAD_TILES; c += 1) {- const k = (r + c + n) % PAD_COLOURS.length;- mesh.setColorAt(r * PAD_TILES + c, (r + c + n) % 3 === 0 ? bright[k] : dim[k]);- }- }- if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;-}--/** A light-up dance floor of 4 × 4 tiles; the colours chase diagonally while the floor is awake. */-function DancePad({ pad, animate }: { pad: Rect; animate: boolean }) {- const w = pad.maxX - pad.minX, d = pad.maxZ - pad.minZ;- const tile = Math.min(w, d) / PAD_TILES;- const { mesh, bright, dim } = useMemo(() => {- const geometry = new PlaneGeometry(tile * 0.9, tile * 0.9).rotateX(-Math.PI / 2);- const material = new MeshBasicMaterial({ color: "#ffffff", toneMapped: false });- const made = new InstancedMesh(geometry, material, PAD_TILES * PAD_TILES);- const dummy = new Object3D();- for (let r = 0; r < PAD_TILES; r += 1) {- for (let c = 0; c < PAD_TILES; c += 1) {- dummy.position.set(pad.minX + (c + 0.5) * tile, 0.008, pad.minZ + (r + 0.5) * tile);- dummy.updateMatrix();- made.setMatrixAt(r * PAD_TILES + c, dummy.matrix);- }- }- made.instanceMatrix.needsUpdate = true;- made.computeBoundingSphere();- return {- mesh: made,- bright: PAD_COLOURS.map((c) => new Color(c)),- dim: PAD_COLOURS.map((c) => new Color(c).multiplyScalar(0.28)),- };- }, [pad.minX, pad.minZ, tile]);- const step = useRef(0);- const since = useRef(0);- useEffect(() => paintPad(mesh, bright, dim, step.current), [mesh, bright, dim]);- useEffect(() => () => { mesh.geometry.dispose(); (mesh.material as MeshBasicMaterial).dispose(); mesh.dispose(); }, [mesh]);- useFrame((_, dt) => {- if (!animate) return;- since.current += dt;- if (since.current < PAD_STEP_S) return;- since.current = 0;- step.current += 1;- paintPad(mesh, bright, dim, step.current);- });- return (- <group>- <mesh position={[(pad.minX + pad.maxX) / 2, 0.004, (pad.minZ + pad.maxZ) / 2]} rotation={[-Math.PI / 2, 0, 0]} material={PAD_BASE} receiveShadow>- <planeGeometry args={[w, d]} />- </mesh>- <primitive object={mesh} />- </group>- );-}--/** The neon logos inlaid in the floors: each game room's symbol, the foyer's welcome coin and the hall's star. */-function FloorLogos({ logos }: { logos: { x: number; z: number; r: number; room: RoomKind }[] }) {- return (- <group>- {logos.map((logo) => {- const symbol = ROOM_SYMBOL[logo.room];- if (!symbol) return null;- return (- <mesh key={`${logo.room}:${logo.x}`} geometry={LOGO_PLANE} material={floorLogoMaterial(symbol, accentOf(logo.room))}- position={[logo.x, 0.009, logo.z]} rotation={[-Math.PI / 2, 0, 0]} scale={[logo.r * 2, logo.r * 2, 1]} renderOrder={1} />- );- })}- </group>- );-}--/** The coloured pool of light each cabinet throws on the carpet in front of it; one instanced draw for all of them. */-function CabinetGlows({ cabinets, near }: { cabinets: Furniture[]; near: string | null }) {- const mesh = useMemo(() => {- const map = cachedCanvasTexture("arcade:glow-spot", 128, 128, drawGlowSpot);- const material = new MeshBasicMaterial({- map, color: "#ffffff", transparent: true, opacity: map ? 1 : 0, depthWrite: false, blending: AdditiveBlending, toneMapped: false,- });- const made = new InstancedMesh(new PlaneGeometry(1, 1).rotateX(-Math.PI / 2), material, Math.max(1, cabinets.length));- made.count = cabinets.length;- return made;- }, [cabinets]);- // Placing and tinting is cheap (ten instances) and only happens when the cabinet you stand at changes.- useEffect(() => {- const dummy = new Object3D();- const colour = new Color();- cabinets.forEach((cabinet, i) => {- const ahead = 0.75, big = cabinet.id === near;- dummy.position.set(cabinet.x + Math.sin(cabinet.rotationY) * ahead, 0.012, cabinet.z + Math.cos(cabinet.rotationY) * ahead);- dummy.rotation.set(0, cabinet.rotationY, 0);- dummy.scale.set(big ? 1.6 : 1.15, 1, big ? 1.3 : 0.95);- dummy.updateMatrix();- mesh.setMatrixAt(i, dummy.matrix);- mesh.setColorAt(i, colour.set(gameForCabinet(cabinet.id)?.look.accent ?? HALL.neon.violet).multiplyScalar(big ? 1.6 : 1));- });- mesh.instanceMatrix.needsUpdate = true;- if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;- mesh.computeBoundingSphere();- }, [mesh, cabinets, near]);- useEffect(() => () => { mesh.geometry.dispose(); (mesh.material as MeshBasicMaterial).dispose(); mesh.dispose(); }, [mesh]);- return <primitive object={mesh} />;-}--/** Flips every attract screen between its two frames; neighbours in the registry run out of step. */-function AttractScreens({ animate }: { animate: boolean }) {- const since = useRef(0);- const frame = useRef<0 | 1>(0);- useFrame((_, dt) => {- if (!animate) return;- since.current += dt;- if (since.current < ATTRACT_FRAME_S) return;- since.current = 0;- frame.current = frame.current === 0 ? 1 : 0;- for (let i = 0; i < ARCADE_GAMES.length; i += 1) setScreenFrame(ARCADE_GAMES[i], ((frame.current + i) % 2) as 0 | 1);- });- return null;-}--// ----------------------------------------------------------------------------// The hall-// -----------------------------------------------------------------------------export function ArcadeHall({ layout, onFloorClick, nearCabinet, awake, reduced }: ArcadeHallProps) {- const t = useT();- const background = useMemo(() => new Color(HALL.space), []);- const { minX, maxX, minZ, maxZ } = layout.bounds;- const span = Math.max(maxX - minX, maxZ - minZ);- const cabinets = useMemo(() => layout.furniture.filter((f) => f.kind === "retroCabinet"), [layout]);- const decor = useMemo(() => arcadeDecor(layout.rooms), [layout]);- const walled = useMemo(() => layout.rooms.filter((r) => r.walled), [layout]);- const animate = awake && !reduced;- return (- <>- <primitive attach="background" object={background} />- <fog attach="fog" args={[HALL.space, span * 2.2, span * 4.5]} />- <Stars radius={span * 3} depth={span} count={2200} factor={4} saturation={0.35} fade speed={reduced ? 0 : 0.3} />- <HallLights layout={layout} />- <HallSlab layout={layout} onFloorClick={onFloorClick} />- {walled.map((room) => <RoomFloor key={room.id} room={room} onFloorClick={onFloorClick} />)}- <GlassWalls walls={layout.walls} rooms={layout.rooms} />- {walled.map((room) => <RoomBoard key={room.id} room={room} label={t(`society.office.room_${room.kind}`)} />)}- <WallSigns layout={layout} />- {layout.furniture.map((item) => <FurniturePiece key={item.id} item={item} />)}- <SnackTables tables={decor.tables} />- <DancePad pad={decor.pad} animate={animate} />- <FloorLogos logos={decor.logos} />- <CabinetGlows cabinets={cabinets} near={nearCabinet} />- <AttractScreens animate={animate} />- </>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/arcade/ArcadeHallProps.tsx b/dodaios/ui/web/frontend/src/components/society/arcade/ArcadeHallProps.tsxdeleted file mode 100644index ea6954cb13..0000000000--- a/dodaios/ui/web/frontend/src/components/society/arcade/ArcadeHallProps.tsx+++ /dev/null@@ -1,410 +0,0 @@-/**- * The arcade floor's machines (merged into PROP_RENDERERS): the playable- * upright cabinets, the prize counter, the token changer, claw machines,- * the air-hockey table, pinball machines and the snack-bar counter.- *- * Every piece is built in local space centred on the origin, front facing- * +z, inside its FURNITURE_SIZE box. Matte parts of a piece are baked into- * one vertex-coloured geometry and its lights into another (arcadeHallLook's- * PartKit), built once per kind — per game for cabinets — and shared by every- * copy; faces and screens are cached canvas materials (arcadeScreens). So a- * cabinet costs four draw calls however much detail it has.- */-import { BoxGeometry, PlaneGeometry, type BufferGeometry, type Material } from "three";-import type { Furniture, FurnitureKind } from "../office/officeLayout";-import { gameForCabinet, type ArcadeGameInfo } from "./arcadeGames";-import { HALL, HALL_MAT, lcg, PartKit, type Vec3 } from "./arcadeHallLook";-import { BLANK_LOOK, FACES, marqueeMaterial, screenMaterial } from "./arcadeScreens";--/** Where a cabinet's screen sits in the cabinet's own space (front +z): centre, size and backward lean. */-export const CABINET_SCREEN = { y: 1.38, z: 0.064, w: 0.5, h: 0.375, tilt: -0.12 } as const;-/** The lit marquee above the screen. */-const CABINET_MARQUEE = { y: 1.82, z: 0.062, w: 0.64, h: 0.16 } as const;--const GEO = {- screen: new PlaneGeometry(CABINET_SCREEN.w, CABINET_SCREEN.h),- marquee: new PlaneGeometry(CABINET_MARQUEE.w, CABINET_MARQUEE.h),- box: new BoxGeometry(1, 1, 1),- plane: new PlaneGeometry(1, 1),-};--/** A stable small hash of an id, to vary machines of the same kind. */-function variantOf(id: string, count: number): number {- let hash = 0;- for (const ch of id) hash = (hash * 31 + ch.charCodeAt(0)) >>> 0;- return hash % count;-}--/** A self-lit or glass face: a unit plane scaled to `size`. */-function Face({ size, position, rotation, material }: {- size: [number, number]; position: Vec3; rotation?: Vec3; material: Material;-}) {- return <mesh geometry={GEO.plane} material={material} position={position} rotation={rotation} scale={[size[0], size[1], 1]} />;-}--/** A glass box: a unit cube scaled to `size`. */-function Glass({ size, position }: { size: Vec3; position: Vec3 }) {- return <mesh geometry={GEO.box} material={HALL_MAT.glass} position={position} scale={size} />;-}--/** The two baked geometries of a piece: matte paint and lights. */-interface Baked { paint: BufferGeometry; glow: BufferGeometry }--function BakedPiece({ baked, gloss = false }: { baked: Baked; gloss?: boolean }) {- return (- <>- <mesh geometry={baked.paint} material={gloss ? HALL_MAT.gloss : HALL_MAT.paint} castShadow receiveShadow />- <mesh geometry={baked.glow} material={HALL_MAT.glow} />- </>- );-}--const bakedCache = new Map<string, Baked>();--/** Build a piece's two geometries once per key; every copy of the piece draws from the same buffers. */-function bake(key: string, build: (paint: PartKit, glow: PartKit) => void): Baked {- let baked = bakedCache.get(key);- if (!baked) {- const paint = new PartKit(), glow = new PartKit();- build(paint, glow);- baked = { paint: paint.build(), glow: glow.build() };- bakedCache.set(key, baked);- }- return baked;-}--/** Plush toys: a squashed body, a head and two round ears, each in one colour. */-function plush(kit: PartKit, x: number, y: number, z: number, r: number, colour: string): void {- kit.sphere(r, [x, y + r * 0.9, z], colour, [1, 0.9, 0.9], 9);- const head = y + r * 1.75;- kit.sphere(r * 0.75, [x, head, z + r * 0.05], colour, undefined, 9);- kit.sphere(r * 0.28, [x - r * 0.5, head + r * 0.6, z], colour, undefined, 6);- kit.sphere(r * 0.28, [x + r * 0.5, head + r * 0.6, z], colour, undefined, 6);-}--// ----------------------------------------------------------------------------// Retro cabinet-// -----------------------------------------------------------------------------/**- * A classic upright: side panels in the game's body colour with two racing- * stripes, neon T-molding along their front edges, a slanted control panel- * with a joystick and two buttons, a coin door with lit slots, the tube in a- * black bezel and the lit marquee on top.- */-function cabinetParts(game: ArcadeGameInfo | null): Baked {- const look = game?.look ?? BLANK_LOOK;- return bake(`arcade:cabinet:${game?.id ?? "blank"}`, (paint, glow) => {- const tilt = 0.22;- for (const side of [-1, 1]) {- const x = side * 0.3575;- paint.box([0.035, 0.98, 0.69], [x, 0.49, -0.045], look.body);- paint.box([0.035, 0.94, 0.51], [x, 1.45, -0.135], look.body);- const sx = side * 0.378;- paint.box([0.006, 0.07, 0.62], [sx, 0.55, -0.05], look.accent, [0.55, 0, 0]);- paint.box([0.006, 0.07, 0.62], [sx, 0.75, -0.05], look.marqueeText, [0.55, 0, 0]);- paint.box([0.006, 0.06, 0.4], [sx, 1.5, -0.14], look.accent, [0.55, 0, 0]);- glow.box([0.04, 0.98, 0.012], [x, 0.49, 0.306], look.accent);- glow.box([0.04, 0.94, 0.012], [x, 1.45, 0.126], look.accent);- glow.box([0.04, 0.012, 0.19], [x, 0.986, 0.215], look.accent);- }- paint.box([0.68, 0.98, 0.64], [0, 0.49, -0.07], look.trim);- paint.box([0.6, 0.1, 0.02], [0, 0.06, 0.26], HALL.black);- paint.box([0.24, 0.3, 0.02], [0, 0.5, 0.26], HALL.steel);- glow.box([0.035, 0.05, 0.008], [-0.055, 0.56, 0.274], "#ff4b2b");- glow.box([0.035, 0.05, 0.008], [0.055, 0.56, 0.274], "#ff4b2b");- // Control panel, its front edge tipped down towards the player.- paint.box([0.68, 0.06, 0.3], [0, 0.99, 0.17], look.trim, [tilt, 0, 0]);- paint.cylinder(0.009, 0.07, [-0.16, 1.045, 0.2], HALL.black, { segments: 8 });- paint.sphere(0.03, [-0.16, 1.09, 0.2], look.accent, undefined, 12);- glow.cylinder(0.025, 0.016, [0.04, 1.02, 0.2], look.accent, { rotation: [tilt, 0, 0], segments: 14 });- glow.cylinder(0.025, 0.016, [0.13, 1.02, 0.2], look.marqueeText, { rotation: [tilt, 0, 0], segments: 14 });- // Upper cabinet: the tube's housing, the bezel, the marquee box and the top cap.- paint.box([0.68, 0.76, 0.42], [0, 1.42, -0.17], look.trim);- paint.box([0.62, 0.52, 0.02], [0, CABINET_SCREEN.y, 0.05], HALL.black, [CABINET_SCREEN.tilt, 0, 0]);- paint.box([0.7, 0.2, 0.4], [0, CABINET_MARQUEE.y, -0.14], look.body);- paint.box([0.72, 0.03, 0.46], [0, 1.935, -0.15], look.trim);- });-}--function RetroCabinet({ item }: { item: Furniture }) {- const game = gameForCabinet(item.id);- return (- <group>- <BakedPiece baked={cabinetParts(game)} />- <mesh geometry={GEO.screen} material={screenMaterial(game)} position={[0, CABINET_SCREEN.y, CABINET_SCREEN.z]}- rotation={[CABINET_SCREEN.tilt, 0, 0]} />- <mesh geometry={GEO.marquee} material={marqueeMaterial(game)} position={[0, CABINET_MARQUEE.y, CABINET_MARQUEE.z]} />- </group>- );-}--// ----------------------------------------------------------------------------// Prize counter-// -----------------------------------------------------------------------------/**- * The redemption counter: a glass display case of small prizes with a lit- * ticket strip on its base and a register on top, and behind it a plum shelf- * wall of plush toys under neon shelf lights.- */-function prizeParts(): Baked {- return bake("arcade:prize-counter", (paint, glow) => {- const plum = "#3b1d4a", deep = "#2a1240", cream = "#efe6f4";- const rand = lcg(0x9e1ce);- const colour = () => HALL.plush[Math.floor(rand() * HALL.plush.length)];- paint.box([3.3, 0.35, 0.42], [0, 0.175, 0.21], plum);- paint.box([3.26, 0.02, 0.38], [0, 0.36, 0.21], "#1b0b24");- for (const x of [-1.635, 1.635]) for (const z of [0.03, 0.39]) paint.box([0.03, 0.64, 0.03], [x, 0.68, z], HALL.chrome);- paint.box([3.36, 0.04, 0.44], [0, 1.02, 0.21], cream);- // Small prizes in the case: balls, boxes and little plush.- for (let i = 0; i < 11; i += 1) {- const x = -1.45 + i * 0.29, kind = i % 3;- if (kind === 0) paint.sphere(0.05, [x, 0.42, 0.2], colour(), undefined, 10);- else if (kind === 1) paint.box([0.1, 0.1, 0.1], [x, 0.42, 0.22], colour(), [0, 0.4, 0]);- else plush(paint, x, 0.37, 0.2, 0.045, colour());- }- // The register on the counter.- paint.box([0.32, 0.16, 0.24], [1.25, 1.12, 0.2], HALL.steel);- glow.box([0.2, 0.05, 0.008], [1.25, 1.15, 0.324], HALL.neon.green);- // The shelf wall.- paint.box([3.4, 2.15, 0.06], [0, 1.075, -0.42], deep);- paint.box([3.3, 1.0, 0.3], [0, 0.5, -0.24], plum);- for (const x of [-1.675, 1.675]) paint.box([0.05, 2.15, 0.36], [x, 1.075, -0.27], deep);- for (const y of [1.28, 1.62, 1.96]) {- paint.box([3.3, 0.03, 0.3], [0, y, -0.24], cream);- glow.box([3.3, 0.012, 0.012], [0, y - 0.022, -0.085], HALL.neon.cyan);- for (let i = 0; i < 8; i += 1) {- plush(paint, -1.4 + i * 0.4 + (rand() - 0.5) * 0.06, y + 0.015, -0.24, 0.065 + rand() * 0.015, colour());- }- }- // A big bear sits on the counter's end.- plush(paint, -1.38, 1.04, 0.2, 0.1, HALL.plush[0]);- glow.box([3.3, 0.025, 0.012], [0, 0.355, 0.426], HALL.neon.magenta);- });-}--function PrizeCounter() {- return (- <group>- <BakedPiece baked={prizeParts()} />- <Glass size={[3.26, 0.62, 0.38]} position={[0, 0.68, 0.21]} />- <Face size={[1.6, 0.3]} position={[0, 0.19, 0.4215]} material={FACES.prizeSign()} />- </group>- );-}--// ----------------------------------------------------------------------------// Token changer-// -----------------------------------------------------------------------------/** A golden change machine: a bill slot, a lit panel (bill → coins), a coin tray and a lit header. */-function tokenParts(): Baked {- return bake("arcade:token-machine", (paint, glow) => {- paint.box([0.58, 0.06, 0.46], [0, 0.03, 0], HALL.black);- paint.box([0.56, 1.52, 0.44], [0, 0.82, -0.02], "#d9a521");- paint.box([0.46, 0.86, 0.02], [0, 1.0, 0.21], "#1c1c24");- paint.box([0.26, 0.1, 0.1], [0, 0.38, 0.2], HALL.steel);- glow.box([0.58, 0.12, 0.46], [0, 1.64, -0.02], HALL.neon.yellow);- glow.box([0.2, 0.02, 0.008], [0, 0.68, 0.224], HALL.neon.green);- });-}--function TokenMachine() {- return (- <group>- <BakedPiece baked={tokenParts()} gloss />- <Face size={[0.4, 0.5]} position={[0, 1.08, 0.2215]} material={FACES.token()} />- </group>- );-}--// ----------------------------------------------------------------------------// Claw machine-// -----------------------------------------------------------------------------const CLAW_BODIES = ["#d23b6a", "#1fa4b8"] as const;--/** A claw crane: a coloured base with a prize chute, a glass box full of plush, the claw on its gantry, a bulb-lit header. */-function clawParts(variant: number): Baked {- return bake(`arcade:claw:${variant}`, (paint, glow) => {- const body = CLAW_BODIES[variant % CLAW_BODIES.length];- const rand = lcg(0xc1a3 + variant * 97);- paint.box([0.96, 0.85, 0.96], [0, 0.425, 0], body);- paint.box([0.28, 0.26, 0.02], [0.24, 0.36, 0.49], HALL.black);- paint.box([0.9, 0.06, 0.14], [0, 0.88, 0.42], HALL.steel);- paint.cylinder(0.008, 0.06, [-0.22, 0.94, 0.42], HALL.black, { segments: 8 });- paint.sphere(0.026, [-0.22, 0.98, 0.42], "#e0443e", undefined, 10);- glow.cylinder(0.024, 0.014, [0.0, 0.917, 0.42], HALL.neon.yellow, { segments: 14 });- for (const x of [-0.46, 0.46]) for (const z of [-0.46, 0.46]) paint.box([0.04, 0.9, 0.04], [x, 1.3, z], body);- paint.box([0.96, 0.25, 0.96], [0, 1.875, 0], body);- paint.box([0.9, 0.02, 0.9], [0, 0.86, 0], "#2a1240");- // The drop chute in the front-right corner, and a pile of plush everywhere else.- paint.box([0.26, 0.2, 0.26], [0.3, 0.97, 0.3], "#c9d3e6");- for (let i = 0; i < 16; i += 1) {- const x = -0.34 + rand() * 0.68, z = -0.34 + rand() * 0.68;- if (x > 0.12 && z > 0.12) continue;- plush(paint, x, 0.87 + rand() * 0.06, z, 0.055 + rand() * 0.02, HALL.plush[Math.floor(rand() * HALL.plush.length)]);- }- // The claw hanging from its gantry.- paint.box([0.9, 0.025, 0.025], [0, 1.732, -0.05], HALL.chrome);- paint.cylinder(0.006, 0.25, [-0.05, 1.62, -0.05], HALL.chrome, { segments: 6 });- paint.sphere(0.035, [-0.05, 1.48, -0.05], HALL.chrome, undefined, 10);- for (let k = 0; k < 3; k += 1) {- const a = (k / 3) * Math.PI * 2;- paint.box([0.012, 0.12, 0.012], [-0.05 + Math.cos(a) * 0.04, 1.42, -0.05 + Math.sin(a) * 0.04], HALL.chrome, [0, -a, 0.35]);- }- glow.box([0.9, 0.015, 0.9], [0, 1.742, 0], "#ffe6f2");- for (let i = 0; i < 9; i += 1) glow.sphere(0.018, [-0.4 + i * 0.1, 1.765, 0.485], HALL.neon.yellow, undefined, 6);- });-}--function ClawMachine({ item }: { item: Furniture }) {- return (- <group>- <BakedPiece baked={clawParts(variantOf(item.id, CLAW_BODIES.length))} />- <Glass size={[0.88, 0.86, 0.88]} position={[0, 1.31, 0]} />- <Face size={[0.8, 0.2]} position={[0, 1.875, 0.481]} material={FACES.clawHeader()} />- </group>- );-}--// ----------------------------------------------------------------------------// Air hockey-// -----------------------------------------------------------------------------/** An air-hockey table: a blue cabinet with neon side strips, white rails, two mallets and a puck. */-function hockeyParts(): Baked {- return bake("arcade:air-hockey", (paint, glow) => {- paint.box([1.9, 0.56, 1.0], [0, 0.38, 0], "#1f3a8a");- for (const x of [-0.85, 0.85]) for (const z of [-0.42, 0.42]) paint.box([0.12, 0.1, 0.12], [x, 0.05, z], HALL.black);- paint.box([1.94, 0.1, 1.04], [0, 0.7, 0], "#16285e");- for (const z of [-0.56, 0.56]) paint.box([2.1, 0.12, 0.08], [0, 0.74, z], "#e9edf5");- for (const x of [-1.01, 1.01]) paint.box([0.08, 0.12, 1.04], [x, 0.74, 0], "#e9edf5");- const mallet = (x: number, colour: string) => {- paint.cylinder(0.06, 0.035, [x, 0.7675, 0], colour, { segments: 18 });- paint.cylinder(0.022, 0.06, [x, 0.815, 0], colour, { segments: 12 });- };- mallet(-0.75, "#e0443e");- mallet(0.75, "#3b82f6");- paint.cylinder(0.04, 0.012, [0.18, 0.756, 0.12], "#ff3d7f", { segments: 16 });- for (const z of [-0.505, 0.505]) glow.box([1.8, 0.03, 0.01], [0, 0.5, z], HALL.neon.cyan);- });-}--function AirHockey() {- return (- <group>- <BakedPiece baked={hockeyParts()} />- <Face size={[1.94, 1.04]} position={[0, 0.751, 0]} rotation={[-Math.PI / 2, 0, 0]} material={FACES.airHockey()} />- </group>- );-}--// ----------------------------------------------------------------------------// Pinball-// -----------------------------------------------------------------------------const PINBALL_BODIES = ["#2a1050", "#0f3a4a", "#4a1022"] as const;-/** The playfield's tilt (back raised) and the tilted cabinet's centre. */-const PINBALL = { tilt: 0.07, y: 0.88, depth: 1.3 } as const;--/** The legs and the backbox; they stand straight. */-function pinballStand(variant: number): Baked {- return bake(`arcade:pinball-stand:${variant}`, (paint, glow) => {- const body = PINBALL_BODIES[variant % PINBALL_BODIES.length];- for (const x of [-0.32, 0.32]) {- paint.box([0.05, 0.78, 0.05], [x, 0.39, 0.6], HALL.chrome);- paint.box([0.05, 0.86, 0.05], [x, 0.43, -0.55], HALL.chrome);- }- paint.box([0.7, 0.8, 0.16], [0, 1.45, -0.62], body);- glow.box([0.66, 0.02, 0.012], [0, 1.84, -0.535], HALL.neon.magenta);- glow.box([0.02, 0.66, 0.012], [-0.33, 1.47, -0.535], HALL.neon.cyan);- glow.box([0.02, 0.66, 0.012], [0.33, 1.47, -0.535], HALL.neon.cyan);- });-}--/** The tilted cabinet in its own frame (origin = the cabinet's centre): body, rails, bumpers, lights and buttons. */-function pinballTable(variant: number): Baked {- return bake(`arcade:pinball-table:${variant}`, (paint, glow) => {- const body = PINBALL_BODIES[variant % PINBALL_BODIES.length];- paint.box([0.7, 0.24, PINBALL.depth], [0, 0, 0], body);- for (const x of [-0.335, 0.335]) paint.box([0.03, 0.08, PINBALL.depth], [x, 0.15, 0], HALL.chrome);- paint.box([0.22, 0.14, 0.01], [0, -0.03, 0.655], HALL.steel);- // Bumpers where the playfield texture draws their rings (u, v from its top-left corner).- const lights = [HALL.neon.magenta, HALL.neon.yellow, HALL.neon.cyan];- [[0.32, 0.28], [0.62, 0.24], [0.48, 0.4]].forEach(([u, v], i) => {- const x = (u - 0.5) * 0.62, z = (v - 0.5) * 1.22;- paint.cylinder(0.045, 0.04, [x, 0.141, z], "#e9e2d6", { segments: 14 });- glow.sphere(0.025, [x, 0.168, z], lights[i], [1, 0.6, 1], 10);- });- for (const x of [-0.36, 0.36]) glow.box([0.02, 0.04, 0.04], [x, 0.05, 0.55], HALL.neon.yellow);- glow.box([0.035, 0.03, 0.006], [-0.05, 0.0, 0.661], "#ff4b2b");- glow.box([0.035, 0.03, 0.006], [0.05, 0.0, 0.661], "#ff4b2b");- paint.cylinder(0.012, 0.05, [0.25, 0.02, 0.665], HALL.chrome, { rotation: [Math.PI / 2, 0, 0], segments: 8 });- });-}--function Pinball({ item }: { item: Furniture }) {- const variant = variantOf(item.id, PINBALL_BODIES.length);- return (- <group>- <BakedPiece baked={pinballStand(variant)} />- <group position={[0, PINBALL.y, 0]} rotation={[PINBALL.tilt, 0, 0]}>- <BakedPiece baked={pinballTable(variant)} />- <Face size={[0.62, 1.22]} position={[0, 0.121, 0]} rotation={[-Math.PI / 2, 0, 0]} material={FACES.playfield()} />- <Face size={[0.64, 1.24]} position={[0, 0.19, 0]} rotation={[-Math.PI / 2, 0, 0]} material={HALL_MAT.glass} />- </group>- <Face size={[0.62, 0.62]} position={[0, 1.47, -0.539]} material={FACES.backglass()} />- </group>- );-}--// ----------------------------------------------------------------------------// Snack counter-// -----------------------------------------------------------------------------/** A diner counter: red front with chrome bands and a lit menu strip, a cream top with cups, a tray and a bell. */-function snackParts(): Baked {- return bake("arcade:snack-counter", (paint, glow) => {- paint.box([2.5, 0.98, 0.62], [0, 0.51, 0.04], "#b8323a");- paint.box([2.5, 0.1, 0.02], [0, 0.05, 0.36], HALL.chrome);- paint.box([2.6, 0.05, 0.8], [0, 1.025, 0], HALL.snack.cream);- const cups = ["#e0443e", "#2de2e6", "#ffd23f", "#e0443e"];- cups.forEach((colour, i) => {- const x = 0.15 + i * 0.12;- paint.cylinder(0.035, 0.08, [x, 1.09, 0.12], colour, { radiusTop: 0.042, segments: 12 });- paint.cylinder(0.043, 0.008, [x, 1.134, 0.12], "#f4f1ea", { segments: 12 });- paint.cylinder(0.004, 0.012, [x + 0.01, 1.142, 0.12], "#ffffff", { segments: 5 });- });- paint.box([0.36, 0.015, 0.26], [-0.6, 1.058, 0.05], "#e0443e");- paint.cylinder(0.06, 0.022, [-0.66, 1.077, 0.05], "#e0a24a", { segments: 14 });- paint.cylinder(0.063, 0.018, [-0.66, 1.097, 0.05], "#6b3a1e", { segments: 14 });- paint.sphere(0.06, [-0.66, 1.106, 0.05], "#e0a24a", [1, 0.55, 1], 12);- paint.box([0.08, 0.07, 0.05], [-0.48, 1.1, 0.05], "#e0443e");- for (let i = -2; i <= 2; i += 1) paint.box([0.008, 0.06, 0.008], [-0.48 + i * 0.013, 1.115, 0.05], HALL.neon.yellow);- paint.box([0.12, 0.09, 0.08], [0.95, 1.095, -0.1], HALL.chrome);- paint.sphere(0.04, [1.12, 1.05, 0.15], "#d9a521", [1, 0.7, 1], 12);- glow.box([2.5, 0.025, 0.012], [0, 0.92, 0.356], HALL.neon.cyan);- glow.box([2.5, 0.025, 0.012], [0, 0.15, 0.356], HALL.neon.magenta);- });-}--function SnackCounter() {- return (- <group>- <BakedPiece baked={snackParts()} gloss />- <Face size={[2.2, 0.4]} position={[0, 0.58, 0.3505]} material={FACES.snackMenu()} />- </group>- );-}--export const ARCADE_RENDERERS = {- retroCabinet: ({ item }) => <RetroCabinet item={item} />,- prizeCounter: () => <PrizeCounter />,- tokenMachine: () => <TokenMachine />,- clawMachine: ({ item }) => <ClawMachine item={item} />,- airHockey: () => <AirHockey />,- pinball: ({ item }) => <Pinball item={item} />,- snackCounter: () => <SnackCounter />,-} satisfies Partial<Record<FurnitureKind, (props: { item: Furniture }) => JSX.Element>>;diff --git a/dodaios/ui/web/frontend/src/components/society/office/ArcadeScene.tsx b/dodaios/ui/web/frontend/src/components/society/arcade/ArcadeScene.tsxsimilarity index 100%rename from dodaios/ui/web/frontend/src/components/society/office/ArcadeScene.tsxrename to dodaios/ui/web/frontend/src/components/society/arcade/ArcadeScene.tsxdiff --git a/dodaios/ui/web/frontend/src/components/society/arcade/RetroArcadeOverlay.tsx b/dodaios/ui/web/frontend/src/components/society/arcade/RetroArcadeOverlay.tsxindex 62f6b4f541..097a1a9fcd 100644--- a/dodaios/ui/web/frontend/src/components/society/arcade/RetroArcadeOverlay.tsx+++ b/dodaios/ui/web/frontend/src/components/society/arcade/RetroArcadeOverlay.tsx@@ -68,10 +68,12 @@ function useCoarsePointer(): boolean {return coarse;}-export function RetroArcadeOverlay({ gameId, onClose, loadGame = loadRetroGame }: {+export function RetroArcadeOverlay({ gameId, onClose, loadGame = loadRetroGame, report = true }: {gameId: RetroGameId;onClose: () => void;loadGame?: GameLoader;+ /** False when the host meters the rounds itself (the ship's holodeck). */+ report?: boolean;}) {const t = useT();const info = arcadeGame(gameId);@@ -91,6 +93,8 @@ export function RetroArcadeOverlay({ gameId, onClose, loadGame = loadRetroGame }// Callers often pass fresh arrow functions; refs keep the listeners and the load from churning on every render.const closeRef = useRef(onClose);closeRef.current = onClose;+ const reportRef = useRef(report);+ reportRef.current = report;const loaderRef = useRef(loadGame);loaderRef.current = loadGame;@@ -149,7 +153,7 @@ export function RetroArcadeOverlay({ gameId, onClose, loadGame = loadRetroGame }const newBest = saveBest(gameId, score);const kept = Math.max(previous, score);// A scored round pays the person a little XP; a new record a little more (metered on the server).- if (score > 0) void reportWorldAction(newBest ? "arcade_record" : "arcade_round");+ if (score > 0 && reportRef.current) void reportWorldAction(newBest ? "arcade_record" : "arcade_round");setBest(kept);setResult({ score, best: kept, newBest, won });overAt = now;diff --git a/dodaios/ui/web/frontend/src/components/society/office/arcade.css b/dodaios/ui/web/frontend/src/components/society/arcade/arcade.csssimilarity index 100%rename from dodaios/ui/web/frontend/src/components/society/office/arcade.cssrename to dodaios/ui/web/frontend/src/components/society/arcade/arcade.cssdiff --git a/dodaios/ui/web/frontend/src/components/society/arcade/arcadeFloorLayout.test.ts b/dodaios/ui/web/frontend/src/components/society/arcade/arcadeFloorLayout.test.tsdeleted file mode 100644index 89717be8e7..0000000000--- a/dodaios/ui/web/frontend/src/components/society/arcade/arcadeFloorLayout.test.ts+++ /dev/null@@ -1,185 +0,0 @@-import { describe, expect, it } from "vitest";-import { ARCADE_GAMES, cabinetId, gameForCabinet } from "./arcadeGames";-import { arcadeDecor, buildArcadeLayout, cabinetPlaySpot, GAME_ROOMS, hallLanes, ROOM_ACCENT, SNACK_TABLE_HALF, uniqueWalls } from "./arcadeFloorLayout";-import { FURNITURE_SIZE, footprint, roomAt, wallRect, wallsOf, type Rect } from "../office/officeLayout";-import { buildNavGrid, findPath, isWalkable } from "../office/officeNav";-import { arrivalPose } from "../office/officeFloors";--const overlaps = (a: Rect, b: Rect) => a.minX < b.maxX - 1e-9 && b.minX < a.maxX - 1e-9 && a.minZ < b.maxZ - 1e-9 && b.minZ < a.maxZ - 1e-9;-const inside = (r: Rect, outer: Rect) => r.minX >= outer.minX && r.maxX <= outer.maxX && r.minZ >= outer.minZ && r.maxZ <= outer.maxZ;--describe("arcade floor layout", () => {- const layout = buildArcadeLayout();- const grid = buildNavGrid(layout);- const cabinets = layout.furniture.filter((f) => f.kind === "retroCabinet");- const pose = arrivalPose(layout, "elevator");- const room = (kind: string) => layout.rooms.find((r) => r.kind === kind)!;-- it("is the arcade variant with no agents' places on it", () => {- expect(layout.variant).toBe("arcade");- expect(layout.departments).toEqual([]);- expect(layout.lead.desks).toEqual([]);- expect(layout.spots).toEqual([]);- expect(layout.command).toBeUndefined();- expect(layout.checkpoints.map((c) => c.id)).toEqual(["elevator"]);- });-- it("is deterministic", () => {- expect(buildArcadeLayout()).toEqual(layout);- });-- it("floats on a slab the size of the floors below", () => {- const { minX, maxX, minZ, maxZ } = layout.bounds;- expect(maxX - minX).toBeGreaterThanOrEqual(24);- expect(maxX - minX).toBeLessThanOrEqual(30);- expect(maxZ - minZ).toBeGreaterThanOrEqual(18);- expect(maxZ - minZ).toBeLessThanOrEqual(22);- expect(inside(layout.floor, layout.bounds)).toBe(true);- });-- it("has three game rooms in the north, the open hall between, foyer, prize shop and snack bar in the south", () => {- expect(layout.rooms.map((r) => r.kind)).toEqual(["classics", "puzzle", "action", "arcade", "foyer", "prizes", "snack"]);- for (const a of layout.rooms) {- expect(inside(a, layout.bounds)).toBe(true);- expect(ROOM_ACCENT[a.kind], a.kind).toBeDefined();- for (const b of layout.rooms) if (a !== b) expect(overlaps(a, b), `${a.kind} × ${b.kind}`).toBe(false);- }- for (const kind of ["classics", "puzzle", "action"]) expect(room(kind).maxZ).toBeLessThanOrEqual(room("arcade").minZ);- for (const kind of ["foyer", "prizes", "snack"]) expect(room(kind).minZ).toBeGreaterThanOrEqual(room("arcade").maxZ);- expect(room("arcade").walled).toBe(false);- for (const r of layout.rooms.filter((x) => x.kind !== "arcade")) {- expect(r.walled, r.kind).toBe(true);- expect(r.doors, r.kind).toHaveLength(1);- }- });-- it("opens every walled room onto the hall, the doors facing each other on three lanes", () => {- const hall = room("arcade");- for (const r of layout.rooms.filter((x) => x.walled)) {- const door = r.doors[0];- expect(door.side, r.kind).toBe(r.maxZ <= hall.minZ ? "south" : "north");- expect(door.at).toBeGreaterThan(r.minX + door.width / 2);- expect(door.at).toBeLessThan(r.maxX - door.width / 2);- }- const lanes = hallLanes(layout);- expect(lanes).toHaveLength(3);- const southDoors = ["foyer", "prizes", "snack"].map((k) => room(k).doors[0].at);- expect(southDoors).toEqual(lanes);- // Nothing solid in the hall stands on a lane.- for (const item of layout.furniture.filter((f) => f.room === "arcade")) {- const r = footprint(item);- for (const x of lanes) expect(r.maxX < x - 0.9 || r.minX > x + 0.9, `${item.id} on lane ${x}`).toBe(true);- }- });-- it("draws and blocks every wall run once", () => {- const all = layout.rooms.flatMap(wallsOf);- expect(layout.walls.length).toBeLessThan(all.length);- expect(uniqueWalls(layout.rooms)).toEqual(layout.walls);- const keys = layout.walls.map((w) => [w.x1, w.z1, w.x2, w.z2].map((v) => v.toFixed(3)).join(","));- expect(new Set(keys).size).toBe(keys.length);- });-- it("groups the games by room and puts every one in exactly one cabinet", () => {- expect(Object.values(GAME_ROOMS).flat().sort()).toEqual(ARCADE_GAMES.map((g) => g.id).sort());- expect(cabinets).toHaveLength(ARCADE_GAMES.length);- for (const game of ARCADE_GAMES) expect(cabinets.filter((c) => c.id === cabinetId(game.id))).toHaveLength(1);- for (const [kind, games] of Object.entries(GAME_ROOMS)) {- const inRoom = cabinets.filter((c) => c.room === kind).sort((a, b) => a.x - b.x);- expect(inRoom.map((c) => gameForCabinet(c.id)?.id)).toEqual(games);- }- expect(new Set(layout.furniture.map((f) => f.id)).size).toBe(layout.furniture.length);- });-- it("stands every cabinet on its room's back wall, screen to the south", () => {- for (const cabinet of cabinets) {- expect(cabinet.rotationY).toBe(0);- const r = room(cabinet.room);- expect(footprint(cabinet).minZ - r.minZ, cabinet.id).toBeLessThan(0.15);- }- });-- it("puts every furniture piece in the room it names", () => {- for (const item of layout.furniture) expect(roomAt(layout, item)?.kind, item.id).toBe(item.room);- });-- it("keeps solid furniture, tables and walls apart and inside the slab", () => {- const solids = layout.furniture.filter((f) => FURNITURE_SIZE[f.kind].solid).map((f) => ({ id: f.id, rect: footprint(f) }));- const tables = arcadeDecor(layout.rooms).tables.map((t, i) => ({- id: `table-${i}`, rect: { minX: t.x - SNACK_TABLE_HALF, maxX: t.x + SNACK_TABLE_HALF, minZ: t.z - SNACK_TABLE_HALF, maxZ: t.z + SNACK_TABLE_HALF },- }));- const walls = layout.walls.map((w, i) => ({ id: `wall-${i}`, rect: wallRect(w) }));- const things = [...solids, ...tables];- expect(tables).toHaveLength(4);- for (let i = 0; i < things.length; i += 1) {- expect(inside(things[i].rect, layout.bounds), things[i].id).toBe(true);- for (let j = i + 1; j < things.length; j += 1) {- expect(overlaps(things[i].rect, things[j].rect), `${things[i].id} × ${things[j].id}`).toBe(false);- }- for (const wall of walls) expect(overlaps(things[i].rect, wall.rect), `${things[i].id} × ${wall.id}`).toBe(false);- }- for (const { rect } of [...things, ...walls]) expect(layout.obstacles).toContainEqual(rect);- });-- it("keeps the floor logos and the dance floor clear of everything solid", () => {- const decor = arcadeDecor(layout.rooms);- const solids = layout.obstacles;- const flats: Rect[] = [decor.pad, ...decor.logos.map((l) => ({ minX: l.x - l.r, maxX: l.x + l.r, minZ: l.z - l.r, maxZ: l.z + l.r }))];- expect(decor.logos.map((l) => l.room).sort()).toEqual(["action", "arcade", "classics", "foyer", "puzzle"]);- for (const flat of flats) for (const solid of solids) expect(overlaps(flat, solid)).toBe(false);- });-- it("can reach every cabinet's play spot from the elevator", () => {- expect(isWalkable(grid, pose)).toBe(true);- expect(isWalkable(grid, layout.spawn)).toBe(true);- expect(isWalkable(grid, layout.arrival)).toBe(true);- for (const cabinet of cabinets) {- const spot = cabinetPlaySpot(cabinet);- expect(isWalkable(grid, spot), cabinet.id).toBe(true);- const path = findPath(grid, pose, spot);- expect(path, cabinet.id).not.toBeNull();- expect(path?.at(-1)).toEqual(spot);- }- });-- it("keeps the play spots of different cabinets at least a metre apart", () => {- const spots = cabinets.map(cabinetPlaySpot);- for (let i = 0; i < spots.length; i += 1) {- for (let j = i + 1; j < spots.length; j += 1) {- expect(Math.hypot(spots[i].x - spots[j].x, spots[i].z - spots[j].z)).toBeGreaterThanOrEqual(1.0);- }- }- });-- it("arrives in the foyer, clear of the token machines", () => {- const stop = layout.checkpoints[0];- expect(stop.room).toBe("foyer");- expect(roomAt(layout, layout.arrival)?.kind).toBe("foyer");- for (const token of layout.furniture.filter((f) => f.kind === "tokenMachine")) {- expect(Math.hypot(token.x - stop.x, token.z - stop.z)).toBeGreaterThan(stop.radius + 0.4);- }- });-- it("reaches the counters, claw machines, token machines, pinballs and the air hockey on foot", () => {- const front = (id: string) => {- const item = layout.furniture.find((f) => f.id === id)!;- const reach = FURNITURE_SIZE[item.kind].d / 2 + 0.5;- return { x: item.x + Math.sin(item.rotationY) * reach, z: item.z + Math.cos(item.rotationY) * reach };- };- const ids = layout.furniture.filter((f) => ["prizeCounter", "snackCounter", "clawMachine", "tokenMachine", "pinball", "airHockey"].includes(f.kind)).map((f) => f.id);- expect(ids.length).toBeGreaterThanOrEqual(12);- for (const id of ids) {- expect(isWalkable(grid, front(id)), id).toBe(true);- expect(findPath(grid, pose, front(id)), id).not.toBeNull();- }- });-- it("lets the person walk from the foyer through the hall into every room", () => {- for (const r of layout.rooms) {- const centre = { x: (r.minX + r.maxX) / 2, z: r.kind === "arcade" ? (r.minZ + r.maxZ) / 2 + 1.2 : (r.minZ + r.maxZ) / 2 };- const target = isWalkable(grid, centre) ? centre : { x: r.doors[0]?.at ?? centre.x, z: r.maxZ <= room("arcade").minZ ? r.maxZ - 1 : r.minZ + 1 };- expect(isWalkable(grid, target), r.kind).toBe(true);- expect(findPath(grid, pose, target), r.kind).not.toBeNull();- }- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/arcade/arcadeFloorLayout.ts b/dodaios/ui/web/frontend/src/components/society/arcade/arcadeFloorLayout.tsdeleted file mode 100644index f742d4d425..0000000000--- a/dodaios/ui/web/frontend/src/components/society/arcade/arcadeFloorLayout.ts+++ /dev/null@@ -1,228 +0,0 @@-/**- * The arcade floor as data: the top floor of the building, one elevator ride- * above the coding floor. It reads like the floors below it: a strip of- * walled rooms in the north, an open hall in the middle and a strip of- * walled rooms in the south, each room with its own door, sign, carpet and- * neon colour, so the person always knows where they are.- *- * ┌──────────── Classics ────────────┬──── Puzzle corner ────┬──────────── Action zone ───────────┐- * │ 4 cabinets on the back wall │ 3 cabinets │ 3 cabinets │- * └───────────────[door]─────────────┴────────[door]─────────┴──────────────[door]───────────────┘- * pinballs · pinball row · ✪ floor logo · air hockey · dance floor ← the hall- * ┌───────────────[door]─────────────┬────────[door]─────────┬──────────────[door]───────────────┐- * │ Foyer: elevator · token machines │ Prize shop: counter, │ Snack bar: counter, bistro tables │- * │ welcome logo │ claw machines │ │- * └──────────────────────────────────┴───────────────────────┴─────────────────────────────────────┘- *- * The doors of the north and south rooms line up on three lanes across the- * hall, and nothing in the hall stands on a lane. Every cabinet stands on a- * game room's back wall with its screen to the south, towards the camera and- * the door. The walls are smoked glass (ArcadeHall), so no camera angle ever- * hides a room or makes a wall pop away.- *- * Pure and deterministic, like officeLayout: the plan never depends on who is- * online (nobody works up here: no departments, desks or hangout spots).- * Units are metres, +x east, +z south, origin at the floor centre.- */-import { cabinetId, type ArcadeGameId } from "./arcadeGames";-import {- FURNITURE_SIZE, footprint, wallRect, wallsOf,- type Checkpoint, type Furniture, type FurnitureKind, type OfficeLayout, type Point, type Rect, type Room, type RoomKind, type WallSegment,-} from "../office/officeLayout";--/** The building's footprint: rooms and hall fill ±FLOOR_X × ±FLOOR_Z; a ledge of EDGE runs round it to the railing. */-const FLOOR_X = 12;-const FLOOR_Z = 9;-const EDGE = 1.2;-/** How far a figure's centre stays from the slab edge (see officeLayout's RAIL_CLEARANCE). */-const RAIL_CLEARANCE = 0.65;-/** The x where the three columns of rooms meet; the middle column is the narrower one. */-const COLUMN_SPLIT = 3.6;-/** The north strip (game rooms) ends here; the south strip (foyer, prize shop, snack bar) starts here. */-const NORTH_END = -3.6;-const SOUTH_START = 2.6;-/** Door widths: game rooms, and the wider foyer door everyone arriving walks through. */-const DOOR = 1.8;-const FOYER_DOOR = 2.4;-/** Wall thickness used by officeLayout's wallRect; furniture stands this far plus a gap from a wall line. */-const WALL_GAP = 0.08;-/** Centre-to-centre pitch of cabinets standing side by side on a back wall. */-const CABINET_PITCH = 1.3;--/** A cabinet is played standing this far in front of it, along its local +z (OfficePlayer). */-export const CABINET_PLAY_DISTANCE = 0.85;--/** The bistro tables of the snack bar: table and stools fit inside a square of this half size. */-export const SNACK_TABLE_HALF = 0.62;--/** Which games stand in which game room, west to east along its back wall. */-export const GAME_ROOMS: Readonly<Record<"classics" | "puzzle" | "action", readonly ArcadeGameId[]>> = {- classics: ["pixel-raiders", "maze-muncher", "city-defense", "paddle-duel"],- puzzle: ["block-drop", "neon-snake", "brick-breaker"],- action: ["asteroid-run", "desert-dash", "road-hopper"],-};--/** Each room's neon colour: its wall caps, its sign, its floor logo. */-export const ROOM_ACCENT: Partial<Record<RoomKind, string>> = {- classics: "#a77bff",- puzzle: "#2de2e6",- action: "#ff8a3d",- arcade: "#ff3fa4",- foyer: "#ff3fa4",- prizes: "#ffd23f",- snack: "#ff5a6e",-};--/** Floor decor drawn by ArcadeHall but placed here, so navigation knows the solid parts. */-export interface ArcadeDecor {- /** Bistro tables (with their stools) in the snack bar; solid. */- tables: Point[];- /** The light-up dance floor at the hall's east end; flat, walkable. */- pad: Rect;- /** Neon logos inlaid in the floors: one per game room, the foyer's welcome logo and the hall's centrepiece; flat, walkable. */- logos: (Point & { r: number; room: RoomKind })[];-}--/** The building's column x-ranges, west to east, shared by the north and the south strip. */-function columns(): [number, number][] {- return [[-FLOOR_X, -COLUMN_SPLIT], [-COLUMN_SPLIT, COLUMN_SPLIT], [COLUMN_SPLIT, FLOOR_X]];-}--const centreX = (r: Rect) => (r.minX + r.maxX) / 2;-const centreZ = (r: Rect) => (r.minZ + r.maxZ) / 2;--/** Where the floor decor lies, from the rooms of an arcade layout (missing rooms leave their decor out). */-export function arcadeDecor(rooms: readonly Room[]): ArcadeDecor {- const room = (kind: RoomKind) => rooms.find((r) => r.kind === kind) ?? null;- const snack = room("snack"), hall = room("arcade");- const tables: Point[] = snack ? [- { x: snack.minX + 3.3, z: snack.minZ + 2.5 }, { x: snack.minX + 6.1, z: snack.minZ + 2.5 },- { x: snack.minX + 3.3, z: snack.minZ + 4.9 }, { x: snack.minX + 6.1, z: snack.minZ + 4.9 },- ] : [];- const pad: Rect = hall- ? { minX: hall.maxX - 2.6, maxX: hall.maxX - 0.4, minZ: centreZ(hall) - 1.1, maxZ: centreZ(hall) + 1.1 }- : { minX: 0, maxX: 0, minZ: 0, maxZ: 0 };- const logos: ArcadeDecor["logos"] = [];- for (const kind of ["classics", "puzzle", "action"] as const) {- const r = room(kind);- if (r) logos.push({ x: centreX(r), z: r.maxZ - 1.9, r: 1.05, room: kind });- }- const foyer = room("foyer");- if (foyer) logos.push({ x: centreX(foyer) + 0.6, z: centreZ(foyer) + 0.3, r: 1.3, room: "foyer" });- if (hall) logos.push({ x: centreX(hall), z: centreZ(hall), r: 1.25, room: "arcade" });- return { tables, pad, logos };-}--/** The spot in front of a cabinet where the person stands to play it. */-export function cabinetPlaySpot(item: Pick<Furniture, "x" | "z" | "rotationY">): Point {- return { x: item.x + Math.sin(item.rotationY) * CABINET_PLAY_DISTANCE, z: item.z + Math.cos(item.rotationY) * CABINET_PLAY_DISTANCE };-}--/** Wall runs of all rooms, each run once: two rooms sharing a wall line would otherwise both draw (and both block) it. */-export function uniqueWalls(rooms: readonly Room[]): WallSegment[] {- const seen = new Set<string>();- const out: WallSegment[] = [];- for (const wall of rooms.flatMap(wallsOf)) {- const [a, b] = [`${wall.x1.toFixed(3)},${wall.z1.toFixed(3)}`, `${wall.x2.toFixed(3)},${wall.z2.toFixed(3)}`].sort();- const key = `${a}|${b}`;- if (seen.has(key)) continue;- seen.add(key);- out.push(wall);- }- return out;-}--/** Build the arcade floor. Takes no input: the hall is the same for everyone. */-export function buildArcadeLayout(): OfficeLayout {- const [west, middle, east] = columns();- const north = -FLOOR_Z, south = FLOOR_Z;- const walled = (kind: RoomKind, [minX, maxX]: [number, number], minZ: number, maxZ: number, doorSide: "north" | "south", width = DOOR): Room =>- ({ id: kind, kind, walled: true, minX, maxX, minZ, maxZ, doors: [{ side: doorSide, at: (minX + maxX) / 2, width }] });-- const classics = walled("classics", west, north, NORTH_END, "south");- const puzzle = walled("puzzle", middle, north, NORTH_END, "south");- const action = walled("action", east, north, NORTH_END, "south");- const hall: Room = { id: "arcade", kind: "arcade", walled: false, doors: [], minX: -FLOOR_X, maxX: FLOOR_X, minZ: NORTH_END, maxZ: SOUTH_START };- const foyer = walled("foyer", west, SOUTH_START, south, "north", FOYER_DOOR);- const prizes = walled("prizes", middle, SOUTH_START, south, "north");- const snack = walled("snack", east, SOUTH_START, south, "north");- const rooms = [classics, puzzle, action, hall, foyer, prizes, snack];-- const piece = (id: string, kind: FurnitureKind, room: RoomKind, x: number, z: number, rotationY = 0): Furniture =>- ({ id, kind, x, z, rotationY, room });- /** Centre offset of a piece standing with its back against a wall (its depth along the wall's normal). */- const off = (kind: FurnitureKind) => WALL_GAP + FURNITURE_SIZE[kind].d / 2;-- // The cabinets: each game room's games side by side on its back (north) wall, screens to the south.- const cabinets: Furniture[] = [];- for (const room of [classics, puzzle, action]) {- const games = GAME_ROOMS[room.kind as keyof typeof GAME_ROOMS];- games.forEach((game, i) => {- const x = centreX(room) + (i - (games.length - 1) / 2) * CABINET_PITCH;- cabinets.push(piece(cabinetId(game), "retroCabinet", room.kind, x, room.minZ + off("retroCabinet")));- });- }-- // The foyer: the elevator on the west wall like on every floor (doors facing east), the token machines north of it.- const elevator = piece("elevator", "elevator", "foyer", foyer.minX + off("elevator"), foyer.maxZ - 2.8, Math.PI / 2);- const tokens = [0, 1].map((i) => piece(`token-${i}`, "tokenMachine", "foyer", foyer.minX + off("tokenMachine"), foyer.minZ + 1.0 + i * 0.8, Math.PI / 2));- // Two big plants soften the foyer's east corners.- const plants = [foyer.minZ + 0.5, foyer.maxZ - 0.5].map((z, i) => piece(`foyer-plant-${i}`, "plant", "foyer", foyer.maxX - 0.5, z));-- // The prize shop: the counter on its west wall facing the room, a claw machine either side of the door and one on the east wall.- const counterZ = centreZ(prizes) + 0.4;- const prizeFurniture = [- piece("prize-counter", "prizeCounter", "prizes", prizes.minX + off("prizeCounter"), counterZ, Math.PI / 2),- piece("claw-a", "clawMachine", "prizes", centreX(prizes) - 2.0, prizes.minZ + off("clawMachine")),- piece("claw-b", "clawMachine", "prizes", centreX(prizes) + 2.0, prizes.minZ + off("clawMachine")),- piece("claw-c", "clawMachine", "prizes", prizes.maxX - off("clawMachine"), counterZ + 0.6, -Math.PI / 2),- ];-- // The snack bar: its counter on the west wall facing the tables.- const snackCounter = piece("snack-counter", "snackCounter", "snack", snack.minX + off("snackCounter"), centreZ(snack) + 0.3, Math.PI / 2);-- // The hall: a pinball pair at the west end and a row of three west of the middle lane, the air-hockey table east of it.- // The three lanes (x of the doors) stay clear.- const mid = centreZ(hall);- const pinballZ = mid - 0.4;- const pinballs = [-11.0, -10.1, -5.4, -4.5, -3.6].map((x, i) => piece(`pinball-${i}`, "pinball", "arcade", x, pinballZ));- const hockey = piece("air-hockey", "airHockey", "arcade", 4.3, mid);-- const furniture: Furniture[] = [...cabinets, elevator, ...tokens, ...plants, ...prizeFurniture, snackCounter, ...pinballs, hockey];-- // The elevator's doors face east into the foyer; its stop is the floor in front of them.- const elevatorStop: Checkpoint = { id: "elevator", room: "foyer", x: elevator.x + 0.95, z: elevator.z, radius: 1.0 };- const decor = arcadeDecor(rooms);- const walls = uniqueWalls(rooms);- const obstacles: Rect[] = [- ...walls.map(wallRect),- ...furniture.filter((f) => FURNITURE_SIZE[f.kind].solid).map(footprint),- ...decor.tables.map((t) => ({ minX: t.x - SNACK_TABLE_HALF, maxX: t.x + SNACK_TABLE_HALF, minZ: t.z - SNACK_TABLE_HALF, maxZ: t.z + SNACK_TABLE_HALF })),- ];-- const bounds: Rect = { minX: -FLOOR_X - EDGE, maxX: FLOOR_X + EDGE, minZ: -FLOOR_Z - EDGE, maxZ: FLOOR_Z + EDGE };- return {- variant: "arcade",- departments: [],- // Nobody leads up here; the rect is the foyer so it stays a real place on the floor.- lead: { minX: foyer.minX, maxX: foyer.maxX, minZ: foyer.minZ, maxZ: foyer.maxZ, desks: [] },- rooms,- walls,- furniture,- spots: [],- checkpoints: [elevatorStop],- obstacles,- spawn: { x: elevator.x + 1.15, z: elevator.z },- arrival: { x: elevator.x + 1.6, z: elevator.z },- floor: {- minX: bounds.minX + RAIL_CLEARANCE, maxX: bounds.maxX - RAIL_CLEARANCE,- minZ: bounds.minZ + RAIL_CLEARANCE, maxZ: bounds.maxZ - RAIL_CLEARANCE,- },- bounds,- };-}--/** The three lanes across the hall: the x of the doors that face each other across it. */-export function hallLanes(layout: Pick<OfficeLayout, "rooms">): number[] {- return layout.rooms.filter((r) => r.walled && r.maxZ <= NORTH_END + 1e-6).map((r) => r.doors[0].at);-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/arcadeGame.test.ts b/dodaios/ui/web/frontend/src/components/society/arcade/arcadeGame.test.tssimilarity index 100%rename from dodaios/ui/web/frontend/src/components/society/office/arcadeGame.test.tsrename to dodaios/ui/web/frontend/src/components/society/arcade/arcadeGame.test.tsdiff --git a/dodaios/ui/web/frontend/src/components/society/office/arcadeGame.ts b/dodaios/ui/web/frontend/src/components/society/arcade/arcadeGame.tssimilarity index 100%rename from dodaios/ui/web/frontend/src/components/society/office/arcadeGame.tsrename to dodaios/ui/web/frontend/src/components/society/arcade/arcadeGame.tsdiff --git a/dodaios/ui/web/frontend/src/components/society/arcade/arcadeHallLook.test.ts b/dodaios/ui/web/frontend/src/components/society/arcade/arcadeHallLook.test.tsdeleted file mode 100644index 2b406965dd..0000000000--- a/dodaios/ui/web/frontend/src/components/society/arcade/arcadeHallLook.test.ts+++ /dev/null@@ -1,141 +0,0 @@-import { describe, expect, it } from "vitest";-import { Color } from "three";-import { ARCADE_GAMES } from "./arcadeGames";-import { drawCarpet, drawGlowSpot, drawPrizeCarpet, drawRoomFloor, drawSnackFloor, PartKit, ROOM_FLOORS } from "./arcadeHallLook";-import { drawFloorLogo, drawRoomBoard, drawScreenFrame, FACE_DRAWINGS, NEON_DRAW, type NeonSymbol } from "./arcadeScreens";--/**- * A stand-in 2D context (jsdom has no canvas): every method is recorded, the- * gradient and text-metric factories return plain objects.- */-function fakeContext(): { ctx: CanvasRenderingContext2D; calls: string[]; texts: string[] } {- const calls: string[] = [];- const texts: string[] = [];- const state: Record<string, unknown> = {};- const gradient = { addColorStop: () => undefined };- const ctx = new Proxy(state, {- get(target, key) {- if (typeof key !== "string") return undefined;- if (key in target) return target[key];- if (key === "createLinearGradient" || key === "createRadialGradient") return () => gradient;- if (key === "measureText") return (text: string) => ({ width: text.length * 10 });- return (...args: unknown[]) => {- if (key === "fillText" || key === "strokeText") texts.push(String(args[0]));- calls.push(`${key}(${args.map((a) => (typeof a === "number" ? a.toFixed(2) : String(a))).join(",")})`);- };- },- set(target, key, value) {- if (typeof key === "string") {- target[key] = value;- calls.push(`${key}=${String(value)}`);- }- return true;- },- });- return { ctx: ctx as unknown as CanvasRenderingContext2D, calls, texts };-}--/** Only digits and spaces may be drawn as text, besides a game's own title: everything else is i18n. */-const NUMERIC = /^[\d\s]*$/;--describe("PartKit", () => {- it("merges placed, painted parts into one vertex-coloured geometry", () => {- const geometry = new PartKit()- .box([1, 2, 3], [1, 0, 0], "#ff0000")- .sphere(0.5, [0, 1, 0], "#00ff00")- .cylinder(0.2, 0.4, [0, 0, -2], "#0000ff", { rotation: [Math.PI / 2, 0, 0] })- .build();- const position = geometry.getAttribute("position");- const colour = geometry.getAttribute("color");- expect(colour.count).toBe(position.count);- const red = new Color("#ff0000");- expect([colour.getX(0), colour.getY(0), colour.getZ(0)]).toEqual([red.r, red.g, red.b]);- const box = geometry.boundingBox!;- // The sphere is a polygon: its extent is within a few centimetres of its radius.- expect(box.min.x).toBeCloseTo(-0.5, 1);- expect(box.max.x).toBeCloseTo(1.5);- expect(box.max.y).toBeCloseTo(1.5);- expect(box.min.z).toBeCloseTo(-2.2);- geometry.dispose();- });-- it("builds an empty geometry from no parts", () => {- const kit = new PartKit();- expect(kit.size).toBe(0);- const geometry = kit.build();- expect(geometry.getAttribute("position")).toBeUndefined();- });-});--describe("hall surfaces", () => {- it.each([- ["carpet", drawCarpet], ["prize carpet", drawPrizeCarpet], ["snack floor", drawSnackFloor],- ["glow spot", drawGlowSpot],- ] as const)("draws the %s the same way every time", (_name, draw) => {- const a = fakeContext(), b = fakeContext();- draw(a.ctx, 256, 256);- draw(b.ctx, 256, 256);- expect(a.calls.length).toBeGreaterThan(0);- expect(a.calls).toEqual(b.calls);- expect(a.texts).toEqual([]);- });-});--describe("attract screens", () => {- it.each(ARCADE_GAMES.map((g) => [g.id, g] as const))("%s has two different frames with its title and no words", (_id, game) => {- const frames = ([0, 1] as const).map((frame) => {- const fake = fakeContext();- drawScreenFrame(fake.ctx, 0, game, frame);- return fake;- });- expect(frames[0].calls).not.toEqual(frames[1].calls);- for (const { texts } of frames) {- expect(texts).toContain(game.title);- for (const text of texts) if (text !== game.title) expect(text).toMatch(NUMERIC);- }- });-- it("draws a blank screen for a cabinet without a game", () => {- const fake = fakeContext();- drawScreenFrame(fake.ctx, 0, null, 0);- expect(fake.texts.every((t) => NUMERIC.test(t))).toBe(true);- });-});--describe("machine faces and neon signs", () => {- it.each(Object.entries(FACE_DRAWINGS))("%s writes nothing but digits", (_name, draw) => {- const fake = fakeContext();- draw(fake.ctx, 256, 128);- expect(fake.calls.length).toBeGreaterThan(0);- for (const text of fake.texts) expect(text).toMatch(NUMERIC);- });-- it.each(Object.keys(NEON_DRAW) as NeonSymbol[])("the %s sign is tubes only", (symbol) => {- const fake = fakeContext();- NEON_DRAW[symbol](fake.ctx, 256);- expect(fake.calls.some((c) => c.startsWith("stroke("))).toBe(true);- expect(fake.texts).toEqual([]);- });-});--describe("room boards and floor logos", () => {- it("writes exactly the room's name on its board", () => {- const fake = fakeContext();- drawRoomBoard(fake.ctx, 680, 160, "Klassiker", "#a77bff");- expect(new Set(fake.texts)).toEqual(new Set(["Klassiker"]));- });-- it.each(Object.keys(NEON_DRAW) as NeonSymbol[])("lays the %s logo on the floor without words", (symbol) => {- const fake = fakeContext();- drawFloorLogo(fake.ctx, 512, symbol, "#2de2e6");- expect(fake.calls.some((c) => c.startsWith("stroke("))).toBe(true);- expect(fake.texts).toEqual([]);- });-- it.each(Object.keys(ROOM_FLOORS))("paints the %s floor", (kind) => {- const fake = fakeContext();- drawRoomFloor(kind as keyof typeof ROOM_FLOORS)(fake.ctx, 256, 256);- expect(fake.calls.length).toBeGreaterThan(0);- expect(fake.texts).toEqual([]);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/arcade/arcadeHallLook.ts b/dodaios/ui/web/frontend/src/components/society/arcade/arcadeHallLook.tsdeleted file mode 100644index 3b32c6e8d8..0000000000--- a/dodaios/ui/web/frontend/src/components/society/arcade/arcadeHallLook.ts+++ /dev/null@@ -1,364 +0,0 @@-/**- * The arcade floor's look: its palette, the hall's blacklight carpet and each- * room's own floor, and a small kit that bakes many coloured primitives into ONE- * geometry with vertex colours.- *- * The kit is why ten cabinets, a pinball row and shelves full of plush cost- * a handful of draw calls: every matte part of a prop shares one material- * (`HALL_MAT.paint`), every glowing part another (`HALL_MAT.glow`), and the- * colour of each part lives in the geometry. Kits are built once per prop- * kind (or per game for cabinets) and shared by every copy.- */-import {- BoxGeometry, BufferGeometry, Color, CylinderGeometry, DoubleSide, Euler, Float32BufferAttribute, Matrix4, MeshBasicMaterial,- MeshStandardMaterial, Quaternion, SphereGeometry, Vector3,-} from "three";-import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";--export type Vec3 = [number, number, number];--/** The arcade floor's colours. Neon on midnight: magenta, cyan, yellow, violet and green. */-export const HALL = {- /** The night round the floating floor, and its fog. */- space: "#0b0718",- /** Hemisphere light: a violet sky and a dark plum bounce off the carpet. */- sky: "#c9b8ff",- ground: "#2a1638",- sun: "#ece6ff",- slabEdge: "#130d22",- /** The glowing rim under the slab's edge. */- rim: "#ff3fa4",- /** The rooms' glass walls: a dark steel frame round smoked glass. */- frame: "#1a1726",- neon: { magenta: "#ff3fa4", cyan: "#2de2e6", yellow: "#ffd23f", violet: "#8b5cff", green: "#39ff88", orange: "#ff8a3d" },- /** The blacklight carpet: near-black ground and its neon squiggles. */- carpet: { base: "#0d0a1c", shapes: ["#ff3fa4", "#2de2e6", "#ffd23f", "#8b5cff", "#39ff88"] },- /** The prize corner's plum carpet with gold stars, and the snack bar's diner checker. */- prizes: { base: "#3a1838", star: "#f5c84a", dot: "#5a2656" },- snack: { red: "#7a1f26", cream: "#e9e2d6" },- /** Plush prizes on the shelves and in the claw machines. */- plush: ["#ff8fc7", "#7fe3ff", "#ffe066", "#b99cff", "#ff9f5a", "#8ff0a4", "#f4f1ea", "#ff6b6b"],- chrome: "#cfd3dc",- steel: "#2a2a33",- black: "#0a0a10",-} as const;--/** Every vertex-coloured matte part of the hall's props. */-export const HALL_MAT = {- paint: new MeshStandardMaterial({ vertexColors: true, roughness: 0.62, metalness: 0.05 }),- /** Chrome, steel and lacquer: the same colours, a shinier finish (barely metallic: the scene has no environment map to reflect). */- gloss: new MeshStandardMaterial({ vertexColors: true, roughness: 0.3, metalness: 0.15 }),- /** Neon tubes, bulbs and buttons: self-lit, never dimmed by the tone mapper. */- glow: new MeshBasicMaterial({ vertexColors: true, toneMapped: false }),- glass: new MeshStandardMaterial({- color: "#d8ecff", transparent: true, opacity: 0.16, roughness: 0.05, metalness: 0.1, side: DoubleSide, depthWrite: false,- }),-};--/**- * Collects primitives, each placed, turned and painted, and merges them into- * one geometry with a `color` attribute. Call `build()` once; it frees the parts.- */-export class PartKit {- private readonly parts: BufferGeometry[] = [];-- box(size: Vec3, at: Vec3, colour: string, rotation?: Vec3): this {- return this.add(new BoxGeometry(size[0], size[1], size[2]), at, colour, rotation);- }-- /** An upright cylinder (or cone when `radiusTop` differs) of `height`, centred on `at`. */- cylinder(radius: number, height: number, at: Vec3, colour: string, { rotation, radiusTop = radius, segments = 12 }: {- rotation?: Vec3; radiusTop?: number; segments?: number;- } = {}): this {- return this.add(new CylinderGeometry(radiusTop, radius, height, segments), at, colour, rotation);- }-- /** A sphere of `radius`, optionally squashed by `scale`. */- sphere(radius: number, at: Vec3, colour: string, scale?: Vec3, segments = 10): this {- return this.add(new SphereGeometry(radius, segments, Math.max(4, Math.round(segments * 0.7))), at, colour, undefined, scale);- }-- add(geometry: BufferGeometry, at: Vec3, colour: string, rotation?: Vec3, scale?: Vec3): this {- const turn = new Quaternion().setFromEuler(new Euler(rotation?.[0] ?? 0, rotation?.[1] ?? 0, rotation?.[2] ?? 0));- geometry.applyMatrix4(new Matrix4().compose(new Vector3(...at), turn, new Vector3(...(scale ?? [1, 1, 1]))));- const c = new Color(colour);- const count = geometry.getAttribute("position").count;- const colours = new Float32Array(count * 3);- for (let i = 0; i < count; i += 1) {- colours[i * 3] = c.r;- colours[i * 3 + 1] = c.g;- colours[i * 3 + 2] = c.b;- }- geometry.setAttribute("color", new Float32BufferAttribute(colours, 3));- this.parts.push(geometry);- return this;- }-- get size(): number {- return this.parts.length;- }-- build(): BufferGeometry {- const merged = this.parts.length > 0 ? mergeGeometries(this.parts, false) : null;- for (const part of this.parts) part.dispose();- this.parts.length = 0;- const out = merged ?? new BufferGeometry();- out.computeBoundingBox();- out.computeBoundingSphere();- return out;- }-}--/** Deterministic pseudo-random numbers, so the carpet and the prize shelves never change between loads. */-export function lcg(seed: number): () => number {- let state = seed >>> 0;- return () => {- state = (state * 1664525 + 1013904223) >>> 0;- return state / 0x1_0000_0000;- };-}--type Ctx = CanvasRenderingContext2D;--/** Metres covered by one repeat of the carpet tile and of the room floors. */-export const CARPET_METRES = 2.6;-export const ROOM_FLOOR_METRES = 1.6;--/** Draw `paint` at every wrapped copy of the tile, so a shape crossing an edge continues on the other side. */-function wrapped(w: number, h: number, paint: (dx: number, dy: number) => void): void {- for (const dx of [-w, 0, w]) for (const dy of [-h, 0, h]) paint(dx, dy);-}--/**- * The blacklight arcade carpet: a near-black ground scattered with neon- * squiggles, rings, triangles, zigzags and specks. Seamless on both axes.- * `density` thins the pattern out (the hall uses a calm 0.4).- */-export function drawCarpet(ctx: Ctx, w: number, h: number, density = 1): void {- const { base, shapes } = HALL.carpet;- const rand = lcg(0xa2cade);- ctx.fillStyle = base;- ctx.fillRect(0, 0, w, h);- // A faint woven speckle first, so the ground is not a flat black.- for (let i = 0; i < 2600; i += 1) {- ctx.fillStyle = rand() > 0.5 ? "rgba(70,60,120,0.35)" : "rgba(0,0,0,0.4)";- ctx.fillRect(Math.floor(rand() * w), Math.floor(rand() * h), 2, 2);- }- ctx.lineCap = "round";- ctx.lineJoin = "round";- const pick = () => shapes[Math.floor(rand() * shapes.length)];- ctx.globalAlpha = density < 1 ? 0.7 : 1;- for (let i = 0; i < Math.round(64 * density); i += 1) {- const x = rand() * w, y = rand() * h, colour = pick(), size = 10 + rand() * 18, turn = rand() * Math.PI * 2;- const kind = i % 5;- ctx.strokeStyle = colour;- ctx.fillStyle = colour;- ctx.lineWidth = 3 + rand() * 2;- wrapped(w, h, (dx, dy) => {- ctx.save();- ctx.translate(x + dx, y + dy);- ctx.rotate(turn);- ctx.beginPath();- if (kind === 0) {- // A squiggle: one wave of a sine.- for (let s = 0; s <= 12; s += 1) {- const px = -size * 1.4 + (s / 12) * size * 2.8, py = Math.sin((s / 12) * Math.PI * 2) * size * 0.35;- if (s === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py);- }- ctx.stroke();- } else if (kind === 1) {- ctx.arc(0, 0, size * 0.55, 0, Math.PI * 2);- ctx.stroke();- } else if (kind === 2) {- ctx.moveTo(0, -size * 0.7);- ctx.lineTo(size * 0.62, size * 0.45);- ctx.lineTo(-size * 0.62, size * 0.45);- ctx.closePath();- ctx.stroke();- } else if (kind === 3) {- // A zigzag bolt.- ctx.moveTo(-size, 0);- for (let s = 1; s <= 4; s += 1) ctx.lineTo(-size + s * size * 0.5, s % 2 === 1 ? -size * 0.35 : size * 0.35);- ctx.stroke();- } else {- // A four-point sparkle.- ctx.moveTo(0, -size * 0.6);- ctx.quadraticCurveTo(0, 0, size * 0.6, 0);- ctx.quadraticCurveTo(0, 0, 0, size * 0.6);- ctx.quadraticCurveTo(0, 0, -size * 0.6, 0);- ctx.quadraticCurveTo(0, 0, 0, -size * 0.6);- ctx.fill();- }- ctx.restore();- });- }- // Small neon specks between the shapes.- for (let i = 0; i < Math.round(140 * density); i += 1) {- ctx.fillStyle = pick();- const x = rand() * w, y = rand() * h, r = 1.5 + rand() * 2;- wrapped(w, h, (dx, dy) => {- ctx.beginPath();- ctx.arc(x + dx, y + dy, r, 0, Math.PI * 2);- ctx.fill();- });- }- ctx.globalAlpha = 1;-}--/** The prize corner's plum carpet: a fine dot grid with small gold stars. Seamless. */-export function drawPrizeCarpet(ctx: Ctx, w: number, h: number): void {- const { base, star, dot } = HALL.prizes;- ctx.fillStyle = base;- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = dot;- for (let y = 8; y < h; y += 16) for (let x = 8; x < w; x += 16) ctx.fillRect(x - 1.5, y - 1.5, 3, 3);- ctx.fillStyle = star;- const cell = w / 4;- for (let row = 0; row < 4; row += 1) {- for (let col = 0; col < 4; col += 1) {- const cx = col * cell + (row % 2 === 0 ? cell / 2 : 0), cy = row * cell + cell / 2;- wrapped(w, h, (dx, dy) => {- starPath(ctx, cx + dx, cy + dy, cell * 0.16, cell * 0.07);- ctx.fill();- });- }- }-}--/** The snack bar's diner floor: a red and cream checkerboard. Seamless (an even number of tiles). */-export function drawSnackFloor(ctx: Ctx, w: number, h: number): void {- const tiles = 4, size = w / tiles;- for (let row = 0; row < tiles; row += 1) {- for (let col = 0; col < tiles; col += 1) {- ctx.fillStyle = (row + col) % 2 === 0 ? HALL.snack.red : HALL.snack.cream;- ctx.fillRect(col * size, row * size, size, size);- }- }- ctx.fillStyle = "rgba(0,0,0,0.12)";- for (let i = 0; i <= tiles; i += 1) {- ctx.fillRect(i * size - 1, 0, 2, h);- ctx.fillRect(0, i * size - 1, w, 2);- }-}--/** Adds a five-point star to the current path (begins a new path). */-export function starPath(ctx: Ctx, cx: number, cy: number, outer: number, inner: number): void {- ctx.beginPath();- for (let i = 0; i < 10; i += 1) {- const r = i % 2 === 0 ? outer : inner;- const a = -Math.PI / 2 + (i * Math.PI) / 5;- if (i === 0) ctx.moveTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r);- else ctx.lineTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r);- }- ctx.closePath();-}--/** A soft white disc fading to transparent: the glow a cabinet throws on the carpet, tinted per instance. */-export function drawGlowSpot(ctx: Ctx, w: number, h: number): void {- ctx.clearRect(0, 0, w, h);- const g = ctx.createRadialGradient(w / 2, h / 2, 0, w / 2, h / 2, w / 2);- g.addColorStop(0, "rgba(255,255,255,0.55)");- g.addColorStop(0.45, "rgba(255,255,255,0.22)");- g.addColorStop(1, "rgba(255,255,255,0)");- ctx.fillStyle = g;- ctx.fillRect(0, 0, w, h);-}--/** The classics room: a violet carpet with tiny gold and lilac sparkles in a loose grid. Seamless. */-function drawClassicsFloor(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#241446";- ctx.fillRect(0, 0, w, h);- const rand = lcg(0xc1a551c);- for (let i = 0; i < 1400; i += 1) {- ctx.fillStyle = rand() > 0.5 ? "rgba(60,36,110,0.6)" : "rgba(18,8,36,0.5)";- ctx.fillRect(Math.floor(rand() * w), Math.floor(rand() * h), 2, 2);- }- const cell = w / 4;- for (let row = 0; row < 4; row += 1) {- for (let col = 0; col < 4; col += 1) {- const x = col * cell + (row % 2 === 0 ? cell / 2 : 0), y = row * cell + cell / 2;- ctx.fillStyle = (row + col) % 3 === 0 ? "#ffd23f" : "#a77bff";- wrapped(w, h, (dx, dy) => {- // A four-point pixel sparkle.- ctx.fillRect(x + dx - 1, y + dy - 5, 2, 10);- ctx.fillRect(x + dx - 5, y + dy - 1, 10, 2);- });- }- }-}--/** The puzzle corner: deep teal with faint outlined blocks in a stepped pattern. Seamless. */-function drawPuzzleFloor(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#0f2a33";- ctx.fillRect(0, 0, w, h);- const cell = w / 8;- ctx.lineWidth = 2;- for (let row = 0; row < 8; row += 1) {- for (let col = 0; col < 8; col += 1) {- const lit = (row * 3 + col * 5) % 7 === 0;- ctx.strokeStyle = lit ? "rgba(45,226,230,0.45)" : "rgba(30,74,88,0.7)";- ctx.strokeRect(col * cell + 3, row * cell + 3, cell - 6, cell - 6);- }- }-}--/** The action zone: dark ember with diagonal racing stripes. Seamless (the stripes repeat with the tile). */-function drawActionFloor(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#2e160c";- ctx.fillRect(0, 0, w, h);- ctx.lineWidth = w / 16;- ctx.strokeStyle = "rgba(70,32,14,0.9)";- for (let k = -2; k <= 2; k += 1) {- ctx.beginPath();- ctx.moveTo(k * w, h);- ctx.lineTo(k * w + w, 0);- ctx.stroke();- ctx.beginPath();- ctx.moveTo(k * w + w / 2, h);- ctx.lineTo(k * w + w * 1.5, 0);- ctx.stroke();- }- ctx.lineWidth = 3;- ctx.strokeStyle = "rgba(255,138,61,0.55)";- for (let k = -2; k <= 2; k += 1) {- ctx.beginPath();- ctx.moveTo(k * w + w / 4, h);- ctx.lineTo(k * w + w * 1.25, 0);- ctx.stroke();- }-}--/** The foyer: dark terrazzo with pale chips and the odd neon fleck. Seamless. */-function drawFoyerFloor(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#24202e";- ctx.fillRect(0, 0, w, h);- const rand = lcg(0xf0e7e2);- const chips = ["#3b3550", "#4a4462", "#17141f", "#5b5574"];- for (let i = 0; i < 520; i += 1) {- const x = rand() * w, y = rand() * h, r = 1 + rand() * 3;- ctx.fillStyle = i % 37 === 0 ? HALL.neon.magenta : i % 41 === 0 ? HALL.neon.cyan : chips[Math.floor(rand() * chips.length)];- wrapped(w, h, (dx, dy) => {- ctx.beginPath();- ctx.arc(x + dx, y + dy, r, 0, Math.PI * 2);- ctx.fill();- });- }-}--/** Each room's floor: its drawing, how many metres one tile covers, and how shiny it is. */-export const ROOM_FLOORS = {- arcade: { draw: (ctx: Ctx, w: number, h: number) => drawCarpet(ctx, w, h, 0.4), metres: CARPET_METRES, roughness: 0.95, glow: 0.18 },- classics: { draw: drawClassicsFloor, metres: ROOM_FLOOR_METRES, roughness: 0.95, glow: 0.12 },- puzzle: { draw: drawPuzzleFloor, metres: ROOM_FLOOR_METRES, roughness: 0.9, glow: 0.12 },- action: { draw: drawActionFloor, metres: ROOM_FLOOR_METRES, roughness: 0.9, glow: 0.1 },- foyer: { draw: drawFoyerFloor, metres: 2.4, roughness: 0.45, glow: 0 },- prizes: { draw: drawPrizeCarpet, metres: ROOM_FLOOR_METRES, roughness: 0.95, glow: 0.08 },- snack: { draw: drawSnackFloor, metres: ROOM_FLOOR_METRES, roughness: 0.4, glow: 0 },-} as const;--export type ArcadeRoomKind = keyof typeof ROOM_FLOORS;--/** The drawing of a room's floor tile. */-export function drawRoomFloor(kind: ArcadeRoomKind): (ctx: Ctx, w: number, h: number) => void {- return ROOM_FLOORS[kind].draw;-}diff --git a/dodaios/ui/web/frontend/src/components/society/arcade/arcadeScreens.ts b/dodaios/ui/web/frontend/src/components/society/arcade/arcadeScreens.tsdeleted file mode 100644index d40183e509..0000000000--- a/dodaios/ui/web/frontend/src/components/society/arcade/arcadeScreens.ts+++ /dev/null@@ -1,914 +0,0 @@-/**- * Everything the arcade floor draws on canvases: each cabinet's attract- * screen and lit marquee, the neon signs on the glass walls and the floor- * logos, the rooms' lit name boards, and the faces of the other machines- * (prize counter, token changer, claw machine, pinball, air hockey, snack bar).- *- * No words on the machines: only the games' own titles (never translated, see- * arcadeGames), digits and symbols; the room boards show the translated room- * names they are given. Static faces are drawn once and cached; an attract- * screen holds two frames stacked in one texture, and the hall flips between- * them by moving the texture's offset, so ten cabinets animate for free.- */-import { DoubleSide, MeshBasicMaterial, MeshStandardMaterial, type Texture } from "three";-import { cachedCanvasTexture, canvasMaterial } from "../office/canvasMaterials";-import type { ArcadeGameId, ArcadeGameInfo, CabinetLook } from "./arcadeGames";-import { retroFont } from "./retroGame";-import { HALL, lcg, starPath } from "./arcadeHallLook";--type Ctx = CanvasRenderingContext2D;--/** One attract-screen frame in canvas pixels (4:3, like the cabinets' tubes). */-export const SCREEN_PX = { w: 256, h: 192 } as const;-export const MARQUEE_PX = { w: 512, h: 128 } as const;--/** The look of a cabinet whose id names no game (a test piece, a game removed from the registry). */-export const BLANK_LOOK: CabinetLook = { body: "#1d1a3a", trim: "#0e0c1f", marquee: "#120f2a", marqueeText: "#facc15", accent: "#8b5cff" };--// ----------------------------------------------------------------------------// Fonts-// -----------------------------------------------------------------------------const fontWaiters = new Set<string>();--/**- * Redraw a cached canvas texture once the pixel face has loaded: a texture- * drawn before that would keep the fallback font for the whole session.- */-function redrawWhenFontLoads(key: string, texture: Texture | null, draw: (ctx: Ctx, w: number, h: number) => void): void {- if (!texture || fontWaiters.has(key) || typeof document === "undefined" || !("fonts" in document)) return;- const font = retroFont(20);- if (document.fonts.check(font)) return;- fontWaiters.add(key);- document.fonts.load(font).then(() => {- const canvas = texture.image as HTMLCanvasElement | undefined;- const ctx = canvas?.getContext?.("2d");- if (!canvas || !ctx) return;- draw(ctx, canvas.width, canvas.height);- texture.needsUpdate = true;- }, () => {- // The face failed to load: the fallback monospace already on the texture stays, which is legible.- });-}--/** A cached material showing a canvas that writes in the pixel face. */-function fontCanvasMaterial(key: string, w: number, h: number, draw: (ctx: Ctx, w: number, h: number) => void,- options: Parameters<typeof canvasMaterial>[4]): MeshStandardMaterial {- const material = canvasMaterial(key, w, h, draw, options);- redrawWhenFontLoads(key, material.map, draw);- return material;-}--// ----------------------------------------------------------------------------// Pixel helpers-// -----------------------------------------------------------------------------/** Paint a little bitmap: each character of `rows` is one block of `size` pixels; "." is empty. */-function pixels(ctx: Ctx, rows: readonly string[], x: number, y: number, size: number, colours: Record<string, string>): void {- rows.forEach((row, r) => {- for (let c = 0; c < row.length; c += 1) {- const colour = colours[row[c]];- if (!colour) continue;- ctx.fillStyle = colour;- ctx.fillRect(x + c * size, y + r * size, size, size);- }- });-}--/** Fit `text` into `room` pixels by shrinking the pixel face from `px` down to `min`. */-function fitFont(ctx: Ctx, text: string, room: number, px: number, min: number, weight = 700): void {- let size = px;- ctx.font = retroFont(size, weight);- while (size > min && ctx.measureText(text).width > room) {- size -= 2;- ctx.font = retroFont(size, weight);- }-}--/** Faint horizontal scanlines over a whole screen frame. */-function scanlines(ctx: Ctx, y0: number, w: number, h: number): void {- ctx.fillStyle = "rgba(0,0,0,0.18)";- for (let y = 0; y < h; y += 3) ctx.fillRect(0, y0 + y, w, 1);-}--// ----------------------------------------------------------------------------// Attract screens-// -----------------------------------------------------------------------------type ScreenArt = (ctx: Ctx, w: number, h: number, frame: 0 | 1, look: CabinetLook) => void;--const ALIEN: readonly (readonly string[])[] = [- ["...XXXXX...", ".XXXXXXXXX.", "XX.XX.XX.XX", "XXXXXXXXXXX", ".X.X...X.X.", "X.........X"],- ["...XXXXX...", ".XXXXXXXXX.", "XX.XX.XX.XX", "XXXXXXXXXXX", "..X.X.X.X..", ".X.......X."],-];--const ART: Record<ArcadeGameId, ScreenArt> = {- "neon-snake": (ctx, w, h, frame) => {- ctx.strokeStyle = "rgba(34,224,122,0.12)";- for (let x = 0; x < w; x += 16) ctx.strokeRect(x, 40, 16, h);- const path = [[3, 9], [4, 9], [5, 9], [6, 9], [6, 8], [6, 7], [7, 7], [8, 7], [9, 7], [10, 7], [10, 8], [10, 9], [11, 9], [12, 9]];- const body = path.slice(frame, frame + 12);- body.forEach(([cx, cy], i) => {- ctx.fillStyle = i === body.length - 1 ? "#d9ffe9" : i % 2 === 0 ? "#22e07a" : "#5dff9c";- ctx.fillRect(cx * 16 + 1, cy * 16 + 1, 14, 14);- });- ctx.fillStyle = "#ff4d6d";- ctx.fillRect(13 * 16 + 3, 6 * 16 + 3, 10, 10);- ctx.fillStyle = "#5dff9c";- ctx.fillRect(13 * 16 + 8, 6 * 16 - 1, 3, 5);- },- "brick-breaker": (ctx, w, _h, frame, look) => {- const colours = ["#ff3d7f", "#ff8a3d", "#ffd23f", "#39ff88", "#2de2e6"];- for (let row = 0; row < 5; row += 1) {- for (let col = 0; col < 10; col += 1) {- if (frame === 1 && row === 4 && col === 6) continue;- ctx.fillStyle = colours[row];- ctx.fillRect(8 + col * 24, 44 + row * 11, 22, 9);- }- }- ctx.fillStyle = look.marqueeText;- ctx.fillRect(frame === 0 ? 96 : 120, 172, 44, 7);- ctx.fillStyle = "#ffffff";- ctx.fillRect(frame === 0 ? 150 : 158, frame === 0 ? 132 : 112, 7, 7);- ctx.fillStyle = "rgba(255,255,255,0.08)";- ctx.fillRect(0, 186, w, 6);- },- "paddle-duel": (ctx, w, h, frame) => {- ctx.fillStyle = "#f5f5f0";- for (let y = 42; y < h; y += 14) ctx.fillRect(w / 2 - 2, y, 4, 8);- ctx.fillRect(16, frame === 0 ? 86 : 100, 7, 38);- ctx.fillRect(w - 23, frame === 0 ? 120 : 104, 7, 38);- ctx.fillRect(frame === 0 ? 88 : 150, frame === 0 ? 110 : 128, 8, 8);- ctx.font = retroFont(34, 700);- ctx.textAlign = "center";- ctx.fillText("3", w / 2 - 40, 76);- ctx.fillText("5", w / 2 + 40, 76);- },- "block-drop": (ctx, _w, h, frame) => {- const cell = 12, x0 = 68, wellW = 10;- ctx.fillStyle = "#3fa2ff";- ctx.fillRect(x0 - 4, 38, 4, h - 38);- ctx.fillRect(x0 + wellW * cell, 38, 4, h - 38);- const colours = ["#3fa2ff", "#ffd23f", "#ff3d7f", "#39ff88", "#b18cff", "#ff8a3d"];- const stack = ["..........", ".....AA...", "B...AAC..D", "BB.EEECCDD", "BFFFEEECDD", "BBFFAACCDD"];- stack.forEach((row, r) => {- for (let c = 0; c < row.length; c += 1) {- if (row[c] === ".") continue;- ctx.fillStyle = colours[(row.charCodeAt(c) - 65) % colours.length];- ctx.fillRect(x0 + c * cell + 1, h - (stack.length - r) * cell + 1, cell - 2, cell - 2);- }- });- // The falling piece, one row lower on the second frame.- ctx.fillStyle = "#b18cff";- const py = 64 + frame * cell;- for (const [dx, dy] of [[0, 0], [1, 0], [2, 0], [1, 1]]) ctx.fillRect(x0 + (3 + dx) * cell + 1, py + dy * cell + 1, cell - 2, cell - 2);- },- "maze-muncher": (ctx, w, h, frame) => {- ctx.strokeStyle = "#2f6bff";- ctx.lineWidth = 3;- ctx.strokeRect(10, 42, w - 20, h - 52);- for (const [x, y, ww, hh] of [[40, 70, 50, 20], [166, 70, 50, 20], [40, 130, 50, 20], [166, 130, 50, 20], [108, 98, 40, 26]]) {- ctx.strokeRect(x, y, ww, hh);- }- ctx.fillStyle = "#ffd9a0";- for (let x = 26; x < w - 20; x += 14) {- ctx.fillRect(x, 56, 3, 3);- ctx.fillRect(x, h - 26, 3, 3);- }- const mx = frame === 0 ? 70 : 84, my = 113;- ctx.fillStyle = "#ffd23f";- ctx.beginPath();- const open = frame === 0 ? 0.6 : 0.12;- ctx.moveTo(mx, my);- ctx.arc(mx, my, 11, open, Math.PI * 2 - open);- ctx.closePath();- ctx.fill();- // A round three-eyed blob with an antenna gives chase.- const bx = frame === 0 ? 176 : 166;- ctx.fillStyle = "#ff5ad1";- ctx.beginPath();- ctx.arc(bx, my, 11, 0, Math.PI * 2);- ctx.fill();- ctx.fillRect(bx - 1, my - 18, 2, 7);- ctx.fillStyle = "#ffffff";- for (const dx of [-5, 0, 5]) ctx.fillRect(bx + dx - 1.5, my - 4, 3, 4);- },- "desert-dash": (ctx, w, h, frame) => {- const sky = ctx.createLinearGradient(0, 40, 0, h);- sky.addColorStop(0, "#3a1660");- sky.addColorStop(1, "#ff8a3d");- ctx.fillStyle = sky;- ctx.fillRect(0, 40, w, h - 40);- ctx.fillStyle = "#ffd23f";- ctx.beginPath();- ctx.arc(196, 92, 22, 0, Math.PI * 2);- ctx.fill();- ctx.fillStyle = "#5a3416";- ctx.beginPath();- ctx.moveTo(0, 160);- for (let x = 0; x <= w; x += 8) ctx.lineTo(x, 156 + Math.sin(x * 0.04) * 6);- ctx.lineTo(w, h);- ctx.lineTo(0, h);- ctx.fill();- const cx = frame === 0 ? 170 : 150;- ctx.fillStyle = "#2f8f4e";- ctx.fillRect(cx, 128, 9, 32);- ctx.fillRect(cx - 9, 136, 9, 5);- ctx.fillRect(cx - 9, 128, 4, 10);- ctx.fillRect(cx + 9, 140, 8, 5);- ctx.fillRect(cx + 13, 132, 4, 10);- // The runner: head, body and legs that swap between frames.- ctx.fillStyle = "#ffe8c2";- ctx.fillRect(60, 124, 10, 10);- ctx.fillRect(58, 134, 12, 14);- ctx.fillRect(frame === 0 ? 56 : 62, 148, 5, 10);- ctx.fillRect(frame === 0 ? 66 : 60, 148, 5, 10);- },- "pixel-raiders": (ctx, w, _h, frame) => {- const colours = ["#c58bff", "#2de2e6", "#39ff88"];- for (let row = 0; row < 3; row += 1) {- for (let col = 0; col < 6; col += 1) {- pixels(ctx, ALIEN[frame], 22 + col * 36 + frame * 6, 48 + row * 26, 2.5, { X: colours[row] });- }- }- ctx.fillStyle = "#39ff88";- ctx.fillRect(116, 172, 24, 8);- ctx.fillRect(124, 166, 8, 6);- ctx.fillStyle = "#ffffff";- ctx.fillRect(127, frame === 0 ? 140 : 128, 2, 10);- ctx.fillStyle = "#5a7d4a";- for (const x of [30, 100, 170]) ctx.fillRect(x + 6, 150, 40, 10);- ctx.fillStyle = "rgba(255,255,255,0.1)";- ctx.fillRect(0, 186, w, 2);- },- "road-hopper": (ctx, w, h, frame) => {- ctx.fillStyle = "#123a6b";- ctx.fillRect(0, 44, w, 46);- ctx.fillStyle = "#7a4a22";- ctx.fillRect(frame === 0 ? 20 : 34, 50, 70, 12);- ctx.fillRect(frame === 0 ? 150 : 136, 72, 80, 12);- ctx.fillStyle = "#2a2a33";- ctx.fillRect(0, 96, w, 70);- ctx.fillStyle = "#e9e2d6";- for (let x = 0; x < w; x += 24) ctx.fillRect(x + (frame * 12), 130, 12, 2);- ctx.fillStyle = "#ff4b2b";- ctx.fillRect(frame === 0 ? 30 : 46, 104, 34, 16);- ctx.fillStyle = "#ffd23f";- ctx.fillRect(frame === 0 ? 190 : 174, 140, 40, 16);- ctx.fillStyle = "#3fa2ff";- ctx.fillRect(frame === 0 ? 110 : 126, 140, 30, 16);- ctx.fillStyle = "#3b6b2e";- ctx.fillRect(0, 166, w, h - 166);- pixels(ctx, frame === 0 ? ["X.X", "XXX", "X.X"] : [".X.", "XXX", "X.X"], 118, 170, 6, { X: "#7ed957" });- },- "city-defense": (ctx, w, h, frame) => {- ctx.fillStyle = "#0a0f2a";- ctx.fillRect(0, 40, w, h - 40);- ctx.fillStyle = "#ffffff";- for (let i = 0; i < 26; i += 1) ctx.fillRect((i * 97) % w, 44 + ((i * 53) % 70), 1.5, 1.5);- ctx.strokeStyle = "#ff4b2b";- ctx.lineWidth = 2;- for (const [x0, x1] of [[30, 90], [140, 110], [230, 190]]) {- const len = frame === 0 ? 0.55 : 0.75;- ctx.beginPath();- ctx.moveTo(x0, 42);- ctx.lineTo(x0 + (x1 - x0) * len, 42 + 120 * len);- ctx.stroke();- }- ctx.fillStyle = frame === 0 ? "rgba(255,207,90,0.85)" : "rgba(255,207,90,0.45)";- ctx.beginPath();- ctx.arc(176, 96, frame === 0 ? 12 : 18, 0, Math.PI * 2);- ctx.fill();- ctx.fillStyle = "#ffcf5a";- for (const [x, ww, hh] of [[14, 22, 20], [44, 18, 28], [92, 26, 16], [150, 20, 24], [196, 24, 18], [226, 18, 26]]) ctx.fillRect(x, h - 14 - hh, ww, hh);- ctx.fillStyle = "#7a4a22";- ctx.fillRect(0, h - 14, w, 14);- ctx.fillStyle = "#2de2e6";- ctx.beginPath();- ctx.arc(128, h - 14, 12, Math.PI, 0);- ctx.fill();- },- "asteroid-run": (ctx, w, h, frame) => {- ctx.fillStyle = "#07060f";- ctx.fillRect(0, 40, w, h - 40);- const rand = lcg(0xa57e);- for (let i = 0; i < 46; i += 1) {- const x = rand() * w, y = 42 + rand() * (h - 44), len = 2 + rand() * 6 + frame * 4;- ctx.fillStyle = `rgba(201,212,255,${0.4 + rand() * 0.5})`;- ctx.fillRect(x, y, len, 1.5);- }- ctx.fillStyle = "#8d93b8";- for (const [x, y, r] of [[200, 70, 16], [46, 150, 11], [222, 158, 9]]) {- ctx.beginPath();- for (let k = 0; k < 7; k += 1) {- const a = (k / 7) * Math.PI * 2, rr = r * (0.75 + ((k * 7) % 4) * 0.1);- if (k === 0) ctx.moveTo(x + Math.cos(a) * rr, y + Math.sin(a) * rr); else ctx.lineTo(x + Math.cos(a) * rr, y + Math.sin(a) * rr);- }- ctx.fill();- }- ctx.save();- ctx.translate(112, 120);- ctx.rotate(Math.PI / 2);- ctx.fillStyle = frame === 0 ? "#ffcc33" : "#ff8a3d";- ctx.beginPath(); ctx.moveTo(-6, 14); ctx.lineTo(0, frame === 0 ? 34 : 42); ctx.lineTo(6, 14); ctx.closePath(); ctx.fill();- ctx.fillStyle = "#e0443e";- ctx.beginPath(); ctx.moveTo(-8, 2); ctx.lineTo(-17, 16); ctx.lineTo(-7, 12); ctx.closePath(); ctx.fill();- ctx.beginPath(); ctx.moveTo(8, 2); ctx.lineTo(17, 16); ctx.lineTo(7, 12); ctx.closePath(); ctx.fill();- ctx.fillStyle = "#eef2f8";- ctx.fillRect(-8, -14, 16, 28);- ctx.fillStyle = "#3b82f6";- ctx.beginPath(); ctx.moveTo(-8, -14); ctx.lineTo(0, -28); ctx.lineTo(8, -14); ctx.closePath(); ctx.fill();- ctx.restore();- },-};--/** One attract frame: the game's art, its title on top, a score of zeros and a blinking coin at the foot. */-export function drawScreenFrame(ctx: Ctx, y0: number, game: ArcadeGameInfo | null, frame: 0 | 1): void {- const { w, h } = SCREEN_PX;- const look = game?.look ?? BLANK_LOOK;- ctx.save();- ctx.beginPath();- ctx.rect(0, y0, w, h);- ctx.clip();- ctx.translate(0, y0);- ctx.fillStyle = "#05040b";- ctx.fillRect(0, 0, w, h);- if (game) ART[game.id](ctx, w, h, frame, look);- // Title band.- ctx.fillStyle = "rgba(5,4,11,0.82)";- ctx.fillRect(0, 0, w, 38);- ctx.textAlign = "center";- ctx.textBaseline = "middle";- ctx.fillStyle = look.marqueeText;- if (game) {- fitFont(ctx, game.title, w - 24, 24, 12);- ctx.fillText(game.title, w / 2, 21);- }- ctx.font = retroFont(11);- ctx.textAlign = "left";- ctx.fillStyle = "#ffffff";- ctx.fillText("000000", 8, 7);- // The blinking coin: shown on the first frame only.- if (frame === 0) {- ctx.fillStyle = "#ffd23f";- ctx.beginPath();- ctx.arc(w - 14, 8, 5, 0, Math.PI * 2);- ctx.fill();- }- scanlines(ctx, 0, w, h);- ctx.restore();-}--/** Both attract frames stacked: frame 0 on top, frame 1 below. */-function drawScreens(game: ArcadeGameInfo | null) {- return (ctx: Ctx) => {- drawScreenFrame(ctx, 0, game, 0);- drawScreenFrame(ctx, SCREEN_PX.h, game, 1);- };-}--const framedScreens = new Set<string>();--/**- * The cached, self-lit attract screen of a game (null = a blank screen).- * Its texture shows one of two stacked frames; `setScreenFrame` flips them.- */-export function screenMaterial(game: ArcadeGameInfo | null): MeshStandardMaterial {- const key = `arcade:screen:${game?.id ?? "blank"}`;- const material = fontCanvasMaterial(key, SCREEN_PX.w, SCREEN_PX.h * 2, drawScreens(game), { glow: 0.95, fallback: "#120f2a", roughness: 0.35 });- if (material.map && !framedScreens.has(key)) {- framedScreens.add(key);- material.map.repeat.set(1, 0.5);- // The canvas's top half is the upper half of the texture (v from 0.5 to 1).- material.map.offset.set(0, 0.5);- }- return material;-}--/** Show attract frame 0 or 1 on a game's screen. */-export function setScreenFrame(game: ArcadeGameInfo, frame: 0 | 1): void {- const map = screenMaterial(game).map;- if (map) map.offset.y = frame === 0 ? 0.5 : 0;-}--// ----------------------------------------------------------------------------// Marquees-// -----------------------------------------------------------------------------function drawMarquee(game: ArcadeGameInfo | null) {- return (ctx: Ctx, w: number, h: number) => {- const look = game?.look ?? BLANK_LOOK;- const g = ctx.createLinearGradient(0, 0, 0, h);- g.addColorStop(0, look.marquee);- g.addColorStop(0.5, look.body);- g.addColorStop(1, look.marquee);- ctx.fillStyle = g;- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = look.accent;- ctx.fillRect(0, 6, w, 5);- ctx.fillRect(0, h - 11, w, 5);- // A pixel star at each end.- for (const x of [26, w - 40]) pixels(ctx, ["..X..", ".XXX.", "XXXXX", ".XXX.", "..X.."], x, h / 2 - 10, 4, { X: look.marqueeText });- if (!game) return;- ctx.textAlign = "center";- ctx.textBaseline = "middle";- fitFont(ctx, game.title, w - 120, 62, 28);- ctx.shadowColor = look.accent;- ctx.shadowBlur = 14;- ctx.fillStyle = look.marqueeText;- ctx.fillText(game.title, w / 2, h / 2 + 3);- ctx.shadowBlur = 0;- };-}--/** The cached lit marquee of a game, its title drawn in the pixel face. */-export function marqueeMaterial(game: ArcadeGameInfo | null): MeshStandardMaterial {- return fontCanvasMaterial(`arcade:marquee:${game?.id ?? "blank"}`, MARQUEE_PX.w, MARQUEE_PX.h, drawMarquee(game),- { glow: 1.1, fallback: game?.look.marquee ?? BLANK_LOOK.marquee, roughness: 0.4 });-}--// ----------------------------------------------------------------------------// Neon signs on the glass walls-// -----------------------------------------------------------------------------export type NeonSymbol = "joystick" | "alien" | "bolt" | "star" | "ticket" | "soda" | "claw" | "coin";--/** Stroke the current path as a neon tube: a wide soft halo, the coloured tube and a pale hot core. */-function tube(ctx: Ctx, colour: string, width: number): void {- ctx.lineCap = "round";- ctx.lineJoin = "round";- ctx.shadowColor = colour;- ctx.shadowBlur = width * 3;- ctx.strokeStyle = colour;- ctx.lineWidth = width;- ctx.stroke();- ctx.shadowBlur = width;- ctx.stroke();- ctx.shadowBlur = 0;- ctx.strokeStyle = "rgba(255,255,255,0.85)";- ctx.lineWidth = width * 0.35;- ctx.stroke();-}--/** Each neon symbol drawn into an `s` × `s` square. */-export const NEON_DRAW: Record<NeonSymbol, (ctx: Ctx, s: number) => void> = {- joystick: (ctx, s) => {- ctx.beginPath();- ctx.ellipse(s * 0.5, s * 0.74, s * 0.3, s * 0.1, 0, 0, Math.PI * 2);- tube(ctx, HALL.neon.cyan, s * 0.035);- ctx.beginPath();- ctx.moveTo(s * 0.5, s * 0.72);- ctx.lineTo(s * 0.42, s * 0.36);- tube(ctx, HALL.neon.cyan, s * 0.035);- ctx.beginPath();- ctx.arc(s * 0.41, s * 0.28, s * 0.08, 0, Math.PI * 2);- tube(ctx, HALL.neon.magenta, s * 0.035);- ctx.beginPath();- ctx.arc(s * 0.72, s * 0.68, s * 0.04, 0, Math.PI * 2);- tube(ctx, HALL.neon.yellow, s * 0.03);- },- alien: (ctx, s) => {- const rows = ALIEN[0], size = s / 15, x0 = s * 0.5 - (rows[0].length * size) / 2, y0 = s * 0.3;- rows.forEach((row, r) => {- for (let c = 0; c < row.length; c += 1) {- if (row[c] !== "X") continue;- ctx.beginPath();- ctx.rect(x0 + c * size + size * 0.18, y0 + r * size + size * 0.18, size * 0.64, size * 0.64);- tube(ctx, HALL.neon.green, size * 0.22);- }- });- },- bolt: (ctx, s) => {- ctx.beginPath();- ctx.moveTo(s * 0.58, s * 0.1);- ctx.lineTo(s * 0.32, s * 0.52);- ctx.lineTo(s * 0.5, s * 0.52);- ctx.lineTo(s * 0.4, s * 0.9);- ctx.lineTo(s * 0.7, s * 0.42);- ctx.lineTo(s * 0.52, s * 0.42);- ctx.closePath();- tube(ctx, HALL.neon.yellow, s * 0.035);- },- star: (ctx, s) => {- starPath(ctx, s * 0.5, s * 0.52, s * 0.36, s * 0.15);- tube(ctx, HALL.neon.magenta, s * 0.035);- for (let i = 0; i < 8; i += 1) {- const a = (i / 8) * Math.PI * 2 + 0.2;- ctx.beginPath();- ctx.moveTo(s * 0.5 + Math.cos(a) * s * 0.42, s * 0.52 + Math.sin(a) * s * 0.42);- ctx.lineTo(s * 0.5 + Math.cos(a) * s * 0.47, s * 0.52 + Math.sin(a) * s * 0.47);- tube(ctx, HALL.neon.cyan, s * 0.025);- }- },- ticket: (ctx, s) => {- const x0 = s * 0.12, x1 = s * 0.88, y0 = s * 0.3, y1 = s * 0.7, r = s * 0.07;- ctx.beginPath();- ctx.moveTo(x0, y0);- ctx.lineTo(x1, y0);- ctx.arc(x1, (y0 + y1) / 2, r, -Math.PI / 2, Math.PI / 2, true);- ctx.lineTo(x1, y1);- ctx.lineTo(x0, y1);- ctx.arc(x0, (y0 + y1) / 2, r, Math.PI / 2, -Math.PI / 2, true);- ctx.closePath();- tube(ctx, HALL.neon.orange, s * 0.03);- starPath(ctx, s * 0.5, s * 0.5, s * 0.12, s * 0.05);- tube(ctx, HALL.neon.yellow, s * 0.025);- },- soda: (ctx, s) => {- ctx.beginPath();- ctx.moveTo(s * 0.32, s * 0.32);- ctx.lineTo(s * 0.68, s * 0.32);- ctx.lineTo(s * 0.62, s * 0.86);- ctx.lineTo(s * 0.38, s * 0.86);- ctx.closePath();- tube(ctx, HALL.neon.cyan, s * 0.032);- ctx.beginPath();- ctx.moveTo(s * 0.54, s * 0.32);- ctx.lineTo(s * 0.6, s * 0.12);- ctx.lineTo(s * 0.7, s * 0.12);- tube(ctx, HALL.neon.magenta, s * 0.028);- ctx.beginPath();- ctx.moveTo(s * 0.36, s * 0.48);- ctx.lineTo(s * 0.64, s * 0.48);- tube(ctx, HALL.neon.magenta, s * 0.02);- },- claw: (ctx, s) => {- ctx.beginPath();- ctx.moveTo(s * 0.5, s * 0.06);- ctx.lineTo(s * 0.5, s * 0.3);- tube(ctx, HALL.neon.cyan, s * 0.03);- ctx.beginPath();- ctx.moveTo(s * 0.5, s * 0.3);- ctx.quadraticCurveTo(s * 0.26, s * 0.36, s * 0.3, s * 0.56);- ctx.moveTo(s * 0.5, s * 0.3);- ctx.quadraticCurveTo(s * 0.74, s * 0.36, s * 0.7, s * 0.56);- tube(ctx, HALL.neon.cyan, s * 0.03);- // The heart it is about to grab.- const cx = s * 0.5, cy = s * 0.7, r = s * 0.12;- ctx.beginPath();- ctx.moveTo(cx, cy + r * 1.2);- ctx.bezierCurveTo(cx - r * 2, cy - r * 0.2, cx - r * 0.8, cy - r * 1.6, cx, cy - r * 0.5);- ctx.bezierCurveTo(cx + r * 0.8, cy - r * 1.6, cx + r * 2, cy - r * 0.2, cx, cy + r * 1.2);- tube(ctx, HALL.neon.magenta, s * 0.03);- },- coin: (ctx, s) => {- ctx.beginPath();- ctx.arc(s * 0.5, s * 0.5, s * 0.34, 0, Math.PI * 2);- tube(ctx, HALL.neon.yellow, s * 0.035);- ctx.beginPath();- ctx.arc(s * 0.5, s * 0.5, s * 0.26, 0, Math.PI * 2);- tube(ctx, HALL.neon.orange, s * 0.02);- starPath(ctx, s * 0.5, s * 0.5, s * 0.14, s * 0.06);- tube(ctx, HALL.neon.yellow, s * 0.025);- },-};--const neonMaterials = new Map<NeonSymbol, MeshBasicMaterial>();--/** A neon sign's tubes on a transparent sheet; it glows on its own and lets the wall show between the tubes. */-export function neonMaterial(symbol: NeonSymbol): MeshBasicMaterial {- let material = neonMaterials.get(symbol);- if (!material) {- const map = cachedCanvasTexture(`arcade:neon:${symbol}`, 256, 256, (ctx, w) => {- ctx.clearRect(0, 0, w, w);- NEON_DRAW[symbol](ctx, w);- });- // Double-sided: the signs hang on glass, so they read from inside the room and through the glass from outside.- material = map- ? new MeshBasicMaterial({ map, transparent: true, depthWrite: false, toneMapped: false, side: DoubleSide })- : new MeshBasicMaterial({ color: HALL.neon.magenta, transparent: true, opacity: 0, depthWrite: false });- neonMaterials.set(symbol, material);- }- return material;-}--let medallion: MeshBasicMaterial | null = null;-/** The star medallion inlaid in the carpet: a neon ring round a star, on a transparent sheet. */-export function medallionMaterial(): MeshBasicMaterial {- let material = medallion;- if (!material) {- const map = cachedCanvasTexture("arcade:medallion", 512, 512, (ctx, w) => {- ctx.clearRect(0, 0, w, w);- ctx.beginPath();- ctx.arc(w / 2, w / 2, w * 0.44, 0, Math.PI * 2);- tube(ctx, HALL.neon.cyan, w * 0.018);- ctx.beginPath();- ctx.arc(w / 2, w / 2, w * 0.38, 0, Math.PI * 2);- tube(ctx, HALL.neon.magenta, w * 0.012);- starPath(ctx, w / 2, w / 2, w * 0.3, w * 0.12);- tube(ctx, HALL.neon.yellow, w * 0.018);- });- material = map- ? new MeshBasicMaterial({ map, transparent: true, depthWrite: false, toneMapped: false, polygonOffset: true, polygonOffsetFactor: -2 })- : new MeshBasicMaterial({ color: HALL.neon.cyan, transparent: true, opacity: 0, depthWrite: false });- medallion = material;- }- return material;-}--// ----------------------------------------------------------------------------// Faces of the other machines-// -----------------------------------------------------------------------------/** The prize counter's lit front: tickets and stars in a row. */-function drawPrizeSign(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#1b0b24";- ctx.fillRect(0, 0, w, h);- const step = w / 6;- for (let i = 0; i < 6; i += 1) {- const cx = step * (i + 0.5), cy = h / 2;- if (i % 2 === 0) {- ctx.fillStyle = HALL.neon.orange;- ctx.fillRect(cx - 26, cy - 14, 52, 28);- ctx.fillStyle = "#1b0b24";- ctx.beginPath();- ctx.arc(cx - 26, cy, 6, 0, Math.PI * 2);- ctx.arc(cx + 26, cy, 6, 0, Math.PI * 2);- ctx.fill();- ctx.fillStyle = HALL.neon.yellow;- starPath(ctx, cx, cy, 9, 4);- ctx.fill();- } else {- ctx.fillStyle = HALL.neon.magenta;- starPath(ctx, cx, cy, 20, 8);- ctx.fill();- }- }-}--/** The token changer's panel: a bill turning into a stack of coins. */-function drawTokenFace(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#14141c";- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "#39ff88";- ctx.fillRect(w * 0.2, h * 0.1, w * 0.6, h * 0.2);- ctx.fillStyle = "#14141c";- ctx.beginPath();- ctx.arc(w / 2, h * 0.2, h * 0.06, 0, Math.PI * 2);- ctx.fill();- ctx.fillStyle = "#ffffff";- ctx.beginPath();- ctx.moveTo(w / 2 - 12, h * 0.38);- ctx.lineTo(w / 2 + 12, h * 0.38);- ctx.lineTo(w / 2, h * 0.48);- ctx.closePath();- ctx.fill();- for (let i = 0; i < 4; i += 1) {- ctx.fillStyle = i % 2 === 0 ? HALL.neon.yellow : "#e0a92a";- ctx.beginPath();- ctx.ellipse(w / 2, h * 0.82 - i * h * 0.07, w * 0.22, h * 0.05, 0, 0, Math.PI * 2);- ctx.fill();- }-}--/** The claw machine's lit header: a heart between two stars. */-function drawClawHeader(ctx: Ctx, w: number, h: number): void {- const g = ctx.createLinearGradient(0, 0, w, 0);- g.addColorStop(0, "#2a0d3a");- g.addColorStop(0.5, "#4a1660");- g.addColorStop(1, "#2a0d3a");- ctx.fillStyle = g;- ctx.fillRect(0, 0, w, h);- const cx = w / 2, cy = h / 2, r = h * 0.2;- ctx.fillStyle = HALL.neon.magenta;- ctx.beginPath();- ctx.moveTo(cx, cy + r * 1.3);- ctx.bezierCurveTo(cx - r * 2.2, cy - r * 0.2, cx - r * 0.8, cy - r * 1.8, cx, cy - r * 0.5);- ctx.bezierCurveTo(cx + r * 0.8, cy - r * 1.8, cx + r * 2.2, cy - r * 0.2, cx, cy + r * 1.3);- ctx.fill();- ctx.fillStyle = HALL.neon.yellow;- for (const x of [w * 0.2, w * 0.8]) {- starPath(ctx, x, cy, h * 0.28, h * 0.12);- ctx.fill();- }-}--/** A pinball backglass: a ringed planet over a starfield, and the score reels. */-function drawBackglass(ctx: Ctx, w: number, h: number): void {- const g = ctx.createLinearGradient(0, 0, 0, h);- g.addColorStop(0, "#1a0b3a");- g.addColorStop(1, "#3a1050");- ctx.fillStyle = g;- ctx.fillRect(0, 0, w, h);- const rand = lcg(0xb411);- for (let i = 0; i < 70; i += 1) {- ctx.fillStyle = `rgba(255,255,255,${0.3 + rand() * 0.7})`;- ctx.fillRect(rand() * w, rand() * h * 0.7, 2, 2);- }- ctx.fillStyle = HALL.neon.orange;- ctx.beginPath();- ctx.arc(w * 0.5, h * 0.4, w * 0.2, 0, Math.PI * 2);- ctx.fill();- ctx.strokeStyle = HALL.neon.cyan;- ctx.lineWidth = 6;- ctx.beginPath();- ctx.ellipse(w * 0.5, h * 0.4, w * 0.36, w * 0.08, -0.25, 0, Math.PI * 2);- ctx.stroke();- ctx.fillStyle = HALL.neon.magenta;- starPath(ctx, w * 0.18, h * 0.18, 16, 7);- ctx.fill();- ctx.fillStyle = "#05040b";- ctx.fillRect(w * 0.12, h * 0.76, w * 0.76, h * 0.16);- ctx.fillStyle = HALL.neon.yellow;- ctx.font = retroFont(30, 700);- ctx.textAlign = "center";- ctx.textBaseline = "middle";- ctx.fillText("000000", w / 2, h * 0.84 + 2);-}--/** A pinball playfield seen from above: lanes, lit inserts, bumper rings and the two flippers. */-function drawPlayfield(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#101a4a";- ctx.fillRect(0, 0, w, h);- ctx.strokeStyle = "#e9e2d6";- ctx.lineWidth = 3;- ctx.beginPath();- ctx.moveTo(w * 0.85, h);- ctx.lineTo(w * 0.85, h * 0.12);- ctx.quadraticCurveTo(w * 0.85, 4, w * 0.5, 4);- ctx.quadraticCurveTo(w * 0.1, 4, w * 0.1, h * 0.15);- ctx.stroke();- const inserts = [HALL.neon.magenta, HALL.neon.yellow, HALL.neon.cyan, HALL.neon.green, HALL.neon.orange];- for (let i = 0; i < 5; i += 1) {- ctx.fillStyle = inserts[i];- ctx.beginPath();- ctx.moveTo(w * 0.47, h * (0.5 + i * 0.05));- ctx.lineTo(w * 0.53, h * (0.5 + i * 0.05));- ctx.lineTo(w * 0.5, h * (0.535 + i * 0.05));- ctx.closePath();- ctx.fill();- }- ctx.strokeStyle = HALL.neon.cyan;- ctx.lineWidth = 4;- for (const [x, y] of [[0.32, 0.28], [0.62, 0.24], [0.48, 0.4]]) {- ctx.beginPath();- ctx.arc(w * x, h * y, w * 0.09, 0, Math.PI * 2);- ctx.stroke();- }- ctx.fillStyle = "#e9e2d6";- ctx.save();- ctx.translate(w * 0.36, h * 0.9);- ctx.rotate(0.45);- ctx.fillRect(0, -3, w * 0.16, 6);- ctx.restore();- ctx.save();- ctx.translate(w * 0.64, h * 0.9);- ctx.rotate(Math.PI - 0.45);- ctx.fillRect(0, -3, w * 0.16, 6);- ctx.restore();-}--/** The air-hockey surface: ice white, a red centre line, blue face-off circles, goal creases and air holes. */-function drawAirHockey(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#e8f4ff";- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "rgba(60,90,140,0.25)";- for (let y = 10; y < h; y += 16) for (let x = 10; x < w; x += 16) ctx.fillRect(x, y, 2, 2);- ctx.fillStyle = "#e0443e";- ctx.fillRect(w / 2 - 3, 0, 6, h);- ctx.strokeStyle = "#3b82f6";- ctx.lineWidth = 5;- ctx.beginPath();- ctx.arc(w / 2, h / 2, h * 0.22, 0, Math.PI * 2);- ctx.stroke();- for (const x of [0, w]) {- ctx.beginPath();- ctx.arc(x, h / 2, h * 0.26, 0, Math.PI * 2);- ctx.stroke();- }- ctx.fillStyle = "#1c2440";- ctx.fillRect(0, h / 2 - h * 0.14, 8, h * 0.28);- ctx.fillRect(w - 8, h / 2 - h * 0.14, 8, h * 0.28);-}--/** The snack bar's lit menu strip: burger, fries, soda, popcorn and ice cream, each with a price in coins. */-function drawSnackMenu(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#1a0a0c";- ctx.fillRect(0, 0, w, h);- const step = w / 5, cy = h * 0.42;- const items: ((x: number) => void)[] = [- (x) => {- ctx.fillStyle = "#e0a24a"; ctx.beginPath(); ctx.arc(x, cy, 18, Math.PI, 0); ctx.fill();- ctx.fillStyle = "#6b3a1e"; ctx.fillRect(x - 18, cy + 2, 36, 7);- ctx.fillStyle = "#39ff88"; ctx.fillRect(x - 19, cy, 38, 3);- ctx.fillStyle = "#e0a24a"; ctx.fillRect(x - 17, cy + 10, 34, 7);- },- (x) => {- ctx.fillStyle = HALL.neon.yellow;- for (let i = -3; i <= 3; i += 1) ctx.fillRect(x + i * 4 - 1, cy - 22 + Math.abs(i) * 2, 3, 20);- ctx.fillStyle = "#e0443e"; ctx.fillRect(x - 14, cy - 6, 28, 22);- },- (x) => {- ctx.fillStyle = HALL.neon.cyan;- ctx.beginPath(); ctx.moveTo(x - 13, cy - 16); ctx.lineTo(x + 13, cy - 16); ctx.lineTo(x + 9, cy + 18); ctx.lineTo(x - 9, cy + 18); ctx.fill();- ctx.fillStyle = "#ffffff"; ctx.fillRect(x + 2, cy - 28, 3, 14);- },- (x) => {- ctx.fillStyle = "#fff4d6";- for (const [dx, dy] of [[-8, -14], [0, -18], [8, -14], [-4, -8], [5, -9]]) { ctx.beginPath(); ctx.arc(x + dx, cy + dy, 6, 0, Math.PI * 2); ctx.fill(); }- ctx.fillStyle = "#e0443e"; ctx.fillRect(x - 13, cy - 8, 26, 26);- ctx.fillStyle = "#ffffff"; ctx.fillRect(x - 4, cy - 8, 8, 26);- },- (x) => {- ctx.fillStyle = "#e0a24a";- ctx.beginPath(); ctx.moveTo(x - 11, cy - 4); ctx.lineTo(x + 11, cy - 4); ctx.lineTo(x, cy + 20); ctx.fill();- ctx.fillStyle = "#ff8fc7"; ctx.beginPath(); ctx.arc(x, cy - 10, 12, 0, Math.PI * 2); ctx.fill();- },- ];- ctx.font = retroFont(16, 700);- ctx.textAlign = "center";- ctx.textBaseline = "middle";- items.forEach((paint, i) => {- const x = step * (i + 0.5);- paint(x);- // The price: a number of tokens.- const price = String([3, 2, 1, 2, 1][i]);- ctx.fillStyle = HALL.neon.yellow;- ctx.beginPath();- ctx.arc(x + 9, h * 0.86, 6, 0, Math.PI * 2);- ctx.fill();- ctx.fillStyle = "#ffffff";- ctx.fillText(price, x - 5, h * 0.86 + 1);- });-}--/** The faces' drawings, by face. */-export const FACE_DRAWINGS = {- prizeSign: drawPrizeSign, token: drawTokenFace, clawHeader: drawClawHeader, backglass: drawBackglass,- playfield: drawPlayfield, airHockey: drawAirHockey, snackMenu: drawSnackMenu,-} as const;--/** The machines' faces, each a cached self-lit material. */-export const FACES = {- prizeSign: () => canvasMaterial("arcade:face:prize", 512, 96, drawPrizeSign, { glow: 0.85, fallback: "#1b0b24" }),- token: () => canvasMaterial("arcade:face:token", 128, 160, drawTokenFace, { glow: 0.7, fallback: "#14141c" }),- clawHeader: () => canvasMaterial("arcade:face:claw", 256, 64, drawClawHeader, { glow: 0.9, fallback: "#4a1660" }),- backglass: () => fontCanvasMaterial("arcade:face:backglass", 256, 256, drawBackglass, { glow: 0.85, fallback: "#2a0d45" }),- playfield: () => canvasMaterial("arcade:face:playfield", 128, 256, drawPlayfield, { glow: 0.45, fallback: "#101a4a", roughness: 0.3 }),- airHockey: () => canvasMaterial("arcade:face:hockey", 512, 288, drawAirHockey, { glow: 0.3, fallback: "#e8f4ff", roughness: 0.25 }),- snackMenu: () => fontCanvasMaterial("arcade:face:menu", 512, 96, drawSnackMenu, { glow: 0.75, fallback: "#1a0a0c" }),-};--// ----------------------------------------------------------------------------// Room boards and floor logos-// -----------------------------------------------------------------------------/** A room's lit name board in canvas pixels (the board is 2.5 m × 0.58 m). */-export const ROOM_BOARD_PX = { w: 860, h: 200 } as const;--/** A midnight board with a neon frame in the room's colour and its name written in the pixel face, glowing. */-export function drawRoomBoard(ctx: Ctx, w: number, h: number, label: string, accent: string): void {- ctx.fillStyle = "#0b0816";- ctx.fillRect(0, 0, w, h);- ctx.beginPath();- ctx.roundRect(10, 10, w - 20, h - 20, 18);- tube(ctx, accent, 6);- ctx.textAlign = "center";- ctx.textBaseline = "middle";- fitFont(ctx, label, w - 90, 112, 48, 600);- ctx.shadowColor = accent;- ctx.shadowBlur = 18;- ctx.fillStyle = accent;- ctx.fillText(label, w / 2, h / 2 + 4);- ctx.shadowBlur = 4;- ctx.fillStyle = "rgba(255,255,255,0.85)";- ctx.fillText(label, w / 2, h / 2 + 4);- ctx.shadowBlur = 0;-}--/** The cached, self-lit name board of a room (one per label and colour). */-export function roomBoardMaterial(label: string, accent: string): MeshStandardMaterial {- return fontCanvasMaterial(`arcade:board:${accent}:${label}`, ROOM_BOARD_PX.w, ROOM_BOARD_PX.h,- (ctx, w, h) => drawRoomBoard(ctx, w, h, label, accent), { glow: 1, fallback: "#0b0816", roughness: 0.5 });-}--/** A floor logo: two neon rings in the room's colour round the room's symbol. */-export function drawFloorLogo(ctx: Ctx, w: number, symbol: NeonSymbol, accent: string): void {- ctx.clearRect(0, 0, w, w);- ctx.beginPath();- ctx.arc(w / 2, w / 2, w * 0.45, 0, Math.PI * 2);- tube(ctx, accent, w * 0.016);- ctx.beginPath();- ctx.arc(w / 2, w / 2, w * 0.4, 0, Math.PI * 2);- tube(ctx, accent, w * 0.008);- ctx.save();- ctx.translate(w * 0.2, w * 0.2);- NEON_DRAW[symbol](ctx, w * 0.6);- ctx.restore();-}--const logoMaterials = new Map<string, MeshBasicMaterial>();--/** The cached floor logo of a symbol in a colour, on a transparent sheet that lies on the carpet. */-export function floorLogoMaterial(symbol: NeonSymbol, accent: string): MeshBasicMaterial {- const key = `${symbol}:${accent}`;- let material = logoMaterials.get(key);- if (!material) {- const map = cachedCanvasTexture(`arcade:logo:${key}`, 512, 512, (ctx, w) => drawFloorLogo(ctx, w, symbol, accent));- material = map- ? new MeshBasicMaterial({ map, transparent: true, depthWrite: false, toneMapped: false, polygonOffset: true, polygonOffsetFactor: -2 })- : new MeshBasicMaterial({ color: accent, transparent: true, opacity: 0, depthWrite: false });- logoMaterials.set(key, material);- }- return material;-}diff --git a/dodaios/ui/web/frontend/src/components/society/companion/AgentAppearanceDialog.tsx b/dodaios/ui/web/frontend/src/components/society/companion/AgentAppearanceDialog.tsxindex 23a869df25..65d74e17fe 100644--- a/dodaios/ui/web/frontend/src/components/society/companion/AgentAppearanceDialog.tsx+++ b/dodaios/ui/web/frontend/src/components/society/companion/AgentAppearanceDialog.tsx@@ -9,9 +9,9 @@ import { Button } from "@/components/ui/button";import type { SocietyAgent } from "../data";import { AgentSwatch } from "../AgentSwatch";import { defaultRecipe, EDITABLE_CELLS, resolvePalette, type FigureRecipe } from "../figures/figureRecipe";-import { HAIR_STYLES } from "../office/playerProfile";-import { toyLookFor } from "../office/toyFigureModel";-import { pinLook, withHair } from "../office/wardrobe";+import { HAIR_STYLES } from "../figures/toy/playerProfile";+import { toyLookFor } from "../figures/toy/toyFigureModel";+import { pinLook, withHair } from "../figures/toy/wardrobe";import { CompanionEditor } from "./CompanionEditor";import { resolveCompanion } from "./appearance";diff --git a/dodaios/ui/web/frontend/src/components/society/office/codingFloor.test.ts b/dodaios/ui/web/frontend/src/components/society/crewFeeds/codingFloor.test.tssimilarity index 90%rename from dodaios/ui/web/frontend/src/components/society/office/codingFloor.test.tsrename to dodaios/ui/web/frontend/src/components/society/crewFeeds/codingFloor.test.tsindex bad4f0ff55..59587131d6 100644--- a/dodaios/ui/web/frontend/src/components/society/office/codingFloor.test.ts+++ b/dodaios/ui/web/frontend/src/components/society/crewFeeds/codingFloor.test.ts@@ -12,8 +12,7 @@ import { resetWorkspacePanesPoll, useWorkspacePanesStore } from "@/store/workspaimport {isPaneAgentId, paneAgentId, paneFigure, paneLabel, paneOccupants, panePlateName, paneRunState, plateTitle, useCodingFloorOccupants,} from "./codingFloor";-import { allDesks, buildOfficeLayout } from "./officeLayout";-import { toyLookFor } from "./toyFigureModel";+import { toyLookFor } from "../figures/toy/toyFigureModel";function pane(name: string, workspaceId: string, overrides: Partial<WorkspacePaneRow> = {}): WorkspacePaneRow {return {@@ -121,18 +120,6 @@ describe("coding floor roster", () => {expect(distinct("pants")).toBeGreaterThan(1);expect(distinct("outfit")).toBeGreaterThan(2);});-- it("seats every occupant at a desk of its workspace's department on the coding floor", () => {- const rows = [pane("T1", "w1"), pane("T2", "w1", { activity: "asking" }), pane("T1", "w2", { activity: "" })];- const occupants = paneOccupants(rows);- const layout = buildOfficeLayout(occupants.map((o) => o.agent), { variant: "coding" });- const seated = new Map(allDesks(layout).filter((d) => d.agentId).map((d) => [d.agentId!, d.id]));- expect(seated.size).toBe(3);- for (const o of occupants) {- const dept = layout.departments.find((d) => d.desks.some((desk) => desk.agentId === o.agent.agentId))!;- expect(dept.label).toBe(o.agent.providerLabel);- }- });});describe("useCodingFloorOccupants", () => {diff --git a/dodaios/ui/web/frontend/src/components/society/office/codingFloor.ts b/dodaios/ui/web/frontend/src/components/society/crewFeeds/codingFloor.tssimilarity index 98%rename from dodaios/ui/web/frontend/src/components/society/office/codingFloor.tsrename to dodaios/ui/web/frontend/src/components/society/crewFeeds/codingFloor.tsindex ea618addce..c33c18ea42 100644--- a/dodaios/ui/web/frontend/src/components/society/office/codingFloor.ts+++ b/dodaios/ui/web/frontend/src/components/society/crewFeeds/codingFloor.ts@@ -23,8 +23,8 @@ import { sessionTitle } from "@/components/agentic/sessionTitle";import type { AgentRunState, SocietyAgent } from "../data";import { resolvePalette, type FigureRecipe } from "../figures/figureRecipe";-import { hashString, SKIN_TONES } from "./toyFigureModel";-import { randomLook } from "./wardrobe";+import { hashString, SKIN_TONES } from "../figures/toy/toyFigureModel";+import { randomLook } from "../figures/toy/wardrobe";export interface PaneOccupant {agent: SocietyAgent;diff --git a/dodaios/ui/web/frontend/src/components/society/office/codingNavigate.test.ts b/dodaios/ui/web/frontend/src/components/society/crewFeeds/codingNavigate.test.tssimilarity index 69%rename from dodaios/ui/web/frontend/src/components/society/office/codingNavigate.test.tsrename to dodaios/ui/web/frontend/src/components/society/crewFeeds/codingNavigate.test.tsindex bcb5738fcf..7a45da0d06 100644--- a/dodaios/ui/web/frontend/src/components/society/office/codingNavigate.test.ts+++ b/dodaios/ui/web/frontend/src/components/society/crewFeeds/codingNavigate.test.ts@@ -3,17 +3,14 @@ import { useEventStore } from "@/store/events";import { useIdeChatStore } from "@/store/ideChat";import { useIdeThreadsStore } from "@/store/ideThreads";import { openPaneSession } from "./codingNavigate";-import { useOfficeStore } from "./officeStore";describe("open a coding session from the office", () => {const initialSection = useEventStore.getState().activeSection;- const initialSelection = useOfficeStore.getState().selection;const initialLayout = useIdeThreadsStore.getState().layout;afterEach(() => {useIdeThreadsStore.setState({ layout: initialLayout });useEventStore.setState({ activeSection: initialSection });useIdeChatStore.setState({ paneRequest: null });- useOfficeStore.setState({ selection: initialSelection });});it("switches to the Agentic IDE and asks it to focus the pane", () => {@@ -32,19 +29,6 @@ describe("open a coding session from the office", () => {expect(useIdeChatStore.getState().paneRequest!.nonce).toBe(first + 1);});- it("closes the small viewer every time a session is opened at full size", () => {- const pane = { workspace_id: "ws-1", name: "T2" };- useOfficeStore.getState().select({ kind: "agent", id: "coding-agent" });- openPaneSession(pane);- expect(useOfficeStore.getState().selection).toBeNull();-- // Opening the same pane again must release the preview even though the- // grid already has this pane maximized.- useOfficeStore.getState().select({ kind: "agent", id: "coding-agent" });- openPaneSession(pane);- expect(useOfficeStore.getState().selection).toBeNull();- expect(useIdeChatStore.getState().paneRequest).toMatchObject({ maximize: true });- });it("leaves the thread layout so the pane itself shows, not the last open thread", () => {useIdeThreadsStore.setState({ layout: "threads" });diff --git a/dodaios/ui/web/frontend/src/components/society/office/codingNavigate.ts b/dodaios/ui/web/frontend/src/components/society/crewFeeds/codingNavigate.tssimilarity index 62%rename from dodaios/ui/web/frontend/src/components/society/office/codingNavigate.tsrename to dodaios/ui/web/frontend/src/components/society/crewFeeds/codingNavigate.tsindex 6873991f5b..d62e5498d3 100644--- a/dodaios/ui/web/frontend/src/components/society/office/codingNavigate.ts+++ b/dodaios/ui/web/frontend/src/components/society/crewFeeds/codingNavigate.ts@@ -1,18 +1,14 @@-/** Leave the coding floor for the real session: the Agentic IDE with that pane maximized. */+/** Leave the ship for the real session: the Agentic IDE with that pane maximized. */import type { WorkspacePaneRow } from "@/lib/agenticIdeApi";import { useEventStore } from "@/store/events";import { useIdeChatStore } from "@/store/ideChat";import { useIdeSidePanelStore } from "@/store/ideSidePanel";-import { useOfficeStore } from "./officeStore";export function openPaneSession(pane: Pick<WorkspacePaneRow, "workspace_id" | "name">): void {- // Retire the small viewer and its size lead, including when this pane is- // already maximized in the grid and therefore has no new layout transition.- useOfficeStore.getState().select(null);const events = useEventStore.getState();if (events.activeSection !== "agentic-ide") events.setActiveSection("agentic-ide");// The terminal opens full-size in the grid, live, the way the agent works in it.useIdeChatStore.getState().requestPane(pane.workspace_id, pane.name, { maximize: true });- // A full-view office would hide the very pane it just focused.+ // A full-view side panel would hide the very pane it just focused.useIdeSidePanelStore.getState().setMaximized(false);}diff --git a/dodaios/ui/web/frontend/src/components/society/office/deskChat.test.ts b/dodaios/ui/web/frontend/src/components/society/crewFeeds/deskChat.test.tssimilarity index 100%rename from dodaios/ui/web/frontend/src/components/society/office/deskChat.test.tsrename to dodaios/ui/web/frontend/src/components/society/crewFeeds/deskChat.test.tsdiff --git a/dodaios/ui/web/frontend/src/components/society/office/deskChat.ts b/dodaios/ui/web/frontend/src/components/society/crewFeeds/deskChat.tssimilarity index 100%rename from dodaios/ui/web/frontend/src/components/society/office/deskChat.tsrename to dodaios/ui/web/frontend/src/components/society/crewFeeds/deskChat.tsdiff --git a/dodaios/ui/web/frontend/src/components/society/office/pollSignal.ts b/dodaios/ui/web/frontend/src/components/society/crewFeeds/pollSignal.tssimilarity index 100%rename from dodaios/ui/web/frontend/src/components/society/office/pollSignal.tsrename to dodaios/ui/web/frontend/src/components/society/crewFeeds/pollSignal.tsdiff --git a/dodaios/ui/web/frontend/src/components/society/crewFeeds/seated.ts b/dodaios/ui/web/frontend/src/components/society/crewFeeds/seated.tsnew file mode 100644index 0000000000..c060e344cb--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/crewFeeds/seated.ts@@ -0,0 +1,6 @@+/**+ * Who sits at their console right now, by agent id. The ship's crew layer+ * keeps it current every frame; the screen and chat feeds read it, so only+ * consoles somebody sits at are polled.+ */+export const seatedCrew = new Set<string>();diff --git a/dodaios/ui/web/frontend/src/components/society/office/teamwork.test.ts b/dodaios/ui/web/frontend/src/components/society/crewFeeds/teamwork.test.tssimilarity index 99%rename from dodaios/ui/web/frontend/src/components/society/office/teamwork.test.tsrename to dodaios/ui/web/frontend/src/components/society/crewFeeds/teamwork.test.tsindex dae301a7f1..c9514f7243 100644--- a/dodaios/ui/web/frontend/src/components/society/office/teamwork.test.ts+++ b/dodaios/ui/web/frontend/src/components/society/crewFeeds/teamwork.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";import type { SocietyMeeting } from "@/lib/societyChatGroups";-import { bubbleText } from "./officeTalk";+/** The host shortens and un-marks a line; here only the emphasis matters. */+const bubbleText = (text: string) => text.split("**").join("");import {HANDOFF_BUBBLE_MS, HANDOFF_FRESH_MS, MAX_ROUND_LINES, ROLE_GRACE_MS, SPOKE_LINGER_MS, applyRoomChange, applyRoomLine, applySnapshot, emptyRound,freshHandoffs, handoffFrom, isSpeaking, lastSpokeBy, meetingTeamId, pendingHandoff, queueHandoff, roundFor, roundRole, steadyRole, teamBubble, teamBubbleLive,diff --git a/dodaios/ui/web/frontend/src/components/society/office/teamwork.ts b/dodaios/ui/web/frontend/src/components/society/crewFeeds/teamwork.tssimilarity index 98%rename from dodaios/ui/web/frontend/src/components/society/office/teamwork.tsrename to dodaios/ui/web/frontend/src/components/society/crewFeeds/teamwork.tsindex 19fa3669d7..e2b929c57b 100644--- a/dodaios/ui/web/frontend/src/components/society/office/teamwork.ts+++ b/dodaios/ui/web/frontend/src/components/society/crewFeeds/teamwork.ts@@ -25,7 +25,14 @@import { create } from "zustand";import type { SocietyMeeting } from "@/lib/societyChatGroups";import type { AgentRunState, SocietyAgent } from "../data";-import type { Bubble } from "./officeTalk";+/** A line over a crew member's head. */+export interface Bubble {+ kind: "thought" | "speech" | "ask" | "error";+ text: string;+ /** Still streaming or working: the bubble never expires. */+ live: boolean;+ atMs: number;+}/** One line of a team's transcript; `speaker` is an agent id, or "user" for the person. */export interface RoundLine { id: string; speaker: string; text: string }diff --git a/dodaios/ui/web/frontend/src/components/society/office/terminalScreen.test.ts b/dodaios/ui/web/frontend/src/components/society/crewFeeds/terminalScreen.test.tssimilarity index 100%rename from dodaios/ui/web/frontend/src/components/society/office/terminalScreen.test.tsrename to dodaios/ui/web/frontend/src/components/society/crewFeeds/terminalScreen.test.tsdiff --git a/dodaios/ui/web/frontend/src/components/society/office/terminalScreen.ts b/dodaios/ui/web/frontend/src/components/society/crewFeeds/terminalScreen.tssimilarity index 100%rename from dodaios/ui/web/frontend/src/components/society/office/terminalScreen.tsrename to dodaios/ui/web/frontend/src/components/society/crewFeeds/terminalScreen.tsdiff --git a/dodaios/ui/web/frontend/src/components/society/office/useDeskChats.test.tsx b/dodaios/ui/web/frontend/src/components/society/crewFeeds/useDeskChats.test.tsxsimilarity index 96%rename from dodaios/ui/web/frontend/src/components/society/office/useDeskChats.test.tsxrename to dodaios/ui/web/frontend/src/components/society/crewFeeds/useDeskChats.test.tsxindex c81f57f8dc..ec20d59457 100644--- a/dodaios/ui/web/frontend/src/components/society/office/useDeskChats.test.tsx+++ b/dodaios/ui/web/frontend/src/components/society/crewFeeds/useDeskChats.test.tsx@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { act, cleanup, renderHook } from "@testing-library/react";import { READ_TIMEOUT_MS, readSignal, withReadSignal } from "./pollSignal";import { MAX_PER_TICK, dueDesks, keptChats, useDeskChats, type DeskChat } from "./useDeskChats";-import { seatedAtDesk } from "./walkerRegistry";+import { seatedCrew } from "./seated";const reads = vi.hoisted(() => ({ calls: [] as string[], signals: [] as (AbortSignal | undefined)[], hang: new Set<string>(), fail: new Set<string>(), seq: 0 }));vi.mock("@/lib/agentChatApi", () => ({@@ -25,12 +25,12 @@ beforeEach(() => {vi.spyOn(Math, "random").mockReturnValue(0.5);vi.spyOn(console, "debug").mockImplementation(() => undefined);reads.calls.length = 0; reads.signals.length = 0; reads.hang.clear(); reads.fail.clear(); reads.seq = 0;- seatedAtDesk.clear();+ seatedCrew.clear();});afterEach(() => {cleanup();- seatedAtDesk.clear();+ seatedCrew.clear();vi.restoreAllMocks();vi.useRealTimers();});@@ -64,7 +64,7 @@ describe("which desks are read on a tick", () => {describe("useDeskChats", () => {it("gives every seated agent its turn on a floor with more of them than one tick reads", async () => {const sessions = sessionsFor(14);- for (const id of sessions.keys()) seatedAtDesk.add(id);+ for (const id of sessions.keys()) seatedCrew.add(id);const view = renderHook(() => useDeskChats(sessions, true));await tick();expect(reads.calls).toHaveLength(MAX_PER_TICK);@@ -78,7 +78,7 @@ describe("useDeskChats", () => {it("is not frozen by a read that never answers, and does not let it keep its place in every tick", async () => {const sessions = sessionsFor(8);- for (const id of sessions.keys()) seatedAtDesk.add(id);+ for (const id of sessions.keys()) seatedCrew.add(id);reads.hang.add("s0");const view = renderHook(() => useDeskChats(sessions, true));await tick();@@ -100,7 +100,7 @@ describe("useDeskChats", () => {it("aborts what is in flight when the stage sleeps, and drops the chat of an agent that left", async () => {const sessions = sessionsFor(3);- for (const id of sessions.keys()) seatedAtDesk.add(id);+ for (const id of sessions.keys()) seatedCrew.add(id);const view = renderHook(({ list, awake }) => useDeskChats(list, awake), { initialProps: { list: sessions as ReadonlyMap<string, string>, awake: true } });await tick();expect(view.result.current.size).toBe(3);diff --git a/dodaios/ui/web/frontend/src/components/society/office/useDeskChats.ts b/dodaios/ui/web/frontend/src/components/society/crewFeeds/useDeskChats.tssimilarity index 96%rename from dodaios/ui/web/frontend/src/components/society/office/useDeskChats.tsrename to dodaios/ui/web/frontend/src/components/society/crewFeeds/useDeskChats.tsindex b4feb4e4ea..dd160bfac0 100644--- a/dodaios/ui/web/frontend/src/components/society/office/useDeskChats.ts+++ b/dodaios/ui/web/frontend/src/components/society/crewFeeds/useDeskChats.ts@@ -14,7 +14,7 @@ import { useEffect, useRef, useState } from "react";import { fetchAgentChatSession } from "@/lib/agentChatApi";import { chatLines, chatVersion, type ChatLine } from "./deskChat";import { withReadSignal } from "./pollSignal";-import { seatedAtDesk } from "./walkerRegistry";+import { seatedCrew } from "./seated";/** Events fetched per poll: enough for a full screen after tool noise is filtered out. */const TAIL_EVENTS = 60;@@ -84,7 +84,7 @@ export function useDeskChats(sessions: ReadonlyMap<string, string>, awake: boole};const tick = () => {for (const id of [...lastRead.keys()]) if (!sessionsRef.current.has(id)) lastRead.delete(id);- for (const agentId of dueDesks(seatedAtDesk, sessionsRef.current, lastRead, inFlight)) void read(agentId);+ for (const agentId of dueDesks(seatedCrew, sessionsRef.current, lastRead, inFlight)) void read(agentId);// The next tick does not wait for these reads: one that hangs holds nothing back.timer = setTimeout(tick, POLL_MS + Math.random() * JITTER_MS);};diff --git a/dodaios/ui/web/frontend/src/components/society/office/usePaneScreens.test.ts b/dodaios/ui/web/frontend/src/components/society/crewFeeds/usePaneScreens.test.tssimilarity index 83%rename from dodaios/ui/web/frontend/src/components/society/office/usePaneScreens.test.tsrename to dodaios/ui/web/frontend/src/components/society/crewFeeds/usePaneScreens.test.tsindex fe2d88c10f..312c766d7d 100644--- a/dodaios/ui/web/frontend/src/components/society/office/usePaneScreens.test.ts+++ b/dodaios/ui/web/frontend/src/components/society/crewFeeds/usePaneScreens.test.ts@@ -1,7 +1,6 @@import { describe, expect, it } from "vitest";import type { PaneScreen } from "@/lib/paneScreensApi";import { dueTargets, MAX_SCREEN_TARGETS, mergeScreens } from "./usePaneScreens";-import { nearestSeated } from "./TerminalMonitors";const target = (n: number) => ({ agentId: `pane:ws:${n}`, workspaceId: "ws", key: `T${n}` });const screen = (key: string, at: number): PaneScreen => ({@@ -34,10 +33,4 @@ describe("terminal screen polling", () => {expect(mergeScreens(first, [], [], new Set()).size).toBe(0);});- it("picks the nearest seated monitors, in a stable order", () => {- const picked = nearestSeated([- { id: "c", distance: 3 }, { id: "a", distance: 9 }, { id: "b", distance: 1 }, { id: "far", distance: 30 },- ], 3);- expect(picked).toEqual(["a", "b", "c"]);- });});diff --git a/dodaios/ui/web/frontend/src/components/society/office/usePaneScreens.ts b/dodaios/ui/web/frontend/src/components/society/crewFeeds/usePaneScreens.tssimilarity index 97%rename from dodaios/ui/web/frontend/src/components/society/office/usePaneScreens.tsrename to dodaios/ui/web/frontend/src/components/society/crewFeeds/usePaneScreens.tsindex 56d1bb40c9..7a600f6b85 100644--- a/dodaios/ui/web/frontend/src/components/society/office/usePaneScreens.ts+++ b/dodaios/ui/web/frontend/src/components/society/crewFeeds/usePaneScreens.ts@@ -10,7 +10,7 @@import { useEffect, useRef, useState } from "react";import { fetchPaneScreens, type PaneScreen } from "@/lib/paneScreensApi";import { screenChanged } from "./terminalScreen";-import { seatedAtDesk } from "./walkerRegistry";+import { seatedCrew } from "./seated";// The feed is an in-memory read of the pane's screen buffer and unchanged// screens are never redrawn, so a near-live rate costs next to nothing.@@ -64,7 +64,7 @@ export function usePaneScreens(targets: PaneScreenTarget[], awake: boolean): Realet timer: ReturnType<typeof setTimeout>;const schedule = () => { timer = setTimeout(() => void tick(), POLL_MIN_MS + Math.random() * POLL_JITTER_MS); };const tick = async () => {- const due = dueTargets(targetsRef.current, seatedAtDesk);+ const due = dueTargets(targetsRef.current, seatedCrew);if (due.length > 0) {try {const fetched = await fetchPaneScreens(due.map((t) => ({ workspaceId: t.workspaceId, key: t.key })));diff --git a/dodaios/ui/web/frontend/src/components/society/office/useTeamRounds.test.tsx b/dodaios/ui/web/frontend/src/components/society/crewFeeds/useTeamRounds.test.tsxsimilarity index 98%rename from dodaios/ui/web/frontend/src/components/society/office/useTeamRounds.test.tsxrename to dodaios/ui/web/frontend/src/components/society/crewFeeds/useTeamRounds.test.tsxindex e09e38c373..61b3cbf6f5 100644--- a/dodaios/ui/web/frontend/src/components/society/office/useTeamRounds.test.tsx+++ b/dodaios/ui/web/frontend/src/components/society/crewFeeds/useTeamRounds.test.tsx@@ -3,7 +3,7 @@ import { act, cleanup, renderHook } from "@testing-library/react";import type { SocietyMeeting } from "@/lib/societyChatGroups";import { useEventStore } from "@/store/events";import type { SocietyAgent } from "../data";-import type { Studio } from "./officeLayout";+import type { TeamWatch } from "./useTeamRounds";import { READ_TIMEOUT_MS } from "./pollSignal";import { boardWatch, emptyRound, useTeamwork } from "./teamwork";import { BOARD_REFRESH_MS, MAX_FAILED_READS, ROUND_POLL_MS, SWEEP_MS, afterFailedRead, useTeamRounds } from "./useTeamRounds";@@ -25,9 +25,7 @@ const STAGE = Symbol("test-stage");const agent = (agentId: string, tier = "specialist", checkpoint = "desk") => ({ agentId, name: agentId.toUpperCase(), tier, checkpoint } as unknown as SocietyAgent);const roster = (extra: SocietyAgent[] = []) => new Map([agent("jarvis", "lead"), agent("nora"), agent("ben"), agent("kai"), ...extra].map((a) => [a.agentId, a]));-const studio = (teamId: string | null, members: string[]): Studio => ({- deptId: `studio-${teamId ?? "pool"}`, teamId, name: teamId ?? "", members, leadId: null, board: null, huddleSpotIds: [], centre: { x: 0, z: 0 },-});+const studio = (teamId: string | null, members: string[]): TeamWatch => ({ teamId, members });const studios = [studio(null, ["kai"]), studio("t1", ["nora", "ben"]), studio("t2", [])];const meeting = (running: boolean, messages: [string, string, string][] = [], next: string | null = null): SocietyMeeting => ({messages: messages.map(([id, speaker, text]) => ({ id, speaker, text })), running, room: { state: running ? "running" : "settled", settle_reason: "", next_speaker: next },diff --git a/dodaios/ui/web/frontend/src/components/society/office/useTeamRounds.ts b/dodaios/ui/web/frontend/src/components/society/crewFeeds/useTeamRounds.tssimilarity index 97%rename from dodaios/ui/web/frontend/src/components/society/office/useTeamRounds.tsrename to dodaios/ui/web/frontend/src/components/society/crewFeeds/useTeamRounds.tsindex 49317d13d7..ffc6238b1e 100644--- a/dodaios/ui/web/frontend/src/components/society/office/useTeamRounds.ts+++ b/dodaios/ui/web/frontend/src/components/society/crewFeeds/useTeamRounds.ts@@ -24,7 +24,8 @@ import { useEffect, useRef, useState } from "react";import { fetchSocietyMeeting } from "@/lib/societyChatGroups";import { useEventStore } from "@/store/events";import type { SocietyAgent } from "../data";-import type { Studio } from "./officeLayout";+/** A team the poller watches: its id (null for the crew without a team) and its members. */+export interface TeamWatch { teamId: string | null; members: readonly string[] }import { withReadSignal } from "./pollSignal";import {applyRoomChange, applyRoomLine, applySnapshot, boardWatch, emptyRound, handoffFrom, meetingTeamId, useTeamwork, type TeamRound,@@ -133,7 +134,7 @@ function usePollerLease(wanted: boolean): boolean {* Feed the teamwork store while `awake`. `studios` are the floor's studios* (a team = a studio with a team id); `agents` is the roster.*/-export function useTeamRounds(studios: readonly Studio[], agents: ReadonlyMap<string, SocietyAgent>, awake: boolean): void {+export function useTeamRounds(studios: readonly TeamWatch[], agents: ReadonlyMap<string, SocietyAgent>, awake: boolean): void {const roster = useRef(agents);roster.current = agents;const teams = useRef(studios);diff --git a/dodaios/ui/web/frontend/src/components/society/figures/AgentFigureViewer.tsx b/dodaios/ui/web/frontend/src/components/society/figures/AgentFigureViewer.tsxindex abf29f5c38..3164806c26 100644--- a/dodaios/ui/web/frontend/src/components/society/figures/AgentFigureViewer.tsx+++ b/dodaios/ui/web/frontend/src/components/society/figures/AgentFigureViewer.tsx@@ -28,8 +28,8 @@ import { frameDistance } from "./figureFraming";import { resolvePalette, type FigureRecipe } from "./figureRecipe";import type { FigureDrive, FigureMode } from "./FigureRig";import { LobbyStage } from "./LobbyStage";-import { ToyFigure } from "../office/ToyFigure";-import { toyLookFor, TOY_HEIGHT, type ToyLook } from "../office/toyFigureModel";+import { ToyFigure } from "../figures/toy/ToyFigure";+import { toyLookFor, TOY_HEIGHT, type ToyLook } from "../figures/toy/toyFigureModel";/** How tall the preview figure is drawn, hair included, for framing. */const FRAMED_HEIGHT_M = TOY_HEIGHT * 1.04;diff --git a/dodaios/ui/web/frontend/src/components/society/office/StaticBatch.test.tsx b/dodaios/ui/web/frontend/src/components/society/figures/toy/StaticBatch.test.tsxsimilarity index 100%rename from dodaios/ui/web/frontend/src/components/society/office/StaticBatch.test.tsxrename to dodaios/ui/web/frontend/src/components/society/figures/toy/StaticBatch.test.tsxdiff --git a/dodaios/ui/web/frontend/src/components/society/office/StaticBatch.tsx b/dodaios/ui/web/frontend/src/components/society/figures/toy/StaticBatch.tsxsimilarity index 100%rename from dodaios/ui/web/frontend/src/components/society/office/StaticBatch.tsxrename to dodaios/ui/web/frontend/src/components/society/figures/toy/StaticBatch.tsxdiff --git a/dodaios/ui/web/frontend/src/components/society/office/ToyFigure.tsx b/dodaios/ui/web/frontend/src/components/society/figures/toy/ToyFigure.tsxsimilarity index 99%rename from dodaios/ui/web/frontend/src/components/society/office/ToyFigure.tsxrename to dodaios/ui/web/frontend/src/components/society/figures/toy/ToyFigure.tsxindex 6e0eb72905..2aef784480 100644--- a/dodaios/ui/web/frontend/src/components/society/office/ToyFigure.tsx+++ b/dodaios/ui/web/frontend/src/components/society/figures/toy/ToyFigure.tsx@@ -20,7 +20,7 @@ import {} from "three";import { RoundedBoxGeometry } from "three-stdlib";-import type { FigureMode } from "../figures/FigureRig";+import type { FigureMode } from "../../figures/FigureRig";import {blendPose, copyPose, createPose, poseFor, TOY, TOY_HEIGHT, walkCadence,type HairStyle, type OutfitId, type PoseOptions, type ToyLook, type ToyPose, type UniformStyle,diff --git a/dodaios/ui/web/frontend/src/components/society/office/outfitCatalog.ts b/dodaios/ui/web/frontend/src/components/society/figures/toy/outfitCatalog.tssimilarity index 100%rename from dodaios/ui/web/frontend/src/components/society/office/outfitCatalog.tsrename to dodaios/ui/web/frontend/src/components/society/figures/toy/outfitCatalog.tsdiff --git a/dodaios/ui/web/frontend/src/components/society/office/playerProfile.ts b/dodaios/ui/web/frontend/src/components/society/figures/toy/playerProfile.tssimilarity index 96%rename from dodaios/ui/web/frontend/src/components/society/office/playerProfile.tsrename to dodaios/ui/web/frontend/src/components/society/figures/toy/playerProfile.tsindex 27bdb8e673..6bc79515a4 100644--- a/dodaios/ui/web/frontend/src/components/society/office/playerProfile.ts+++ b/dodaios/ui/web/frontend/src/components/society/figures/toy/playerProfile.ts@@ -5,8 +5,8 @@* roster data, so it never touches society.db. Every read and write tolerates* a missing or blocked storage and falls back to the default look.*/-import { CATALOG } from "../figures/figureRegistry";-import type { FigureRecipe } from "../figures/figureRecipe";+import { CATALOG } from "../../figures/figureRegistry";+import type { FigureRecipe } from "../../figures/figureRecipe";import { HAIR_STYLES, toyLookFor, type HairStyle, type ToyLook } from "./toyFigureModel";const STORAGE_KEY = "jarvis.office.player.v1";diff --git a/dodaios/ui/web/frontend/src/components/society/office/toyFigureModel.test.ts b/dodaios/ui/web/frontend/src/components/society/figures/toy/toyFigureModel.test.tssimilarity index 99%rename from dodaios/ui/web/frontend/src/components/society/office/toyFigureModel.test.tsrename to dodaios/ui/web/frontend/src/components/society/figures/toy/toyFigureModel.test.tsindex 8df52d0057..097ee6f889 100644--- a/dodaios/ui/web/frontend/src/components/society/office/toyFigureModel.test.ts+++ b/dodaios/ui/web/frontend/src/components/society/figures/toy/toyFigureModel.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import type { FigureRecipe } from "../figures/figureRecipe";+import type { FigureRecipe } from "../../figures/figureRecipe";import { OUTFITS } from "./outfitCatalog";import {blendPose, createPose, isNaturalSkin, KEYBOARD, lowestSoleY, poseFor, SEAT_BACK_CLEARANCE, SEAT_HEIGHT,diff --git a/dodaios/ui/web/frontend/src/components/society/office/toyFigureModel.ts b/dodaios/ui/web/frontend/src/components/society/figures/toy/toyFigureModel.tssimilarity index 99%rename from dodaios/ui/web/frontend/src/components/society/office/toyFigureModel.tsrename to dodaios/ui/web/frontend/src/components/society/figures/toy/toyFigureModel.tsindex ae343f0ec5..b5b7467d7f 100644--- a/dodaios/ui/web/frontend/src/components/society/office/toyFigureModel.ts+++ b/dodaios/ui/web/frontend/src/components/society/figures/toy/toyFigureModel.ts@@ -17,8 +17,8 @@* the hip joints sit HIP_UP above it.*/-import { recipeKey, type FigureRecipe, type Palette } from "../figures/figureRecipe";-import type { FigureMode } from "../figures/FigureRig";+import { recipeKey, type FigureRecipe, type Palette } from "../../figures/figureRecipe";+import type { FigureMode } from "../../figures/FigureRig";import { OUTFITS, type Colourway } from "./outfitCatalog";// ---------------------------------------------------------------------------diff --git a/dodaios/ui/web/frontend/src/components/society/office/wardrobe.css b/dodaios/ui/web/frontend/src/components/society/figures/toy/wardrobe.csssimilarity index 100%rename from dodaios/ui/web/frontend/src/components/society/office/wardrobe.cssrename to dodaios/ui/web/frontend/src/components/society/figures/toy/wardrobe.cssdiff --git a/dodaios/ui/web/frontend/src/components/society/office/wardrobe.test.ts b/dodaios/ui/web/frontend/src/components/society/figures/toy/wardrobe.test.tssimilarity index 97%rename from dodaios/ui/web/frontend/src/components/society/office/wardrobe.test.tsrename to dodaios/ui/web/frontend/src/components/society/figures/toy/wardrobe.test.tsindex efaa1b0ea7..68f03057e1 100644--- a/dodaios/ui/web/frontend/src/components/society/office/wardrobe.test.ts+++ b/dodaios/ui/web/frontend/src/components/society/figures/toy/wardrobe.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { recipeKey, type FigureRecipe } from "../figures/figureRecipe";+import { recipeKey, type FigureRecipe } from "../../figures/figureRecipe";import { HAIR_STYLES, OUTFIT_IDS, toyLookFor } from "./toyFigureModel";import { colourwayIndexOf, dressIn, OUTFITS, pinLook, randomLook, withEyewear, withHair, withHairColour, withSkin } from "./wardrobe";diff --git a/dodaios/ui/web/frontend/src/components/society/office/wardrobe.ts b/dodaios/ui/web/frontend/src/components/society/figures/toy/wardrobe.tssimilarity index 98%rename from dodaios/ui/web/frontend/src/components/society/office/wardrobe.tsrename to dodaios/ui/web/frontend/src/components/society/figures/toy/wardrobe.tsindex 47a8e738e5..cf5f689e91 100644--- a/dodaios/ui/web/frontend/src/components/society/office/wardrobe.ts+++ b/dodaios/ui/web/frontend/src/components/society/figures/toy/wardrobe.ts@@ -7,7 +7,7 @@* shirt under a jacket), so a dressed figure looks the same in the office,* the creator preview and the appearance editor.*/-import type { FigureRecipe } from "../figures/figureRecipe";+import type { FigureRecipe } from "../../figures/figureRecipe";import { OUTFITS, type Outfit } from "./outfitCatalog";import { hashString, SKIN_TONES, toyLookFor, type Eyewear, type HairStyle, type OutfitId } from "./toyFigureModel";diff --git a/dodaios/ui/web/frontend/src/components/society/office/AgentFace.tsx b/dodaios/ui/web/frontend/src/components/society/office/AgentFace.tsxdeleted file mode 100644index fd35233269..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/AgentFace.tsx+++ /dev/null@@ -1,27 +0,0 @@-/**- * An agent's face in a list of the office (the directory, team rows, member- * lists, the member picker): its symbol on a neutral tile.- *- * Two things a bare symbol gets wrong in a list. Its colour is the agent's- * own, and a white or very pale one vanishes on a light dialog (a black one- * on a dark dialog): the tile and a hairline round the symbol's own outline,- * both from theme tokens, keep every colour readable in both themes. And a- * working agent's symbol turns into three "thinking" dots, which in a row of- * faces reads as a picture that is still loading: the run state is left out- * here, the state dot beside the face says it.- */-import { AgentSwatch } from "../AgentSwatch";-import type { SocietyAgent } from "../data";-import "./agentFace.css";--/** The tile is this much wider than the symbol on it. */-const TILE_MARGIN_PX = 8;--export function AgentFace({ agent, size = 24 }: { agent: SocietyAgent; size?: number }) {- const tile = size + TILE_MARGIN_PX;- return (- <span className="office-face" style={{ width: tile, height: tile }}>- <AgentSwatch agent={{ ...agent, state: undefined }} size={size} />- </span>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/AgentTalkPanel.tsx b/dodaios/ui/web/frontend/src/components/society/office/AgentTalkPanel.tsxdeleted file mode 100644index eab3b4fe9b..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/AgentTalkPanel.tsx+++ /dev/null@@ -1,316 +0,0 @@-/**- * The agent panel in the office: a walkie-talkie to that agent.- *- * Speak (hold T, or hold / tap the microphone) or type; the words go into the- * agent's own chat and it answers over its head. The panel keeps the last few- * exchanges readable, and the map actions (walk there, call over, show,- * team up, open the full chat) sit in one icon row underneath.- *- * Voice uses the app's existing in-app dictation (`stt_dictate`): the final- * transcript is delivered into the focused field (lib/dictationTarget.ts), so- * the panel focuses its own box before listening and sends whatever lands- * there once the microphone is closed. The global `dictating` flag is left- * alone on purpose — composers elsewhere mirror every partial while it is- * set, and the Agents workspace keeps one mounted behind the map.- */-import { useCallback, useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type PointerEvent } from "react";-import { useQueryClient } from "@tanstack/react-query";-import { ArrowUp, Footprints, Hand, LocateFixed, Maximize2, Mic, Square, UserPlus, X } from "lucide-react";-import { useT } from "@/i18n";-import { getWSClient } from "@/hooks/useWebSocket";-import { useEventStore } from "@/store/events";-import type { TimelineItem } from "@/components/agentchat/reduce";-import type { SocietyAgent } from "../data";-import { player, useOfficeStore } from "./officeStore";-import { CALL_MS } from "./stations";--// The session command panel imports the call duration from here.-export { CALL_MS };-import { agentPositions } from "./walkerRegistry";-import { ownsKeyboard } from "./OfficePlayer";-import { useBubbleLabels } from "./OfficeBubbles";-import { bubbleText, itemsFor, talkStoreFor, turnBubble, useOfficeTalk } from "./officeTalk";-import "./officeTalk.css";--/** A press on the microphone longer than this is push-to-talk: releasing sends. */-const HOLD_MS = 350;-/** After the microphone closes, the transcript usually lands within a few seconds. */-const FINAL_WAIT_MS = 15_000;-/** Quiet time after the transcript lands before it is sent on its own. */-const SETTLE_MS = 350;-/** Exchanges the panel keeps on screen; the full chat has the rest. */-const RECENT_ITEMS = 6;--export interface TalkActions {- onOpenAgent: (id: string) => void;-}--async function bindAgentChat(agentId: string): Promise<void> {- const res = await fetch(`/api/society/agents/${encodeURIComponent(agentId)}/chat`, { method: "POST" });- if (!res.ok) throw new Error(`HTTP ${res.status}`);-}--function sendDictation(mode: "start" | "stop") {- getWSClient()?.send({ type: "command", action: "stt_dictate", payload: { mode } });-}--function StateDot({ state }: { state: SocietyAgent["state"] }) {- return <i className="office-dot" data-state={state} aria-hidden />;-}--function LogEntry({ item }: { item: TimelineItem }) {- const labels = useBubbleLabels();- if (item.type === "user") return <li className="office-talk-msg" data-from="you"><p>{item.text}</p></li>;- if (item.type === "error") return <li className="office-talk-msg" data-from="error"><p>{bubbleText(item.text, 300)}</p></li>;- if (item.type !== "turn") return null;- if (item.status === "running") {- const live = turnBubble(item, labels);- return (- <li className="office-talk-msg" data-from="agent" data-live>- <p>{live.text}<span className="office-bubble-dots" aria-hidden><i /><i /><i /></span></p>- </li>- );- }- const text = [...item.blocks].reverse().find((b) => b.kind === "text" && b.text.trim());- const body = text && text.kind === "text" ? bubbleText(text.text, 900) : turnBubble(item, labels).text;- return <li className="office-talk-msg" data-from={item.status === "error" ? "error" : "agent"}><p>{body}</p></li>;-}--export function AgentTalkPanel({ agent, actions, onClose }: { agent: SocietyAgent; actions: TalkActions; onClose: () => void }) {- const t = useT();- const headingId = useId();- const client = useQueryClient();- const office = useOfficeStore();- const useChat = talkStoreFor(agent);- const timeline = useChat((s) => s.timeline);- const activeSessionId = useChat((s) => s.activeSessionId);- const busy = useChat((s) => s.busy);- const lastError = useChat((s) => s.lastError);- const connected = useEventStore((s) => s.connected);- const listening = useOfficeTalk((s) => s.listening);- const interim = useEventStore((s) => (listening ? s.dictationText : ""));- const [value, setValue] = useState("");- const [bindError, setBindError] = useState<string | null>(null);- const [called, setCalled] = useState(false);- const panel = useRef<HTMLElement>(null);- const input = useRef<HTMLTextAreaElement>(null);- const log = useRef<HTMLOListElement>(null);-- const isLead = agent.tier === "lead";- const ready = isLead || (!!agent.chatSessionId && agent.chatSessionId === activeSessionId);- const items = itemsFor(agent, activeSessionId, timeline);- const recent = useMemo(() => items.filter((i) => i.type === "user" || i.type === "turn" || i.type === "error").slice(-RECENT_ITEMS), [items]);- const last = recent[recent.length - 1];- const running = last?.type === "user" || (last?.type === "turn" && last.status === "running");- const approvals = ready ? timeline.pendingApprovals.length : 0;- const inDraft = office.teamDraft.includes(agent.agentId);- const where = agentPositions.get(agent.agentId);-- // This agent is the one the office listens to now; its bubble follows this chat.- useEffect(() => { useOfficeTalk.getState().setAgent(agent.agentId); setCalled(false); setValue(""); }, [agent.agentId]);- useEffect(() => { panel.current?.focus({ preventScroll: true }); }, [agent.agentId]);-- // Open the agent's own chat. Bind is idempotent; it creates the session a- // brand-new agent does not have yet, and the roster then carries its id.- useEffect(() => {- const chat = useChat.getState();- if (isLead) { if (!chat.activeSessionId) void chat.loadSessions(); return; }- let alive = true;- setBindError(null);- if (agent.chatSessionId) chat.openSession(agent.chatSessionId);- void bindAgentChat(agent.agentId)- .then(() => { if (alive && !agent.chatSessionId) void client.invalidateQueries({ queryKey: ["society", "roster"] }); })- .catch((err) => { if (alive) setBindError(err instanceof Error ? err.message : String(err)); });- return () => { alive = false; };- }, [agent.agentId, agent.chatSessionId, isLead, useChat, client]);-- // Newest exchange in view.- useEffect(() => { log.current?.scrollTo({ top: log.current.scrollHeight }); }, [recent]);-- const submit = useCallback(async (text: string) => {- const content = text.trim();- if (!content || !ready) return;- setValue("");- useOfficeTalk.getState().say(bubbleText(content, 160));- await useChat.getState().send(content);- }, [ready, useChat]);-- // --- voice -------------------------------------------------------------- const awaiting = useRef(false);- const awaitTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);- const settleTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);- const startVoice = useCallback(() => {- if (!connected || !ready || useOfficeTalk.getState().listening) return;- clearTimeout(settleTimer.current);- awaiting.current = false;- useEventStore.getState().setDictationInterim("");- // The final transcript goes to whatever field has focus: make that this box.- input.current?.focus({ preventScroll: true });- useOfficeTalk.getState().setListening(true);- sendDictation("start");- }, [connected, ready]);- const stopVoice = useCallback(() => {- if (!useOfficeTalk.getState().listening) return;- sendDictation("stop");- useOfficeTalk.getState().setListening(false);- input.current?.focus({ preventScroll: true });- awaiting.current = true;- clearTimeout(awaitTimer.current);- awaitTimer.current = setTimeout(() => { awaiting.current = false; }, FINAL_WAIT_MS);- }, []);- const voice = useRef({ startVoice, stopVoice });- voice.current = { startVoice, stopVoice };-- // Closing the panel (or switching agents) never leaves the microphone open.- useEffect(() => () => {- clearTimeout(awaitTimer.current);- clearTimeout(settleTimer.current);- if (useOfficeTalk.getState().listening) { sendDictation("stop"); useOfficeTalk.getState().setListening(false); }- }, [agent.agentId]);-- // Hold T to talk, anywhere on the map (a text field keeps its own T).- useEffect(() => {- let held = false;- const down = (event: globalThis.KeyboardEvent) => {- if (event.code !== "KeyT" || event.ctrlKey || event.metaKey || event.altKey) return;- // Key repeats while held land in the focused box; they must not type there.- if (held) { event.preventDefault(); return; }- if (event.repeat || ownsKeyboard(event.target)) return;- event.preventDefault();- held = true;- voice.current.startVoice();- };- const up = (event: globalThis.KeyboardEvent) => {- if (event.code !== "KeyT" || !held) return;- held = false;- event.preventDefault();- voice.current.stopVoice();- };- const release = () => { if (held) { held = false; voice.current.stopVoice(); } };- window.addEventListener("keydown", down, true);- window.addEventListener("keyup", up, true);- window.addEventListener("blur", release);- return () => {- window.removeEventListener("keydown", down, true);- window.removeEventListener("keyup", up, true);- window.removeEventListener("blur", release);- };- }, []);-- // The microphone button: a long press is push-to-talk, a tap toggles.- const press = useRef<{ at: number; wasListening: boolean } | null>(null);- const onMicDown = (event: PointerEvent<HTMLButtonElement>) => {- if (event.button !== 0) return;- event.preventDefault();- press.current = { at: Date.now(), wasListening: useOfficeTalk.getState().listening };- if (!press.current.wasListening) startVoice();- };- const onMicUp = () => {- const p = press.current;- press.current = null;- if (!p) return;- if (p.wasListening || Date.now() - p.at > HOLD_MS) stopVoice();- };- const onMicKey = (event: KeyboardEvent<HTMLButtonElement>) => {- if (event.key !== "Enter" && event.key !== " ") return;- event.preventDefault();- if (useOfficeTalk.getState().listening) stopVoice(); else startVoice();- };-- const onChange = (next: string) => {- setValue(next);- if (!awaiting.current) return;- // The spoken words just landed: send them once the box stops changing.- clearTimeout(settleTimer.current);- settleTimer.current = setTimeout(() => {- awaiting.current = false;- clearTimeout(awaitTimer.current);- void submit(input.current?.value ?? next);- panel.current?.focus({ preventScroll: true });- }, SETTLE_MS);- };-- const status = !ready- ? bindError ? `${t("society.card.chat_bind_failed")} (${bindError})` : t("society.office.talk_connecting")- : listening ? (interim || t("society.office.talk_listening")) : t("society.office.talk_hint");-- return (- <aside ref={panel} className="office-card office-panel office-talk" data-office-ui aria-labelledby={headingId} tabIndex={-1}>- <header className="office-talk-head">- <span className="office-talk-avatar" style={{ background: agent.palette.primary }} aria-hidden>- {isLead ? "★" : agent.name.slice(0, 1).toUpperCase()}- </span>- <div className="office-talk-who">- <h2 id={headingId}>{agent.name}</h2>- <span><StateDot state={agent.state} />{t(`society.office.state_${agent.state}`)}{agent.title || agent.providerLabel ? ` · ${agent.title || agent.providerLabel}` : ""}</span>- </div>- <button type="button" className="office-icon-button" onClick={onClose} aria-label={t("society.office.close")}><X size={16} aria-hidden /></button>- </header>-- <ol ref={log} className="office-talk-log" aria-live="polite" aria-label={t("society.office.talk_log").replace("{0}", agent.name)}>- {recent.length === 0- ? <li className="office-talk-empty">{t("society.office.talk_empty").replace("{0}", agent.name)}</li>- : recent.map((item) => <LogEntry key={item.id} item={item} />)}- </ol>-- {approvals > 0 && (- <p className="office-talk-alert" role="status">- {t("society.office.talk_approval").replace("{0}", agent.name)}- <button type="button" className="office-link" onClick={() => actions.onOpenAgent(agent.agentId)}>{t("society.office.talk_review")}</button>- </p>- )}- {lastError && ready && <p role="alert" className="office-talk-error">{lastError}</p>}-- <div className="office-talk-composer" data-listening={listening || undefined}>- <button type="button" className="office-talk-mic" data-jarvis-dictation-trigger aria-pressed={listening}- disabled={!connected || !ready}- aria-label={listening ? t("society.office.talk_mic_stop") : t("society.office.talk_mic_start")}- title={listening ? t("society.office.talk_mic_stop") : t("society.office.talk_mic_start")}- onPointerDown={onMicDown} onPointerUp={onMicUp} onPointerLeave={() => { if (press.current && Date.now() - press.current.at > HOLD_MS) onMicUp(); }}- onKeyDown={onMicKey}>- {listening ? <Square aria-hidden /> : <Mic aria-hidden />}- </button>- <textarea ref={input} rows={1} value={value} maxLength={4000}- placeholder={t("society.office.talk_placeholder").replace("{0}", agent.name)}- aria-label={t("society.office.talk_placeholder").replace("{0}", agent.name)}- onChange={(e) => onChange(e.target.value)}- onKeyDown={(e) => {- if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); void submit(value); }- // Escape leaves the box so the arrow keys walk again; a second Escape closes the panel.- else if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); panel.current?.focus({ preventScroll: true }); }- }} />- {running && !value.trim() && !listening- ? <button type="button" className="office-talk-send" data-stop onClick={() => void useChat.getState().cancel()}- aria-label={t("society.office.talk_cancel")} title={t("society.office.talk_cancel")}><Square aria-hidden /></button>- : <button type="button" className="office-talk-send" disabled={!ready || busy || !value.trim()} onClick={() => void submit(value)}- aria-label={t("society.office.talk_send")} title={t("society.office.talk_send")}><ArrowUp aria-hidden /></button>}- </div>- <p className="office-talk-status" data-listening={listening || undefined} aria-live="polite">{status}</p>-- <div className="office-talk-tools" role="toolbar" aria-label={t("society.office.talk_tools")}>- <button type="button" disabled={!where} onClick={() => where && office.requestWalk(where)} title={t("society.office.action_walk")}>- <Footprints aria-hidden /><span>{t("society.office.tool_walk")}</span>- </button>- <button type="button" onClick={() => { office.summon([agent.agentId], { x: player.x, z: player.z }, CALL_MS); setCalled(true); }} title={t("society.office.action_call")}>- <Hand aria-hidden /><span>{t("society.office.tool_call")}</span>- </button>- <button type="button" disabled={!where} onClick={() => where && office.focusOn(where)} title={t("society.office.action_focus")}>- <LocateFixed aria-hidden /><span>{t("society.office.tool_focus")}</span>- </button>- <button type="button" aria-pressed={inDraft} onClick={() => office.toggleDraft(agent.agentId)}- title={t(inDraft ? "society.office.action_undraft" : "society.office.action_draft")}>- <UserPlus aria-hidden /><span>{t("society.office.tool_team")}</span>- </button>- <button type="button" onClick={() => actions.onOpenAgent(agent.agentId)} title={t("society.office.action_chat")}>- <Maximize2 aria-hidden /><span>{t("society.office.tool_chat")}</span>- </button>- </div>- {called && <p className="office-hint office-talk-note" role="status">{t("society.office.call_sent").replace("{0}", agent.name)}</p>}- {office.teamDraft.length > 0 && (- <button type="button" className="office-link office-talk-note" onClick={() => office.select({ kind: "checkpoint", id: "team" })}>- {t("society.office.draft_count").replace("{0}", String(office.teamDraft.length))}- </button>- )}- </aside>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/AgentsFloorAmbience.tsx b/dodaios/ui/web/frontend/src/components/society/office/AgentsFloorAmbience.tsxdeleted file mode 100644index 6efa84e87e..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/AgentsFloorAmbience.tsx+++ /dev/null@@ -1,335 +0,0 @@-/**- * The agents floor's planting, fittings and light: olive trees in pale stone- * pots at the end of every street and in a few deliberate groups, cushioned- * oak benches, slatted oak planters of grasses (every studio's planted front- * among them), the built fittings of studios and commons (`CampusFittings`),- * a slim linear pendant light over every desk row with a soft pool of light- * below, and one warm fill light for the whole floor.- *- * Every repeated part is one instanced mesh, so the whole dressing costs a- * few dozen draw calls however large the campus grows. The solid pieces are- * the plan's `ambience` items, which the layout also adds to its obstacles;- * the pendants and light pools are out of reach (a metre over every head, or- * flat on the floor), and nothing overhead is wide enough to hide a desk.- */-import { useMemo } from "react";-import { AdditiveBlending, MeshBasicMaterial, MeshStandardMaterial, PlaneGeometry } from "three";-import { cachedCanvasTexture } from "./canvasMaterials";-import { BENCH_H, PLANTER_H, type AgentsAmbienceItem } from "./agentsAmbience";-import { FACADE } from "./BuildingShell";-import { AGENTS_SCENE } from "./AgentsFloorLook";-import { CampusFittings } from "./CampusFittings";-import { benchesOf, Instances, type Placement } from "./CodingFloorAmbience";-import { GEO, MAT, matte } from "./OfficeFurniture";-import type { Department, OfficeLayout } from "./officeLayout";--// ----------------------------------------------------------------------------// Materials-// -----------------------------------------------------------------------------const AMB = {- stone: matte("#e4ddd1", { roughness: 0.8 }),- stoneDark: matte("#cfc6b8", { roughness: 0.85 }),- gravel: matte("#b9b0a3", { roughness: 1 }),- bark: matte("#7a6a58", { roughness: 0.9 }),- oak: matte("#d9bf97", { roughness: 0.6 }),- oakDark: matte("#b89b74", { roughness: 0.65 }),- linen: matte("#efe7d8", { roughness: 1 }),- /** White, so each instance's colour is the fabric's or the felt's colour. */- fabric: matte("#ffffff", { roughness: 1 }),- plume: matte("#e9dcc0", { roughness: 1 }),- stalk: matte("#b7a582", { roughness: 1 }),-};--/** Olive leaves: silvery sage greens, lighter than the office's other plants. */-const OLIVE_LEAVES = [- matte("#8c9c6e", { flatShading: true }), matte("#9fae82", { flatShading: true }),- matte("#77885d", { flatShading: true }), matte("#b0b995", { flatShading: true }),-];-/** Grasses in the planters: deeper greens, the office's own leaf tones. */-const GRASS = [MAT.leaf, MAT.leafDark, MAT.leafLight, OLIVE_LEAVES[0]];-/** Throw pillows on the benches: clay, sage, mustard, dusty blue and oat. */-const PILLOWS = ["#c07f63", "#8fa383", "#d2a650", "#7f93a8", "#d9c9ab"];--/** Deterministic pseudo-random numbers per seed, so the dressing never changes between loads. */-function lcg(seed: number): () => number {- let state = seed >>> 0;- return () => {- state = (state * 1664525 + 1013904223) >>> 0;- return state / 0x1_0000_0000;- };-}--function seedOf(id: string): number {- let h = 2166136261;- for (let i = 0; i < id.length; i += 1) h = Math.imul(h ^ id.charCodeAt(i), 16777619);- return h >>> 0;-}--// ----------------------------------------------------------------------------// Olive trees-// -----------------------------------------------------------------------------/** An olive in a round stone pot: a leaning, forked trunk and an airy crown of small silvery clusters. */-function Olives({ items }: { items: readonly AgentsAmbienceItem[] }) {- const parts = useMemo(() => {- const pot: Placement[] = [], lip: Placement[] = [], gravel: Placement[] = [], trunk: Placement[] = [];- const leaves: Placement[][] = OLIVE_LEAVES.map(() => []);- for (const item of items) {- const x = (item.minX + item.maxX) / 2, z = (item.minZ + item.maxZ) / 2, r = (item.maxX - item.minX) / 2;- const rand = lcg(seedOf(item.id));- pot.push({ position: [x, 0.3, z], scale: [r - 0.03, 0.6, r - 0.03] });- lip.push({ position: [x, 0.61, z], scale: [r, 0.04, r] });- // The gravel tops out 5 mm above the lip (0.63): flush tops fought in flickering bands up close.- gravel.push({ position: [x, 0.63, z], scale: [r - 0.07, 0.01, r - 0.07] });- // Two leaning stems that fork from a short trunk.- const lean = (rand() - 0.5) * 0.3;- trunk.push({ position: [x, 0.85, z], scale: [0.055, 0.5, 0.055], rotation: [lean * 0.5, 0, 0.06] });- trunk.push({ position: [x - 0.08, 1.35, z + 0.02], scale: [0.035, 0.62, 0.035], rotation: [0.1, 0, 0.28] });- trunk.push({ position: [x + 0.09, 1.4, z - 0.03], scale: [0.032, 0.66, 0.032], rotation: [-0.12, 0, -0.26] });- // The crown: an open dome of small clusters, so the trunk shows through.- for (let k = 0; k < 11; k += 1) {- const a = (k / 11) * Math.PI * 2 + rand() * 0.6, ring = 0.15 + rand() * 0.42;- const y = 1.55 + rand() * 0.7 - ring * 0.35;- const s = 0.15 + rand() * 0.1;- leaves[Math.floor(rand() * leaves.length)].push({- position: [x + Math.cos(a) * ring, y, z + Math.sin(a) * ring], scale: [s * 1.3, s * 0.8, s * 1.3],- });- }- }- return { pot, lip, gravel, trunk, leaves };- }, [items]);- return (- <group>- <Instances geometry={GEO.potCyl} material={AMB.stone} items={parts.pot} />- <Instances geometry={GEO.cyl} material={AMB.stoneDark} items={parts.lip} cast={false} />- <Instances geometry={GEO.cyl} material={AMB.gravel} items={parts.gravel} cast={false} />- <Instances geometry={GEO.cyl} material={AMB.bark} items={parts.trunk} />- {/* Flat-shaded clusters: twenty faces each read the same as eighty. */}- {/* Two of a crown's three tones throw its shadow; the third would only draw it again. */}- {parts.leaves.map((list, i) => <Instances key={i} geometry={GEO.facet} material={OLIVE_LEAVES[i]} items={list} cast={i < 2} />)}- </group>- );-}--// ----------------------------------------------------------------------------// Window benches-// -----------------------------------------------------------------------------/**- * A long oak bench against the glass: a recessed plinth, an oak seat box, a- * linen seat cushion, back cushions leaning on the glass side, a few throw- * pillows and now and then a book left behind.- */-function Benches({ items }: { items: readonly AgentsAmbienceItem[] }) {- const parts = useMemo(() => {- const plinth: Placement[] = [], box: Placement[] = [], cushion: Placement[] = [], fabric: Placement[] = [];- for (const item of items) {- const rand = lcg(seedOf(item.id));- const depth = item.maxX - item.minX, len = item.maxZ - item.minZ;- const cx = (item.minX + item.maxX) / 2, cz = (item.minZ + item.maxZ) / 2;- // The glass side: -1 (west) when the bench faces east, +1 when it faces west.- const out = item.facing === "east" ? -1 : 1;- const seatTop = BENCH_H - 0.1;- plinth.push({ position: [cx + out * 0.03, 0.04, cz], scale: [depth - 0.1, 0.08, len - 0.1] });- box.push({ position: [cx, 0.08 + (seatTop - 0.08) / 2, cz], scale: [depth, seatTop - 0.08, len] });- cushion.push({ position: [cx - out * 0.02, seatTop + 0.05, cz], scale: [depth - 0.06, 0.1, len - 0.06] });- // Back cushions, one per ~0.8 m, leaning back onto the glass.- const backs = Math.max(1, Math.round(len / 0.8));- const bw = (len - 0.1) / backs;- for (let b = 0; b < backs; b += 1) {- cushion.push({- position: [cx + out * (depth / 2 - 0.07), seatTop + 0.3, item.minZ + 0.05 + bw * (b + 0.5)],- scale: [0.1, 0.38, bw - 0.03], rotation: [0, 0, -out * 0.16],- });- }- // Two or three throw pillows in front of the back cushions.- const pillows = 2 + Math.floor(rand() * 2);- for (let p = 0; p < pillows; p += 1) {- const pz = item.minZ + 0.3 + rand() * (len - 0.6);- fabric.push({- position: [cx + out * (depth / 2 - 0.16), seatTop + 0.24, pz], scale: [0.1, 0.3, 0.32],- rotation: [(rand() - 0.5) * 0.3, 0, -out * 0.3], color: PILLOWS[Math.floor(rand() * PILLOWS.length)],- });- }- if (rand() < 0.5) {- fabric.push({- position: [cx - out * 0.06, seatTop + 0.115, item.minZ + len * (0.2 + rand() * 0.6)], scale: [0.16, 0.03, 0.22],- rotation: [0, rand() * 0.8, 0], color: PILLOWS[Math.floor(rand() * PILLOWS.length)],- });- }- }- return { plinth, box, cushion, fabric };- }, [items]);- return (- <group>- <Instances geometry={GEO.box} material={AMB.oakDark} items={parts.plinth} cast={false} />- <Instances geometry={GEO.box} material={AMB.oak} items={parts.box} />- <Instances geometry={GEO.box} material={AMB.linen} items={parts.cushion} cast={false} />- <Instances geometry={GEO.box} material={AMB.fabric} items={parts.fabric} cast={false} />- </group>- );-}--// ----------------------------------------------------------------------------// Slatted planters-// -----------------------------------------------------------------------------/** Long oak planters wrapped in vertical slats, planted with tall grasses and a few pale feather-grass plumes. */-function Planters({ items }: { items: readonly AgentsAmbienceItem[] }) {- const parts = useMemo(() => {- const liner: Placement[] = [], slats: Placement[] = [], cap: Placement[] = [], soil: Placement[] = [], plumes: Placement[] = [], stalks: Placement[] = [];- const grass: Placement[][] = GRASS.map(() => []);- const mounds: Placement[][] = GRASS.map(() => []);- for (const item of items) {- const rand = lcg(seedOf(item.id));- const depth = item.maxX - item.minX, len = item.maxZ - item.minZ;- const cx = (item.minX + item.maxX) / 2, cz = (item.minZ + item.maxZ) / 2;- const bodyH = PLANTER_H - 0.03;- liner.push({ position: [cx, bodyH / 2, cz], scale: [depth - 0.03, bodyH, len - 0.03] });- // Slats every 7 cm down both long faces, and across both ends.- for (let z = item.minZ + 0.035; z < item.maxZ - 0.02; z += 0.07) {- for (const x of [item.minX + 0.012, item.maxX - 0.012]) slats.push({ position: [x, bodyH / 2, z], scale: [0.024, bodyH, 0.045] });- }- for (let x = item.minX + 0.05; x < item.maxX - 0.03; x += 0.07) {- for (const z of [item.minZ + 0.012, item.maxZ - 0.012]) slats.push({ position: [x, bodyH / 2, z], scale: [0.045, bodyH, 0.024] });- }- cap.push({ position: [cx, PLANTER_H - 0.015, cz], scale: [depth + 0.01, 0.03, len + 0.01] });- soil.push({ position: [cx, PLANTER_H + 0.002, cz], scale: [depth - 0.06, 0.006, len - 0.06] });- // Clumps of fine blades fanning out of a low mound, and every so often a pale plume above them.- // A planter runs along its longer side; the clumps follow it.- const alongX = depth > len;- const [from, to] = alongX ? [item.minX, item.maxX] : [item.minZ, item.maxZ];- for (let at = from + 0.12; at < to - 0.08; at += 0.11 + rand() * 0.05) {- const across = (alongX ? cz : cx) + (rand() - 0.5) * 0.1, tone = Math.floor(rand() * GRASS.length);- const bx = alongX ? at : across, z = alongX ? across : at;- mounds[tone].push({ position: [bx, PLANTER_H + 0.03, z], scale: [0.07, 0.06, 0.07] });- let tallest = 0;- for (let k = 0; k < 6; k += 1) {- const h = 0.18 + rand() * 0.24, rx = (rand() - 0.5) * 0.9, rz = (rand() - 0.5) * 0.9;- tallest = Math.max(tallest, h);- grass[(tone + (k % 2)) % GRASS.length].push({- // A blade's local +y leans to (-sin rz, cos rz · cos rx, sin rx): its centre sits one half-length up that line.- position: [bx - Math.sin(rz) * h * 0.9, PLANTER_H + Math.cos(rz) * Math.cos(rx) * h * 0.9, z + Math.sin(rx) * h * 0.9],- scale: [0.018 + rand() * 0.01, h, 0.028], rotation: [rx, 0, rz],- });- }- if (rand() < 0.3) {- // A plume on a thin stalk rising just above the clump.- const top = tallest * 1.9 + 0.1;- plumes.push({ position: [bx, PLANTER_H + top, z], scale: [0.03, 0.12, 0.03] });- stalks.push({ position: [bx, PLANTER_H + top / 2, z], scale: [0.004, top, 0.004] });- }- }- }- return { liner, slats, cap, soil, grass, mounds, plumes, stalks };- }, [items]);- return (- <group>- <Instances geometry={GEO.box} material={AMB.oakDark} items={parts.liner} />- <Instances geometry={GEO.box} material={AMB.oak} items={parts.slats} cast={false} />- <Instances geometry={GEO.box} material={AMB.oak} items={parts.cap} cast={false} />- <Instances geometry={GEO.box} material={MAT.soil} items={parts.soil} cast={false} />- {/* Hundreds of blades per planter: each is a slim spindle of eight faces, the mound under them a facet. */}- {parts.grass.map((list, i) => <Instances key={i} geometry={GEO.blade} material={GRASS[i]} items={list} cast={false} />)}- {parts.mounds.map((list, i) => <Instances key={`m${i}`} geometry={GEO.facet} material={GRASS[i]} items={list} cast={false} />)}- <Instances geometry={GEO.facet} material={AMB.plume} items={parts.plumes} cast={false} />- <Instances geometry={GEO.cyl} material={AMB.stalk} items={parts.stalks} cast={false} />- </group>- );-}--// ----------------------------------------------------------------------------// Pendant lights over the benches-// -----------------------------------------------------------------------------/**- * A slim linear pendant over each desk row: its height and its housing. Its two wires run up to the ceiling line.- * A line five centimetres wide a metre over every head never stands between the camera and the people at the desks.- */-const PENDANT = { y: 2.75, w: 0.05, h: 0.035 } as const;-const PENDANT_MAT = {- housing: matte("#2a2724", { roughness: 0.5 }),- glow: new MeshStandardMaterial({ color: AGENTS_SCENE.light.glow, emissive: AGENTS_SCENE.light.glow, emissiveIntensity: 1.5, toneMapped: false }),-};--let poolMaterial: MeshBasicMaterial | null = null;-/** A soft oval of warm light, added onto the floor. */-function pool(): MeshBasicMaterial {- if (!poolMaterial) {- const map = cachedCanvasTexture("agents:pool", 128, 128, (ctx, w, h) => {- const g = ctx.createRadialGradient(w / 2, h / 2, 0, w / 2, h / 2, w / 2);- g.addColorStop(0, "rgba(255,255,255,1)");- g.addColorStop(0.55, "rgba(255,255,255,0.4)");- g.addColorStop(1, "rgba(255,255,255,0)");- ctx.fillStyle = g;- ctx.fillRect(0, 0, w, h);- });- poolMaterial = new MeshBasicMaterial({- color: AGENTS_SCENE.light.pool, map, transparent: true, opacity: map ? 0.13 : 0, blending: AdditiveBlending, depthWrite: false,- });- }- return poolMaterial;-}-const POOL_GEOMETRY = new PlaneGeometry(1, 1).rotateX(-Math.PI / 2);--/** The housing of every pendant on the floor: its middle, its length along x, its height and its width. Pure. */-export function pendantHousings(departments: readonly Pick<Department, "id" | "desks">[]): { x: number; y: number; z: number; length: number; h: number; w: number }[] {- return benchesOf(departments).flatMap((bench) => {- const length = Math.max(1.2, bench.length - 1.3);- // One over each desk row of the bench.- return [-0.45, 0.45].map((dz) => ({ x: bench.x, y: PENDANT.y + PENDANT.h / 2, z: bench.z + dz, length, h: PENDANT.h, w: PENDANT.w }));- });-}--function Pendants({ departments }: { departments: readonly Department[] }) {- const parts = useMemo(() => {- const housings: Placement[] = [], glows: Placement[] = [], wires: Placement[] = [], pools: Placement[] = [];- const wire = FACADE.h - PENDANT.y - PENDANT.h;- for (const { x, y, z, length: run, h, w } of pendantHousings(departments)) {- housings.push({ position: [x, y, z], scale: [run, h, w] });- glows.push({ position: [x, PENDANT.y - 0.006, z], scale: [run - 0.04, 0.012, w - 0.014] });- for (const dx of [-run * 0.4, run * 0.4]) {- wires.push({ position: [x + dx, PENDANT.y + h + wire / 2, z], scale: [0.006, wire, 0.006] });- }- }- for (const bench of benchesOf(departments)) {- pools.push({ position: [bench.x, 0.012, bench.z], scale: [bench.length + 1.4, 1, 3.4] });- }- // Housings and wires are the same steel: one mesh.- return { steel: [...housings, ...wires], glows, pools };- }, [departments]);- return (- <group>- <Instances geometry={GEO.box} material={PENDANT_MAT.housing} items={parts.steel} cast={false} />- <Instances geometry={GEO.box} material={PENDANT_MAT.glow} items={parts.glows} cast={false} />- <Instances geometry={POOL_GEOMETRY} material={pool()} items={parts.pools} cast={false} />- </group>- );-}--// ----------------------------------------------------------------------------// The floor's ambience-// -----------------------------------------------------------------------------export function AgentsFloorAmbience({ layout }: { layout: OfficeLayout }) {- const items = useMemo(() => layout.ambience ?? [], [layout]);- const byKind = useMemo(() => ({- olive: items.filter((i) => i.kind === "olive"),- bench: items.filter((i) => i.kind === "bench"),- planter: items.filter((i) => i.kind === "planter"),- }), [items]);- const { minX, maxZ } = layout.bounds;- return (- <group>- {/* Soft warm daylight from the south-west, no shadows: the one extra light the floor pays for. */}- <directionalLight position={[minX - 12, 14, maxZ + 8]} intensity={0.35} color="#ffdcb4" />- <Olives items={byKind.olive} />- <Benches items={byKind.bench} />- <Planters items={byKind.planter} />- {/* Studio screens, cabinets, sofas and tables, and the commons' step seating, kitchen, booths and large trees. */}- <CampusFittings items={items} />- <Pendants departments={layout.departments} />- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/AgentsFloorLook.letters.test.tsx b/dodaios/ui/web/frontend/src/components/society/office/AgentsFloorLook.letters.test.tsxdeleted file mode 100644index 13b391eac8..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/AgentsFloorLook.letters.test.tsx+++ /dev/null@@ -1,130 +0,0 @@-/**- * A studio's lettering shows a name the person typed. Each wall owns its- * lettering and lets go of it: renaming, creating and deleting teams all- * session long must leave exactly one texture per wall on screen.- */-import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";-import { act, createRoot, extend, type ReconcilerRoot } from "@react-three/fiber";-import * as THREE from "three";-import type { Mesh, MeshStandardMaterial, Object3D } from "three";-import { AgentsDepartment } from "./AgentsFloorLook";-import { buildOfficeLayout, type Department, type OfficeAgentInput } from "./officeLayout";--/** Just enough of a WebGLRenderer for R3F to mount a scene graph without a GPU. */-function fakeRenderer(canvas: HTMLCanvasElement) {- const noop = () => undefined;- return {- domElement: canvas,- render: noop, setSize: noop, setPixelRatio: noop, setAnimationLoop: noop, dispose: noop,- getPixelRatio: () => 1,- shadowMap: { enabled: false, type: 0, needsUpdate: false },- xr: { enabled: false, isPresenting: false, addEventListener: noop, removeEventListener: noop, setAnimationLoop: noop },- outputColorSpace: "srgb", toneMapping: 0, toneMappingExposure: 1,- info: { render: {}, memory: {} },- };-}--/**- * A 2D context that accepts every call and draws nothing: jsdom has no canvas, and without a context no texture- * is made at all. Measuring text answers a fixed width, a gradient takes its stops.- */-function inertContext(): CanvasRenderingContext2D {- const gradient = { addColorStop: () => undefined };- return new Proxy({}, {- get: (_target, prop) => {- if (prop === "measureText") return () => ({ width: 10 });- if (prop === "createLinearGradient" || prop === "createRadialGradient") return () => gradient;- if (prop === "createImageData") return (w: number, h: number) => ({ data: new Uint8ClampedArray(w * h * 4), width: w, height: h });- return () => undefined;- },- set: () => true,- }) as CanvasRenderingContext2D;-}--extend(THREE);--const realGetContext = HTMLCanvasElement.prototype.getContext;-beforeAll(() => {- HTMLCanvasElement.prototype.getContext = (() => inertContext()) as unknown as typeof HTMLCanvasElement.prototype.getContext;-});-afterAll(() => {- HTMLCanvasElement.prototype.getContext = realGetContext;-});--let root: ReconcilerRoot<HTMLCanvasElement> | null = null;-let scene: Object3D | null = null;--/** Render into one root, so a second call updates what the first one mounted. */-async function render(element: JSX.Element): Promise<Object3D> {- if (!root) {- const canvas = document.createElement("canvas");- root = createRoot(canvas);- root.configure({- // Test double: R3F only needs the renderer's shape here, nothing is drawn.- gl: fakeRenderer(canvas) as unknown as NonNullable<Parameters<typeof root.configure>[0]>["gl"],- frameloop: "never",- size: { width: 100, height: 100, top: 0, left: 0 },- });- }- const current = root;- await act(async () => { current.render(<group ref={(g) => { if (g) scene = g; }}>{element}</group>); });- if (!scene) throw new Error("the element did not mount");- return scene;-}--afterEach(() => {- root?.unmount();- root = null;- scene = null;-});--const staff: OfficeAgentInput[] = Array.from({ length: 6 }, (_, i) => ({- agentId: `a${i + 1}`, name: `Agent ${i + 1}`, tier: "specialist", providerLabel: "Codex", state: "idle", createdMs: i,-}));-const studio: Department = buildOfficeLayout(staff, { teams: [{ id: "g1", name: "Launch crew", members: ["a1", "a2", "a3"], createdMs: 1 }] })- .departments.find((d) => d.teamId === "g1")!;--/** The wall's lettering: the one cut-out, textured sheet on it. */-function lettering(node: Object3D): MeshStandardMaterial {- const found: MeshStandardMaterial[] = [];- node.traverse((child) => {- const material = (child as Mesh).isMesh ? ((child as Mesh).material as MeshStandardMaterial) : null;- if (material?.isMeshStandardMaterial && material.alphaTest > 0.25 && material.alphaTest < 0.35) found.push(material);- });- expect(found).toHaveLength(1);- return found[0];-}--describe("a studio's lettering", () => {- it("belongs to its wall: a renamed team's old lettering is disposed, texture and all, and the last one with the studio", async () => {- let made = 0, gone = 0, texturesGone = 0;- const seen = new Set<MeshStandardMaterial>();- const watch = (material: MeshStandardMaterial) => {- if (seen.has(material)) return material;- seen.add(material);- made += 1;- material.addEventListener("dispose", () => { gone += 1; });- expect(material.map).toBeTruthy();- material.map!.addEventListener("dispose", () => { texturesGone += 1; });- return material;- };- const first = watch(lettering(await render(<AgentsDepartment dept={studio} />)));- // The same name again draws nothing new.- expect(lettering(await render(<AgentsDepartment dept={{ ...studio }} />))).toBe(first);- expect([made, gone]).toEqual([1, 0]);-- // Forty renames: forty new letterings, each replacing the one before.- for (let i = 0; i < 40; i += 1) {- const next = watch(lettering(await render(<AgentsDepartment dept={{ ...studio, label: `Launch crew ${i}` }} />)));- expect(next).not.toBe(first);- expect(made - gone, `rename ${i}`).toBe(1);- expect(texturesGone).toBe(gone);- }- expect(made).toBe(41);-- // The team is deleted: its studio goes, and its lettering with it.- await act(async () => { root?.unmount(); });- root = null;- expect([gone, texturesGone]).toEqual([41, 41]);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/AgentsFloorLook.tsx b/dodaios/ui/web/frontend/src/components/society/office/AgentsFloorLook.tsxdeleted file mode 100644index f7dfd67815..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/AgentsFloorLook.tsx+++ /dev/null@@ -1,513 +0,0 @@-/**- * The agents floor's own look — the same company as the coding floor above,- * but lighter and Scandinavian where that one is walnut and amber: wide- * pale-oak planks framed by a warm limestone band along the windows with a- * bronze inlay, a soft warm rim round the slab, and every team studio on a- * bordered rug in its own colour in front of a pale-oak tambour wall capped- * in that colour, the team's name lettered in ink on its west half (the- * studio board hangs in front of the east half).- *- * Purely visual. The only solid part is the studio wall, which stays inside- * the name-wall footprint the layout already walks round.- */-import { useEffect, useMemo } from "react";-import type { ThreeEvent } from "@react-three/fiber";-import { AdditiveBlending, MeshBasicMaterial, MeshStandardMaterial, RepeatWrapping, Shape, type Texture } from "three";-import { useT } from "@/i18n";-import { cachedCanvasTexture, ownedCanvasTexture } from "./canvasMaterials";-import { Box, matte } from "./OfficeFurniture";-import { studioWallParts } from "./campusLayout";-import type { Department, OfficeLayout } from "./officeLayout";--/** The agents floor's surfaces and light. */-export const AGENTS_SCENE = {- /** Warm daylight sky and a warm bounce off the oak. */- sky: "#fff3e4",- ground: "#8c7c6a",- slabEdge: "#2e2925",- rim: "#ffe2bd",- /** Wide plank light oak: the joint colour and the plank tones. */- oak: { seam: "#b39571", planks: ["#e4d0ae", "#dcc6a1", "#e9d8ba", "#d8bf98", "#e1caa5", "#ecdcc1"] },- /** The limestone band along the windows, and its bronze inlay. */- stone: { base: "#e7e0d4", cloud: ["#ddd5c7", "#efe9df", "#e2dace"], inlay: "#a8865a" },- /** Tambour oak walls behind each department. */- tambour: { flute: "#dec7a3", shade: "#b99d77", cap: "#cfb48d" },- ink: "#2b2926",- /** Felt clouds over the benches: their linear light and the pool it throws. */- light: { glow: "#fff0d8", pool: "#ffe1b3" },-} as const;--export type RugWeave = "boucle" | "pinstripe" | "basket" | "chevron" | "windowpane" | "rib";--/** A department's rug: woven field, weave tone, border band, and the felt of its cloud and wall kick band. */-export interface AgentsRug { weave: RugWeave; field: string; thread: string; border: string; felt: string }--/**- * One rug per department, cycled: linen, sage, clay and friends, woven- * tone-on-tone, each in the hue family of its zone's desk screens and seats.- */-export const AGENTS_RUGS: readonly AgentsRug[] = [- { weave: "boucle", field: "#c9d1bd", thread: "#bac4ac", border: "#86997c", felt: "#9fb094" },- { weave: "pinstripe", field: "#c8d0d8", thread: "#b9c3cd", border: "#74889c", felt: "#93a4b5" },- { weave: "basket", field: "#e5dac5", thread: "#d8cab0", border: "#b49a74", felt: "#cbb592" },- { weave: "chevron", field: "#e6d0c3", thread: "#dbc0b0", border: "#bb7f66", felt: "#cf9d88" },- { weave: "windowpane", field: "#d2ccdc", thread: "#c4bdd1", border: "#8c84a6", felt: "#aaa3c0" },- { weave: "rib", field: "#c5d7d0", thread: "#b5cbc3", border: "#6a988c", felt: "#8fb3a9" },- // Mustard, rose, sky, olive, cocoa and indigo: a full campus of twelve studios never repeats a colour.- { weave: "chevron", field: "#e6d7a6", thread: "#dccb93", border: "#b8963c", felt: "#cdb05f" },- { weave: "boucle", field: "#dcc3cb", thread: "#d1b4be", border: "#a8647c", felt: "#bf8a9c" },- { weave: "pinstripe", field: "#b9cfdc", thread: "#a9c2d1", border: "#4f86a6", felt: "#7ba5bf" },- { weave: "basket", field: "#cfd3aa", thread: "#c2c798", border: "#868c4a", felt: "#a4a96c" },- { weave: "rib", field: "#d9c4b4", thread: "#cdb5a3", border: "#9a6a4c", felt: "#b68b70" },- { weave: "windowpane", field: "#bfc6d9", thread: "#b0b8ce", border: "#5c6aa0", felt: "#8590bb" },-];--/** The rug a department lies on: cycles through the set by the department's tint index. */-export function agentsRug(index: number): AgentsRug {- const n = AGENTS_RUGS.length;- return AGENTS_RUGS[((index % n) + n) % n];-}--/** Metres covered by one repeat of the plank tile and of a rug weave. */-const OAK_METRES = 3.2;-const WEAVE_METRES = 1.6;--/** Deterministic pseudo-random numbers, so the planks never shimmer between loads. */-function lcg(seed: number): () => number {- let state = seed >>> 0;- return () => {- state = (state * 1664525 + 1013904223) >>> 0;- return state / 0x1_0000_0000;- };-}--/**- * Wide oak planks running east–west, 20 cm by 1.0–2.0 m, staggered row by row.- * Each row's joints are laid round the tile's width, so the tile wraps.- */-function drawPlanks(ctx: CanvasRenderingContext2D, w: number, h: number): void {- const { seam, planks } = AGENTS_SCENE.oak;- const rand = lcg(0x0a4e75);- const rowH = 32;- ctx.fillStyle = seam;- ctx.fillRect(0, 0, w, h);- for (let y = 0; y < h; y += rowH) {- const start = rand() * w;- let x = start;- while (x < start + w) {- const len = Math.min(160 + rand() * 160, start + w - x);- const tone = planks[Math.floor(rand() * planks.length)];- const grainSeed = rand() * 1000, knot = rand();- // Drawn at its wrapped position and one tile to the left, so it continues past the edge.- for (const dx of [0, -w]) {- const px = x + dx;- if (px > w || px + len < 0) continue;- ctx.fillStyle = tone;- ctx.fillRect(px + 1, y + 1, len - 1.5, rowH - 1.5);- // Long, slightly wavy grain lines and now and then a small knot.- for (let g = 0; g < 4; g += 1) {- ctx.fillStyle = g % 2 === 0 ? "rgba(140,104,66,0.10)" : "rgba(255,248,232,0.16)";- const gy = y + 4 + ((g * 7 + grainSeed) % (rowH - 8));- for (let sx = 0; sx < len - 4; sx += 16) {- ctx.fillRect(px + 2 + sx, gy + Math.sin((sx + grainSeed) * 0.05) * 1.4, 16, 0.9);- }- }- if (knot < 0.18) {- ctx.fillStyle = "rgba(120,86,52,0.28)";- ctx.beginPath();- ctx.ellipse(px + len * (0.2 + knot * 3), y + rowH / 2, 4, 2, 0, 0, Math.PI * 2);- ctx.fill();- }- }- x += len;- }- }-}--/** Warm limestone: soft clouds of tone and a fine fossil grain, seamless on both axes. */-function drawStone(ctx: CanvasRenderingContext2D, w: number, h: number): void {- const { base, cloud } = AGENTS_SCENE.stone;- const rand = lcg(0x5701e);- ctx.fillStyle = base;- ctx.fillRect(0, 0, w, h);- for (let i = 0; i < 36; i += 1) {- const x = rand() * w, y = rand() * h, r = 18 + rand() * 46;- const tone = cloud[i % cloud.length];- for (const dx of [-w, 0, w]) {- for (const dy of [-h, 0, h]) {- const g = ctx.createRadialGradient(x + dx, y + dy, 0, x + dx, y + dy, r);- g.addColorStop(0, `${tone}aa`);- g.addColorStop(1, `${tone}00`);- ctx.fillStyle = g;- ctx.fillRect(x + dx - r, y + dy - r, r * 2, r * 2);- }- }- }- for (let i = 0; i < 1400; i += 1) {- ctx.fillStyle = rand() > 0.55 ? "rgba(255,255,255,0.16)" : "rgba(120,104,84,0.10)";- const s = rand() > 0.9 ? 2 : 1;- ctx.fillRect(Math.floor(rand() * w), Math.floor(rand() * h), s, s);- }-}--/** A cached base texture, cloned per surface with its own repeat. */-export function repeated(base: Texture | null, repeatX: number, repeatZ: number): Texture | null {- if (!base) return null;- const map = base.clone();- map.wrapS = map.wrapT = RepeatWrapping;- map.anisotropy = 8;- map.repeat.set(repeatX, repeatZ);- map.needsUpdate = true;- return map;-}--/** A limestone surface `along` × `across` metres, one repeat of the stone per 3 m. The caller owns (and disposes) it. */-export function limestone(along: number, across: number): MeshStandardMaterial {- const map = repeated(cachedCanvasTexture("agents:stone", 256, 256, drawStone), along / 3, across / 3);- return new MeshStandardMaterial({ color: map ? "#ffffff" : AGENTS_SCENE.stone.base, map, roughness: 0.45 });-}--/** Width of the limestone band along the slab's edge, and of its bronze inlay. */-const BAND_M = 1.35;-const INLAY_M = 0.03;--/**- * The slab and floor of the agents floor: wide pale-oak planks, framed by a- * limestone band with a bronze inlay along the windows, a warm stone edge and- * a soft warm rim. The floor's edges (window walls, balustrades) are the- * building shell's.- */-export function AgentsSlab({ layout, onFloorClick }: { layout: OfficeLayout; onFloorClick: (event: ThreeEvent<MouseEvent>) => void }) {- const { minX, maxX, minZ, maxZ } = layout.bounds;- const w = maxX - minX, d = maxZ - minZ, cx = (minX + maxX) / 2, cz = (minZ + maxZ) / 2;- const innerW = w - BAND_M * 2, innerD = d - BAND_M * 2;- const floor = useMemo(() => {- const map = repeated(cachedCanvasTexture("agents:planks", 512, 512, drawPlanks), w / OAK_METRES, d / OAK_METRES);- return new MeshStandardMaterial({ color: map ? "#ffffff" : AGENTS_SCENE.oak.planks[0], map, roughness: 0.55 });- }, [w, d]);- // The band's strips: north and south run the full width, east and west fit between them; one repeat per 3 m.- const band = useMemo(() => {- const base = cachedCanvasTexture("agents:stone", 256, 256, drawStone);- const strip = (along: number, across: number) => {- const map = repeated(base, along / 3, across / 3);- return new MeshStandardMaterial({ color: map ? "#ffffff" : AGENTS_SCENE.stone.base, map, roughness: 0.45 });- };- return { ns: strip(w, BAND_M), ew: strip(BAND_M, innerD) };- }, [w, innerD]);- const inlay = useMemo(() => matte(AGENTS_SCENE.stone.inlay, { roughness: 0.4, metalness: 0.45 }), []);- const edge = useMemo(() => matte(AGENTS_SCENE.slabEdge, { roughness: 0.75 }), []);- const rim = useMemo(() => new MeshStandardMaterial({- color: AGENTS_SCENE.rim, emissive: AGENTS_SCENE.rim, emissiveIntensity: 0.9, roughness: 0.4, toneMapped: false,- }), []);- useEffect(() => () => {- for (const m of [floor, band.ns, band.ew]) { m.map?.dispose(); m.dispose(); }- inlay.dispose(); edge.dispose(); rim.dispose();- }, [floor, band, inlay, edge, rim]);- const glow = 0.05;- return (- <group>- <Box size={[w, 0.6, d]} position={[cx, -0.3, cz]} material={edge} cast={false} />- {/* The rim runs just below the floor's edge on all four sides. */}- <Box size={[w + glow, glow, glow]} position={[cx, -0.06, minZ]} material={rim} cast={false} />- <Box size={[w + glow, glow, glow]} position={[cx, -0.06, maxZ]} material={rim} cast={false} />- <Box size={[glow, glow, d + glow]} position={[minX, -0.06, cz]} material={rim} cast={false} />- <Box size={[glow, glow, d + glow]} position={[maxX, -0.06, cz]} material={rim} cast={false} />- <mesh position={[cx, 0.001, cz]} rotation={[-Math.PI / 2, 0, 0]} material={floor} receiveShadow onClick={onFloorClick}>- <planeGeometry args={[w, d]} />- </mesh>- {[minZ + BAND_M / 2, maxZ - BAND_M / 2].map((z) => (- <mesh key={`ns${z}`} position={[cx, 0.002, z]} rotation={[-Math.PI / 2, 0, 0]} material={band.ns} receiveShadow onClick={onFloorClick}>- <planeGeometry args={[w, BAND_M]} />- </mesh>- ))}- {[minX + BAND_M / 2, maxX - BAND_M / 2].map((x) => (- <mesh key={`ew${x}`} position={[x, 0.002, cz]} rotation={[-Math.PI / 2, 0, 0]} material={band.ew} receiveShadow onClick={onFloorClick}>- <planeGeometry args={[BAND_M, innerD]} />- </mesh>- ))}- {/* The bronze inlay where oak meets stone. */}- <Box size={[innerW + INLAY_M, 0.004, INLAY_M]} position={[cx, 0.002, minZ + BAND_M]} material={inlay} cast={false} />- <Box size={[innerW + INLAY_M, 0.004, INLAY_M]} position={[cx, 0.002, maxZ - BAND_M]} material={inlay} cast={false} />- <Box size={[INLAY_M, 0.004, innerD]} position={[minX + BAND_M, 0.002, cz]} material={inlay} cast={false} />- <Box size={[INLAY_M, 0.004, innerD]} position={[maxX - BAND_M, 0.002, cz]} material={inlay} cast={false} />- </group>- );-}--// ----------------------------------------------------------------------------// Rugs-// -----------------------------------------------------------------------------/** A tone-on-tone weave, 256 px per WEAVE_METRES, seamless on both axes. */-function drawWeave(rug: AgentsRug, ctx: CanvasRenderingContext2D, w: number, h: number): void {- const rand = lcg(rug.weave.length * 977 + rug.field.charCodeAt(1));- ctx.fillStyle = rug.field;- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = rug.thread;- ctx.strokeStyle = rug.thread;- switch (rug.weave) {- case "boucle":- // Small loops of yarn scattered evenly.- ctx.lineWidth = 1.6;- for (let i = 0; i < 520; i += 1) {- const x = rand() * w, y = rand() * h;- ctx.beginPath();- ctx.arc(x, y, 1.6 + rand() * 1.6, 0, Math.PI * 2);- ctx.stroke();- }- break;- case "pinstripe":- for (let y = 0; y < h; y += 16) ctx.fillRect(0, y, w, 3);- ctx.fillStyle = "rgba(255,255,255,0.18)";- for (let y = 8; y < h; y += 32) ctx.fillRect(0, y, w, 1.5);- break;- case "basket":- // 32-px squares of three threads, alternating direction like a basketweave.- for (let y = 0; y < h; y += 32) {- for (let x = 0; x < w; x += 32) {- const across = ((x + y) / 32) % 2 === 0;- for (let k = 0; k < 3; k += 1) {- if (across) ctx.fillRect(x + 2, y + 4 + k * 10, 28, 5);- else ctx.fillRect(x + 4 + k * 10, y + 2, 5, 28);- }- }- }- break;- case "chevron":- ctx.lineWidth = 6;- for (let y = -32; y < h + 32; y += 32) {- ctx.beginPath();- for (let x = 0; x <= w; x += 32) ctx.lineTo(x, y + ((x / 32) % 2 === 0 ? 0 : 16));- ctx.stroke();- }- break;- case "windowpane":- for (let at = 0; at < w; at += 64) { ctx.fillRect(at, 0, 3, h); ctx.fillRect(0, at, w, 3); }- ctx.fillStyle = "rgba(255,255,255,0.14)";- for (let at = 32; at < w; at += 64) { ctx.fillRect(at, 0, 1.5, h); ctx.fillRect(0, at, w, 1.5); }- break;- case "rib":- // Soft raised ribs: a shaded band per 16 px.- for (let x = 0; x < w; x += 16) {- const g = ctx.createLinearGradient(x, 0, x + 16, 0);- g.addColorStop(0, "rgba(255,255,255,0.20)");- g.addColorStop(0.5, `${rug.thread}00`);- g.addColorStop(1, "rgba(60,50,40,0.10)");- ctx.fillStyle = g;- ctx.fillRect(x, 0, 16, h);- }- break;- }- // A fine fibre grain over every weave.- for (let i = 0; i < 1600; i += 1) {- ctx.fillStyle = rand() > 0.5 ? "rgba(255,255,255,0.10)" : "rgba(60,50,40,0.06)";- ctx.fillRect(Math.floor(rand() * w), Math.floor(rand() * h), 1, 1);- }-}--/** Rug materials, one per style. Shape UVs are in metres, so one material fits every rug size. */-const rugMaterials = new Map<AgentsRug, { field: MeshStandardMaterial; border: MeshStandardMaterial; line: MeshStandardMaterial; felt: MeshStandardMaterial }>();-function rugKit(rug: AgentsRug) {- let kit = rugMaterials.get(rug);- if (!kit) {- const base = cachedCanvasTexture(`agents:weave:${rug.weave}:${rug.field}`, 256, 256, (ctx, w, h) => drawWeave(rug, ctx, w, h));- const map = repeated(base, 1 / WEAVE_METRES, 1 / WEAVE_METRES);- kit = {- field: new MeshStandardMaterial({ color: map ? "#ffffff" : rug.field, map, roughness: 0.97 }),- border: matte(rug.border, { roughness: 1 }),- line: matte("#f3ede2", { roughness: 1 }),- felt: matte(rug.felt, { roughness: 1 }),- };- rugMaterials.set(rug, kit);- }- return kit;-}--/** A flat rounded rectangle in the XY plane, laid on the floor by its mesh's rotation. */-function roundedRect(w: number, d: number, r: number): Shape {- const x = -w / 2, y = -d / 2;- const shape = new Shape();- shape.moveTo(x + r, y);- shape.lineTo(x + w - r, y);- shape.quadraticCurveTo(x + w, y, x + w, y + r);- shape.lineTo(x + w, y + d - r);- shape.quadraticCurveTo(x + w, y + d, x + w - r, y + d);- shape.lineTo(x + r, y + d);- shape.quadraticCurveTo(x, y + d, x, y + d - r);- shape.lineTo(x, y + r);- shape.quadraticCurveTo(x, y, x + r, y);- return shape;-}--// ----------------------------------------------------------------------------// Department wall-// -----------------------------------------------------------------------------const WALL_H = 1.9;-const LETTERS = { w: 1024, h: 224 } as const;--/** Tambour: half-round oak flutes, four per 64-px repeat, lit from the upper left. */-function drawTambour(ctx: CanvasRenderingContext2D, w: number, h: number): void {- const { flute, shade } = AGENTS_SCENE.tambour;- for (let x = 0; x < w; x += 16) {- const g = ctx.createLinearGradient(x, 0, x + 16, 0);- g.addColorStop(0, shade);- g.addColorStop(0.2, flute);- g.addColorStop(0.45, "#f1e2c8");- g.addColorStop(0.8, flute);- g.addColorStop(1, shade);- ctx.fillStyle = g;- ctx.fillRect(x, 0, 16, h);- }- // A faint vertical grain.- ctx.fillStyle = "rgba(140,104,66,0.08)";- for (let x = 3; x < w; x += 7) ctx.fillRect(x, 0, 0.8, h);-}--const tambourMaterials = new Map<string, MeshStandardMaterial>();-/** Flutes about 4 cm wide: one texture repeat per 16 cm of wall. */-function tambourMaterial(width: number): MeshStandardMaterial {- const key = width.toFixed(2);- let material = tambourMaterials.get(key);- if (!material) {- const map = repeated(cachedCanvasTexture("agents:tambour", 64, 64, drawTambour), width / 0.16, 1);- material = new MeshStandardMaterial({ color: map ? "#ffffff" : AGENTS_SCENE.tambour.flute, map, roughness: 0.7 });- tambourMaterials.set(key, material);- }- return material;-}--/** Ink letters on a transparent ground: the studio's name, a short rule in its colour and a caption under it. */-function drawLetters(label: string, caption: string, accent: string, ctx: CanvasRenderingContext2D, w: number, h: number): void {- ctx.clearRect(0, 0, w, h);- const tracked = (text: string, font: string, y: number, spacing: number, fill: string) => {- ctx.font = font;- const chars = [...text];- const widths = chars.map((ch) => ctx.measureText(ch).width);- const total = widths.reduce((sum, cw) => sum + cw, 0) + spacing * Math.max(0, chars.length - 1);- // Squeeze a long name to fit rather than cutting it off.- const scale = Math.min(1, (w - 60) / total);- ctx.save();- ctx.translate(w / 2, y);- ctx.scale(scale, 1);- let x = -total / 2;- ctx.fillStyle = fill;- chars.forEach((ch, i) => {- ctx.fillText(ch, x, 0);- x += widths[i] + spacing;- });- ctx.restore();- };- ctx.textAlign = "left";- ctx.textBaseline = "middle";- const name = label.length > 24 ? `${label.slice(0, 23)}…` : label;- tracked(name, "600 104px Inter, system-ui, -apple-system, 'Segoe UI', sans-serif", 84, 4, AGENTS_SCENE.ink);- ctx.fillStyle = accent;- ctx.fillRect(w / 2 - 44, 154, 88, 5);- tracked(caption.toLocaleUpperCase(), "600 32px Inter, system-ui, -apple-system, 'Segoe UI', sans-serif", 194, 10, "#5d564e");-}--/**- * A studio's lettering. A team's name is whatever the person typed, so this is never cached by its text: the wall- * that shows it owns the material and its texture, and disposes both when the name changes or the studio goes.- */-function letterMaterial(label: string, caption: string, accent: string): MeshStandardMaterial {- const map = ownedCanvasTexture(LETTERS.w, LETTERS.h, (ctx, w, h) => drawLetters(label, caption, accent, ctx, w, h));- return new MeshStandardMaterial({ color: map ? "#ffffff" : AGENTS_SCENE.ink, map, transparent: true, alphaTest: 0.3, roughness: 0.6 });-}--let washCache: MeshBasicMaterial | null = null;-/** Soft warm light grazing down the flutes from the strip under the cap. */-function washMaterial(): MeshBasicMaterial {- if (!washCache) {- const map = cachedCanvasTexture("agents:wash", 64, 128, (ctx, w, h) => {- const g = ctx.createLinearGradient(0, 0, 0, h);- g.addColorStop(0, "rgba(255,236,206,0.9)");- g.addColorStop(1, "rgba(255,236,206,0)");- ctx.fillStyle = g;- ctx.fillRect(0, 0, w, h);- ctx.globalCompositeOperation = "destination-in";- const sides = ctx.createLinearGradient(0, 0, w, 0);- sides.addColorStop(0, "rgba(0,0,0,0)");- sides.addColorStop(0.08, "rgba(0,0,0,1)");- sides.addColorStop(0.92, "rgba(0,0,0,1)");- sides.addColorStop(1, "rgba(0,0,0,0)");- ctx.fillStyle = sides;- ctx.fillRect(0, 0, w, h);- });- washCache = new MeshBasicMaterial({ color: "#ffffff", map, transparent: true, opacity: map ? 0.3 : 0, blending: AdditiveBlending, depthWrite: false });- }- return washCache;-}--const WALL_MAT = {- cap: matte(AGENTS_SCENE.tambour.cap, { roughness: 0.55 }),- strip: new MeshStandardMaterial({ color: AGENTS_SCENE.light.glow, emissive: AGENTS_SCENE.light.glow, emissiveIntensity: 1.4, toneMapped: false }),-};--/**- * A studio's name wall, centred on its front face: a pale-oak tambour panel- * under a cap in the studio's colour with a warm light strip, a felt kick- * band in the same colour, and the name in ink letters on the west half.- */-function StudioWall({ label, caption, width, nameX, position, rug }: {- label: string; caption: string; width: number; nameX: number; position: [number, number, number]; rug: AgentsRug;-}) {- const kit = rugKit(rug);- const plateW = Math.min(3.0, width / 2 - 0.5);- const plateH = (plateW * LETTERS.h) / LETTERS.w;- const accent = rug.border;- const letters = useMemo(() => letterMaterial(label, caption, accent), [label, caption, accent]);- useEffect(() => () => { letters.map?.dispose(); letters.dispose(); }, [letters]);- return (- <group position={position}>- <Box size={[width, WALL_H, 0.1]} position={[0, WALL_H / 2, -0.02]} material={WALL_MAT.cap} />- <mesh position={[0, WALL_H / 2 + 0.04, 0.031]} material={tambourMaterial(width - 0.06)} receiveShadow>- <planeGeometry args={[width - 0.06, WALL_H - 0.16]} />- </mesh>- <Box size={[width - 0.06, 0.12, 0.02]} position={[0, 0.08, 0.04]} material={kit.felt} cast={false} />- {/* The cap wears the studio's colour, so a team reads from across the campus. */}- <Box size={[width + 0.04, 0.09, 0.16]} position={[0, WALL_H + 0.045, 0]} material={kit.border} />- {/* The light strip tucked under the cap, washing down the flutes. */}- <Box size={[width - 0.2, 0.012, 0.02]} position={[0, WALL_H - 0.012, 0.06]} material={WALL_MAT.strip} cast={false} />- <mesh position={[0, WALL_H - 0.42, 0.035]} material={washMaterial()}>- <planeGeometry args={[width - 0.1, 0.8]} />- </mesh>- <mesh position={[nameX, 1.3, 0.04]} material={letters}>- <planeGeometry args={[plateW, plateH]} />- </mesh>- </group>- );-}--/** One team studio's ground and name wall: a bordered, rounded rug in the studio's colour and the tambour wall. */-export function AgentsDepartment({ dept }: { dept: Department }) {- const t = useT();- const rug = agentsRug(dept.tint);- const kit = rugKit(rug);- const w = dept.maxX - dept.minX, d = dept.maxZ - dept.minZ;- const cx = (dept.minX + dept.maxX) / 2, cz = (dept.minZ + dept.maxZ) / 2;- const shapes = useMemo(() => ({- border: roundedRect(w - 0.1, d - 0.1, 0.4),- line: roundedRect(w - 0.36, d - 0.36, 0.28),- field: roundedRect(w - 0.44, d - 0.44, 0.24),- }), [w, d]);- // The pool has no team name: the wall says what it is.- const pool = dept.teamId === null || dept.teamId === undefined;- return (- <group>- <mesh position={[cx, 0.005, cz]} rotation={[-Math.PI / 2, 0, 0]} material={kit.border} receiveShadow>- <shapeGeometry args={[shapes.border, 6]} />- </mesh>- <mesh position={[cx, 0.006, cz]} rotation={[-Math.PI / 2, 0, 0]} material={kit.line} receiveShadow>- <shapeGeometry args={[shapes.line, 6]} />- </mesh>- <mesh position={[cx, 0.007, cz]} rotation={[-Math.PI / 2, 0, 0]} material={kit.field} receiveShadow>- <shapeGeometry args={[shapes.field, 6]} />- </mesh>- <StudioWall label={dept.label || t("society.office.studio_pool")}- caption={t(pool ? "society.office.studio_sign_pool" : "society.office.studio_sign_team")}- width={w - 0.4} nameX={studioWallParts(dept).nameX - cx} position={[cx, 0, dept.minZ + 0.1]} rug={rug} />- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/BreakLounge.tsx b/dodaios/ui/web/frontend/src/components/society/office/BreakLounge.tsxdeleted file mode 100644index 8862101123..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/BreakLounge.tsx+++ /dev/null@@ -1,1006 +0,0 @@-/**- * The break room as a cosy startup lounge (it stands on both floors): an L of- * oatmeal bouclé sofa modules with plump cushions and knitted throws round a- * solid-oak coffee table laid with magazines, a board game and a chess game;- * a large kilim rug; a reading nook with a sage armchair and a linen floor- * lamp by the dog's basket; a bookcase wall with sage-backed bays, books and- * objects under warm shelf lights; a foosball table; beanbags; a- * filtered-water station; monsteras in woven baskets; a pixel mat in front- * of the arcade; globe pendants over the table, a "take five" neon over the- * coffee bar and a small gallery of prints on the west wall.- *- * Same rules as OfficeProps: every furniture piece is built in local space- * centred on the origin, front facing +z, inside its `FURNITURE_SIZE` box.- * Repeated parts (books, leaves, foosball men, chess pieces) are merged into- * one geometry per material, and canvas faces are drawn once and shared.- */-import { memo } from "react";-import { useT } from "@/i18n";-import {- BoxGeometry, BufferGeometry, CylinderGeometry, DoubleSide, Euler, Matrix4, MeshBasicMaterial, MeshStandardMaterial, Quaternion,- SphereGeometry, Vector3,-} from "three";-import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";-import { cachedCanvasTexture, canvasMaterial } from "./canvasMaterials";-import { Box, GEO, matte, Rounded } from "./OfficeFurniture";-import { FURNITURE_SIZE, type Furniture, type FurnitureKind, type Room } from "./officeLayout";--type Vec3 = [number, number, number];--// ----------------------------------------------------------------------------// Materials: light Scandinavian oak, oatmeal bouclé, sage, linen, brass,-// with terracotta and mustard accents.-// -----------------------------------------------------------------------------const C = {- oak: "#d6b98f",- oakLight: "#e2c9a2",- oakDark: "#a88660",- boucle: "#e3d9c8",- boucleShade: "#cfc3ae",- sage: "#93a58a",- sageDeep: "#6f8468",- linen: "#efe7d8",- terracotta: "#c0714f",- mustard: "#d4a24c",- charcoal: "#34363a",- cream: "#f4eee3",- navy: "#2f3d56",- led: "#ffdcae",-} as const;--const BM = {- oak: matte(C.oak, { roughness: 0.6 }),- oakLight: matte(C.oakLight, { roughness: 0.6 }),- oakDark: matte(C.oakDark, { roughness: 0.65 }),- boucle: matte(C.boucle, { roughness: 1 }),- boucleShade: matte(C.boucleShade, { roughness: 1 }),- sage: matte(C.sage, { roughness: 0.95 }),- sagePaint: matte(C.sageDeep, { roughness: 0.8 }),- linen: matte(C.linen, { roughness: 1 }),- terracotta: matte(C.terracotta, { roughness: 0.95 }),- mustard: matte(C.mustard, { roughness: 0.95 }),- charcoal: matte(C.charcoal, { roughness: 0.7 }),- cream: matte(C.cream, { roughness: 0.45 }),- navy: matte(C.navy, { roughness: 0.7 }),- brass: matte("#b08d5c", { roughness: 0.35, metalness: 0.6 }),- chrome: matte("#d5d8dc", { roughness: 0.25, metalness: 0.7 }),- black: matte("#1d1e21", { roughness: 0.5 }),- marble: matte("#ece9e4", { roughness: 0.3 }),- soil: matte("#3b2f26"),- stem: matte("#58703f", { roughness: 0.8 }),- leaves: ["#3d7444", "#2c5a35", "#5a9654"].map((c) => matte(c, { flatShading: true, roughness: 0.7 })),- beanbags: [C.sage, C.mustard, C.terracotta].map((c) => matte(c, { roughness: 1 })),- books: ["#c0714f", "#e9dcc4", "#51705c", "#2f3d56", "#d4a24c", "#8b6246", "#7c8fa8", "#b9c7b0"].map((c) => matte(c, { roughness: 0.8 })),- // Lit from within, so they read as light in any scene lighting.- led: new MeshStandardMaterial({ color: C.led, emissive: C.led, emissiveIntensity: 1.2, toneMapped: false }),- bulb: new MeshStandardMaterial({ color: "#fff4e0", emissive: "#ffe6c2", emissiveIntensity: 1.1, roughness: 0.3, toneMapped: false }),- shade: new MeshStandardMaterial({ color: "#f3ead9", emissive: "#ffdcae", emissiveIntensity: 0.35, roughness: 0.9, side: DoubleSide }),- glass: new MeshStandardMaterial({ color: "#e4f1f4", transparent: true, opacity: 0.35, roughness: 0.05, depthWrite: false }),- water: new MeshStandardMaterial({ color: "#a9d6e6", transparent: true, opacity: 0.6, roughness: 0.1, depthWrite: false }),- acrylic: new MeshStandardMaterial({ color: "#ffffff", transparent: true, opacity: 0.12, roughness: 0.05, depthWrite: false }),- pixelGlow: new MeshStandardMaterial({ color: "#c77dff", emissive: "#c77dff", emissiveIntensity: 1.1, toneMapped: false }),-};--// ----------------------------------------------------------------------------// Canvas faces-// -----------------------------------------------------------------------------type Ctx = CanvasRenderingContext2D;--/** Deterministic pseudo-random numbers, so drawn patterns and book runs never change between loads. */-function lcg(seed: number): () => number {- let state = seed >>> 0;- return () => {- state = (state * 1664525 + 1013904223) >>> 0;- return state / 0x1_0000_0000;- };-}--/** A hand-woven kilim: cream field, stepped diamonds in sage, terracotta and mustard, charcoal borders, fringed ends. */-function drawKilim(ctx: Ctx, w: number, h: number): void {- const rand = lcg(2024);- ctx.fillStyle = "#efe4d0";- ctx.fillRect(0, 0, w, h);- for (let i = 0; i < 9000; i += 1) {- ctx.fillStyle = rand() > 0.5 ? "rgba(255,255,255,0.14)" : "rgba(110,80,50,0.07)";- ctx.fillRect(rand() * w, rand() * h, 3, 2);- }- const fringe = 26;- // Fringe along the short ends.- ctx.strokeStyle = "#e6dac4";- ctx.lineWidth = 3;- for (let x = 4; x < w; x += 9) {- ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x + (rand() - 0.5) * 4, fringe); ctx.stroke();- ctx.beginPath(); ctx.moveTo(x, h); ctx.lineTo(x + (rand() - 0.5) * 4, h - fringe); ctx.stroke();- }- const x0 = 0, y0 = fringe, x1 = w, y1 = h - fringe;- // Border bands: charcoal, terracotta with a zigzag, charcoal.- ctx.fillStyle = C.charcoal;- ctx.fillRect(x0, y0, x1 - x0, y1 - y0);- ctx.fillStyle = C.terracotta;- ctx.fillRect(x0 + 14, y0 + 14, x1 - x0 - 28, y1 - y0 - 28);- ctx.fillStyle = "#efe4d0";- ctx.fillRect(x0 + 56, y0 + 56, x1 - x0 - 112, y1 - y0 - 112);- ctx.strokeStyle = "#efe4d0";- ctx.lineWidth = 6;- const zig = (ax: number, ay: number, bx: number, by: number) => {- const horizontal = ay === by;- const len = horizontal ? bx - ax : by - ay;- ctx.beginPath();- for (let s = 0; s <= len; s += 20) {- const off = (s / 20) % 2 === 0 ? -8 : 8;- if (horizontal) ctx.lineTo(ax + s, ay + off); else ctx.lineTo(ax + off, ay + s);- }- ctx.stroke();- };- zig(x0 + 40, y0 + 35, x1 - 40, y0 + 35);- zig(x0 + 40, y1 - 35, x1 - 40, y1 - 35);- zig(x0 + 35, y0 + 40, x0 + 35, y1 - 40);- zig(x1 - 35, y0 + 40, x1 - 35, y1 - 40);- // Field: a row of stepped diamonds, small crosses between them.- const fx0 = x0 + 80, fx1 = x1 - 80, fy0 = y0 + 80, fy1 = y1 - 80;- const cy = (fy0 + fy1) / 2;- const count = 3;- const pitch = (fx1 - fx0) / count;- const tones = [C.sageDeep, C.terracotta, C.mustard];- const diamond = (cx: number, r: number, colour: string) => {- const step = r / 5;- ctx.fillStyle = colour;- for (let i = 0; i < 5; i += 1) {- const half = r - i * step;- ctx.fillRect(cx - half, cy - (i + 1) * step * 1.3, half * 2, step * 1.3);- ctx.fillRect(cx - half, cy + i * step * 1.3, half * 2, step * 1.3);- }- };- for (let i = 0; i < count; i += 1) {- const cx = fx0 + pitch * (i + 0.5);- const r = Math.min(pitch * 0.42, (fy1 - fy0) * 0.36);- diamond(cx, r, C.charcoal);- diamond(cx, r * 0.78, tones[i]);- diamond(cx, r * 0.42, "#efe4d0");- diamond(cx, r * 0.2, tones[(i + 1) % 3]);- }- ctx.fillStyle = C.sageDeep;- for (let i = 0; i <= count; i += 1) {- const cx = fx0 + pitch * i;- for (const y of [fy0 + 40, fy1 - 40]) {- ctx.fillRect(cx - 18, y - 5, 36, 10);- ctx.fillRect(cx - 5, y - 18, 10, 36);- }- }- ctx.fillStyle = C.terracotta;- for (let i = 0; i < count; i += 1) {- const cx = fx0 + pitch * (i + 0.5);- for (const y of [fy0 + 30, fy1 - 30]) ctx.fillRect(cx - 40, y - 4, 80, 8);- }-}--/** A dark game mat of pixel invaders and stars in front of the arcade. */-function drawPixelMat(ctx: Ctx, w: number, h: number, player: string): void {- const rand = lcg(77);- ctx.fillStyle = "#16142a";- ctx.fillRect(0, 0, w, h);- for (let i = 0; i < 70; i += 1) {- ctx.fillStyle = rand() > 0.5 ? "rgba(255,255,255,0.5)" : "rgba(199,125,255,0.5)";- ctx.fillRect(Math.floor(rand() * w / 4) * 4, Math.floor(rand() * h / 4) * 4, 4, 4);- }- const invader = ["00100000100", "00010001000", "00111111100", "01101110110", "11111111111", "10111111101", "10100000101", "00011011000"];- const draw = (cx: number, cy: number, px: number, colour: string) => {- ctx.fillStyle = colour;- invader.forEach((row, r) => [...row].forEach((bit, c) => {- if (bit === "1") ctx.fillRect(cx + (c - 5.5) * px, cy + (r - 4) * px, px, px);- }));- };- draw(w * 0.28, h * 0.3, 9, "#ff5fa2");- draw(w * 0.72, h * 0.3, 9, "#4fd1c5");- draw(w * 0.5, h * 0.62, 12, "#ffd166");- ctx.strokeStyle = "#c77dff";- ctx.lineWidth = 8;- ctx.strokeRect(10, 10, w - 20, h - 20);- ctx.fillStyle = "#ffffff";- ctx.font = "700 30px ui-monospace, 'Cascadia Mono', monospace";- ctx.textAlign = "center";- ctx.fillText(player, w / 2, h - 34, w - 40);-}--/** Neon tubes on a transparent sheet: a soft halo under a bright core. */-function drawNeon(text: string, colour: string) {- return (ctx: Ctx, w: number, h: number) => {- ctx.clearRect(0, 0, w, h);- ctx.textAlign = "center";- ctx.textBaseline = "middle";- // Shrink the script until a longer translation still fits between the board's edges.- let px = 132;- ctx.font = `italic 600 ${px}px 'Segoe Script', 'Brush Script MT', 'Snell Roundhand', cursive`;- while (px > 48 && ctx.measureText(text).width > w * 0.86) {- px -= 6;- ctx.font = `italic 600 ${px}px 'Segoe Script', 'Brush Script MT', 'Snell Roundhand', cursive`;- }- ctx.lineJoin = "round";- ctx.shadowColor = colour;- ctx.shadowBlur = 44;- ctx.strokeStyle = colour;- ctx.lineWidth = 20;- ctx.strokeText(text, w / 2, h / 2 + 6);- ctx.shadowBlur = 14;- ctx.lineWidth = 12;- ctx.strokeText(text, w / 2, h / 2 + 6);- ctx.shadowBlur = 0;- ctx.strokeStyle = "#fff1f5";- ctx.lineWidth = 5;- ctx.strokeText(text, w / 2, h / 2 + 6);- };-}--/** Three prints for the gallery wall. */-function drawArches(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#f4eee3";- ctx.fillRect(0, 0, w, h);- const bands = [C.terracotta, C.mustard, C.sage, "#f4eee3"];- bands.forEach((colour, i) => {- ctx.fillStyle = colour;- const r = w * (0.38 - i * 0.09);- ctx.beginPath();- ctx.moveTo(w / 2 - r, h * 0.82);- ctx.arc(w / 2, h * 0.82, r, Math.PI, 0);- ctx.closePath();- ctx.fill();- });- ctx.fillStyle = C.navy;- ctx.fillRect(w * 0.1, h * 0.82, w * 0.8, 4);-}--function drawSunset(ctx: Ctx, w: number, h: number): void {- const grad = ctx.createLinearGradient(0, 0, 0, h);- grad.addColorStop(0, "#f3d9b8");- grad.addColorStop(1, "#e6a57e");- ctx.fillStyle = grad;- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "#fbe7c6";- ctx.beginPath(); ctx.arc(w * 0.5, h * 0.45, w * 0.2, 0, Math.PI * 2); ctx.fill();- ctx.fillStyle = C.sageDeep;- ctx.beginPath(); ctx.moveTo(0, h * 0.72); ctx.lineTo(w * 0.35, h * 0.52); ctx.lineTo(w * 0.62, h * 0.66); ctx.lineTo(w, h * 0.5); ctx.lineTo(w, h); ctx.lineTo(0, h); ctx.fill();- ctx.fillStyle = "#4d6149";- ctx.beginPath(); ctx.moveTo(0, h * 0.85); ctx.lineTo(w * 0.5, h * 0.7); ctx.lineTo(w, h * 0.82); ctx.lineTo(w, h); ctx.lineTo(0, h); ctx.fill();-}--function drawBotanical(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#efe9dc";- ctx.fillRect(0, 0, w, h);- ctx.strokeStyle = "#51705c";- ctx.fillStyle = "#6f8468";- ctx.lineWidth = 3;- ctx.beginPath(); ctx.moveTo(w / 2, h * 0.9); ctx.quadraticCurveTo(w * 0.45, h * 0.5, w / 2, h * 0.12); ctx.stroke();- for (let i = 0; i < 7; i += 1) {- const y = h * (0.8 - i * 0.1);- const side = i % 2 === 0 ? 1 : -1;- ctx.beginPath();- ctx.ellipse(w / 2 + side * w * 0.14, y, w * 0.15, h * 0.035, side * -0.5, 0, Math.PI * 2);- ctx.fill();- }-}--/** A clock face: cream dial, charcoal ticks, hands at ten past ten. */-function drawClock(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#f6f1e8";- ctx.beginPath(); ctx.arc(w / 2, h / 2, w / 2, 0, Math.PI * 2); ctx.fill();- ctx.strokeStyle = C.charcoal;- for (let i = 0; i < 12; i += 1) {- const a = (i / 12) * Math.PI * 2;- ctx.lineWidth = i % 3 === 0 ? 7 : 3;- ctx.beginPath();- ctx.moveTo(w / 2 + Math.sin(a) * w * 0.36, h / 2 - Math.cos(a) * h * 0.36);- ctx.lineTo(w / 2 + Math.sin(a) * w * 0.44, h / 2 - Math.cos(a) * h * 0.44);- ctx.stroke();- }- ctx.lineCap = "round";- ctx.lineWidth = 8;- ctx.beginPath(); ctx.moveTo(w / 2, h / 2); ctx.lineTo(w / 2 - w * 0.2, h / 2 - h * 0.12); ctx.stroke();- ctx.lineWidth = 5;- ctx.beginPath(); ctx.moveTo(w / 2, h / 2); ctx.lineTo(w / 2 + w * 0.3, h / 2 - h * 0.17); ctx.stroke();- ctx.fillStyle = C.terracotta;- ctx.beginPath(); ctx.arc(w / 2, h / 2, 7, 0, Math.PI * 2); ctx.fill();-}--/** A board game lid: a hex map in island colours under a title band. */-function drawGameLid(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#2b6f8f";- ctx.fillRect(0, 0, w, h);- const tiles = ["#d4a24c", "#5a9654", "#c0714f", "#e9dcc4", "#3d7444", "#8b6246"];- const r = 18;- for (let row = 0; row < 3; row += 1) {- for (let col = 0; col < 5; col += 1) {- const cx = 46 + col * r * 1.75 + (row % 2) * r * 0.88;- const cy = 64 + row * r * 1.5;- ctx.fillStyle = tiles[(row * 5 + col) % tiles.length];- ctx.beginPath();- for (let k = 0; k < 6; k += 1) {- const a = (k / 6) * Math.PI * 2 + Math.PI / 6;- ctx.lineTo(cx + Math.cos(a) * r, cy + Math.sin(a) * r);- }- ctx.closePath();- ctx.fill();- }- }- ctx.fillStyle = "#f4eee3";- ctx.fillRect(0, 0, w, 30);- ctx.fillStyle = C.navy;- ctx.font = "800 20px system-ui, sans-serif";- ctx.textAlign = "center";- ctx.fillText("SETTLERS", w / 2, 22);-}--/** Two magazine covers side by side: a big cover line over a photo block. */-function drawMagazines(ctx: Ctx, w: number, h: number): void {- const covers = [["#f4eee3", C.terracotta, "KINFOLK"], ["#dfe7da", C.navy, "WIRED"]] as const;- covers.forEach(([paper, ink, title], i) => {- const x = (i * w) / 2;- ctx.fillStyle = paper;- ctx.fillRect(x, 0, w / 2, h);- ctx.fillStyle = ink;- ctx.font = "800 26px Georgia, serif";- ctx.textAlign = "center";- ctx.fillText(title, x + w / 4, 34);- ctx.fillStyle = i === 0 ? C.sage : C.mustard;- ctx.fillRect(x + 16, 50, w / 2 - 32, h * 0.52);- ctx.fillStyle = "rgba(40,40,40,0.5)";- for (let l = 0; l < 3; l += 1) ctx.fillRect(x + 16, h - 50 + l * 12, w / 2 - 50 - l * 14, 5);- });-}--/** A chess board: eight by eight in oak tones with a walnut rim. */-function drawChess(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#6a4631";- ctx.fillRect(0, 0, w, h);- const pad = w * 0.06, cell = (w - pad * 2) / 8;- for (let r = 0; r < 8; r += 1) {- for (let c = 0; c < 8; c += 1) {- ctx.fillStyle = (r + c) % 2 === 0 ? "#efdcbc" : "#9c7650";- ctx.fillRect(pad + c * cell, pad + r * cell, cell, cell);- }- }-}--/** The foosball pitch: felt green with white lines. */-function drawPitch(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#3f7d4a";- ctx.fillRect(0, 0, w, h);- for (let x = 0; x < w; x += w / 8) {- ctx.fillStyle = "rgba(255,255,255,0.05)";- ctx.fillRect(x, 0, w / 16, h);- }- ctx.strokeStyle = "rgba(255,255,255,0.85)";- ctx.lineWidth = 4;- ctx.strokeRect(8, 8, w - 16, h - 16);- ctx.beginPath(); ctx.moveTo(w / 2, 8); ctx.lineTo(w / 2, h - 8); ctx.stroke();- ctx.beginPath(); ctx.arc(w / 2, h / 2, h * 0.18, 0, Math.PI * 2); ctx.stroke();- ctx.strokeRect(8, h * 0.28, w * 0.1, h * 0.44);- ctx.strokeRect(w - 8 - w * 0.1, h * 0.28, w * 0.1, h * 0.44);-}--/** A woven seagrass basket. */-function drawWeave(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#c9ab7c";- ctx.fillRect(0, 0, w, h);- for (let y = 0; y < h; y += 8) {- for (let x = 0; x < w; x += 12) {- ctx.fillStyle = ((x / 12 + y / 8) % 2) === 0 ? "rgba(90,60,30,0.22)" : "rgba(255,240,210,0.18)";- ctx.fillRect(x, y, 12, 6);- }- }-}--const faces = {- kilim: () => canvasMaterial("break:kilim", 1024, 832, drawKilim, { fallback: "#efe4d0", roughness: 1 }),- pixelMat: (player: string) => canvasMaterial(`break:pixel-mat:${player}`, 256, 280, (ctx, w, h) => drawPixelMat(ctx, w, h, player), { glow: 0.25, fallback: "#16142a", roughness: 1 }),- arches: () => canvasMaterial("break:print-arches", 160, 200, drawArches, { fallback: "#f4eee3", roughness: 0.8 }),- sunset: () => canvasMaterial("break:print-sunset", 240, 300, drawSunset, { fallback: "#f3d9b8", roughness: 0.8 }),- botanical: () => canvasMaterial("break:print-botanical", 160, 200, drawBotanical, { fallback: "#efe9dc", roughness: 0.8 }),- clock: () => canvasMaterial("break:clock", 128, 128, drawClock, { fallback: "#f6f1e8", roughness: 0.5 }),- gameLid: () => canvasMaterial("break:game-lid", 256, 160, drawGameLid, { fallback: "#2b6f8f", roughness: 0.7 }),- magazines: () => canvasMaterial("break:magazines", 256, 170, drawMagazines, { fallback: "#f4eee3", roughness: 0.7 }),- chess: () => canvasMaterial("break:chess", 128, 128, drawChess, { fallback: "#9c7650", roughness: 0.6 }),- pitch: () => canvasMaterial("break:pitch", 256, 136, drawPitch, { fallback: "#3f7d4a", roughness: 0.95 }),- weave: () => canvasMaterial("break:weave", 128, 64, drawWeave, { fallback: "#c9ab7c", roughness: 1 }),-};--/** The neon sign glows on its own and lets the wall show through between the tubes. */-const neonMaterials = new Map<string, MeshBasicMaterial>();-function neon(text: string): MeshBasicMaterial {- let neonMaterial = neonMaterials.get(text);- if (!neonMaterial) {- const map = cachedCanvasTexture(`break:neon:${text}`, 1024, 300, drawNeon(text, "#ff6f91"));- neonMaterial = map- ? new MeshBasicMaterial({ map, transparent: true, depthWrite: false, toneMapped: false })- : new MeshBasicMaterial({ color: "#ff6f91", transparent: true, opacity: 0, depthWrite: false });- neonMaterials.set(text, neonMaterial);- }- return neonMaterial;-}--// ----------------------------------------------------------------------------// Shared geometry-// -----------------------------------------------------------------------------const BGEO = {- cyl: new CylinderGeometry(1, 1, 1, 20),- sphere: new SphereGeometry(1, 24, 16),- basket: new CylinderGeometry(0.24, 0.2, 0.42, 28, 1, true),- lampShade: new CylinderGeometry(0.09, 0.11, 0.2, 24, 1, true),- globe: new SphereGeometry(0.13, 24, 16),- bag: new SphereGeometry(1, 28, 18),-};--function Cyl({ radius, height, position, material, rotation, cast = true }: {- radius: number; height: number; position: Vec3; material: MeshStandardMaterial; rotation?: Vec3; cast?: boolean;-}) {- return <mesh geometry={BGEO.cyl} material={material} position={position} rotation={rotation} scale={[radius, height, radius]} castShadow={cast} receiveShadow />;-}--function Panel({ size, position, material, rotation }: {- size: [number, number]; position: Vec3; material: MeshStandardMaterial | MeshBasicMaterial; rotation?: Vec3;-}) {- return <mesh position={position} rotation={rotation} material={material}><planeGeometry args={size} /></mesh>;-}--/** Merge parts into one geometry and free the parts. */-function merge(parts: BufferGeometry[]): BufferGeometry {- const merged = mergeGeometries(parts, false);- parts.forEach((p) => p.dispose());- return merged;-}--/** A box part placed at `at`, for merging. */-function boxPart(size: Vec3, at: Vec3, rotZ = 0): BufferGeometry {- const g = new BoxGeometry(size[0], size[1], size[2]);- if (rotZ) g.rotateZ(rotZ);- return g.translate(at[0], at[1], at[2]);-}--/**- * The bookcase's books, one merged geometry per spine colour: runs of upright- * books with a leaning one at the end, and a few flat stacks.- */-const BOOKCASE = { w: FURNITURE_SIZE.breakBookcase.w, bays: [-1.035, -0.345, 0.345, 1.035], bayW: 0.64, shelves: [0.64, 1.1, 1.56] };-const BOOK_GEOMETRIES: BufferGeometry[] = (() => {- const rand = lcg(31337);- const byTone: BufferGeometry[][] = BM.books.map(() => []);- const add = (size: Vec3, at: Vec3, rotZ = 0) => byTone[Math.floor(rand() * byTone.length)].push(boxPart(size, at, rotZ));- // Which part of each bay holds books, as [from, to] fractions of its width; the rest holds objects.- const runs: Record<string, [number, number]> = {- "0:0": [0, 1], "0:2": [0, 0.55], "0:3": [0.05, 0.95],- "1:0": [0.4, 1], "1:1": [0, 1], "1:3": [0, 0.6],- "2:1": [0.45, 1], "2:2": [0, 1],- };- BOOKCASE.shelves.forEach((y, level) => {- BOOKCASE.bays.forEach((bx, bay) => {- const run = runs[`${level}:${bay}`];- if (!run) return;- let x = bx - BOOKCASE.bayW / 2 + run[0] * BOOKCASE.bayW + 0.01;- const end = bx - BOOKCASE.bayW / 2 + run[1] * BOOKCASE.bayW - 0.01;- while (x < end - 0.06) {- const bw = 0.024 + rand() * 0.026;- const bh = 0.22 + rand() * 0.14;- const bd = 0.2 + rand() * 0.06;- add([bw, bh, bd], [x + bw / 2, y + bh / 2, 0.02]);- x += bw + 0.002;- }- // One book leaning on the run's end, where it fits.- const lh = 0.26;- if (x + 0.08 < end) add([0.03, lh, 0.22], [x + 0.04, y + (lh / 2) * Math.cos(0.3) + 0.004, 0.02], -0.3);- });- });- // Flat stacks on two shelves.- for (const [x, y] of [[0.53, 0.64], [1.23, 1.1]] as const) {- let top = y;- for (let i = 0; i < 4; i += 1) {- const t = 0.03 + rand() * 0.015;- add([0.2 - i * 0.015, t, 0.18 - i * 0.01], [x + (rand() - 0.5) * 0.02, top + t / 2, 0.03]);- top += t;- }- }- return byTone.map((parts) => merge(parts));-})();--/** A monstera's split leaves on arching stems, merged per leaf tone plus one stem geometry. */-const MONSTERA: { leaves: BufferGeometry[]; stems: BufferGeometry } = (() => {- const base = new SphereGeometry(1, 12, 8);- const tones: BufferGeometry[][] = [[], [], []];- const stems: BufferGeometry[] = [];- const matrix = new Matrix4(), rotation = new Quaternion(), euler = new Euler(0, 0, 0, "YXZ");- const at = new Vector3(), scale = new Vector3();- const count = 13;- for (let i = 0; i < count; i += 1) {- const t = i / (count - 1);- const angle = i * 2.39996;- const tip = 0.95 + (1 - Math.abs(t - 0.45)) * 0.75;- const reach = 0.04 + 0.05 * Math.sin(Math.PI * t);- const half = 0.15 - 0.03 * Math.abs(t - 0.5);- // Stem: a thin cylinder from the soil to under the leaf.- const stem = new CylinderGeometry(0.008, 0.011, 1, 6);- const dx = Math.sin(angle) * reach, dz = Math.cos(angle) * reach;- const length = Math.hypot(dx, tip - 0.5, dz);- matrix.lookAt(new Vector3(0, 0, 0), new Vector3(dx, tip - 0.5, dz), new Vector3(0, 0, 1));- stem.rotateX(Math.PI / 2);- stem.scale(1, 1, length);- stem.applyMatrix4(new Matrix4().extractRotation(matrix));- stem.translate(dx / 2, 0.5 + (tip - 0.5) / 2, dz / 2);- stems.push(stem);- // Leaf: a broad flattened ellipsoid tipping outward and down.- const droop = 0.35 + 0.35 * (1 - t);- at.set(dx + Math.sin(angle) * half * 0.5, tip + 0.02, dz + Math.cos(angle) * half * 0.5);- euler.set(droop, angle, ((i % 3) - 1) * 0.25);- rotation.setFromEuler(euler);- scale.set(half * 0.85, 0.012, half);- matrix.compose(at, rotation, scale);- tones[i % 3].push(base.clone().applyMatrix4(matrix));- }- base.dispose();- return { leaves: tones.map((parts) => merge(parts)), stems: merge(stems) };-})();--/** Foosball: which team each of the eight rods belongs to and how many men it carries (goalie to goalie). */-const FOOS_RODS: readonly [team: 0 | 1, men: number][] = [[0, 1], [0, 2], [1, 3], [0, 5], [1, 5], [0, 3], [1, 2], [1, 1]];-const FOOS = { pitchY: 0.52, rodY: 0.6, pitch: 0.13, halfZ: 0.25 };-const FOOS_GEOMETRIES: { men: BufferGeometry[]; rods: BufferGeometry; handles: BufferGeometry } = (() => {- const men: BufferGeometry[][] = [[], []];- const rods: BufferGeometry[] = [];- const handles: BufferGeometry[] = [];- FOOS_RODS.forEach(([team, count], i) => {- const x = -((FOOS_RODS.length - 1) * FOOS.pitch) / 2 + i * FOOS.pitch;- // Team 0 works its rods from the +z side, team 1 from the -z side.- const side = team === 0 ? 1 : -1;- rods.push(new CylinderGeometry(0.007, 0.007, 0.86, 8).rotateX(Math.PI / 2).translate(x, FOOS.rodY, side * 0.06));- handles.push(new CylinderGeometry(0.017, 0.017, 0.1, 12).rotateX(Math.PI / 2).translate(x, FOOS.rodY, side * 0.46));- for (let m = 0; m < count; m += 1) {- const z = -FOOS.halfZ + ((m + 0.5) * FOOS.halfZ * 2) / count;- men[team].push(new BoxGeometry(0.022, 0.07, 0.032).translate(x, FOOS.rodY - 0.03, z));- men[team].push(new SphereGeometry(0.017, 10, 8).translate(x, FOOS.rodY + 0.022, z));- }- });- return { men: men.map((parts) => merge(parts)), rods: merge(rods), handles: merge(handles) };-})();--/** Chess pieces mid-game, merged per side: a base disc, a body and a head. */-const CHESS_GEOMETRIES: BufferGeometry[] = (() => {- const cell = 0.3 * 0.88 / 8;- const origin = -0.3 * 0.44 + cell / 2;- const squares: [number, number, number, boolean][] = [- // [file, rank, height, tall]- [0, 0, 0.034, false], [4, 0, 0.05, true], [5, 1, 0.026, false], [6, 1, 0.026, false], [2, 2, 0.04, false], [4, 3, 0.026, false], [3, 0, 0.046, true],- [0, 7, 0.034, false], [4, 7, 0.05, true], [3, 6, 0.026, false], [5, 5, 0.04, false], [6, 6, 0.026, false], [4, 4, 0.026, false], [7, 7, 0.034, false],- ];- const sides: BufferGeometry[][] = [[], []];- squares.forEach(([file, rank, height, tall], i) => {- const x = origin + file * cell, z = origin + rank * cell;- const side = i < 7 ? 0 : 1;- sides[side].push(new CylinderGeometry(0.011, 0.013, 0.006, 12).translate(x, 0.003, z));- sides[side].push(new CylinderGeometry(tall ? 0.006 : 0.007, 0.01, height, 12).translate(x, height / 2, z));- sides[side].push(new SphereGeometry(tall ? 0.009 : 0.008, 10, 8).translate(x, height + 0.004, z));- });- return sides.map((parts) => merge(parts));-})();--// ----------------------------------------------------------------------------// Furniture-// -----------------------------------------------------------------------------/**- * The sofa modules' open end, by furniture id: +1 = the +x end, -1 = the -x end.- * The two long modules meet the corner module there, so that end has no arm.- */-const SOFA_OPEN_END: Record<string, 1 | -1> = { "break-sofa-a": 1, "break-sofa-b": -1 };--/** Seat cushion top: the couch seat height figures sit at. */-const SEAT_TOP = 0.56;--/** An accent pillow, leaning back against the back cushions. */-function Pillow({ position, material, rotationY = 0, tilt = -0.28 }: { position: Vec3; material: MeshStandardMaterial; rotationY?: number; tilt?: number }) {- return (- <group position={position} rotation={[tilt, rotationY, 0]}>- <Rounded size={[0.38, 0.34, 0.11]} radius={0.05} position={[0, 0, 0]} material={material} />- </group>- );-}--/**- * A long bouclé sofa module facing +z: a recessed oak plinth, a deep base,- * two seat and two back cushions, an arm on the closed end, accent pillows- * and — on the module with an arm facing the room — a sage throw over it.- */-function SofaModule({ id }: { id: string }) {- const open = SOFA_OPEN_END[id] ?? 1;- const armX = -open * 1.01;- const seatCentre = open * 0.09;- return (- <group>- <Box size={[2.1, 0.07, 0.78]} position={[0, 0.035, 0]} material={BM.oakDark} />- <Rounded size={[2.2, 0.28, 0.9]} radius={0.05} position={[0, 0.21, 0]} material={BM.boucleShade} />- <Rounded size={[2.2, 0.38, 0.2]} radius={0.06} position={[0, 0.53, -0.35]} material={BM.boucleShade} />- <Rounded size={[0.18, 0.36, 0.9]} radius={0.07} position={[armX, 0.52, 0]} material={BM.boucleShade} />- {[-0.5, 0.5].map((dx) => (- <group key={dx}>- <Rounded size={[0.98, 0.2, 0.68]} radius={0.07} position={[seatCentre + dx, SEAT_TOP - 0.1, 0.1]} material={BM.boucle} />- <group position={[seatCentre + dx, 0.66, -0.23]} rotation={[-0.12, 0, 0]}>- <Rounded size={[0.96, 0.36, 0.2]} radius={0.09} position={[0, 0, 0]} material={BM.boucle} />- </group>- </group>- ))}- <Pillow position={[seatCentre - 0.72, 0.67, -0.1]} material={BM.terracotta} rotationY={0.18} />- <Pillow position={[seatCentre + 0.2, 0.66, -0.1]} material={BM.mustard} rotationY={-0.1} />- {/* The knitted throw over the arm: the top fold and the drape down the outside. */}- <Box size={[0.2, 0.014, 0.52]} position={[armX, 0.707, 0.05]} material={BM.sage} />- <Box size={[0.014, 0.34, 0.52]} position={[armX - open * 0.093, 0.54, 0.05]} material={BM.sage} />- </group>- );-}--/** The sectional's corner module: backs along -z and +x, open towards -x and +z, a throw folded on the seat. */-function SofaCorner() {- return (- <group>- <Box size={[0.8, 0.07, 0.8]} position={[0, 0.035, 0]} material={BM.oakDark} />- <Rounded size={[0.9, 0.28, 0.9]} radius={0.05} position={[0, 0.21, 0]} material={BM.boucleShade} />- <Rounded size={[0.9, 0.38, 0.2]} radius={0.06} position={[0, 0.53, -0.35]} material={BM.boucleShade} />- <Rounded size={[0.2, 0.38, 0.9]} radius={0.06} position={[0.35, 0.53, 0]} material={BM.boucleShade} />- <Rounded size={[0.68, 0.2, 0.68]} radius={0.07} position={[-0.1, SEAT_TOP - 0.1, 0.1]} material={BM.boucle} />- <group position={[-0.1, 0.66, -0.23]} rotation={[-0.12, 0, 0]}>- <Rounded size={[0.66, 0.36, 0.2]} radius={0.09} position={[0, 0, 0]} material={BM.boucle} />- </group>- <group position={[0.23, 0.66, 0.1]} rotation={[0, 0, 0.12]}>- <Rounded size={[0.2, 0.36, 0.66]} radius={0.09} position={[0, 0, 0]} material={BM.boucle} />- </group>- <Pillow position={[0.05, 0.67, -0.05]} material={BM.sage} rotationY={-Math.PI / 4} tilt={-0.2} />- {/* A folded throw in terracotta on the seat. */}- <Rounded size={[0.42, 0.06, 0.3]} radius={0.02} position={[-0.18, SEAT_TOP + 0.03, 0.22]} material={BM.terracotta} />- <Box size={[0.42, 0.004, 0.02]} position={[-0.18, SEAT_TOP + 0.061, 0.3]} material={BM.cream} cast={false} />- </group>- );-}--/**- * Solid-oak coffee table on chunky legs with a lower shelf of magazines. On- * top: a chess game in progress, a board game box on a second one, fanned- * magazines, a mug and a small succulent bowl.- */-function BreakTable() {- return (- <group>- {[-0.56, 0.56].flatMap((x) => [-0.29, 0.29].map((z) => (- <Box key={`${x}:${z}`} size={[0.07, 0.34, 0.07]} position={[x, 0.17, z]} material={BM.oak} />- )))}- <Box size={[1.18, 0.025, 0.6]} position={[0, 0.11, 0]} material={BM.oakLight} />- <Rounded size={[1.3, 0.06, 0.75]} radius={0.025} position={[0, 0.37, 0]} material={BM.oak} />- {/* Magazines on the shelf. */}- <Box size={[0.3, 0.02, 0.22]} position={[-0.3, 0.132, 0.04]} material={BM.books[2]} cast={false} />- <Box size={[0.29, 0.02, 0.21]} position={[-0.29, 0.152, 0.04]} material={BM.books[1]} cast={false} />- <Box size={[0.26, 0.05, 0.26]} position={[0.3, 0.148, -0.04]} material={BM.navy} />- {/* The chess game. */}- <group position={[-0.32, 0.4, 0.02]}>- <Box size={[0.3, 0.014, 0.3]} position={[0, 0.007, 0]} material={faces.chess()} />- <group position={[0, 0.014, 0]}>- <mesh geometry={CHESS_GEOMETRIES[0]} material={BM.cream} castShadow />- <mesh geometry={CHESS_GEOMETRIES[1]} material={BM.black} castShadow />- </group>- </group>- {/* Board game boxes. */}- <Box size={[0.3, 0.05, 0.2]} position={[0.3, 0.425, -0.14]} material={BM.terracotta} />- <group position={[0.3, 0.4725, -0.14]} rotation={[0, 0.12, 0]}>- <Box size={[0.26, 0.045, 0.17]} position={[0, 0, 0]} material={BM.navy} />- <Panel size={[0.26, 0.17]} position={[0, 0.0231, 0]} rotation={[-Math.PI / 2, 0, 0]} material={faces.gameLid()} />- </group>- {/* Fanned magazines, a mug and a succulent. */}- <group position={[0.22, 0.401, 0.16]} rotation={[0, -0.25, 0]}>- <Panel size={[0.34, 0.225]} position={[0, 0.002, 0]} rotation={[-Math.PI / 2, 0, 0]} material={faces.magazines()} />- </group>- <Cyl radius={0.04} height={0.08} position={[0.5, 0.44, 0.08]} material={BM.cream} />- <Box size={[0.012, 0.04, 0.012]} position={[0.545, 0.44, 0.08]} material={BM.cream} cast={false} />- <Cyl radius={0.06} height={0.04} position={[0.02, 0.42, -0.24]} material={BM.terracotta} />- {[[-0.02, 0, -0.24], [0.04, 0, -0.22], [0.01, 0, -0.28]].map(([x, , z], i) => (- <mesh key={i} geometry={GEO.blob} material={BM.leaves[i]} position={[x, 0.45, z]} scale={[0.025, 0.02, 0.025]} castShadow />- ))}- </group>- );-}--/** The kilim rug, sized per instance. */-function BreakRug({ w, d }: { w: number; d: number }) {- return <Box size={[w, 0.014, d]} position={[0, 0.007, 0]} material={faces.kilim()} cast={false} />;-}--/** The pixel game mat in front of the arcade, with a violet glow strip along its edge. */-function ArcadeMat({ w, d }: { w: number; d: number }) {- const t = useT();- return (- <group>- <Box size={[w, 0.012, d]} position={[0, 0.006, 0]} material={faces.pixelMat(t("society.office.break_player_one"))} cast={false} />- <Box size={[0.02, 0.006, d - 0.04]} position={[-w / 2 + 0.03, 0.015, 0]} material={BM.pixelGlow} cast={false} />- </group>- );-}--/**- * The bookcase wall: an oak carcass with sage-painted back panels, four bays- * over a cabinet with sage doors and brass pulls, warm light strips under the- * shelves, runs of books and objects — vases, a trailing pothos, a framed- * photo, stacked board games, a little brass trophy.- */-function BreakBookcase() {- const w = BOOKCASE.w;- return (- <group>- {/* Carcass: back, ends, top, cabinet top and shelves, bay dividers. */}- <Box size={[w - 0.04, 1.98, 0.015]} position={[0, 1.0, -0.185]} material={BM.sagePaint} cast={false} />- {[-w / 2 + 0.015, w / 2 - 0.015].map((x) => <Box key={x} size={[0.03, 2.03, 0.38]} position={[x, 1.015, 0]} material={BM.oak} />)}- <Box size={[w, 0.035, 0.4]} position={[0, 2.0125, 0]} material={BM.oak} />- <Box size={[w - 0.06, 0.03, 0.38]} position={[0, 0.625, 0]} material={BM.oak} />- {BOOKCASE.shelves.slice(1).map((y) => <Box key={y} size={[w - 0.06, 0.025, 0.36]} position={[0, y - 0.0125, 0]} material={BM.oak} />)}- {[-0.69, 0, 0.69].map((x) => <Box key={x} size={[0.025, 1.36, 0.36]} position={[x, 1.315, 0]} material={BM.oak} />)}- {/* Cabinet: body, four sage doors with brass pulls, a recessed kick plinth. */}- <Box size={[w - 0.06, 0.52, 0.34]} position={[0, 0.35, -0.01]} material={BM.oakLight} />- <Box size={[w - 0.06, 0.08, 0.3]} position={[0, 0.04, -0.03]} material={BM.oakDark} />- {BOOKCASE.bays.map((x) => (- <group key={x}>- <Box size={[0.64, 0.5, 0.014]} position={[x, 0.35, 0.167]} material={BM.sage} />- <Box size={[0.12, 0.014, 0.02]} position={[x, 0.54, 0.18]} material={BM.brass} cast={false} />- </group>- ))}- {/* Warm light strips under each shelf, at the front edge. */}- {[1.075, 1.535, 1.99].map((y) => (- <Box key={y} size={[w - 0.12, 0.006, 0.014]} position={[0, y - 0.005, 0.16]} material={BM.led} cast={false} />- ))}- {BOOK_GEOMETRIES.map((geometry, i) => <mesh key={i} geometry={geometry} material={BM.books[i]} castShadow receiveShadow />)}- {/* Bottom shelf: stacked board games in bay 1. */}- <Box size={[0.4, 0.07, 0.28]} position={[-0.345, 0.675, 0.01]} material={BM.navy} />- <Box size={[0.38, 0.06, 0.26]} position={[-0.34, 0.74, 0.01]} material={BM.terracotta} />- <Box size={[0.36, 0.08, 0.27]} position={[-0.35, 0.81, 0.01]} material={BM.mustard} />- <Box size={[0.3, 0.05, 0.22]} position={[-0.34, 0.875, 0.01]} material={BM.cream} />- {/* Middle shelf: a pothos in bay 0, a framed photo and a sculpture in bay 2. */}- <Cyl radius={0.065} height={0.12} position={[-1.2, 1.16, 0.02]} material={BM.cream} />- {[[-1.22, 1.25, 0.03, 0.09], [-1.15, 1.23, 0.07, 0.07], [-1.26, 1.2, 0.1, 0.06], [-1.18, 1.15, 0.13, 0.05]].map(([x, y, z, s], i) => (- <mesh key={i} geometry={GEO.blob} material={BM.leaves[i % 3]} position={[x, y, z]} scale={[s, s * 0.8, s]} castShadow />- ))}- <group position={[0.24, 1.1, -0.06]} rotation={[-0.1, 0.15, 0]}>- <Box size={[0.24, 0.3, 0.02]} position={[0, 0.15, 0]} material={BM.oakDark} />- <Panel size={[0.19, 0.25]} position={[0, 0.15, 0.0105]} material={faces.sunset()} />- </group>- <mesh geometry={BGEO.sphere} material={BM.cream} position={[0.5, 1.2, 0.02]} scale={[0.06, 0.06, 0.06]} castShadow />- <Cyl radius={0.03} height={0.04} position={[0.5, 1.12, 0.02]} material={BM.charcoal} />- {/* Top shelf: vases in bay 0, a brass trophy in bay 1, a trailing plant in bay 3. */}- <Cyl radius={0.05} height={0.24} position={[-1.2, 1.68, 0.02]} material={BM.sage} />- <Cyl radius={0.04} height={0.15} position={[-1.06, 1.635, 0.03]} material={BM.cream} />- <mesh geometry={BGEO.sphere} material={BM.terracotta} position={[-0.9, 1.61, 0.03]} scale={[0.05, 0.05, 0.05]} castShadow />- <Cyl radius={0.035} height={0.03} position={[-0.47, 1.575, 0.02]} material={BM.charcoal} />- <Cyl radius={0.008} height={0.08} position={[-0.47, 1.63, 0.02]} material={BM.brass} />- <mesh geometry={BGEO.sphere} material={BM.brass} position={[-0.47, 1.69, 0.02]} scale={[0.04, 0.035, 0.04]} castShadow />- <Cyl radius={0.07} height={0.1} position={[1.05, 1.61, 0.02]} material={BM.terracotta} />- {[[1.0, 1.68, 0.05, 0.08], [1.1, 1.66, 0.08, 0.07], [1.05, 1.56, 0.14, 0.05], [0.98, 1.46, 0.15, 0.045], [1.12, 1.5, 0.15, 0.045], [1.04, 1.36, 0.16, 0.04]]- .map(([x, y, z, s], i) => (- <mesh key={i} geometry={GEO.blob} material={BM.leaves[(i + 1) % 3]} position={[x, y, z]} scale={[s, s * 0.8, s * 0.6]} castShadow />- ))}- </group>- );-}--/**- * The reading nook: a sage bouclé tub armchair on oak legs with a terracotta- * lumbar pillow and an open book on the arm, and a linen-shaded floor lamp- * on a marble foot in the corner behind it.- */-const NOOK_CHAIR = { x: 0.08, z: 0.08 } as const;-function ReadingNook() {- return (- <group>- <group position={[NOOK_CHAIR.x, 0, NOOK_CHAIR.z]}>- {[-0.27, 0.27].flatMap((x) => [-0.26, 0.26].map((z) => (- <Cyl key={`${x}:${z}`} radius={0.018} height={0.22} position={[x, 0.11, z]} material={BM.oak} />- )))}- <Rounded size={[0.7, 0.2, 0.7]} radius={0.06} position={[0, 0.31, 0]} material={BM.sage} />- <Rounded size={[0.5, 0.15, 0.54]} radius={0.06} position={[0, SEAT_TOP - 0.075, 0.06]} material={BM.linen} />- <group position={[0, 0.62, -0.28]} rotation={[-0.14, 0, 0]}>- <Rounded size={[0.7, 0.48, 0.14]} radius={0.07} position={[0, 0, 0]} material={BM.sage} />- </group>- {[-0.295, 0.295].map((x) => <Rounded key={x} size={[0.11, 0.26, 0.66]} radius={0.05} position={[x, 0.5, 0]} material={BM.sage} />)}- <Pillow position={[0, 0.7, -0.17]} material={BM.terracotta} tilt={-0.22} />- <group position={[0.295, 0.636, 0.12]} rotation={[0, 0.3, 0]}>- <Box size={[0.16, 0.012, 0.11]} position={[0, 0, 0]} material={BM.cream} cast={false} />- <Box size={[0.004, 0.014, 0.11]} position={[0, 0.001, 0]} material={BM.navy} cast={false} />- </group>- </group>- {/* Floor lamp: marble foot, brass pole, linen drum shade lit from inside. */}- <group position={[-0.34, 0, -0.34]}>- <Cyl radius={0.09} height={0.03} position={[0, 0.015, 0]} material={BM.marble} />- <Cyl radius={0.01} height={1.42} position={[0, 0.74, 0]} material={BM.brass} />- <mesh geometry={BGEO.lampShade} material={BM.shade} position={[0, 1.52, 0]} castShadow />- <mesh geometry={BGEO.sphere} material={BM.bulb} position={[0, 1.48, 0]} scale={0.03} />- </group>- </group>- );-}--/** A pear-shaped beanbag with a dimpled seat, a raised back on the -z side and piping round its middle. */-function Beanbag({ id }: { id: string }) {- let hash = 0;- for (const ch of id) hash = (hash * 31 + ch.charCodeAt(0)) >>> 0;- const material = BM.beanbags[hash % BM.beanbags.length];- return (- <group>- <mesh geometry={BGEO.bag} material={material} position={[0, 0.22, 0.02]} scale={[0.43, 0.22, 0.42]} castShadow receiveShadow />- <mesh geometry={BGEO.bag} material={material} position={[0, 0.4, -0.18]} scale={[0.36, 0.2, 0.22]} castShadow receiveShadow />- <mesh geometry={BGEO.bag} material={material} position={[0, 0.33, 0.06]} scale={[0.3, 0.1, 0.28]} castShadow receiveShadow />- <mesh geometry={BGEO.cyl} material={BM.charcoal} position={[0, 0.2, 0.02]} scale={[0.425, 0.012, 0.415]} />- <Box size={[0.12, 0.03, 0.02]} position={[0, 0.5, -0.33]} material={BM.charcoal} cast={false} />- </group>- );-}--/**- * Filtered-water station: an oak-clad cabinet, a dispensing niche with- * chrome taps over a drip tray, a glass bottle on a ceramic collar and a- * paper-cup tube on the side.- */-function WaterStation() {- return (- <group>- <Rounded size={[0.34, 0.86, 0.34]} radius={0.03} position={[0, 0.43, 0]} material={BM.oakLight} />- <Box size={[0.26, 0.26, 0.02]} position={[0, 0.68, 0.162]} material={BM.charcoal} cast={false} />- <Box size={[0.22, 0.015, 0.08]} position={[0, 0.56, 0.2]} material={BM.chrome} />- <Cyl radius={0.014} height={0.05} position={[-0.05, 0.77, 0.19]} material={BM.chrome} />- <Cyl radius={0.014} height={0.05} position={[0.05, 0.77, 0.19]} material={BM.chrome} />- <Cyl radius={0.016} height={0.012} position={[-0.05, 0.8, 0.19]} material={BM.navy} cast={false} />- <Cyl radius={0.016} height={0.012} position={[0.05, 0.8, 0.19]} material={BM.terracotta} cast={false} />- <Box size={[0.26, 0.012, 0.02]} position={[0, 0.2, 0.171]} material={BM.brass} cast={false} />- <Cyl radius={0.13} height={0.04} position={[0, 0.88, 0]} material={BM.cream} />- <Cyl radius={0.05} height={0.04} position={[0, 0.915, 0]} material={BM.glass} cast={false} />- <Cyl radius={0.15} height={0.3} position={[0, 1.085, 0]} material={BM.glass} cast={false} />- <Cyl radius={0.14} height={0.24} position={[0, 1.06, 0]} material={BM.water} cast={false} />- <Cyl radius={0.13} height={0.03} position={[0, 1.25, 0]} material={BM.glass} cast={false} />- <Cyl radius={0.032} height={0.3} position={[0.2, 0.6, 0.06]} material={BM.cream} />- <Cyl radius={0.028} height={0.03} position={[0.2, 0.44, 0.06]} material={BM.chrome} cast={false} />- </group>- );-}--/**- * Foosball table, long side along x: an oak cabinet on four legs, the green- * pitch with its lines, eight chrome rods with black handles, terracotta men- * against navy men, a ball and bead score counters.- */-function Foosball() {- const y = FOOS.pitchY;- return (- <group>- {[-0.52, 0.52].flatMap((x) => [-0.25, 0.25].map((z) => (- <Box key={`${x}:${z}`} size={[0.07, y - 0.06, 0.07]} position={[x, (y - 0.06) / 2, z]} material={BM.oakDark} />- )))}- <Box size={[1.0, 0.03, 0.04]} position={[0, 0.14, -0.25]} material={BM.oakDark} />- <Box size={[1.0, 0.03, 0.04]} position={[0, 0.14, 0.25]} material={BM.oakDark} />- <Box size={[1.2, 0.05, 0.66]} position={[0, y - 0.035, 0]} material={BM.oak} />- <Panel size={[1.12, 0.58]} position={[0, y - 0.008, 0]} rotation={[-Math.PI / 2, 0, 0]} material={faces.pitch()} />- {[-0.31, 0.31].map((z) => <Box key={z} size={[1.2, 0.18, 0.04]} position={[0, y + 0.07, z]} material={BM.oak} />)}- {[-0.58, 0.58].map((x) => (- <group key={x}>- <Box size={[0.04, 0.18, 0.58]} position={[x, y + 0.07, 0]} material={BM.oak} />- <Box size={[0.012, 0.06, 0.18]} position={[x * 0.97, y + 0.03, 0]} material={BM.black} cast={false} />- </group>- ))}- <mesh geometry={FOOS_GEOMETRIES.rods} material={BM.chrome} castShadow />- <mesh geometry={FOOS_GEOMETRIES.handles} material={BM.black} castShadow />- <mesh geometry={FOOS_GEOMETRIES.men[0]} material={BM.terracotta} castShadow />- <mesh geometry={FOOS_GEOMETRIES.men[1]} material={BM.navy} castShadow />- <mesh geometry={BGEO.sphere} material={BM.cream} position={[0.07, y + 0.012, 0.05]} scale={0.014} castShadow />- {/* Bead score counters on the rails. */}- {[-1, 1].map((s) => (- <group key={s} position={[s * 0.5, y + 0.165, s * 0.31]}>- <Cyl radius={0.003} height={0.14} position={[0, 0, 0]} rotation={[0, 0, Math.PI / 2]} material={BM.chrome} cast={false} />- {[0, 1, 2].map((i) => <mesh key={i} geometry={BGEO.sphere} material={s < 0 ? BM.terracotta : BM.navy} position={[-0.05 + i * 0.022, 0, 0]} scale={0.009} />)}- </group>- ))}- </group>- );-}--/** A monstera in a woven seagrass basket. */-function BreakPlant() {- return (- <group>- <mesh geometry={BGEO.basket} material={faces.weave()} position={[0, 0.21, 0]} castShadow receiveShadow />- <Cyl radius={0.2} height={0.02} position={[0, 0.01, 0]} material={BM.oakDark} />- <Cyl radius={0.225} height={0.012} position={[0, 0.39, 0]} material={BM.soil} cast={false} />- <Box size={[0.5, 0.02, 0.02]} position={[0, 0.41, 0]} material={BM.oakDark} cast={false} />- <mesh geometry={MONSTERA.stems} material={BM.stem} castShadow />- {MONSTERA.leaves.map((geometry, i) => <mesh key={i} geometry={geometry} material={BM.leaves[i]} castShadow receiveShadow />)}- </group>- );-}--/** Renderers of the break room's furniture kinds; merged into OfficeProps' exhaustive table. */-export const BREAK_RENDERERS = {- breakSofa: ({ item }: { item: Furniture }) => <SofaModule id={item.id} />,- breakSofaCorner: () => <SofaCorner />,- breakTable: () => <BreakTable />,- breakRug: ({ item }: { item: Furniture }) => {- const size = item.size ?? FURNITURE_SIZE.breakRug;- return <BreakRug w={size.w} d={size.d} />;- },- arcadeMat: ({ item }: { item: Furniture }) => {- const size = item.size ?? FURNITURE_SIZE.arcadeMat;- return <ArcadeMat w={size.w} d={size.d} />;- },- breakBookcase: () => <BreakBookcase />,- readingNook: () => <ReadingNook />,- foosball: () => <Foosball />,- breakPlant: () => <BreakPlant />,- beanbag: ({ item }: { item: Furniture }) => <Beanbag id={item.id} />,- waterCooler: () => <WaterStation />,-} satisfies Partial<Record<FurnitureKind, (props: { item: Furniture }) => JSX.Element>>;--// ----------------------------------------------------------------------------// Room fittings: what hangs rather than stands-// -----------------------------------------------------------------------------/** A globe pendant on a long cord: brass canopy cap, opal glass lit from within. */-function GlobePendant({ position }: { position: Vec3 }) {- return (- <group position={position}>- <Box size={[0.006, 0.6, 0.006]} position={[0, 0.44, 0]} material={BM.black} cast={false} />- <Cyl radius={0.035} height={0.05} position={[0, 0.14, 0]} material={BM.brass} cast={false} />- <mesh geometry={BGEO.globe} material={BM.bulb} />- </group>- );-}--/**- * The lounge's hanging and wall-mounted pieces: two globe pendants over the- * coffee table with one warm light, the "take five" neon on a sage board over- * the coffee bar, a gallery of prints and a clock- * on the west wall.- */-export const BreakLoungeFittings = memo(function BreakLoungeFittings({ room, furniture }: { room: Room; furniture: readonly Furniture[] }) {- const table = furniture.find((f) => f.kind === "breakTable");- const bar = furniture.find((f) => f.kind === "coffeeBar" && f.room === "break");- const wallX = room.minX + 0.075;- const t = useT();- // The gallery and the clock hang either side of the west door, wherever a floor's break room has it.- const westDoor = room.doors.find((door) => door.side === "west");- const galleryZ = westDoor ? westDoor.at + westDoor.width / 2 + 0.55 : room.minZ + 5.55;- const clockZ = westDoor ? westDoor.at - westDoor.width / 2 - 0.65 : room.minZ + 2.35;- return (- <group>- {table && (- <group position={[table.x, 0, table.z]}>- <GlobePendant position={[-0.38, 1.82, 0]} />- <GlobePendant position={[0.38, 1.72, 0]} />- <pointLight position={[0, 1.55, 0]} color="#ffd9ad" intensity={5} distance={5.5} decay={2} />- </group>- )}- {bar && (- <group position={[bar.x, 0, room.minZ + 0.085]}>- <Box size={[1.5, 0.5, 0.03]} position={[0, 1.6, 0]} material={BM.oak} />- <Box size={[1.44, 0.44, 0.006]} position={[0, 1.6, 0.016]} material={BM.sagePaint} cast={false} />- <Box size={[1.36, 0.4, 0.01]} position={[0, 1.6, 0.03]} material={BM.acrylic} cast={false} />- <Panel size={[1.36, 0.4]} position={[0, 1.6, 0.036]} material={neon(t("society.office.break_neon"))} />- </group>- )}- {/* West wall: a gallery of three prints south of the door, a clock north of it. */}- <group position={[wallX, 0, 0]} rotation={[0, Math.PI / 2, 0]}>- {([- [galleryZ, 1.42, 0.36, 0.45, faces.arches()],- [galleryZ + 0.7, 1.3, 0.56, 0.7, faces.sunset()],- [galleryZ + 1.4, 1.48, 0.36, 0.45, faces.botanical()],- ] as const).map(([z, y, fw, fh, face]) => (- <group key={z} position={[-z, y, 0]}>- <Box size={[fw + 0.05, fh + 0.05, 0.025]} position={[0, 0, 0]} material={BM.oak} />- <Box size={[fw - 0.01, fh - 0.01, 0.004]} position={[0, 0, 0.013]} material={BM.cream} cast={false} />- <Panel size={[fw - 0.08, fh - 0.08]} position={[0, 0, 0.0155]} material={face} />- </group>- ))}- <group position={[-clockZ, 1.55, 0]}>- <Cyl radius={0.17} height={0.03} position={[0, 0, 0]} rotation={[Math.PI / 2, 0, 0]} material={BM.oak} />- <mesh position={[0, 0, 0.0155]} material={faces.clock()}><circleGeometry args={[0.15, 32]} /></mesh>- </group>- </group>- </group>- );-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/BuildingShell.tsx b/dodaios/ui/web/frontend/src/components/society/office/BuildingShell.tsxdeleted file mode 100644index 6c3ed5dda7..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/BuildingShell.tsx+++ /dev/null@@ -1,131 +0,0 @@-/**- * What makes the agents floor (and the Level Hall above it) a floor of a- * 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.- *- * Purely visual and out of reach: everything stands on or beyond the slab's- * edge, outside the walkable floor. Nothing here casts a shadow.- */-import { useMemo, useRef } from "react";-import { useFrame } from "@react-three/fiber";-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";-import type { SkyPad } from "./skyPad";--/** 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;-/** 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;--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 }),-};--type Side = "north" | "south" | "west" | "east";--/**- * One side's window wall, in its own frame: it runs along +x, the floor lies towards +z. An `opening` (a range of- * x) is a doorway the full height of the glass: sill and glass stop at its jambs, the head runs on over it.- */-function WindowWall({ length, opening }: { length: number; opening?: readonly [number, number] }) {- const mullions = useMemo<Placement[]>(() => {- const count = Math.max(2, Math.round(length / FACADE.pitch) + 1);- const at = Array.from({ length: count }, (_, i) => -length / 2 + (length * i) / (count - 1))- .filter((x) => !opening || x < opening[0] - 0.3 || x > opening[1] + 0.3);- if (opening) at.push(opening[0], opening[1]);- return at.map((x) => ({ position: [x, FACADE.h / 2, 0] as [number, number, number], scale: [0.07, FACADE.h, 0.12] as [number, number, number] }));- }, [length, opening]);- // The runs of sill and glass: the whole length, or the two stretches either side of the doorway.- const runs: [number, number][] = opening ? [[-length / 2, opening[0]], [opening[1], length / 2]] : [[-length / 2, length / 2]];- return (- <group userData={{ windowWall: true }}>- {runs.map(([a, b]) => (- <group key={a}>- <Box size={[b - a, 0.22, 0.14]} position={[(a + b) / 2, 0.11, 0]} material={SHELL.steel} cast={false} />- <Box size={[b - a, FACADE.h - 0.5, 0.03]} position={[(a + b) / 2, 0.22 + (FACADE.h - 0.5) / 2, 0]} material={SHELL.glass} cast={false} />- </group>- ))}- <Box size={[length, 0.28, 0.2]} position={[0, FACADE.h - 0.14, 0]} material={SHELL.steel} cast={false} />- {/* The ceiling's edge: a pale band running into the floor from the head of the wall. */}- <Box size={[length, 0.1, FACADE.soffit]} position={[0, FACADE.h + 0.05, FACADE.soffit / 2 - 0.1]} material={SHELL.soffit} cast={false} />- <Instances geometry={GEO.box} material={SHELL.steel} items={mullions} cast={false} />- </group>- );-}--/**- * The floor's four edges. Each has a window wall and a balustrade; the wall- * shows on the sides the camera looks towards, the balustrade on the others.- */-function Edges({ bounds, skyPad }: { bounds: Rect; skyPad?: SkyPad }) {- const { minX, maxX, minZ, maxZ } = bounds;- const cx = (minX + maxX) / 2, cz = (minZ + maxZ) / 2, w = maxX - minX, d = maxZ - minZ;- const walls = useRef<Partial<Record<Side, Group | null>>>({});- const rails = useRef<Partial<Record<Side, Group | null>>>({});- // The home view looks from the south-east: north and west are the backdrop.- const shown = useRef<Record<Side, boolean>>({ north: true, west: true, south: false, east: false });- useFrame(({ camera }) => {- const dx = camera.position.x - cx, dz = camera.position.z - cz;- const next = shown.current;- if (Math.abs(dz) > SIDE_DEAD_BAND_M) { next.north = dz > 0; next.south = dz < 0; }- if (Math.abs(dx) > SIDE_DEAD_BAND_M) { next.west = dx > 0; next.east = dx < 0; }- for (const side of ["north", "south", "west", "east"] as const) {- const wall = walls.current[side], rail = rails.current[side];- if (wall) wall.visible = next[side];- if (rail) rail.visible = !next[side];- }- });- // The walls stand just inside the slab's edge and meet in its corners; the balustrade keeps its own line.- const inset = 0.12, rail = 0.2;- // A wall's frame: +x along the edge, +z into the floor.- const sides: { side: Side; position: [number, number, number]; rotationY: number; length: number; from: [number, number]; to: [number, number] }[] = [- { side: "north", position: [cx, 0, minZ + inset], rotationY: 0, length: w - inset * 2, from: [minX + rail, minZ + rail], to: [maxX - rail, minZ + rail] },- { side: "south", position: [cx, 0, maxZ - inset], rotationY: Math.PI, length: w - inset * 2, from: [maxX - rail, maxZ - rail], to: [minX + rail, maxZ - rail] },- { side: "west", position: [minX + inset, 0, cz], rotationY: Math.PI / 2, length: d - inset * 2, from: [minX + rail, maxZ - rail], to: [minX + rail, minZ + rail] },- { side: "east", position: [maxX - inset, 0, cz], rotationY: -Math.PI / 2, length: d - inset * 2, from: [maxX - rail, minZ + rail], to: [maxX - rail, maxZ - rail] },- ];- // The bridge to the sky pad leaves through the east side: a doorway in its wall (the east wall's +x is world +z)- // and a gap in its balustrade.- const gap = skyPad?.gap;- const eastOpening = useMemo(() => (gap ? [gap.minZ - cz, gap.maxZ - cz] as const : undefined), [gap, cz]);- return (- <group>- {sides.map(({ side, position, rotationY, length, from, to }) => (- <group key={side}>- <group ref={(g) => { walls.current[side] = g; }} position={position} rotation={[0, rotationY, 0]} visible={shown.current[side]}>- <WindowWall length={length} opening={side === "east" ? eastOpening : undefined} />- </group>- <group ref={(g) => { rails.current[side] = g; }} visible={!shown.current[side]}>- {side === "east" && gap- ? <>- <Railing from={from} to={[to[0], gap.minZ]} />- <Railing from={[from[0], gap.maxZ]} to={to} />- </>- : <Railing from={from} to={to} />}- </group>- </group>- ))}- </group>- );-}--export function BuildingShell({ layout, reduced = false }: { layout: OfficeLayout; reduced?: boolean }) {- return (- <group>- <SingularityCity bounds={layout.bounds} reduced={reduced} />- <Edges bounds={layout.bounds} skyPad={layout.skyPad} />- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/CampusFittings.tsx b/dodaios/ui/web/frontend/src/components/society/office/CampusFittings.tsxdeleted file mode 100644index 98fc5535c9..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/CampusFittings.tsx+++ /dev/null@@ -1,264 +0,0 @@-/**- * The agents floor's built fittings: what encloses and furnishes a team- * studio (low felt-and-glass screens, a storage cabinet, a sofa, a standing- * table) and what furnishes the commons (the atrium's step seating, the- * café's kitchen run and island, focus booths, large trees).- *- * Every piece is assembled from a handful of shapes, and every shape of one- * material is one instanced mesh for the whole floor: a campus of twelve- * furnished studios costs the same sixteen draw calls as an empty one. Each- * piece is built inside the box the plan (`layout.ambience`) gives it, which- * is also what navigation walks round; a studio's pieces wear its colour.- */-import { useMemo } from "react";-import { MeshStandardMaterial } from "three";-import {- BOOTH, CABINET, COUNTER, CRATE, HIGH_TABLE, ISLAND, SCREEN, SOFA, STEPS, ownSize, stepsSeats, yawOf, type AgentsAmbienceItem,-} from "./agentsAmbience";-import { agentsRug, AGENTS_RUGS } from "./AgentsFloorLook";-import { Instances, type Placement } from "./CodingFloorAmbience";-import { GEO, MAT, matte } from "./OfficeFurniture";--const FIT = {- oak: matte("#d9bf97", { roughness: 0.6 }),- oakDark: matte("#b89b74", { roughness: 0.65 }),- /** White, so each instance's colour is its felt, fabric or paint. */- tint: matte("#ffffff", { roughness: 0.95 }),- steel: matte("#23262b", { roughness: 0.45, metalness: 0.4 }),- stone: matte("#e4ddd1", { roughness: 0.6 }),- bark: matte("#6f5d4b", { roughness: 0.9 }),- glass: new MeshStandardMaterial({ color: "#d6ecff", transparent: true, opacity: 0.28, roughness: 0.08, depthWrite: false }),- glow: new MeshStandardMaterial({ color: "#fff0d8", emissive: "#fff0d8", emissiveIntensity: 1.5, toneMapped: false }),-};--/** Neutral tones for pieces that belong to no team, and the small things that stand on them. */-const NEUTRAL = { felt: "#cfc7ba", fabric: "#d6cfc2", paint: "#f3f1ec", linen: "#e9e1d2", sage: "#9fb094", ceramic: "#f2ece2" } as const;-const ACCENTS = ["#c07f63", "#8fa383", "#d2a650", "#7f93a8", "#d9c9ab"] as const;--function lcg(seed: number): () => number {- let state = seed >>> 0;- return () => {- state = (state * 1664525 + 1013904223) >>> 0;- return state / 0x1_0000_0000;- };-}--function seedOf(id: string): number {- let h = 2166136261;- for (let i = 0; i < id.length; i += 1) h = Math.imul(h ^ id.charCodeAt(i), 16777619);- return h >>> 0;-}--/** The shapes of the whole floor, sorted by the instanced mesh that draws them. */-export interface Parts {- oak: Placement[]; oakDark: Placement[]; tint: Placement[]; steel: Placement[]; stone: Placement[]; glass: Placement[]; glow: Placement[];- roundOak: Placement[]; roundSteel: Placement[]; roundTint: Placement[]; roundStone: Placement[]; pot: Placement[]; bark: Placement[];- leaf: Placement[]; leafDark: Placement[]; leafLight: Placement[];-}--/**- * Places a shape given in a piece's own frame (x along its front, z towards- * its front, origin on the floor under its middle) into the world.- */-function frameOf(item: AgentsAmbienceItem) {- const yaw = yawOf(item.facing), cos = Math.cos(yaw), sin = Math.sin(yaw);- const cx = (item.minX + item.maxX) / 2, cz = (item.minZ + item.maxZ) / 2;- return (lx: number, y: number, lz: number, sx: number, sy: number, sz: number, color?: string): Placement => ({- position: [cx + lx * cos + lz * sin, y, cz - lx * sin + lz * cos], scale: [sx, sy, sz], rotation: [0, yaw, 0], ...(color ? { color } : {}),- });-}--const feltOf = (item: AgentsAmbienceItem) => (item.tint === undefined ? NEUTRAL.felt : agentsRug(item.tint).felt);-const accentOf = (item: AgentsAmbienceItem) => (item.tint === undefined ? "#8e8a84" : agentsRug(item.tint).border);--/** A low screen: a felt panel in the studio's colour on a steel shoe, a band of glass above it and a slim steel cap. */-function buildScreen(item: AgentsAmbienceItem, p: Parts): void {- const dx = item.maxX - item.minX, dz = item.maxZ - item.minZ, alongX = dx > dz;- const cx = (item.minX + item.maxX) / 2, cz = (item.minZ + item.maxZ) / 2;- const felt = 0.92, glass = SCREEN.h - felt - 0.09;- p.steel.push({ position: [cx, 0.03, cz], scale: [dx + (alongX ? 0 : 0.02), 0.06, dz + (alongX ? 0.02 : 0)] });- p.tint.push({ position: [cx, 0.06 + felt / 2, cz], scale: [dx, felt, dz], color: feltOf(item) });- p.glass.push({ position: [cx, 0.06 + felt + glass / 2, cz], scale: alongX ? [dx, glass, 0.02] : [0.02, glass, dz] });- p.steel.push({ position: [cx, SCREEN.h - 0.015, cz], scale: alongX ? [dx, 0.03, 0.05] : [0.05, 0.03, dz] });-}--/** A storage cabinet: white fronts on a recessed plinth under an oak top, a line in the studio's colour, books and a plant on it. */-function buildCabinet(item: AgentsAmbienceItem, p: Parts): void {- const at = frameOf(item), { w, d } = CABINET;- p.oakDark.push(at(0, 0.03, 0, w - 0.06, 0.06, d - 0.06));- p.tint.push(at(0, 0.46, 0, w, 0.8, d - 0.02, NEUTRAL.paint));- p.oak.push(at(0, 0.8775, 0, w + 0.02, 0.035, d + 0.02));- p.tint.push(at(0, 0.78, d / 2 - 0.004, w - 0.1, 0.05, 0.012, accentOf(item)));- p.tint.push(at(-0.45, 0.92, 0, 0.3, 0.05, 0.22, ACCENTS[0]));- p.tint.push(at(-0.43, 0.97, 0, 0.26, 0.05, 0.2, ACCENTS[4]));- p.roundTint.push(at(0.5, 0.965, 0, 0.09, 0.14, 0.09, NEUTRAL.ceramic));- p.leafLight.push(at(0.5, 1.13, 0, 0.16, 0.14, 0.16));-}--/** A two-seat sofa on a recessed plinth: a deep base, two seat cushions, a back and two arms, in the studio's felt. */-function buildSofa(item: AgentsAmbienceItem, p: Parts): void {- const at = frameOf(item), { w, d } = SOFA;- const fabric = item.tint === undefined ? NEUTRAL.fabric : agentsRug(item.tint).felt;- p.oakDark.push(at(0, 0.06, 0, w - 0.12, 0.12, d - 0.14));- p.tint.push(at(0, 0.22, 0, w, 0.2, d, fabric));- for (const lx of [-0.44, 0.44]) p.tint.push(at(lx, 0.39, 0.08, w / 2 - 0.2, 0.14, d - 0.3, fabric));- p.tint.push(at(0, 0.57, -d / 2 + 0.11, w - 0.28, 0.42, 0.2, fabric));- for (const lx of [-(w / 2 - 0.07), w / 2 - 0.07]) p.tint.push(at(lx, 0.44, 0, 0.14, 0.32, d - 0.02, fabric));- p.tint.push(at(0.62, 0.58, -0.12, 0.32, 0.26, 0.1, ACCENTS[seedOf(item.id) % ACCENTS.length]));-}--/** A round standing table: an oak top on a steel stem, a cup left on it. */-function buildHighTable(item: AgentsAmbienceItem, p: Parts): void {- const x = (item.minX + item.maxX) / 2, z = (item.minZ + item.maxZ) / 2, { r, h } = HIGH_TABLE;- p.roundSteel.push({ position: [x, 0.015, z], scale: [0.24, 0.03, 0.24] });- p.roundSteel.push({ position: [x, (h - 0.04) / 2, z], scale: [0.03, h - 0.04, 0.03] });- p.roundOak.push({ position: [x, h - 0.02, z], scale: [r, 0.04, r] });- p.roundTint.push({ position: [x + 0.14, h + 0.045, z - 0.06], scale: [0.04, 0.09, 0.04], color: NEUTRAL.ceramic });-}--/** A focus booth: oak walls and roof round a felt back panel with a shelf and a light, a glass sidelight beside the doorway. */-function buildBooth(item: AgentsAmbienceItem, p: Parts): void {- const at = frameOf(item), { w, d, h, wall } = BOOTH;- const wallH = h - 0.04, wallY = 0.04 + wallH / 2;- p.oakDark.push(at(0, 0.02, 0, w, 0.04, d));- p.oak.push(at(0, wallY, -d / 2 + wall / 2, w, wallH, wall));- for (const lx of [-(w / 2 - wall / 2), w / 2 - wall / 2]) p.oak.push(at(lx, wallY, wall / 2, wall, wallH, d - wall));- p.oak.push(at(0, h - 0.04, 0, w, 0.08, d));- p.tint.push(at(0, 1.35, -d / 2 + wall + 0.01, w - 0.2, 1.3, 0.02, feltOf(item)));- p.oak.push(at(0, 1.02, -d / 2 + wall + 0.15, w - 0.24, 0.035, 0.3));- p.glow.push(at(0, h - 0.1, 0, w - 0.3, 0.02, 0.05));- p.glass.push(at(-(w / 2 - wall - 0.15), 0.04 + (h - 0.3) / 2, d / 2 - 0.02, 0.3, h - 0.3, 0.02));-}--/** The thickness of the steel cheeks that close the step seating's lowest tier. */-const CHEEK = 0.024;--/**- * Step seating, the atrium's own furniture. Each tier is a dark riser under a pale timber tread that noses out- * over it. The lowest tier is plainly a seat: a linen pad per place and a back cushion against the next riser.- * Higher up lie loose cushions in the studios' colours, as if the teams had left them there.- */-function buildSteps(item: AgentsAmbienceItem, p: Parts): void {- const at = frameOf(item), { w, d } = ownSize(item);- const tread = 0.05, nose = 0.035;- for (let k = 0; k < STEPS.tiers; k += 1) {- const top = STEPS.rise * (k + 1), front = d / 2 - STEPS.tier * k;- // The riser: the tier's body, set back a little under the tread and darker, so every step casts a line.- p.oakDark.push(at(0, (top - tread) / 2, front - STEPS.tier / 2 - 0.01, w - 0.04, top - tread, STEPS.tier - 0.02));- // The lowest tread ends between the steel cheeks: flush with them, the two end faces z-fight into a flickering band.- const treadW = k === 0 ? w - CHEEK * 2 : w;- p.oak.push(at(0, top - tread / 2, front - STEPS.tier / 2 + nose / 2, treadW, tread, STEPS.tier + nose));- }- // Steel cheeks close both ends.- for (const lx of [-w / 2 + CHEEK / 2, w / 2 - CHEEK / 2]) p.steel.push(at(lx, STEPS.rise / 2, d / 2 - STEPS.tier / 2, CHEEK, STEPS.rise, STEPS.tier));- const seats = stepsSeats(item).length, seatZ = d / 2 - STEPS.tier / 2;- for (let i = 0; i < seats; i += 1) {- const lx = (i - (seats - 1) / 2) * 0.9;- // A thin pad: a seated figure's height is the tread's.- p.tint.push(at(lx, STEPS.rise + 0.0125, seatZ + 0.06, 0.74, 0.025, 0.58, NEUTRAL.linen));- p.tint.push(at(lx, STEPS.rise + 0.2, seatZ - STEPS.tier / 2 + 0.07, 0.7, 0.3, 0.1, NEUTRAL.fabric));- }- const rand = lcg(seedOf(item.id));- const count = Math.max(3, Math.round(w / 1.3));- for (let i = 0; i < count; i += 1) {- const tier = 1 + (i % 2), top = STEPS.rise * (tier + 1);- const lx = -w / 2 + 0.5 + ((w - 1) * (i + rand() * 0.6)) / count;- p.tint.push(at(lx, top + 0.05, d / 2 - STEPS.tier * tier - STEPS.tier / 2 + (rand() - 0.5) * 0.2, 0.44, 0.1, 0.44,- AGENTS_RUGS[Math.floor(rand() * AGENTS_RUGS.length)].border));- }-}--/** Two moving crates, one on the other and a little askew, with dark handles and a label. */-function buildCrate(item: AgentsAmbienceItem, p: Parts): void {- const at = frameOf(item), { w, d, h } = CRATE;- const half = h / 2 - 0.01;- p.oak.push(at(0, half / 2, 0, w, half, d));- p.oak.push(at(0.06, half + 0.01 + half / 2, -0.03, w - 0.14, half, d - 0.08));- for (const y of [half / 2, half + 0.01 + half / 2]) p.oakDark.push(at(y < half ? 0 : 0.06, y, d / 2 - 0.02 - (y < half ? 0 : 0.07), 0.24, 0.05, 0.012));- p.tint.push(at(-0.2, half * 0.55, d / 2 + 0.002, 0.2, 0.13, 0.006, NEUTRAL.paint));-}--/** The café's kitchen run: white base units under a stone top, an oak back wall with two shelves of cups and jars, a coffee machine. */-function buildCounter(item: AgentsAmbienceItem, p: Parts): void {- const at = frameOf(item), { w, d } = ownSize(item);- const top = 0.92, back = -d / 2 + 0.025, shelfZ = -d / 2 + 0.18;- p.oakDark.push(at(0, 0.04, 0.02, w, 0.08, d - 0.12));- p.tint.push(at(0, 0.48, 0, w, 0.8, d - 0.04, NEUTRAL.paint));- p.stone.push(at(0, 0.9, 0, w + 0.02, 0.04, d + 0.02));- p.oak.push(at(0, top + (COUNTER.h - top) / 2, back, w, COUNTER.h - top, 0.05));- for (const y of [1.42, 1.78]) p.oak.push(at(0, y, shelfZ, w - 0.3, 0.035, 0.26));- p.glow.push(at(0, 1.75, shelfZ + 0.1, w - 0.4, 0.015, 0.03));- p.steel.push(at(-w / 4, top + 0.23, -0.05, 0.5, 0.46, 0.42));- for (let i = 0; i < 6; i += 1) p.roundTint.push(at(0.2 + i * 0.17, 1.42 + 0.0175 + 0.045, shelfZ, 0.04, 0.09, 0.04, NEUTRAL.ceramic));- for (let i = 0; i < 5; i += 1) p.roundTint.push(at(-w / 2 + 0.5 + i * 0.26, 1.78 + 0.0175 + 0.08, shelfZ, 0.06, 0.16, 0.06, ACCENTS[i % ACCENTS.length]));-}--/** The café's island: a sage base under an oak top that overhangs it, a bowl and a plant on it. */-function buildIsland(item: AgentsAmbienceItem, p: Parts): void {- const at = frameOf(item), { w, d, h } = ISLAND;- p.tint.push(at(0, (h - 0.05) / 2, 0, w - 0.3, h - 0.05, d - 0.24, NEUTRAL.sage));- p.oak.push(at(0, h - 0.025, 0, w, 0.05, d));- p.roundTint.push(at(-0.7, h + 0.03, 0, 0.17, 0.06, 0.17, NEUTRAL.ceramic));- p.roundTint.push(at(0.75, h + 0.07, 0.05, 0.08, 0.14, 0.08, ACCENTS[0]));- p.leaf.push(at(0.75, h + 0.24, 0.05, 0.17, 0.15, 0.17));-}--/** A large tree: a round stone planter, a tall trunk with two boughs and a full crown that spreads above head height. */-function buildTree(item: AgentsAmbienceItem, p: Parts): void {- const x = (item.minX + item.maxX) / 2, z = (item.minZ + item.maxZ) / 2, r = (item.maxX - item.minX) / 2;- const rand = lcg(seedOf(item.id));- p.pot.push({ position: [x, 0.35, z], scale: [r - 0.05, 0.7, r - 0.05] });- p.roundStone.push({ position: [x, 0.72, z], scale: [r - 0.02, 0.05, r - 0.02] });- p.bark.push({ position: [x, 1.85, z], scale: [0.09, 2.2, 0.09], rotation: [(rand() - 0.5) * 0.08, 0, (rand() - 0.5) * 0.08] });- p.bark.push({ position: [x - 0.3, 2.9, z + 0.1], scale: [0.05, 1.0, 0.05], rotation: [0.15, 0, 0.55] });- p.bark.push({ position: [x + 0.32, 3.0, z - 0.12], scale: [0.045, 1.1, 0.045], rotation: [-0.18, 0, -0.5] });- const crowns = [p.leaf, p.leafDark, p.leafLight];- // A crown of a few large clusters reads as one tree; many small ones only cost triangles.- for (let k = 0; k < 14; k += 1) {- const a = (k / 14) * Math.PI * 2 + rand() * 0.5, ring = 0.2 + rand() * 1.0;- const y = 3.45 + (rand() - 0.5) * 0.8 - ring * 0.35;- const s = 0.46 + rand() * 0.26;- crowns[Math.floor(rand() * 2.4)].push({ position: [x + Math.cos(a) * ring, y, z + Math.sin(a) * ring], scale: [s * 1.25, s * 0.85, s * 1.25] });- }-}--const BUILDERS: Partial<Record<AgentsAmbienceItem["kind"], (item: AgentsAmbienceItem, parts: Parts) => void>> = {- screen: buildScreen, cabinet: buildCabinet, sofa: buildSofa, hightable: buildHighTable,- booth: buildBooth, steps: buildSteps, counter: buildCounter, island: buildIsland, tree: buildTree, crate: buildCrate,-};--/** Every shape of the floor's fittings, sorted by the instanced mesh that draws it. */-export function fittingParts(items: readonly AgentsAmbienceItem[]): Parts {- const parts: Parts = {- oak: [], oakDark: [], tint: [], steel: [], stone: [], glass: [], glow: [],- roundOak: [], roundSteel: [], roundTint: [], roundStone: [], pot: [], bark: [], leaf: [], leafDark: [], leafLight: [],- };- for (const item of items) BUILDERS[item.kind]?.(item, parts);- return parts;-}--/** Every built fitting of the floor, drawn by sixteen instanced meshes. */-export function CampusFittings({ items }: { items: readonly AgentsAmbienceItem[] }) {- const p = useMemo(() => fittingParts(items), [items]);- return (- <group>- <Instances geometry={GEO.box} material={FIT.oak} items={p.oak} />- <Instances geometry={GEO.box} material={FIT.oakDark} items={p.oakDark} cast={false} />- <Instances geometry={GEO.box} material={FIT.tint} items={p.tint} />- <Instances geometry={GEO.box} material={FIT.steel} items={p.steel} />- <Instances geometry={GEO.box} material={FIT.stone} items={p.stone} />- <Instances geometry={GEO.box} material={FIT.glass} items={p.glass} cast={false} />- <Instances geometry={GEO.box} material={FIT.glow} items={p.glow} cast={false} />- <Instances geometry={GEO.cyl} material={FIT.oak} items={p.roundOak} />- <Instances geometry={GEO.cyl} material={FIT.steel} items={p.roundSteel} />- <Instances geometry={GEO.cyl} material={FIT.tint} items={p.roundTint} cast={false} />- <Instances geometry={GEO.cyl} material={FIT.stone} items={p.roundStone} />- <Instances geometry={GEO.potCyl} material={FIT.stone} items={p.pot} />- <Instances geometry={GEO.cyl} material={FIT.bark} items={p.bark} />- <Instances geometry={GEO.blob} material={MAT.leaf} items={p.leaf} />- <Instances geometry={GEO.blob} material={MAT.leafDark} items={p.leafDark} />- {/* Two of a crown's three tones throw its shadow. */}- <Instances geometry={GEO.blob} material={MAT.leafLight} items={p.leafLight} cast={false} />- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/CampusGround.tsx b/dodaios/ui/web/frontend/src/components/society/office/CampusGround.tsxdeleted file mode 100644index 574c7b9ce7..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/CampusGround.tsx+++ /dev/null@@ -1,234 +0,0 @@-/**- * The agents floor's ground between the studios, and the atrium's crown: the- * two boulevards paved in the limestone of the window band, the atrium's- * round inlay under the spawn point with a ring of light over it, the free- * plot taped out for the next team with its lettering on the floor, and a- * carpet of its own under every commons (moss in a garden court, slate felt- * under the focus booths, warm tiles in the café).- *- * The ring is a light fitting, not a glow: a steel band the size of the disc- * whose inner face is the lamp, hung on six rods from the ceiling line, each- * under its own small canopy.- *- * The ground is flat and takes no pointer events, so walking and clicking the- * floor work through it; the ring hangs above every head. Each surface is- * one mesh; all of it costs about twenty draw calls at any campus size.- */-import { useEffect, useMemo } from "react";-import { BackSide, CylinderGeometry, MeshStandardMaterial, RingGeometry, Shape } from "three";-import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";-import { useT } from "@/i18n";-import { AGENTS_SCENE, limestone } from "./AgentsFloorLook";-import { FACADE } from "./BuildingShell";-import { cachedCanvasTexture } from "./canvasMaterials";-import { Instances, type Placement } from "./CodingFloorAmbience";-import { GEO, matte } from "./OfficeFurniture";-import type { CampusZone, CampusZoneKind, OfficeLayout, Rect } from "./officeLayout";--/**- * Heights of the layers. The plank floor lies at 1 mm; whatever overlaps something else is at least a millimetre- * above it, which is what the depth buffer still tells apart from the far end of the zoom.- */-const Y = { paving: 0.003, moss: 0.003, field: 0.004, mark: 0.005 } as const;-/** The window band's width (see AgentsSlab): the main boulevard's paving runs out to it. */-const WINDOW_BAND = 1.35;-/** The atrium's disc lies between its two flights of step seating; the ring of light hangs over its rim. */-const ATRIUM_R = 4.2;-/** The ring: its top's height, the band's height and thickness, and how many rods carry it up to the ceiling line. */-const ATRIUM_RING = { y: 2.9, band: 0.11, rods: 6 } as const;-const RING_T = 0.03;-/** The band's steel: its outer face and its top edge. Its origin is the ring's middle at the height of its top. */-const RING_BODY = mergeGeometries([- new CylinderGeometry(ATRIUM_R, ATRIUM_R, ATRIUM_RING.band, 72, 1, true).translate(0, -ATRIUM_RING.band / 2, 0),- new RingGeometry(ATRIUM_R - RING_T, ATRIUM_R, 72).rotateX(-Math.PI / 2),-]);-/** The lamp: the band's inner face, seen from inside the ring. */-const RING_LAMP = new CylinderGeometry(ATRIUM_R - RING_T, ATRIUM_R - RING_T, ATRIUM_RING.band - 0.02, 72, 1, true).translate(0, -ATRIUM_RING.band / 2, 0);--/** The rods the ring hangs on, and the canopy at the head of each, round the ring's own middle. */-const RING_RODS: Placement[] = Array.from({ length: ATRIUM_RING.rods }, (_, i) => {- const a = ((i + 0.5) / ATRIUM_RING.rods) * Math.PI * 2, r = ATRIUM_R - RING_T / 2;- const x = Math.cos(a) * r, z = Math.sin(a) * r, drop = FACADE.h - ATRIUM_RING.y;- return [- { position: [x, ATRIUM_RING.y + drop / 2, z], scale: [0.016, drop, 0.016] },- { position: [x, FACADE.h - 0.012, z], scale: [0.12, 0.024, 0.12] },- ] satisfies Placement[];-}).flat();--const GROUND = {- inlay: matte(AGENTS_SCENE.stone.inlay, { roughness: 0.4, metalness: 0.45 }),- disc: matte("#f1ece3", { roughness: 0.5 }),- /** Floor marking tape. */- tape: matte("#e2bc62", { roughness: 0.75 }),- steel: matte("#23262b", { roughness: 0.45, metalness: 0.4 }),- /** Warm and tone-mapped: a lamp behind a diffuser, never a white line. */- lamp: new MeshStandardMaterial({ color: "#f3cf9c", emissive: "#ffbf78", emissiveIntensity: 0.85, roughness: 0.6, side: BackSide }),-};--/** A commons' carpet: a darker rim round a lighter field. The library lies on its own rug and the plain oak. */-const CARPETS: Partial<Record<CampusZoneKind, { edge: MeshStandardMaterial; field: MeshStandardMaterial }>> = {- garden: { edge: matte("#a9b795", { roughness: 1 }), field: matte("#c7d1b5", { roughness: 1 }) },- booths: { edge: matte("#9aa5b1", { roughness: 1 }), field: matte("#c3cbd3", { roughness: 1 }) },- cafe: { edge: matte("#c9ad8c", { roughness: 0.7 }), field: matte("#eadfcd", { roughness: 0.7 }) },-};--/** A flat rounded rectangle in the XY plane, laid on the floor by its mesh's rotation. */-function roundedRect(w: number, d: number, r: number): Shape {- const x = -w / 2, y = -d / 2;- const shape = new Shape();- shape.moveTo(x + r, y);- shape.lineTo(x + w - r, y);- shape.quadraticCurveTo(x + w, y, x + w, y + r);- shape.lineTo(x + w, y + d - r);- shape.quadraticCurveTo(x + w, y + d, x + w - r, y + d);- shape.lineTo(x + r, y + d);- shape.quadraticCurveTo(x, y + d, x, y + d - r);- shape.lineTo(x, y + r);- shape.quadraticCurveTo(x, y, x + r, y);- return shape;-}--const centre = (r: Rect): [number, number] => [(r.minX + r.maxX) / 2, (r.minZ + r.maxZ) / 2];--/** One paved street: limestone at the stone's own scale, whatever the street's size. */-function Paving({ rect }: { rect: Rect }) {- const w = rect.maxX - rect.minX, d = rect.maxZ - rect.minZ;- const material = useMemo(() => limestone(w, d), [w, d]);- useEffect(() => () => { material.map?.dispose(); material.dispose(); }, [material]);- const [x, z] = centre(rect);- return (- <mesh position={[x, Y.paving, z]} rotation={[-Math.PI / 2, 0, 0]} material={material} receiveShadow>- <planeGeometry args={[w, d]} />- </mesh>- );-}--/** The carpet of a commons: a darker rim round a lighter field. */-function Carpet({ zone, edge, field }: { zone: CampusZone; edge: MeshStandardMaterial; field: MeshStandardMaterial }) {- const w = zone.maxX - zone.minX - 0.7, d = zone.maxZ - zone.minZ - 0.7;- const shapes = useMemo(() => ({ edge: roundedRect(w, d, 0.6), field: roundedRect(w - 0.3, d - 0.3, 0.5) }), [w, d]);- const [x, z] = centre(zone);- return (- <group>- <mesh position={[x, Y.moss, z]} rotation={[-Math.PI / 2, 0, 0]} material={edge} receiveShadow>- <shapeGeometry args={[shapes.edge, 6]} />- </mesh>- <mesh position={[x, Y.field, z]} rotation={[-Math.PI / 2, 0, 0]} material={field} receiveShadow>- <shapeGeometry args={[shapes.field, 6]} />- </mesh>- </group>- );-}--const PLOT_TEXT = { w: 1024, h: 320 } as const;-const plotTexts = new Map<string, MeshStandardMaterial>();-/** The plot's lettering, painted on the floor: what the place is for, and where a team is started. */-function plotText(title: string, hint: string): MeshStandardMaterial {- const key = `${title}\n${hint}`;- let material = plotTexts.get(key);- if (!material) {- const map = cachedCanvasTexture(`campus:plot:${key}`, PLOT_TEXT.w, PLOT_TEXT.h, (ctx, w, h) => {- ctx.clearRect(0, 0, w, h);- ctx.textAlign = "center";- ctx.textBaseline = "middle";- const fit = (text: string, px: number, weight: number, y: number, fill: string) => {- let size = px;- const font = (s: number) => `${weight} ${s}px Inter, system-ui, -apple-system, 'Segoe UI', sans-serif`;- ctx.font = font(size);- while (size > px * 0.5 && ctx.measureText(text).width > w - 48) { size -= 2; ctx.font = font(size); }- ctx.fillStyle = fill;- ctx.fillText(text, w / 2, y);- };- fit(title.toLocaleUpperCase(), 92, 700, 118, "#8a7350");- fit(hint, 56, 500, 232, "#9a8a70");- });- material = new MeshStandardMaterial({ color: "#ffffff", map, transparent: true, alphaTest: 0.25, roughness: 0.9, visible: !!map });- plotTexts.set(key, material);- }- return material;-}--/** Tape on the floor: the length of a dash, the gap to the next, a corner's legs and the tape's width. */-const TAPE = { dash: 0.55, gap: 0.4, corner: 0.9, w: 0.06 } as const;--/** The dashes of a taped outline w × d round the origin: solid corners, dashed runs between them. */-function tapeOutline(w: number, d: number): Placement[] {- const out: Placement[] = [];- const piece = (x: number, z: number, along: "x" | "z", length: number) => {- out.push({ position: [x, Y.mark, z], scale: along === "x" ? [length, 0.003, TAPE.w] : [TAPE.w, 0.003, length] });- };- const run = (length: number, place: (offset: number, len: number) => void) => {- const inner = length - TAPE.corner * 2;- const count = Math.max(1, Math.floor((inner - TAPE.gap) / (TAPE.dash + TAPE.gap)));- const dash = (inner - TAPE.gap * (count + 1)) / count;- place(-length / 2 + TAPE.corner / 2, TAPE.corner);- place(length / 2 - TAPE.corner / 2, TAPE.corner);- for (let i = 0; i < count; i += 1) place(-inner / 2 + TAPE.gap + dash / 2 + i * (dash + TAPE.gap), dash);- };- for (const z of [-d / 2, d / 2]) run(w, (offset, len) => piece(offset, z, "x", len));- for (const x of [-w / 2, w / 2]) run(d, (offset, len) => piece(x, offset, "z", len));- return out;-}--/**- * The free plot: the bare floor taped out like a site about to be moved into, with its lettering facing the- * lobby. The stand where a team is started, the crates and the plant are the plan's own pieces.- */-function Plot({ zone }: { zone: CampusZone }) {- const t = useT();- const w = zone.maxX - zone.minX - 0.5, d = zone.maxZ - zone.minZ - 0.5;- const [x, z] = centre(zone);- const tape = useMemo(() => tapeOutline(w, d), [w, d]);- const textW = Math.min(w - 1.2, 5.6), textH = (textW * PLOT_TEXT.h) / PLOT_TEXT.w;- return (- <group position={[x, 0, z]}>- <Instances geometry={GEO.box} material={GROUND.tape} items={tape} cast={false} />- <mesh position={[0, Y.mark, -0.4]} rotation={[-Math.PI / 2, 0, 0]} material={plotText(t("society.office.plot_free"), t("society.office.plot_hint"))}>- <planeGeometry args={[textW, textH]} />- </mesh>- </group>- );-}--export function CampusGround({ layout }: { layout: OfficeLayout }) {- const zones = layout.zones;- const paved = useMemo(() => {- const boulevard = zones?.find((z) => z.kind === "boulevard");- const plaza = zones?.find((z) => z.kind === "plaza");- if (!boulevard || !plaza) return null;- return {- // The boulevard's paving stops at the plaza on both sides: two surfaces never share a plane.- streets: [{ ...boulevard, maxZ: plaza.minZ }, { ...boulevard, minZ: plaza.maxZ }].filter((r) => r.maxZ - r.minZ > 0.01),- // The main boulevard's paving meets the stone band along both windows.- plaza: { ...plaza, minX: layout.bounds.minX + WINDOW_BAND, maxX: layout.bounds.maxX - WINDOW_BAND },- atrium: centre(plaza),- };- }, [zones, layout.bounds]);- if (!zones || !paved) return null;- const [ax, az] = paved.atrium;- return (- <group>- {paved.streets.map((rect) => <Paving key={rect.minZ} rect={rect} />)}- <Paving rect={paved.plaza} />- {/* The atrium: a pale disc inside a bronze ring, the spawn point in its middle. */}- <mesh position={[ax, Y.field, az]} rotation={[-Math.PI / 2, 0, 0]} material={GROUND.disc} receiveShadow>- <circleGeometry args={[ATRIUM_R, 64]} />- </mesh>- <mesh position={[ax, Y.mark, az]} rotation={[-Math.PI / 2, 0, 0]} material={GROUND.inlay} receiveShadow>- <ringGeometry args={[ATRIUM_R - 0.07, ATRIUM_R + 0.07, 64]} />- </mesh>- <mesh position={[ax, Y.mark, az]} rotation={[-Math.PI / 2, 0, 0]} material={GROUND.inlay} receiveShadow>- <ringGeometry args={[2.05, 2.11, 48]} />- </mesh>- {/* The atrium's crown: a steel band hung from the ceiling line, its inner face the lamp. */}- <mesh geometry={RING_BODY} material={GROUND.steel} position={[ax, ATRIUM_RING.y, az]} />- <mesh geometry={RING_LAMP} material={GROUND.lamp} position={[ax, ATRIUM_RING.y, az]} />- <group position={[ax, 0, az]}><Instances geometry={GEO.box} material={GROUND.steel} items={RING_RODS} cast={false} /></group>- {zones.map((zone) => {- if (zone.kind === "plot") return <Plot key={zone.id} zone={zone} />;- const carpet = CARPETS[zone.kind];- return carpet ? <Carpet key={zone.id} zone={zone} edge={carpet.edge} field={carpet.field} /> : null;- })}- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/CampusScene.test.tsx b/dodaios/ui/web/frontend/src/components/society/office/CampusScene.test.tsxdeleted file mode 100644index eb3affb1cc..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/CampusScene.test.tsx+++ /dev/null@@ -1,326 +0,0 @@-import { afterEach, describe, expect, it } from "vitest";-import { act, createRoot, extend, type ReconcilerRoot } from "@react-three/fiber";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import * as THREE from "three";-import { Box3, type InstancedMesh, type Mesh, type Object3D } from "three";-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 { SkyPadStructure } from "./SkyPadStructure";-import { StaticBatch } from "./StaticBatch";-import { ToyFigure } from "./ToyFigure";-import { loadProfile, playerLook } from "./playerProfile";-import { RoomFloors, RoomSign, RoomWalls } from "./OfficeRooms";--/** Just enough of a WebGLRenderer for R3F to mount a scene graph without a GPU. */-function fakeRenderer(canvas: HTMLCanvasElement) {- const noop = () => undefined;- return {- domElement: canvas,- render: noop, setSize: noop, setPixelRatio: noop, setAnimationLoop: noop, dispose: noop,- getPixelRatio: () => 1,- shadowMap: { enabled: false, type: 0, needsUpdate: false },- xr: { enabled: false, isPresenting: false, addEventListener: noop, removeEventListener: noop, setAnimationLoop: noop },- outputColorSpace: "srgb", toneMapping: 0, toneMappingExposure: 1,- info: { render: {}, memory: {} },- };-}--// <Canvas> registers the three namespace; a bare root must do it itself.-extend(THREE);--let root: ReconcilerRoot<HTMLCanvasElement> | null = null;--async function mount(element: JSX.Element): Promise<Object3D> {- const canvas = document.createElement("canvas");- const current = createRoot(canvas);- root = current;- current.configure({- // Test double: R3F only needs the renderer's shape here, nothing is drawn.- gl: fakeRenderer(canvas) as unknown as NonNullable<Parameters<typeof current.configure>[0]>["gl"],- frameloop: "never",- size: { width: 100, height: 100, top: 0, left: 0 },- });- let captured: Object3D | null = null;- await act(async () => {- current.render(- <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>- <group ref={(g) => { captured = g; }}>{element}</group>- </QueryClientProvider>,- );- });- if (!captured) throw new Error("the element did not mount");- return captured;-}--afterEach(() => {- root?.unmount();- root = null;-});--const staff = (count: number): OfficeAgentInput[] => Array.from({ length: count }, (_, i) => ({- agentId: `a${i + 1}`, name: `Agent ${i + 1}`, tier: i === 0 ? "lead" : "specialist", providerLabel: "Codex", state: "idle", createdMs: i,-}));-const teamsOf = (count: number, size: number): OfficeTeamInput[] => Array.from({ length: count }, (_, t) => ({- id: `team-${t}`, name: `Team ${t}`, createdMs: t, members: Array.from({ length: size }, (_, i) => `a${2 + t * size + i}`),-}));--/**- * What a frame costs: every visible mesh is a draw call (however many instances it holds), every one that casts a- * shadow a second one in the shadow pass, and its triangles are drawn in each.- */-function cost(node: Object3D): { meshes: number; casters: number; calls: number; triangles: number } {- let meshes = 0, casters = 0, triangles = 0;- node.traverseVisible((child) => {- const mesh = child as Mesh;- if (!mesh.isMesh) return;- const own = (mesh.geometry.index ? mesh.geometry.index.count : mesh.geometry.getAttribute("position").count) / 3- * ((mesh as unknown as InstancedMesh).isInstancedMesh ? (mesh as unknown as InstancedMesh).count : 1);- meshes += 1;- triangles += own;- if (mesh.castShadow) { casters += 1; triangles += own; }- });- return { meshes, casters, calls: meshes + casters, triangles: Math.round(triangles) };-}--const noClick = () => undefined;-const STATION_KINDS = new Set(["spawnTerminal", "spawnPad", "receptionDesk", "teamBoard", "dressingMirror", "coffeeBar", "elevator", "studioBoard", "teamStand"]);--/** The floor's static dressing, mounted the way the scene mounts it; the agents floor's furniture goes through the batch. */-function Dressing({ layout, batch = layout.variant === "agents" }: { layout: OfficeLayout; batch?: boolean }) {- const desks = layout.departments.flatMap((d) => d.desks);- const table = layout.furniture.find((f) => f.kind === "meetingTable");- const signs = layout.rooms.map((room) => <RoomSign key={room.id} room={room} label={room.kind} />);- const studios = layout.departments.map((dept) => <AgentsDepartment key={dept.id} dept={dept} />);- return (- <>- <AgentsSlab layout={layout} onFloorClick={noClick} />- <BuildingShell layout={layout} />- <AgentsFloorAmbience layout={layout} />- <CampusGround layout={layout} />- <RoomFloors rooms={layout.rooms} campus />- <RoomWalls walls={layout.walls} />- {desks.length > 0 && <DeskInstances desks={desks} agents={new Map()} zones={new Map(layout.departments.flatMap((d) => d.desks.map((desk) => [desk.id, d.tint] as const)))} />}- {desks.length > 0 && <DeskDressing desks={desks} departments={layout.departments} floor="agents" />}- {batch- ? <>- <StaticBatch signature={layout.furniture.map((f) => f.id).join()}>- {signs}{studios}- {layout.furniture.filter((f) => !STATION_KINDS.has(f.kind)).map((item) => <FurniturePiece key={item.id} item={item} />)}- {table && <MeetingChairs table={table} />}- </StaticBatch>- {layout.furniture.filter((f) => STATION_KINDS.has(f.kind)).map((item) => <FurniturePiece key={item.id} item={item} merged />)}- </>- : <>- {signs}{studios}- {layout.furniture.map((item) => <FurniturePiece key={item.id} item={item} />)}- {table && <MeetingChairs table={table} />}- </>}- </>- );-}--describe("campus scene", () => {- it("mounts the agents floor's dressing for 5, 15 and 40 people, and the Level Hall's, within its budget", async () => {- const floors: [string, OfficeLayout][] = [- ["5", buildOfficeLayout(staff(5))],- ["15", buildOfficeLayout(staff(15), { teams: teamsOf(3, 4) })],- ["40", buildOfficeLayout(staff(40), { teams: teamsOf(8, 4) })],- ["hall", buildHallLayout()],- ];- const costs: Record<string, ReturnType<typeof cost>> = {};- for (const [name, layout] of floors) {- const group = await mount(<Dressing layout={layout} />);- costs[name] = cost(group);- root?.unmount();- root = null;- }- // The whole static floor — slab, building, planting, fittings, rooms, studios, desks — in a few hundred draw- // calls, shadow pass included. (Without a GPU no texture exists; in a browser each textured material adds- // a merged mesh of its own, a few dozen on this floor.)- expect(costs["5"].calls).toBeLessThan(520);- expect(costs["15"].calls).toBeLessThan(540);- expect(costs["40"].calls).toBeLessThan(600);- // Studios, desks, fittings and trees are merged or instanced: eight teams cost little more than none.- expect(costs["40"].meshes - costs["5"].meshes).toBeLessThan(60);- // Triangles, both passes: what grows with the roster is the desks and their chairs.- expect(costs["5"].triangles).toBeLessThan(560_000);- expect(costs["15"].triangles).toBeLessThan(700_000);- expect(costs["40"].triangles).toBeLessThan(1_050_000);- expect(costs.hall.calls).toBeLessThan(costs["5"].calls);- });-- it("draws the furniture in a fraction of the calls it takes piece by piece", async () => {- const layout = buildOfficeLayout(staff(15), { teams: teamsOf(3, 4) });- const loose = cost(await mount(<Dressing layout={layout} batch={false} />));- root?.unmount();- const merged = cost(await mount(<Dressing layout={layout} />));- expect(merged.calls).toBeLessThan(loose.calls / 3);- // The same shapes: merging changes how they are drawn, not what is drawn.- expect(merged.triangles).toBeLessThanOrEqual(loose.triangles);- expect(merged.triangles).toBeGreaterThan(loose.triangles * 0.6);- });-- it("keeps the ground flat and inside the slab, and a studio's wall inside its studio", async () => {- const layout = buildOfficeLayout(staff(12), { teams: teamsOf(2, 3) });- const ground = await mount(<CampusGround layout={layout} />);- ground.updateMatrixWorld(true);- const box = new Box3().setFromObject(ground);- // Everything is either flat on the floor or the atrium's ring of light (band, lamp and rods) above every head.- let overhead = 0;- ground.traverse((child) => {- if (!(child as Mesh).isMesh) return;- const own = new Box3().setFromObject(child);- if (own.min.y > 2.6) { overhead += 1; expect(own.max.y).toBeLessThanOrEqual(3.4 + 1e-6); return; }- expect(own.min.y).toBeGreaterThan(0.001);- expect(own.max.y).toBeLessThan(0.02);- });- expect(overhead).toBe(3);- expect(box.min.x).toBeGreaterThanOrEqual(layout.bounds.minX);- expect(box.max.x).toBeLessThanOrEqual(layout.bounds.maxX);- expect(box.min.z).toBeGreaterThanOrEqual(layout.bounds.minZ);- expect(box.max.z).toBeLessThanOrEqual(layout.bounds.maxZ);- root?.unmount();- for (const dept of layout.departments) {- const studio = await mount(<AgentsDepartment dept={dept} />);- studio.updateMatrixWorld(true);- const own = new Box3().setFromObject(studio);- expect(own.min.x, dept.id).toBeGreaterThanOrEqual(dept.minX - 0.01);- expect(own.max.x, dept.id).toBeLessThanOrEqual(dept.maxX + 0.01);- expect(own.min.z, dept.id).toBeGreaterThanOrEqual(dept.minZ - 0.01);- expect(own.max.z, dept.id).toBeLessThanOrEqual(dept.maxZ + 0.01);- root?.unmount();- }- root = null;- });-- it("builds the building's edges on the slab's edge: a window wall and a balustrade per side, the far sides' walls shown", async () => {- const layout = buildOfficeLayout(staff(5));- const shell = await mount(<BuildingShell layout={layout} />);- shell.updateMatrixWorld(true);- const { minX, maxX, minZ, maxZ } = layout.bounds;- // Everything the person could bump into stays out of the walkable floor: nothing of a wall or a rail lies inside it below head height.- const inside = (child: Object3D) => {- const box = new Box3().setFromObject(child);- return box.min.x > layout.floor.minX && box.max.x < layout.floor.maxX && box.min.z > layout.floor.minZ && box.max.z < layout.floor.maxZ && box.min.y < 2;- };- const visible: number[] = [];- let walls = 0;- shell.traverse((child) => {- const box = new Box3().setFromObject(child);- // A window wall's group: tagged, as tall as the façade, on the slab, as long as one of its sides.- if (!child.userData.windowWall) return;- expect(Math.abs(box.max.y - (FACADE.h + 0.1))).toBeLessThan(0.01);- walls += 1;- // The east wall has the doorway to the sky pad's bridge: its glass stands in two runs.- if (Math.abs((box.min.x + box.max.x) / 2 - maxX) < 0.5) expect(child.children.length).toBe(2 + 3);- expect(inside(child)).toBe(false);- expect(box.min.x).toBeGreaterThanOrEqual(minX - 0.01);- expect(box.max.x).toBeLessThanOrEqual(maxX + 0.01);- expect(box.min.z).toBeGreaterThanOrEqual(minZ - 0.01);- expect(box.max.z).toBeLessThanOrEqual(maxZ + 0.01);- if (child.parent?.visible) visible.push(Math.round((box.min.x + box.max.x) / 2) + Math.round((box.min.z + box.max.z) / 2) * 1000);- });- expect(walls).toBe(4);- // The home view looks from the south-east: the north and the west wall stand, the other two sides show the balustrade.- 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("builds the sky pad outside the slab's east edge, its deck at floor level, nothing of it inside the floor", async () => {- const layout = buildOfficeLayout(staff(5));- const pad = layout.skyPad!;- const group = await mount(<SkyPadStructure pad={pad} bounds={layout.bounds} reduced onFloorClick={() => undefined} />);- group.updateMatrixWorld(true);- const box = new Box3().setFromObject(group);- expect(box.min.x).toBeGreaterThanOrEqual(layout.bounds.maxX - 0.7);- expect(box.max.x).toBeLessThanOrEqual(pad.pad.x + pad.pad.r + 0.5);- // The rails and the light masts stand on the deck; nothing rises higher than a mast.- expect(box.max.y).toBeLessThan(3.6);- let clickable = 0;- group.traverse((child) => { if ((child as Mesh).isMesh && (child as unknown as { __r3f?: { handlers?: { onClick?: unknown } } }).__r3f?.handlers?.onClick) clickable += 1; });- expect(clickable).toBe(2);- });-- 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} />);- const tagged: unknown[] = [];- group.traverse((child) => { if (child.userData.officeWall) tagged.push(child.userData.officeWall); });- expect(tagged).toHaveLength(layout.walls.length);- expect(new Set(tagged).size).toBe(layout.walls.length);- });-});--describe("a figure", () => {- const still = { current: { mode: "idle" as const, speed: 0 } };-- it("is a few dozen draw calls: its rigid head, torso and arm halves are merged, only the legs are parts of their own", async () => {- const figure = cost(await mount(<ToyFigure look={playerLook(loadProfile())} drive={still} paused />));- expect(figure.meshes).toBeLessThanOrEqual(22);- // What still casts: head, torso, pelvis, each half of an arm and each segment of a leg.- expect(figure.casters).toBeLessThanOrEqual(14);- // Both passes together.- expect(figure.triangles).toBeLessThan(40_000);- });-- it("keeps its shape when it is merged: the same triangles in the same place, for a bare arm, a sleeve and a held thing", async () => {- const base = playerLook(loadProfile());- const looks = [base, { ...base, outfit: "tee" as const }, { ...base, outfit: "suit" as const }];- for (const look of looks) {- const group = await mount(<ToyFigure look={look} drive={still} paused holding={<mesh><boxGeometry args={[0.05, 0.05, 0.05]} /></mesh>} />);- group.updateMatrixWorld(true);- const merged = { triangles: 0, box: new Box3() }, parts = { triangles: 0, box: new Box3() };- let loose = 0;- group.traverse((child) => {- const mesh = child as Mesh;- if (!mesh.isMesh) return;- if (!mesh.userData.staticBatched) { loose += 1; return; }- const into = mesh.visible ? merged : parts;- into.triangles += (mesh.geometry.index ? mesh.geometry.index.count : mesh.geometry.getAttribute("position").count) / 3;- // Measured vertex by vertex: a turned part's own box would overstate it.- into.box.union(new Box3().setFromObject(mesh, true));- });- expect(merged.triangles, look.outfit).toBe(parts.triangles);- for (const axis of ["x", "y", "z"] as const) {- expect(merged.box.min[axis], look.outfit).toBeCloseTo(parts.box.min[axis], 5);- expect(merged.box.max[axis], look.outfit).toBeCloseTo(parts.box.max[axis], 5);- }- // Outside every batch: the pelvis, three segments of each leg with a sole, and what the hand holds.- expect(loose, look.outfit).toBeLessThanOrEqual(12);- root?.unmount();- root = null;- }- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/CodingFloorAmbience.tsx b/dodaios/ui/web/frontend/src/components/society/office/CodingFloorAmbience.tsxdeleted file mode 100644index 97e1f7fa42..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/CodingFloorAmbience.tsx+++ /dev/null@@ -1,372 +0,0 @@-/**- * The coding floor's ambience between the rooms: tree planters closing the- * cross aisles at the windows; along the glass, beside every neighbourhood, a- * phone booth in the team's colour and a planter trough; down the main street- * a grove of tall trees ringed by oak benches; slim white pendants over every- * long table with soft pools of light below; and one warm fill light.- *- * Every repeated part is one instanced mesh, so the whole dressing costs a- * handful of draw calls. The solid pieces come from `codingAmbience`, which- * the layout also adds to its obstacles; the pendants and light pools are out- * of reach (overhead, or flat on the floor). The pendants hide whenever the- * camera comes down to their height, so they never block a close view.- */-import { useLayoutEffect, useMemo, useRef } from "react";-import { useFrame } from "@react-three/fiber";-import {- AdditiveBlending, Color, Euler, Group, InstancedMesh, Matrix4, MeshBasicMaterial, MeshStandardMaterial, PlaneGeometry, Quaternion, Vector3,- type BufferGeometry, type Material,-} from "three";-import { cachedCanvasTexture } from "./canvasMaterials";-import { BOOTH, codingAmbience, GROVE_H, TROUGH_H, type AmbienceItem } from "./codingAmbience";-import { GEO, MAT, matte } from "./OfficeFurniture";-import type { Department, OfficeLayout } from "./officeLayout";-import { CODING_SCENE, codingTeam } from "./officePalette";--// ----------------------------------------------------------------------------// Instancing-// -----------------------------------------------------------------------------export interface Placement {- position: [number, number, number];- scale: [number, number, number];- /** Rotation (x, y, z) in radians; absent = none. */- rotation?: [number, number, number];- color?: string;-}--const _m = new Matrix4(), _q = new Quaternion(), _e = new Euler(), _p = new Vector3(), _s = new Vector3(), _c = new Color();--/** One instanced mesh for every placement of a part (the agents floor's ambience uses it too). */-export function Instances({ geometry, material, items, cast = true }: {- geometry: BufferGeometry; material: Material; items: readonly Placement[]; cast?: boolean;-}) {- const ref = useRef<InstancedMesh>(null);- useLayoutEffect(() => {- const mesh = ref.current;- if (!mesh) return;- items.forEach((item, i) => {- _e.set(...(item.rotation ?? [0, 0, 0]));- _m.compose(_p.set(...item.position), _q.setFromEuler(_e), _s.set(...item.scale));- mesh.setMatrixAt(i, _m);- if (item.color) mesh.setColorAt(i, _c.set(item.color));- });- mesh.count = items.length;- mesh.instanceMatrix.needsUpdate = true;- if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;- }, [items]);- if (items.length === 0) return null;- return <instancedMesh key={items.length} ref={ref} args={[geometry, material, items.length]} castShadow={cast} receiveShadow frustumCulled={false} />;-}--// ----------------------------------------------------------------------------// Materials-// -----------------------------------------------------------------------------const AMB = {- /** Planters in pale fibre-cement with a white-oak rim. */- planter: matte("#e4e1db", { roughness: 0.8 }),- rim: matte(CODING_SCENE.oak.planks[0], { roughness: 0.55 }),- oak: matte(CODING_SCENE.oak.planks[3], { roughness: 0.55 }),- oakDark: matte(CODING_SCENE.oak.seam, { roughness: 0.6 }),- steel: matte("#2a2c30", { roughness: 0.4, metalness: 0.5 }),- glass: new MeshStandardMaterial({ color: "#dfeff5", transparent: true, opacity: 0.22, roughness: 0.05, depthWrite: false }),- /** White, so each instance's colour is the team's felt. */- felt: matte("#ffffff", { roughness: 0.95 }),- shade: matte("#fff1d6", { emissive: "#ffe2b8", emissiveIntensity: 0.8, roughness: 0.6 }),- olive: matte("#6f8a58", { flatShading: true }),- pendant: matte(CODING_SCENE.pendant.body, { roughness: 0.4, metalness: 0.4 }),- pendantGlow: matte(CODING_SCENE.pendant.glow, { emissive: CODING_SCENE.pendant.glow, emissiveIntensity: 2, toneMapped: false }),-};--/** Deterministic pseudo-random numbers per seed, so the dressing never changes between loads. */-function lcg(seed: number): () => number {- let state = seed >>> 0;- return () => {- state = (state * 1664525 + 1013904223) >>> 0;- return state / 0x1_0000_0000;- };-}--function seedOf(id: string): number {- let h = 2166136261;- for (let i = 0; i < id.length; i += 1) h = Math.imul(h ^ id.charCodeAt(i), 16777619);- return h >>> 0;-}--// ----------------------------------------------------------------------------// Trees-// -----------------------------------------------------------------------------/** Crown clusters of a tree in its own space (x, y, z, radius) and which leaf tone each takes. */-const CROWN: readonly [number, number, number, number, 0 | 1 | 2 | 3][] = [- [0, 1.95, 0, 0.36, 0], [0.24, 1.72, 0.1, 0.27, 1], [-0.22, 1.78, -0.08, 0.28, 2], [0.05, 2.18, 0.08, 0.26, 3],- [-0.1, 1.55, 0.2, 0.22, 1], [0.16, 2.02, -0.2, 0.24, 2], [-0.2, 2.06, 0.16, 0.22, 0], [0.12, 1.5, -0.14, 0.2, 3],-];-const LEAVES = [MAT.leaf, MAT.leafDark, MAT.leafLight, AMB.olive];--/** A tall tree in a square fibre-cement planter with an oak rim, filling its TREE_BOX footprint. */-function Trees({ items }: { items: readonly AmbienceItem[] }) {- const parts = useMemo(() => {- const planter: Placement[] = [], rim: Placement[] = [], soil: Placement[] = [], trunk: Placement[] = [];- const leaves: Placement[][] = LEAVES.map(() => []);- for (const item of items) {- const x = (item.minX + item.maxX) / 2, z = (item.minZ + item.maxZ) / 2, size = item.maxX - item.minX;- const rand = lcg(seedOf(item.id));- const turn = rand() * Math.PI * 2, s = 0.9 + rand() * 0.18;- planter.push({ position: [x, 0.27, z], scale: [size - 0.06, 0.54, size - 0.06] });- rim.push({ position: [x, 0.555, z], scale: [size, 0.03, size] });- soil.push({ position: [x, 0.572, z], scale: [size - 0.14, 0.006, size - 0.14] });- trunk.push({ position: [x, 1.1, z], scale: [0.045, 1.1, 0.045], rotation: [0.04, 0, -0.05] });- for (const [cx, cy, cz, r, tone] of CROWN) {- const lx = cx * Math.cos(turn) - cz * Math.sin(turn), lz = cx * Math.sin(turn) + cz * Math.cos(turn);- leaves[tone].push({ position: [x + lx * s, 0.1 + cy * s, z + lz * s], scale: [r * s, r * s * 0.9, r * s] });- }- }- return { planter, rim, soil, trunk, leaves };- }, [items]);- return (- <group>- <Instances geometry={GEO.box} material={AMB.planter} items={parts.planter} />- <Instances geometry={GEO.box} material={AMB.rim} items={parts.rim} />- <Instances geometry={GEO.box} material={MAT.soil} items={parts.soil} cast={false} />- <Instances geometry={GEO.cyl} material={MAT.trunk} items={parts.trunk} />- {parts.leaves.map((list, i) => <Instances key={i} geometry={GEO.blob} material={LEAVES[i]} items={list} />)}- </group>- );-}--// ----------------------------------------------------------------------------// Phone booths along the glass-// -----------------------------------------------------------------------------/**- * A phone booth: a steel frame with glass walls, its back and floor lined in- * the team's felt, a small bench seat and a lamp under the roof. The open- * front faces into the office.- */-function Booths({ items }: { items: readonly AmbienceItem[] }) {- const parts = useMemo(() => {- const frame: Placement[] = [], glass: Placement[] = [], felt: Placement[] = [], seat: Placement[] = [], lamp: Placement[] = [];- for (const item of items) {- const cx = (item.minX + item.maxX) / 2, cz = (item.minZ + item.maxZ) / 2;- const d = item.maxX - item.minX, len = item.maxZ - item.minZ, h = BOOTH.h;- // Which way is the back wall: away from the office.- const back = item.facing === "east" ? -1 : 1;- const colour = codingTeam(item.tint ?? 0).felt;- frame.push({ position: [cx, h - 0.04, cz], scale: [d, 0.08, len] });- frame.push({ position: [cx, 0.03, cz], scale: [d, 0.06, len] });- for (const [dx, dz] of [[-1, -1], [-1, 1], [1, -1], [1, 1]] as const) {- frame.push({ position: [cx + dx * (d / 2 - 0.025), h / 2, cz + dz * (len / 2 - 0.025)], scale: [0.05, h, 0.05] });- }- // Glass on the two short sides, felt on the back.- for (const dz of [-1, 1]) glass.push({ position: [cx, h / 2, cz + dz * (len / 2 - 0.02)], scale: [d - 0.06, h - 0.14, 0.02] });- felt.push({ position: [cx + back * (d / 2 - 0.03), h / 2, cz], scale: [0.04, h - 0.14, len - 0.08], color: colour });- felt.push({ position: [cx, 0.065, cz], scale: [d - 0.08, 0.01, len - 0.08], color: colour });- seat.push({ position: [cx + back * (d / 2 - 0.25), 0.44, cz], scale: [0.4, 0.08, len - 0.2] });- seat.push({ position: [cx + back * (d / 2 - 0.25), 0.22, cz], scale: [0.36, 0.38, len - 0.3] });- lamp.push({ position: [cx, h - 0.1, cz], scale: [0.18, 0.03, 0.18] });- }- return { frame, glass, felt, seat, lamp };- }, [items]);- return (- <group>- <Instances geometry={GEO.box} material={AMB.steel} items={parts.frame} />- <Instances geometry={GEO.box} material={AMB.glass} items={parts.glass} cast={false} />- <Instances geometry={GEO.box} material={AMB.felt} items={parts.felt} />- <Instances geometry={GEO.box} material={AMB.oak} items={parts.seat} />- <Instances geometry={GEO.cyl} material={AMB.shade} items={parts.lamp} cast={false} />- </group>- );-}--// ----------------------------------------------------------------------------// Groves down the main street-// -----------------------------------------------------------------------------/** A grove's crown in its own space (x, y, z, radius, leaf tone): broad and high, like a street tree. */-const GROVE_CROWN: readonly [number, number, number, number, 0 | 1 | 2 | 3][] = [- [0, 3.5, 0, 0.95, 0], [0.7, 3.2, 0.2, 0.7, 1], [-0.65, 3.3, -0.25, 0.72, 2], [0.15, 4.0, 0.3, 0.65, 3],- [-0.25, 3.0, 0.6, 0.6, 1], [0.4, 3.6, -0.6, 0.62, 2], [-0.6, 3.8, 0.35, 0.55, 0], [0.55, 2.9, -0.35, 0.5, 3],-];--/**- * A grove: a round planter of pale fibre-cement ringed by an oak bench, a tall- * tree in it whose crown spreads over the street, and low planting at its foot.- */-function Groves({ items }: { items: readonly AmbienceItem[] }) {- const parts = useMemo(() => {- const planter: Placement[] = [], rim: Placement[] = [], soil: Placement[] = [], bench: Placement[] = [], trunk: Placement[] = [];- const leaves: Placement[][] = LEAVES.map(() => []);- for (const item of items) {- const x = (item.minX + item.maxX) / 2, z = (item.minZ + item.maxZ) / 2, r = (item.maxX - item.minX) / 2;- const rand = lcg(seedOf(item.id));- bench.push({ position: [x, 0.2, z], scale: [r, 0.4, r] });- bench.push({ position: [x, 0.43, z], scale: [r + 0.02, 0.05, r + 0.02] });- planter.push({ position: [x, 0.36, z], scale: [r - 0.42, 0.72, r - 0.42] });- rim.push({ position: [x, 0.73, z], scale: [r - 0.4, 0.03, r - 0.4] });- soil.push({ position: [x, 0.745, z], scale: [r - 0.5, 0.01, r - 0.5] });- trunk.push({ position: [x, 1.9, z], scale: [0.09, 2.4, 0.09], rotation: [0.03, 0, -0.04] });- const turn = rand() * Math.PI * 2, s = 0.92 + rand() * 0.14;- for (const [cx, cy, cz, cr, tone] of GROVE_CROWN) {- const lx = cx * Math.cos(turn) - cz * Math.sin(turn), lz = cx * Math.sin(turn) + cz * Math.cos(turn);- leaves[tone].push({ position: [x + lx * s, cy * s * (GROVE_H / 4.4), z + lz * s], scale: [cr * s, cr * s * 0.85, cr * s] });- }- // Low planting round the trunk.- for (let k = 0; k < 6; k += 1) {- const a = (k / 6) * Math.PI * 2 + rand(), d = (r - 0.6) * (0.5 + rand() * 0.4);- leaves[k % LEAVES.length].push({ position: [x + Math.cos(a) * d, 0.84, z + Math.sin(a) * d], scale: [0.18, 0.14, 0.18] });- }- }- return { planter, rim, soil, bench, trunk, leaves };- }, [items]);- return (- <group>- <Instances geometry={GEO.cyl} material={AMB.oak} items={parts.bench} />- <Instances geometry={GEO.cyl} material={AMB.planter} items={parts.planter} />- <Instances geometry={GEO.cyl} material={AMB.rim} items={parts.rim} />- <Instances geometry={GEO.cyl} material={MAT.soil} items={parts.soil} cast={false} />- <Instances geometry={GEO.cyl} material={MAT.trunk} items={parts.trunk} />- {parts.leaves.map((list, i) => <Instances key={i} geometry={GEO.blob} material={LEAVES[i]} items={list} />)}- </group>- );-}--// ----------------------------------------------------------------------------// Planter troughs along the glass-// -----------------------------------------------------------------------------/** Long fibre-cement troughs on an oak plinth, planted with low foliage, kept low so they hide nothing. */-function Troughs({ items }: { items: readonly AmbienceItem[] }) {- const parts = useMemo(() => {- const body: Placement[] = [], plinth: Placement[] = [], soil: Placement[] = [];- const leaves: Placement[][] = LEAVES.map(() => []);- for (const item of items) {- const rand = lcg(seedOf(item.id));- const cx = (item.minX + item.maxX) / 2, depth = item.maxX - item.minX;- const len = item.maxZ - item.minZ, cz = (item.minZ + item.maxZ) / 2;- plinth.push({ position: [cx, 0.03, cz], scale: [depth - 0.04, 0.06, len - 0.04] });- body.push({ position: [cx, 0.06 + (TROUGH_H - 0.06) / 2, cz], scale: [depth, TROUGH_H - 0.06, len] });- soil.push({ position: [cx, TROUGH_H + 0.003, cz], scale: [depth - 0.06, 0.006, len - 0.06] });- for (let z = item.minZ + 0.18; z < item.maxZ - 0.12; z += 0.2 + rand() * 0.08) {- const r = 0.13 + rand() * 0.08;- leaves[Math.floor(rand() * LEAVES.length)].push({ position: [cx + (rand() - 0.5) * 0.08, TROUGH_H + r * 0.7, z], scale: [r * 0.9, r * (1 + rand() * 0.6), r] });- }- }- return { body, plinth, soil, leaves };- }, [items]);- return (- <group>- <Instances geometry={GEO.box} material={AMB.oak} items={parts.plinth} />- <Instances geometry={GEO.box} material={AMB.planter} items={parts.body} />- <Instances geometry={GEO.box} material={MAT.soil} items={parts.soil} cast={false} />- {parts.leaves.map((list, i) => <Instances key={i} geometry={GEO.blob} material={LEAVES[i]} items={list} />)}- </group>- );-}--// ----------------------------------------------------------------------------// Pendants over the benches-// -----------------------------------------------------------------------------const PENDANT_Y = 3.0;-/** Below this camera height the pendants hide, so a close or low view never looks through them. */-const PENDANT_HIDE_BELOW = PENDANT_Y + 4;--interface Bench { x: number; z: number; length: number }--/** One bench per pair of desk rows: its centre and length from the desks it holds. */-export function benchesOf(departments: readonly Pick<Department, "id" | "desks">[]): Bench[] {- const out: Bench[] = [];- for (const dept of departments) {- const groups = new Map<string, { xs: number[]; zs: number[] }>();- for (const desk of dept.desks) {- // Desk ids are "<dept>:<bench>:<facing>:<col>".- const key = desk.id.split(":").slice(0, -2).join(":");- const group = groups.get(key) ?? { xs: [], zs: [] };- group.xs.push(desk.x);- group.zs.push(desk.z);- groups.set(key, group);- }- for (const { xs, zs } of groups.values()) {- const minX = Math.min(...xs), maxX = Math.max(...xs);- out.push({ x: (minX + maxX) / 2, z: zs.reduce((s, v) => s + v, 0) / zs.length, length: maxX - minX + 1.2 });- }- }- return out;-}--let poolMaterial: MeshBasicMaterial | null = null;-/** A soft oval of warm light, added onto the floor. */-function pool(): MeshBasicMaterial {- if (!poolMaterial) {- const map = cachedCanvasTexture("coding:pool", 128, 128, (ctx, w, h) => {- const g = ctx.createRadialGradient(w / 2, h / 2, 0, w / 2, h / 2, w / 2);- g.addColorStop(0, "rgba(255,255,255,1)");- g.addColorStop(0.5, "rgba(255,255,255,0.45)");- g.addColorStop(1, "rgba(255,255,255,0)");- ctx.fillStyle = g;- ctx.fillRect(0, 0, w, h);- });- poolMaterial = new MeshBasicMaterial({- color: CODING_SCENE.pendant.pool, map, transparent: true, opacity: map ? 0.16 : 0, blending: AdditiveBlending, depthWrite: false,- });- }- return poolMaterial;-}-const POOL_GEOMETRY = new PlaneGeometry(1, 1).rotateX(-Math.PI / 2);--function Pendants({ departments }: { departments: readonly Department[] }) {- const lamps = useRef<Group>(null);- const parts = useMemo(() => {- const body: Placement[] = [], glow: Placement[] = [], cable: Placement[] = [], pools: Placement[] = [];- for (const bench of benchesOf(departments)) {- const len = bench.length - 0.4;- body.push({ position: [bench.x, PENDANT_Y, bench.z], scale: [len, 0.05, 0.07] });- glow.push({ position: [bench.x, PENDANT_Y - 0.027, bench.z], scale: [len - 0.06, 0.006, 0.045] });- for (const dx of [-len * 0.38, len * 0.38]) cable.push({ position: [bench.x + dx, PENDANT_Y + 0.6, bench.z], scale: [0.006, 1.2, 0.006] });- pools.push({ position: [bench.x, 0.012, bench.z], scale: [bench.length + 1.6, 1, 3.6] });- }- return { body, glow, cable, pools };- }, [departments]);- useFrame(({ camera }) => {- const group = lamps.current;- if (group) group.visible = camera.position.y > PENDANT_HIDE_BELOW;- });- return (- <group>- <group ref={lamps}>- <Instances geometry={GEO.box} material={AMB.pendant} items={parts.body} cast={false} />- <Instances geometry={GEO.box} material={AMB.pendantGlow} items={parts.glow} cast={false} />- <Instances geometry={GEO.box} material={AMB.pendant} items={parts.cable} cast={false} />- </group>- <Instances geometry={POOL_GEOMETRY} material={pool()} items={parts.pools} cast={false} />- </group>- );-}--// ----------------------------------------------------------------------------// The floor's ambience-// -----------------------------------------------------------------------------export function CodingFloorAmbience({ layout }: { layout: OfficeLayout }) {- const items = useMemo(() => codingAmbience(layout), [layout]);- const byKind = useMemo(() => ({- tree: items.filter((i) => i.kind === "tree"),- booth: items.filter((i) => i.kind === "booth"),- trough: items.filter((i) => i.kind === "trough"),- grove: items.filter((i) => i.kind === "grove"),- }), [items]);- const { minX, maxZ } = layout.bounds;- return (- <group>- {/* Warm late-afternoon fill from the south-west, no shadows: the one extra light the floor pays for. */}- <directionalLight position={[minX - 12, 12, maxZ + 6]} intensity={0.4} color="#ffc68a" />- <Trees items={byKind.tree} />- <Booths items={byKind.booth} />- <Troughs items={byKind.trough} />- <Groves items={byKind.grove} />- <Pendants departments={layout.departments} />- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/CodingFloorLook.tsx b/dodaios/ui/web/frontend/src/components/society/office/CodingFloorLook.tsxdeleted file mode 100644index caff817dea..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/CodingFloorLook.tsx+++ /dev/null@@ -1,360 +0,0 @@-/**- * The coding floor's own look: a tech campus floor in the tower. Polished- * pale concrete is the ground; a terrazzo main street with brass edges runs- * down the concourse; and every workspace is a team neighbourhood — an island- * of white oak with long shared tables (CodingTables) and, along its north- * edge, a living moss wall in a white-oak frame carrying the team's name on- * an oak header with a stripe of the team's colour.- *- * Purely visual. The only solid part is the moss wall, which stays inside the- * sign-wall footprint the layout already walks round.- */-import { useEffect, useMemo } from "react";-import type { ThreeEvent } from "@react-three/fiber";-import { MeshStandardMaterial, RepeatWrapping, type Texture } from "three";-import { fill, useT } from "@/i18n";-import type { SocietyAgent } from "../data";-import { cachedCanvasTexture, ownedCanvasTexture } from "./canvasMaterials";-import { CodingTables } from "./CodingTables";-import { Box, matte } from "./OfficeFurniture";-import type { Department, OfficeLayout, Rect } from "./officeLayout";-import { CODING_SCENE, codingTeam } from "./officePalette";--/** Metres covered by one repeat of the concrete, the terrazzo and the oak. */-const CONCRETE_METRES = 4.5;-const TERRAZZO_METRES = 3;-const OAK_METRES = 3.6;--/** Deterministic pseudo-random numbers, so the surfaces never shimmer between loads. */-function lcg(seed: number): () => number {- let state = seed >>> 0;- return () => {- state = (state * 1664525 + 1013904223) >>> 0;- return state / 0x1_0000_0000;- };-}--/** A cached base texture, cloned per surface with its own repeat. */-function repeated(base: Texture | null, repeatX: number, repeatZ: number): Texture | null {- if (!base) return null;- const map = base.clone();- map.wrapS = map.wrapT = RepeatWrapping;- map.anisotropy = 8;- map.repeat.set(repeatX, repeatZ);- map.needsUpdate = true;- return map;-}--/** Polished concrete: soft clouds of tone, a fine aggregate, and saw-cut joints every 1.5 m; seamless. */-function drawConcrete(ctx: CanvasRenderingContext2D, w: number, h: number): void {- const { base, cloud, joint } = CODING_SCENE.concrete;- const rand = lcg(0xc0c4e7e);- ctx.fillStyle = base;- ctx.fillRect(0, 0, w, h);- for (let i = 0; i < 46; i += 1) {- const x = rand() * w, y = rand() * h, r = 20 + rand() * 70;- const tone = cloud[i % cloud.length];- for (const dx of [-w, 0, w]) {- for (const dy of [-h, 0, h]) {- const g = ctx.createRadialGradient(x + dx, y + dy, 0, x + dx, y + dy, r);- g.addColorStop(0, `${tone}aa`);- g.addColorStop(1, `${tone}00`);- ctx.fillStyle = g;- ctx.fillRect(x + dx - r, y + dy - r, r * 2, r * 2);- }- }- }- for (let i = 0; i < 3200; i += 1) {- ctx.fillStyle = rand() > 0.5 ? "rgba(255,255,255,0.10)" : "rgba(90,84,76,0.07)";- ctx.fillRect(Math.floor(rand() * w), Math.floor(rand() * h), 1, 1);- }- // Saw cuts: three per repeat (4.5 m), on both axes.- ctx.fillStyle = joint;- for (let i = 0; i < 3; i += 1) {- ctx.fillRect((i * w) / 3, 0, 1.5, h);- ctx.fillRect(0, (i * h) / 3, w, 1.5);- }-}--/** Terrazzo: a warm pale ground with chips of stone in several sizes; seamless. */-function drawTerrazzo(ctx: CanvasRenderingContext2D, w: number, h: number): void {- const { base, chips } = CODING_SCENE.terrazzo;- const rand = lcg(0x7e4a);- ctx.fillStyle = base;- ctx.fillRect(0, 0, w, h);- for (let i = 0; i < 1900; i += 1) {- ctx.fillStyle = chips[Math.floor(rand() * chips.length)];- const s = 1 + rand() * (rand() > 0.92 ? 7 : 3);- const x = rand() * w, y = rand() * h;- ctx.beginPath();- ctx.ellipse(x, y, s, s * (0.55 + rand() * 0.45), rand() * Math.PI, 0, Math.PI * 2);- ctx.fill();- }-}--/** White-oak planks, 18 cm wide, staggered ends, a fine grain; seamless along both axes. */-function drawOak(ctx: CanvasRenderingContext2D, w: number, h: number): void {- const { seam, planks } = CODING_SCENE.oak;- const rand = lcg(0x0a4);- const rows = 20, rowH = h / rows;- ctx.fillStyle = seam;- ctx.fillRect(0, 0, w, h);- for (let r = 0; r < rows; r += 1) {- // One row is exactly one period long, drawn twice (at x and x + w), so it wraps without a seam.- const start = -rand() * w * 0.5;- let x = start;- while (x < start + w - 1) {- const len = Math.min(w * (0.35 + rand() * 0.4), start + w - x);- const tone = planks[Math.floor(rand() * planks.length)];- for (const dx of [0, w]) {- ctx.fillStyle = tone;- ctx.fillRect(x + dx + 1, r * rowH + 1, len - 2, rowH - 2);- ctx.fillStyle = "rgba(120,92,58,0.08)";- for (const gy of [0.3, 0.65]) ctx.fillRect(x + dx + 1, r * rowH + rowH * gy, len - 2, 1);- }- x += len;- }- }-}--/** Width of the concrete band's brass strip along the main street's edges. */-const STRIP_M = 0.04;--/** The concourse: the strip between the two neighbourhood columns, from the north rooms to the south strip. */-export function mainStreet(layout: Pick<OfficeLayout, "departments" | "rooms">): Rect | null {- const depts = layout.departments;- if (depts.length === 0) return null;- const colMinX = Math.min(...depts.map((d) => d.minX)), colMaxX = Math.max(...depts.map((d) => d.maxX));- const west = depts.filter((d) => d.minX <= colMinX + 1e-6);- const east = depts.filter((d) => d.maxX >= colMaxX - 1e-6 && d.minX > colMinX + 1e-6);- if (west.length === 0 || east.length === 0) return null;- const firstZ = Math.min(...depts.map((d) => d.minZ)), lastZ = Math.max(...depts.map((d) => d.maxZ));- const north = layout.rooms.filter((r) => r.maxZ <= firstZ + 1e-6).map((r) => r.maxZ);- const south = layout.rooms.filter((r) => r.minZ >= lastZ - 1e-6).map((r) => r.minZ);- return {- minX: Math.max(...west.map((d) => d.maxX)), maxX: Math.min(...east.map((d) => d.minX)),- minZ: north.length > 0 ? Math.max(...north) : firstZ, maxZ: south.length > 0 ? Math.min(...south) : lastZ,- };-}--/**- * The slab and floor of the coding floor: polished concrete everywhere, the- * terrazzo main street with brass strips down the concourse, a dark edge and a- * warm rim. The tower's window walls and balustrade stand round it (BuildingShell).- */-export function CodingSlab({ layout, onFloorClick }: { layout: OfficeLayout; onFloorClick: (event: ThreeEvent<MouseEvent>) => void }) {- const { minX, maxX, minZ, maxZ } = layout.bounds;- const w = maxX - minX, d = maxZ - minZ, cx = (minX + maxX) / 2, cz = (minZ + maxZ) / 2;- const street = useMemo(() => mainStreet(layout), [layout]);- const floor = useMemo(() => {- const map = repeated(cachedCanvasTexture("coding:concrete", 512, 512, drawConcrete), w / CONCRETE_METRES, d / CONCRETE_METRES);- return new MeshStandardMaterial({ color: map ? "#ffffff" : CODING_SCENE.concrete.base, map, roughness: 0.42, metalness: 0.05 });- }, [w, d]);- const terrazzo = useMemo(() => {- if (!street) return null;- const map = repeated(cachedCanvasTexture("coding:terrazzo", 512, 512, drawTerrazzo),- (street.maxX - street.minX) / TERRAZZO_METRES, (street.maxZ - street.minZ) / TERRAZZO_METRES);- return new MeshStandardMaterial({ color: map ? "#ffffff" : CODING_SCENE.terrazzo.base, map, roughness: 0.35 });- }, [street]);- const brass = useMemo(() => matte(CODING_SCENE.brass, { roughness: 0.35, metalness: 0.55 }), []);- const edge = useMemo(() => matte(CODING_SCENE.slabEdge, { roughness: 0.7 }), []);- const rim = useMemo(() => new MeshStandardMaterial({- color: CODING_SCENE.rim, emissive: CODING_SCENE.rim, emissiveIntensity: 0.9, roughness: 0.4, toneMapped: false,- }), []);- useEffect(() => () => {- floor.map?.dispose(); floor.dispose(); terrazzo?.map?.dispose(); terrazzo?.dispose();- brass.dispose(); edge.dispose(); rim.dispose();- }, [floor, terrazzo, brass, edge, rim]);- const glow = 0.05;- return (- <group>- <Box size={[w, 0.6, d]} position={[cx, -0.3, cz]} material={edge} cast={false} />- <Box size={[w + glow, glow, glow]} position={[cx, -0.06, minZ]} material={rim} cast={false} />- <Box size={[w + glow, glow, glow]} position={[cx, -0.06, maxZ]} material={rim} cast={false} />- <Box size={[glow, glow, d + glow]} position={[minX, -0.06, cz]} material={rim} cast={false} />- <Box size={[glow, glow, d + glow]} position={[maxX, -0.06, cz]} material={rim} cast={false} />- <mesh position={[cx, 0.001, cz]} rotation={[-Math.PI / 2, 0, 0]} material={floor} receiveShadow onClick={onFloorClick}>- <planeGeometry args={[w, d]} />- </mesh>- {street && terrazzo && (- <group>- <mesh position={[(street.minX + street.maxX) / 2, 0.003, (street.minZ + street.maxZ) / 2]} rotation={[-Math.PI / 2, 0, 0]}- material={terrazzo} receiveShadow onClick={onFloorClick}>- <planeGeometry args={[street.maxX - street.minX, street.maxZ - street.minZ]} />- </mesh>- {[street.minX + 0.3, street.maxX - 0.3].map((x) => (- <Box key={x} size={[STRIP_M, 0.004, street.maxZ - street.minZ]} position={[x, 0.004, (street.minZ + street.maxZ) / 2]}- material={brass} cast={false} />- ))}- </group>- )}- </group>- );-}--// ----------------------------------------------------------------------------// The living wall-// -----------------------------------------------------------------------------const WALL_H = 1.95;-const HEADER = { h: 0.42, w: 1024, px: 160 } as const;--/** Moss: dense tufts in several greens with fern sprays; seamless (white-free, lit by the scene). */-function drawMoss(ctx: CanvasRenderingContext2D, w: number, h: number): void {- const { base, tones, fern } = CODING_SCENE.moss;- const rand = lcg(0x3055);- ctx.fillStyle = base;- ctx.fillRect(0, 0, w, h);- for (let i = 0; i < 1400; i += 1) {- const x = rand() * w, y = rand() * h, r = 2 + rand() * 7;- ctx.fillStyle = tones[Math.floor(rand() * tones.length)];- for (const dx of [-w, 0, w]) {- for (const dy of [-h, 0, h]) {- ctx.beginPath();- ctx.arc(x + dx, y + dy, r, 0, Math.PI * 2);- ctx.fill();- }- }- }- // Fern sprays: a stem with short leaflets either side.- ctx.strokeStyle = fern;- ctx.lineWidth = 1.4;- for (let i = 0; i < 26; i += 1) {- const x = rand() * w, y = rand() * h, len = 14 + rand() * 18, a = -Math.PI / 2 + (rand() - 0.5) * 1.2;- for (let k = 0; k < len; k += 3) {- const px = x + Math.cos(a) * k, py = y + Math.sin(a) * k, leaf = (len - k) * 0.35;- ctx.beginPath();- ctx.moveTo(px, py); ctx.lineTo(px + Math.cos(a + 1.1) * leaf, py + Math.sin(a + 1.1) * leaf);- ctx.moveTo(px, py); ctx.lineTo(px + Math.cos(a - 1.1) * leaf, py + Math.sin(a - 1.1) * leaf);- ctx.stroke();- }- }-}--/** The oak header: the team's name in dark capitals, the room number small beside it, a stripe of the team's colour below. */-function drawHeader(label: string, caption: string, accent: string, ctx: CanvasRenderingContext2D, w: number, h: number): void {- const { planks, seam } = CODING_SCENE.oak;- ctx.fillStyle = planks[2];- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "rgba(120,92,58,0.10)";- for (let y = 6; y < h; y += 9) ctx.fillRect(0, y, w, 1);- ctx.fillStyle = seam;- ctx.fillRect(0, h - 3, w, 3);- ctx.fillStyle = accent;- ctx.fillRect(0, h - 18, w, 12);- const name = label.length > 26 ? `${label.slice(0, 25)}…` : label;- ctx.textBaseline = "middle";- ctx.font = "700 72px system-ui, -apple-system, 'Segoe UI', sans-serif";- const nameW = Math.min(ctx.measureText(name).width, w - 260);- ctx.save();- ctx.translate(48, (h - 18) / 2);- ctx.scale(nameW / Math.max(1, ctx.measureText(name).width), 1);- ctx.fillStyle = "#2b2622";- ctx.fillText(name, 0, 2);- ctx.restore();- ctx.font = "600 30px system-ui, -apple-system, 'Segoe UI', sans-serif";- ctx.fillStyle = "#6b5d4c";- ctx.textAlign = "right";- ctx.fillText(caption, w - 40, (h - 18) / 2 + 2);-}--const WALL_MAT = {- frame: matte(CODING_SCENE.moss.frame, { roughness: 0.55 }),- planter: matte(CODING_SCENE.oak.planks[3], { roughness: 0.55 }),- leaf: matte(CODING_SCENE.moss.tones[2], { flatShading: true, roughness: 0.8 }),-};--const mossMaterials = new Map<string, MeshStandardMaterial>();-function mossMaterial(width: number, height: number): MeshStandardMaterial {- const key = `${width.toFixed(2)}x${height.toFixed(2)}`;- let material = mossMaterials.get(key);- if (!material) {- const map = repeated(cachedCanvasTexture("coding:moss", 256, 256, drawMoss), width / 1.1, height / 1.1);- material = new MeshStandardMaterial({ color: map ? "#ffffff" : CODING_SCENE.moss.base, map, roughness: 1 });- mossMaterials.set(key, material);- }- return material;-}--/**- * A neighbourhood's living wall, centred on its front face: a white-oak frame- * round a field of moss and ferns, an oak header carrying the team's name, and- * an oak planter along its foot with trailing plants.- */-function LivingWall({ label, caption, accent, width, position }: {- label: string; caption: string; accent: string; width: number; position: [number, number, number];-}) {- const header = useMemo(() => {- const map = ownedCanvasTexture(HEADER.w, HEADER.px, (ctx, w, h) => drawHeader(label, caption, accent, ctx, w, h));- return new MeshStandardMaterial({ color: map ? "#ffffff" : CODING_SCENE.oak.planks[2], map, roughness: 0.6 });- }, [label, caption, accent]);- useEffect(() => () => { header.map?.dispose(); header.dispose(); }, [header]);- const mossH = WALL_H - HEADER.h - 0.42;- const headerW = Math.min(width - 0.2, (HEADER.h * HEADER.w) / HEADER.px);- const trailing = useMemo(() => {- const count = Math.max(2, Math.floor(width / 0.7));- return Array.from({ length: count }, (_, i) => -width / 2 + 0.35 + (i * (width - 0.7)) / (count - 1));- }, [width]);- return (- <group position={position}>- <Box size={[width, WALL_H, 0.12]} position={[0, WALL_H / 2, -0.02]} material={WALL_MAT.frame} />- <mesh position={[0, 0.36 + mossH / 2, 0.041]} material={mossMaterial(width - 0.14, mossH)} receiveShadow>- <planeGeometry args={[width - 0.14, mossH]} />- </mesh>- <mesh position={[0, WALL_H - HEADER.h / 2 - 0.04, 0.042]} material={header}>- <planeGeometry args={[headerW, HEADER.h]} />- </mesh>- {/* The planter at the wall's foot, with trailing plants spilling over its lip. */}- <Box size={[width, 0.36, 0.3]} position={[0, 0.18, 0.13]} material={WALL_MAT.planter} />- {trailing.map((x) => (- <mesh key={x} position={[x, 0.38, 0.18]} scale={[0.26, 0.14, 0.16]} material={WALL_MAT.leaf} castShadow>- <icosahedronGeometry args={[1, 0]} />- </mesh>- ))}- </group>- );-}--// ----------------------------------------------------------------------------// Neighbourhoods-// -----------------------------------------------------------------------------const oakMaterials = new Map<string, MeshStandardMaterial>();-function oakMaterial(w: number, d: number): MeshStandardMaterial {- const key = `${w.toFixed(2)}x${d.toFixed(2)}`;- let material = oakMaterials.get(key);- if (!material) {- const map = repeated(cachedCanvasTexture("coding:oak", 512, 512, drawOak), w / OAK_METRES, d / OAK_METRES);- material = new MeshStandardMaterial({ color: map ? "#ffffff" : CODING_SCENE.oak.planks[0], map, roughness: 0.55 });- oakMaterials.set(key, material);- }- return material;-}--const EDGE_MAT = matte(CODING_SCENE.oak.seam, { roughness: 0.5 });--/** One workspace as a team neighbourhood: a white-oak island, its living wall with the team's name, and its long tables. */-export function CodingStudio({ dept, agents }: { dept: Department; agents: ReadonlyMap<string, SocietyAgent> }) {- const t = useT();- const team = codingTeam(dept.tint);- const w = dept.maxX - dept.minX, d = dept.maxZ - dept.minZ;- const cx = (dept.minX + dept.maxX) / 2, cz = (dept.minZ + dept.maxZ) / 2;- const caption = fill(t("society.office.studio_n"), { number: String(dept.tint + 1).padStart(2, "0") });- return (- <group>- <mesh position={[cx, 0.005, cz]} rotation={[-Math.PI / 2, 0, 0]} material={oakMaterial(w, d)} receiveShadow>- <planeGeometry args={[w, d]} />- </mesh>- {/* A thin darker oak edge round the island. */}- {([[cx, dept.minZ, w, 0.04], [cx, dept.maxZ, w, 0.04]] as const).map(([x, z, sx, sz]) => (- <Box key={`z${z}`} size={[sx, 0.008, sz]} position={[x, 0.006, z]} material={EDGE_MAT} cast={false} />- ))}- {([[dept.minX, cz, 0.04, d], [dept.maxX, cz, 0.04, d]] as const).map(([x, z, sx, sz]) => (- <Box key={`x${x}`} size={[sx, 0.008, sz]} position={[x, 0.006, z]} material={EDGE_MAT} cast={false} />- ))}- <LivingWall label={dept.label || t("society.office.open_space")} caption={caption} accent={team.accent}- width={w - 0.4} position={[cx, 0, dept.minZ + 0.1]} />- <CodingTables desks={dept.desks} agents={agents} team={team} />- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/CodingPlaza.tsx b/dodaios/ui/web/frontend/src/components/society/office/CodingPlaza.tsxdeleted file mode 100644index 53bcba7d71..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/CodingPlaza.tsx+++ /dev/null@@ -1,86 +0,0 @@-/**- * The coding floor's town square: where the concourse meets the cross aisle- * round the spawn terminal, a round terrazzo medallion with brass rings and a- * compass of fine brass lines is set into the oak, under a soft pool of warm- * light — the floor's centre, readable from every desk.- *- * Purely visual and flat, so navigation is unchanged.- */-import { useEffect, useMemo } from "react";-import { AdditiveBlending, MeshBasicMaterial, MeshStandardMaterial } from "three";-import { cachedCanvasTexture } from "./canvasMaterials";-import type { Point } from "./officeLayout";-import { CODING_SCENE } from "./officePalette";--/** The medallion's radius (m). */-export const PLAZA_RADIUS = 2.7;--/** Terrazzo with brass rings and a compass rose of fine brass lines, on a transparent ground. */-function drawMedallion(ctx: CanvasRenderingContext2D, w: number, h: number): void {- ctx.clearRect(0, 0, w, h);- const c = w / 2, r = w / 2 - 2;- let seed = 0x7e44a20;- const rand = () => { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 0x1_0000_0000; };- // The terrazzo field: a warm pale ground with small chips.- ctx.save();- ctx.beginPath();- ctx.arc(c, c, r, 0, Math.PI * 2);- ctx.clip();- ctx.fillStyle = CODING_SCENE.plaza.terrazzo;- ctx.fillRect(0, 0, w, h);- for (let i = 0; i < 2600; i += 1) {- ctx.fillStyle = CODING_SCENE.plaza.chips[Math.floor(rand() * CODING_SCENE.plaza.chips.length)];- const s = 1.5 + rand() * 3.5;- ctx.fillRect(rand() * w, rand() * h, s, s * (0.6 + rand() * 0.6));- }- ctx.restore();- // Brass: an outer band, two inner rings and the compass lines between them.- ctx.strokeStyle = CODING_SCENE.brass;- ctx.lineWidth = w * 0.018;- ctx.beginPath(); ctx.arc(c, c, r - ctx.lineWidth / 2, 0, Math.PI * 2); ctx.stroke();- ctx.lineWidth = w * 0.006;- ctx.beginPath(); ctx.arc(c, c, r * 0.86, 0, Math.PI * 2); ctx.stroke();- ctx.beginPath(); ctx.arc(c, c, r * 0.5, 0, Math.PI * 2); ctx.stroke();- ctx.lineWidth = w * 0.004;- for (let i = 0; i < 16; i += 1) {- const a = (i / 16) * Math.PI * 2, inner = i % 4 === 0 ? 0.5 : 0.62;- ctx.beginPath();- ctx.moveTo(c + Math.cos(a) * r * inner, c + Math.sin(a) * r * inner);- ctx.lineTo(c + Math.cos(a) * r * 0.86, c + Math.sin(a) * r * 0.86);- ctx.stroke();- }-}--/** A soft round pool of warm light on the floor (white centre fading out; the material tints it). */-function drawPool(ctx: CanvasRenderingContext2D, w: number, h: number): void {- const g = ctx.createRadialGradient(w / 2, h / 2, w * 0.2, w / 2, h / 2, w / 2);- g.addColorStop(0, "rgba(255,255,255,0.55)");- g.addColorStop(0.6, "rgba(255,255,255,0.3)");- g.addColorStop(1, "rgba(255,255,255,0)");- ctx.fillStyle = g;- ctx.fillRect(0, 0, w, h);-}--export function CodingPlaza({ at }: { at: Point }) {- const surfaces = useMemo(() => ({- medallion: new MeshStandardMaterial({- map: cachedCanvasTexture("coding:medallion", 1024, 1024, drawMedallion), transparent: true, roughness: 0.4, metalness: 0.1,- polygonOffset: true, polygonOffsetFactor: -2,- }),- pool: new MeshBasicMaterial({- map: cachedCanvasTexture("coding:plaza-pool", 128, 128, drawPool), color: CODING_SCENE.pendant.pool, transparent: true,- opacity: 0.3, blending: AdditiveBlending, depthWrite: false,- }),- }), []);- useEffect(() => () => { surfaces.medallion.dispose(); surfaces.pool.dispose(); }, [surfaces]);- return (- <group position={[at.x, 0, at.z]}>- <mesh position={[0, 0.006, 0]} rotation={[-Math.PI / 2, 0, 0]} material={surfaces.medallion} receiveShadow>- <circleGeometry args={[PLAZA_RADIUS, 96]} />- </mesh>- <mesh position={[0, 0.009, 0]} rotation={[-Math.PI / 2, 0, 0]} material={surfaces.pool}>- <planeGeometry args={[PLAZA_RADIUS * 2.4, PLAZA_RADIUS * 2.4]} />- </mesh>- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/CodingTables.tsx b/dodaios/ui/web/frontend/src/components/society/office/CodingTables.tsxdeleted file mode 100644index 4e95530c30..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/CodingTables.tsx+++ /dev/null@@ -1,143 +0,0 @@-/**- * The coding floor's long shared tables. Each bench of the layout — two rows- * of desk slots facing each other — is one continuous white-oak table on dark- * steel A-frames, with a low felt screen in the team's colour down its spine.- * Every seat keeps what a desk had: a monitor on an arm (the live terminal is- * drawn on its screen, exactly where it was), a keyboard and a task chair- * whose seat is upholstered in the team's felt.- *- * Every repeated part is one instanced mesh per neighbourhood; the slots and- * their footprints are the layout's, so seating and navigation are unchanged.- */-import { useEffect, useLayoutEffect, useMemo, useRef } from "react";-import { BufferGeometry, Euler, InstancedMesh, Matrix4, MeshStandardMaterial, PlaneGeometry, Quaternion, Vector3, type Material } from "three";-import { RoundedBoxGeometry } from "three-stdlib";-import type { SocietyAgent } from "../data";-import { CHAIR_MAT, TASK_CHAIR_PARTS, type ChairFinish } from "./OfficeChairs";-import { GEO, MAT, screenMaterial } from "./OfficeFurniture";-import { DESK_SIZE, type DeskSlot } from "./officeLayout";-import { CODING_SCENE, type TeamColours } from "./officePalette";-import type { ScreenFace } from "./screenTextures";--const TM = {- top: new MeshStandardMaterial({ color: CODING_SCENE.table.top, roughness: 0.5 }),- edge: new MeshStandardMaterial({ color: CODING_SCENE.table.edge, roughness: 0.5 }),- leg: new MeshStandardMaterial({ color: CODING_SCENE.table.leg, roughness: 0.4, metalness: 0.5 }),- spine: new MeshStandardMaterial({ color: CODING_SCENE.table.spine, roughness: 0.5, metalness: 0.3 }),- chairFrame: new MeshStandardMaterial({ color: "#2a2c30", roughness: 0.45, metalness: 0.2 }),-};--/** A table: one bench's slots, its centre, length along x and depth across. */-export interface LongTable { key: string; x: number; z: number; length: number; depth: number }--/** One long table per bench of desk slots ("<dept>:<bench>:<facing>:<col>"). Pure. */-export function longTables(desks: readonly DeskSlot[]): LongTable[] {- const benches = new Map<string, DeskSlot[]>();- for (const desk of desks) {- if (desk.size) continue;- const key = desk.id.split(":").slice(0, -2).join(":");- benches.set(key, [...(benches.get(key) ?? []), desk]);- }- return [...benches.entries()].map(([key, slots]) => {- const xs = slots.map((s) => s.x), zs = slots.map((s) => s.z);- const minX = Math.min(...xs) - DESK_SIZE.w / 2, maxX = Math.max(...xs) + DESK_SIZE.w / 2;- const minZ = Math.min(...zs) - DESK_SIZE.d / 2, maxZ = Math.max(...zs) + DESK_SIZE.d / 2;- return { key, x: (minX + maxX) / 2, z: (minZ + maxZ) / 2, length: maxX - minX, depth: maxZ - minZ };- });-}--const _q = new Quaternion(), _e = new Euler(), _p = new Vector3(), _s = new Vector3();-function compose(position: [number, number, number], scale: [number, number, number], rotY = 0): Matrix4 {- return new Matrix4().compose(_p.set(...position), _q.setFromEuler(_e.set(0, rotY, 0)), _s.set(...scale));-}--function seatMatrix(desk: DeskSlot, local: [number, number, number], scale: [number, number, number] = [1, 1, 1]): Matrix4 {- const turn = desk.facing === "north" ? 0 : Math.PI;- return compose([desk.x, 0, desk.z], [1, 1, 1], turn).multiply(compose(local, scale));-}--function InstancedParts({ geometry, material, matrices, cast = true }: {- geometry: BufferGeometry; material: Material; matrices: readonly Matrix4[]; cast?: boolean;-}) {- const ref = useRef<InstancedMesh>(null);- useLayoutEffect(() => {- const mesh = ref.current;- if (!mesh) return;- matrices.forEach((m, i) => mesh.setMatrixAt(i, m));- mesh.count = matrices.length;- mesh.instanceMatrix.needsUpdate = true;- mesh.computeBoundingSphere();- }, [matrices]);- if (matrices.length === 0) return null;- // Remount when the count changes: an instanced mesh cannot grow in place.- return <instancedMesh key={matrices.length} ref={ref} args={[geometry, material, matrices.length]} castShadow={cast} receiveShadow frustumCulled={false} />;-}--const TOP = new RoundedBoxGeometry(1, 1, 1, 1, 0.02);-const MONITOR = new RoundedBoxGeometry(0.72, 0.43, 0.022, 1, 0.012);-const SCREEN = new PlaneGeometry(0.66, 0.38);-const FACES: ScreenFace[] = ["working", "idle", "waiting", "paused", "empty"];-const CHAIR_FINISH: Record<ChairFinish, "frame" | "seat" | "metal" | "mesh"> = { frame: "frame", fabric: "seat", metal: "metal", mesh: "mesh" };--/** The long tables of one neighbourhood and everything at their seats. */-export function CodingTables({ desks, agents, team }: {- desks: readonly DeskSlot[]; agents: ReadonlyMap<string, SocietyAgent>; team: TeamColours;-}) {- const felt = useMemo(() => new MeshStandardMaterial({ color: team.felt, roughness: 0.95 }), [team.felt]);- useEffect(() => () => felt.dispose(), [felt]);- const tables = useMemo(() => longTables(desks), [desks]);- const parts = useMemo(() => {- const top: Matrix4[] = [], edge: Matrix4[] = [], legs: Matrix4[] = [], spine: Matrix4[] = [], screen: Matrix4[] = [];- for (const t of tables) {- top.push(compose([t.x, 0.755, t.z], [t.length, 0.035, t.depth]));- edge.push(compose([t.x, 0.728, t.z], [t.length - 0.04, 0.022, t.depth - 0.04]));- // A-frames at both ends and, on a long table, in the middle.- const frames = t.length > 4 ? [-t.length / 2 + 0.28, 0, t.length / 2 - 0.28] : [-t.length / 2 + 0.28, t.length / 2 - 0.28];- for (const fx of frames) {- legs.push(compose([t.x + fx, 0.36, t.z - t.depth / 2 + 0.22], [0.06, 0.72, 0.06]));- legs.push(compose([t.x + fx, 0.36, t.z + t.depth / 2 - 0.22], [0.06, 0.72, 0.06]));- legs.push(compose([t.x + fx, 0.03, t.z], [0.06, 0.04, t.depth - 0.4]));- }- // The spine: a cable rail and a low felt screen in the team's colour.- spine.push(compose([t.x, 0.79, t.z], [t.length - 0.3, 0.04, 0.1]));- screen.push(compose([t.x, 0.98, t.z], [t.length - 0.4, 0.34, 0.03]));- }- const seats = desks.filter((desk) => !desk.size);- const arm = seats.flatMap((d) => [- seatMatrix(d, [0, 0.8, -0.3], [0.08, 0.05, 0.06]),- seatMatrix(d, [0, 0.95, -0.3], [0.018, 0.3, 0.018]),- seatMatrix(d, [0, 1.1, -0.26], [0.04, 0.03, 0.08]),- ]);- const monitor = seats.map((d) => seatMatrix(d, [0, 1.18, -0.224]));- const keys = seats.flatMap((d) => [- seatMatrix(d, [0, 0.784, 0.2], [0.46, 0.014, 0.14]),- seatMatrix(d, [0.34, 0.786, 0.2], [0.05, 0.02, 0.08]),- ]);- const chair = seats.map((d) => seatMatrix(d, [0, 0, 0.62]));- const faces = new Map<ScreenFace, Matrix4[]>(FACES.map((f) => [f, []]));- for (const d of seats) {- const agent = d.agentId ? agents.get(d.agentId) : undefined;- faces.get(agent ? agent.state : "empty")!.push(seatMatrix(d, [0, 1.18, -0.212]));- }- return { top, edge, legs, spine, screen, arm, monitor, keys, chair, faces };- }, [tables, desks, agents]);- const chairMaterial: Record<"frame" | "seat" | "metal" | "mesh", Material> = {- frame: TM.chairFrame, seat: felt, metal: CHAIR_MAT.aluminium, mesh: CHAIR_MAT.mesh,- };- return (- <group>- <InstancedParts geometry={TOP} material={TM.top} matrices={parts.top} />- <InstancedParts geometry={GEO.box} material={TM.edge} matrices={parts.edge} cast={false} />- <InstancedParts geometry={GEO.box} material={TM.leg} matrices={parts.legs} />- <InstancedParts geometry={GEO.box} material={TM.spine} matrices={parts.spine} cast={false} />- <InstancedParts geometry={GEO.box} material={felt} matrices={parts.screen} />- <InstancedParts geometry={GEO.box} material={MAT.monitorArm} matrices={parts.arm} cast={false} />- <InstancedParts geometry={MONITOR} material={MAT.monitor} matrices={parts.monitor} />- <InstancedParts geometry={GEO.box} material={MAT.keyboard} matrices={parts.keys} cast={false} />- {TASK_CHAIR_PARTS.map((part, i) => (- <InstancedParts key={i} geometry={part.geometry} material={chairMaterial[CHAIR_FINISH[part.finish]]} matrices={parts.chair} cast={part.cast} />- ))}- {FACES.map((face) => <InstancedParts key={face} geometry={SCREEN} material={screenMaterial(face)} matrices={parts.faces.get(face)!} cast={false} />)}- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/CommandOffice.tsx b/dodaios/ui/web/frontend/src/components/society/office/CommandOffice.tsxdeleted file mode 100644index d434b2099c..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/CommandOffice.tsx+++ /dev/null@@ -1,540 +0,0 @@-/**- * Mission Control, the coding floor's own office: a walnut slat wall with a- * live video wall, and a desk with three live monitors and an executive chair.- * Working it (E in the room, or a click on the video wall or the desk) opens- * the Mission Control panel: start new coding agents, brief several at once.- *- * The video wall is a live board of the floor, drawn from the same shared pane- * poll the figures ride: each agent as a tile. The desk's three monitors run- * real app sections live (MissionScreens): Spend (left), the Agents view- * (centre) and the Agentic IDE (right). A click on one dives the camera into- * its glass and opens that section; from afar each shows a quiet title card.- *- * Pieces are built in local space centred on the origin, front facing +z, and- * stay inside their FURNITURE_SIZE box.- */-import { useContext, useEffect, useMemo, useRef, useState, type RefObject } from "react";-import { CanvasActivity } from "@/hooks/useCanvasAwake";-import { Html } from "@react-three/drei";-import { useFrame, type ThreeEvent } from "@react-three/fiber";-import { CanvasTexture, CylinderGeometry, MeshBasicMaterial, MeshStandardMaterial, Quaternion, SRGBColorSpace, Vector3, type Group } from "three";-import { useT } from "@/i18n";-import { useRunLocale } from "@/components/runs/format";-import { useWorkspacePanesStore } from "@/store/workspacePanes";-import type { AgentRunState } from "../data";-import { Box, MAT, matte, Rounded } from "./OfficeFurniture";-import { paneOccupants } from "./codingFloor";-import { COMMAND_DESK, COMMAND_DESK_OFFSET, type Furniture, type FurnitureKind } from "./officeLayout";-import { useLeadSeat } from "./leadSeat";-import { MissionLiveScreen, preloadMissionScreens } from "./MissionScreens";-import { useOfficeStore, type MonitorSection } from "./officeStore";--// ----------------------------------------------------------------------------// Live data-// -----------------------------------------------------------------------------export interface FloorAgent {- name: string;- state: AgentRunState;- stateKey: string;- cli: string;- workspace: string;- prompt: string;- promptAt: number | null;- topic: string;-}--export interface FloorData {- counts: { total: number; working: number; waiting: number; idle: number };- agents: FloorAgent[];- workspaces: { name: string; total: number; working: number }[];-}--function useFloorData(): FloorData {- const panes = useWorkspacePanesStore((s) => s.panes);- return useMemo(() => {- const counts = { total: 0, working: 0, waiting: 0, idle: 0 };- const agents: FloorAgent[] = [];- const byWorkspace = new Map<string, { name: string; total: number; working: number }>();- for (const { agent, pane, stateKey } of paneOccupants(panes)) {- counts.total += 1;- if (agent.state === "working") counts.working += 1;- else if (agent.state === "waiting") counts.waiting += 1;- else counts.idle += 1;- agents.push({- name: agent.name, state: agent.state, stateKey, cli: pane.display_name || pane.agent,- workspace: pane.workspace_name, prompt: pane.last_prompt.trim(), promptAt: pane.last_prompt_at, topic: pane.recap.trim(),- });- const ws = byWorkspace.get(pane.workspace_id) ?? { name: pane.workspace_name, total: 0, working: 0 };- ws.total += 1;- if (agent.state === "working") ws.working += 1;- byWorkspace.set(pane.workspace_id, ws);- }- return { counts, agents, workspaces: [...byWorkspace.values()] };- }, [panes]);-}--/** Everything the screens say, in the viewer's language. */-export interface ScreenLabels {- title: string; agents: string; none: string;- /** The desk monitors' sections, named as the navigation names them. */- costs: string; agentsView: string; ide: string;- working: string; waiting: string; idle: string;- state: (key: string) => string;- since: (at: number | null) => string;-}--function useScreenLabels(): ScreenLabels {- const t = useT();- return {- title: t("society.office.cp_mission"),- agents: t("society.office.mission_screen_agents"),- costs: t("nav.costs"),- agentsView: t("nav.agents"),- ide: t("nav.agentic_ide"),- none: t("society.office.mission_screen_none"),- working: t("society.office.state_working"),- waiting: t("society.office.state_waiting"),- idle: t("society.office.state_idle"),- state: (key) => t(`society.office.pane_state_${key}`),- since: (at) => {- if (!at) return "";- const s = Math.max(0, Date.now() / 1000 - at);- if (s < 60) return t("society.office.since_now");- if (s < 3600) return t("society.office.since_minutes").replace("{0}", String(Math.floor(s / 60)));- if (s < 86400) return t("society.office.since_hours").replace("{0}", String(Math.floor(s / 3600)));- return t("society.office.since_days").replace("{0}", String(Math.floor(s / 86400)));- },- };-}--// ----------------------------------------------------------------------------// Drawing: one quiet dark UI, white type, colour only for state.-// -----------------------------------------------------------------------------const INK = "#f4f6f8", MUTED = "#8b929c";-const FONT = "Inter, system-ui, -apple-system, 'Segoe UI', sans-serif";-const STATE: Record<AgentRunState, string> = { working: "#4ade80", waiting: "#fbbf24", idle: "#8b929c", paused: "#8b929c" };--type Ctx = CanvasRenderingContext2D;--function ground(ctx: Ctx, w: number, h: number): void {- const bg = ctx.createLinearGradient(0, 0, 0, h);- bg.addColorStop(0, "#15181d");- bg.addColorStop(1, "#0b0d10");- ctx.fillStyle = bg;- ctx.fillRect(0, 0, w, h);- ctx.textBaseline = "alphabetic";- ctx.textAlign = "left";-}--/** `text` cut with an ellipsis so it fits `max` pixels in the current font. */-function fit(ctx: Ctx, text: string, max: number): string {- if (ctx.measureText(text).width <= max) return text;- let lo = 0, hi = text.length;- while (lo < hi) {- const mid = Math.ceil((lo + hi) / 2);- if (ctx.measureText(`${text.slice(0, mid)}…`).width <= max) lo = mid; else hi = mid - 1;- }- return `${text.slice(0, lo)}…`;-}--function dot(ctx: Ctx, x: number, y: number, r: number, colour: string): void {- ctx.fillStyle = colour;- ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill();-}--function heading(ctx: Ctx, text: string, x: number, y: number): void {- ctx.fillStyle = MUTED;- ctx.font = `600 30px ${FONT}`;- ctx.fillText(text, x, y);-}--/** A desk monitor seen from afar: the section it runs, and one line of what it holds. */-export function drawTitleCard(ctx: Ctx, w: number, h: number, title: string, detail: string): void {- ground(ctx, w, h);- const pad = 56;- heading(ctx, detail, pad, pad + 26);- ctx.fillStyle = INK;- ctx.font = `700 96px ${FONT}`;- ctx.fillText(fit(ctx, title, w - pad * 2), pad, h - pad - 10);-}--/** The video wall: a header with the time, then one tile per agent on the floor. */-export function drawVideoWall(ctx: Ctx, w: number, h: number, data: FloorData, l: ScreenLabels, clock: string): void {- ground(ctx, w, h);- const pad = 48;- ctx.fillStyle = INK;- ctx.font = `700 44px ${FONT}`;- ctx.fillText(l.title, pad, pad + 38);- ctx.textAlign = "right";- ctx.font = `600 44px ${FONT}`;- ctx.fillText(clock, w - pad, pad + 38);- ctx.fillStyle = MUTED;- ctx.font = `500 28px ${FONT}`;- const { counts } = data;- const summary = `${counts.working} ${l.working} · ${counts.waiting} ${l.waiting} · ${counts.idle} ${l.idle}`;- ctx.fillText(summary, w - pad - ctx.measureText(clock).width - 60, pad + 34);- ctx.textAlign = "left";- const top = pad + 80, cols = 4, rows = 2, gap = 20;- const tw = (w - pad * 2 - gap * (cols - 1)) / cols, th = (h - top - pad - gap * (rows - 1)) / rows;- if (data.agents.length === 0) {- ctx.fillStyle = MUTED;- ctx.font = `500 40px ${FONT}`;- ctx.textAlign = "center";- ctx.fillText(l.none, w / 2, top + (h - top) / 2);- ctx.textAlign = "left";- return;- }- const order: Record<AgentRunState, number> = { waiting: 0, working: 1, idle: 2, paused: 3 };- const tiles = [...data.agents].sort((a, b) => order[a.state] - order[b.state]).slice(0, cols * rows);- tiles.forEach((a, i) => {- const x = pad + (i % cols) * (tw + gap), y = top + Math.floor(i / cols) * (th + gap);- ctx.fillStyle = "rgba(255,255,255,0.045)";- ctx.beginPath(); ctx.roundRect(x, y, tw, th, 16); ctx.fill();- ctx.fillStyle = STATE[a.state];- ctx.beginPath(); ctx.roundRect(x, y, 6, th, [16, 0, 0, 16]); ctx.fill();- const ix = x + 28, iw = tw - 48;- ctx.fillStyle = INK;- ctx.font = `600 32px ${FONT}`;- ctx.fillText(fit(ctx, a.name, iw), ix, y + 50);- ctx.fillStyle = MUTED;- ctx.font = `500 24px ${FONT}`;- ctx.fillText(fit(ctx, `${a.cli} · ${a.workspace}`, iw), ix, y + 86);- dot(ctx, ix + 7, y + th - 34, 7, STATE[a.state]);- ctx.fillStyle = INK;- ctx.font = `500 26px ${FONT}`;- ctx.fillText(fit(ctx, l.state(a.stateKey), iw - 24), ix + 22, y + th - 25);- if (a.topic && th > 170) {- ctx.fillStyle = MUTED;- ctx.font = `400 24px ${FONT}`;- ctx.fillText(fit(ctx, a.topic, iw), ix, y + 124);- }- });-}--// ----------------------------------------------------------------------------// Live screens-// -----------------------------------------------------------------------------/** A canvas-backed screen material that redraws whenever `key` changes. */-function useLiveScreen(width: number, height: number, key: string, draw: (ctx: Ctx, w: number, h: number) => void): MeshBasicMaterial {- const canvas = useMemo(() => (typeof document !== "undefined" ? document.createElement("canvas") : null), []);- const material = useMemo(() => {- if (!canvas) return new MeshBasicMaterial({ color: "#0b0d10" });- canvas.width = width;- canvas.height = height;- const texture = new CanvasTexture(canvas);- texture.colorSpace = SRGBColorSpace;- texture.anisotropy = 8;- return new MeshBasicMaterial({ map: texture, toneMapped: false });- }, [canvas, width, height]);- const drawRef = useRef(draw);- drawRef.current = draw;- useEffect(() => {- let ctx: Ctx | null = null;- try { ctx = canvas?.getContext("2d") ?? null; } catch {- // jsdom without the canvas package: the plain dark screen is the right fallback.- ctx = null;- }- if (!ctx || !material.map) return;- drawRef.current(ctx, width, height);- material.map.needsUpdate = true;- }, [key, canvas, material, width, height]);- useEffect(() => () => { material.map?.dispose(); material.dispose(); }, [material]);- return material;-}--/** Minutes change the clock; a timer ticks it without any network. */-function useClock(): string {- const active = useContext(CanvasActivity);- const locale = useRunLocale();- const [now, setNow] = useState(() => new Date());- useEffect(() => {- if (!active) return;- const timer = setInterval(() => setNow(new Date()), 20_000);- return () => clearInterval(timer);- }, [active]);- return now.toLocaleTimeString(locale, { hour: "2-digit", minute: "2-digit" });-}--/** Opening Mission Control from anything in the office that is clicked. */-function useOpenMission() {- const hovered = useRef(false);- useEffect(() => () => { if (hovered.current) document.body.style.cursor = ""; }, []);- return {- onClick: (event: ThreeEvent<MouseEvent>) => {- event.stopPropagation();- useOfficeStore.getState().select({ kind: "checkpoint", id: "mission" });- },- onPointerOver: (event: ThreeEvent<PointerEvent>) => { event.stopPropagation(); hovered.current = true; document.body.style.cursor = "pointer"; },- onPointerOut: () => { hovered.current = false; document.body.style.cursor = ""; },- };-}--function Screen({ w, h, material }: { w: number; h: number; material: MeshBasicMaterial }) {- return (- <group>- <Rounded size={[w + 0.03, h + 0.03, 0.028]} radius={0.01} position={[0, 0, 0]} material={MAT.monitor} />- <mesh position={[0, 0, 0.0145]} material={material}>- <planeGeometry args={[w, h]} />- </mesh>- </group>- );-}--// ----------------------------------------------------------------------------// The slat wall with the video wall-// -----------------------------------------------------------------------------const CM = {- felt: matte("#202328", { roughness: 1 }),- walnut: matte("#5b3b27", { roughness: 0.7 }),- // Light strips: lit from within, so they read as light in any scene lighting.- cove: new MeshStandardMaterial({ color: "#ffe6c4", emissive: "#ffe6c4", emissiveIntensity: 1.1, toneMapped: false }),- ice: new MeshStandardMaterial({ color: "#cfe9ff", emissive: "#cfe9ff", emissiveIntensity: 1.1, toneMapped: false }),- speaker: matte("#1b1d21", { roughness: 0.6 }),-};-const SLAT_PITCH = 0.13;-const SLATS = Array.from({ length: Math.floor(7.7 / SLAT_PITCH) }, (_, i) => -3.85 + SLAT_PITCH / 2 + i * SLAT_PITCH);-const WALL_SCREEN = { w: 3.4, h: 1.36, y: 1.6 };-const WALL_CANVAS = { w: 1600, h: Math.round((1600 * 1.36) / 3.4) };--export function CommandWall() {- const data = useFloorData();- const labels = useScreenLabels();- const clock = useClock();- const key = JSON.stringify([data, clock, labels.title, labels.none, labels.working]);- const screen = useLiveScreen(WALL_CANVAS.w, WALL_CANVAS.h, key, (ctx, w, h) => drawVideoWall(ctx, w, h, data, labels, clock));- const open = useOpenMission();- return (- <group>- {/* Dark felt backing, a full-height walnut slat screen, warm light in coves top and bottom. */}- <Box size={[7.8, 2.7, 0.06]} position={[0, 1.35, -0.12]} material={CM.felt} />- {SLATS.map((x) => <Box key={x} size={[0.06, 2.62, 0.06]} position={[x, 1.35, -0.06]} material={CM.walnut} cast={false} />)}- <Box size={[7.7, 0.012, 0.02]} position={[0, 0.03, -0.02]} material={CM.cove} cast={false} />- <Box size={[7.7, 0.012, 0.02]} position={[0, 2.67, -0.02]} material={CM.cove} cast={false} />- {/* The video wall, flush on the slats; a floating oak shelf with a pair of speakers under it. */}- <group position={[0, WALL_SCREEN.y, 0.02]} {...open}>- <Screen w={WALL_SCREEN.w} h={WALL_SCREEN.h} material={screen} />- </group>- <Rounded size={[2.6, 0.045, 0.24]} radius={0.01} position={[0, 0.66, 0.02]} material={MAT.deskTop} />- {[-1.05, 1.05].map((x) => <Rounded key={x} size={[0.16, 0.24, 0.16]} radius={0.02} position={[x, 0.805, 0.03]} material={CM.speaker} />)}- </group>- );-}--// ----------------------------------------------------------------------------// The desk with three monitors, and its chair-// -----------------------------------------------------------------------------const MONITOR = { w: 0.72, h: 0.42, y: 1.14 };-const MONITOR_CANVAS = { w: 1024, h: Math.round((1024 * 0.42) / 0.72) };-const DESK_Z = -COMMAND_DESK_OFFSET;-const CHAIR_Z = DESK_Z + COMMAND_DESK.chairZ;-const MUG = new CylinderGeometry(0.04, 0.036, 0.1, 16);--/** The boss chair's leather and chrome. */-const BOSS = {- leather: new MeshStandardMaterial({ color: "#17181b", roughness: 0.42, metalness: 0.05 }),- seam: new MeshStandardMaterial({ color: "#0c0d0f", roughness: 0.6 }),- chrome: new MeshStandardMaterial({ color: "#d4d8de", roughness: 0.16, metalness: 0.95 }),- caster: new MeshStandardMaterial({ color: "#101113", roughness: 0.5 }),-};-const GAS_LIFT = new CylinderGeometry(0.032, 0.032, 0.26, 16);-const SHROUD = new CylinderGeometry(0.055, 0.075, 0.1, 20);-/** Mission Control's chair is a seat the person can take (leadSeat); its id is the desk's. */-const COMMAND_SEAT = "command";--/**- * A high-back executive chair in black leather on a polished five-star base:- * a thick seat, four channel-stitched back cushions leaning back, a headrest,- * side bolsters and chrome armrests with leather pads. Local space: seat on- * the floor at the origin, the sitter faces -z, the back is on the +z side.- */-function BossChair() {- return (- <group>- {/* Chrome star base with casters, a shroud and the gas lift. */}- {[0, 1, 2, 3, 4].map((i) => (- <group key={i} rotation={[0, (i * Math.PI * 2) / 5 + Math.PI / 5, 0]}>- <Box size={[0.055, 0.035, 0.33]} position={[0, 0.085, 0.165]} material={BOSS.chrome} />- <Box size={[0.05, 0.06, 0.07]} position={[0, 0.03, 0.31]} material={BOSS.caster} cast={false} />- </group>- ))}- <mesh geometry={SHROUD} material={BOSS.leather} position={[0, 0.14, 0]} castShadow />- <mesh geometry={GAS_LIFT} material={BOSS.chrome} position={[0, 0.27, 0]} castShadow />- {/* Seat: a thick cushion on a dark frame, a stitch line round its top. */}- <Box size={[0.5, 0.04, 0.46]} position={[0, 0.4, 0]} material={BOSS.seam} />- <Rounded size={[0.62, 0.13, 0.58]} radius={0.055} position={[0, 0.48, -0.01]} material={BOSS.leather} />- <Box size={[0.52, 0.006, 0.48]} position={[0, 0.547, -0.01]} material={BOSS.seam} cast={false} />- {/* High back, leaning back: a shell, four stitched cushions, bolsters, the headrest. */}- <group position={[0, 0.56, 0.27]} rotation={[0.14, 0, 0]}>- <Rounded size={[0.6, 0.94, 0.07]} radius={0.04} position={[0, 0.47, 0.05]} material={BOSS.leather} />- {[0.14, 0.34, 0.54, 0.74].map((y) => (- <Rounded key={y} size={[0.48, 0.19, 0.1]} radius={0.045} position={[0, y, -0.01]} material={BOSS.leather} />- ))}- {[-0.28, 0.28].map((x) => (- <Rounded key={x} size={[0.07, 0.86, 0.13]} radius={0.03} position={[x, 0.45, 0.0]} material={BOSS.leather} />- ))}- <Rounded size={[0.42, 0.18, 0.12]} radius={0.05} position={[0, 0.98, 0.0]} material={BOSS.leather} />- </group>- {/* Chrome loop armrests with leather pads. */}- {[-0.34, 0.34].map((x) => (- <group key={x}>- <Box size={[0.03, 0.26, 0.03]} position={[x, 0.6, 0.12]} material={BOSS.chrome} />- <Box size={[0.03, 0.2, 0.03]} position={[x, 0.58, -0.14]} material={BOSS.chrome} />- <Rounded size={[0.08, 0.05, 0.36]} radius={0.02} position={[x, 0.74, -0.01]} material={BOSS.leather} />- </group>- ))}- </group>- );-}--/**- * The chair behind the desk: click it (or press E beside it) to sit down. While- * seated the camera looks through the person's eyes at the monitors, so the- * chair steps out of the way; any movement stands them up again.- */-function ExecutiveChair() {- const t = useT();- const seated = useLeadSeat((s) => s.seated === COMMAND_SEAT);- const near = useLeadSeat((s) => s.near === COMMAND_SEAT);- const hovered = useRef(false);- useEffect(() => () => { if (hovered.current) document.body.style.cursor = ""; }, []);- const takeSeat = (event: ThreeEvent<MouseEvent>) => {- if (event.delta > 6) return;- event.stopPropagation();- const at = new Vector3(0, 0, CHAIR_Z);- event.eventObject.parent?.localToWorld(at);- useLeadSeat.getState().set({ pending: COMMAND_SEAT });- useOfficeStore.getState().requestWalk({ x: at.x, z: at.z });- };- return (- <group position={[0, 0, CHAIR_Z]}>- <group visible={!seated} onClick={takeSeat}- onPointerOver={(event) => { event.stopPropagation(); hovered.current = true; document.body.style.cursor = "pointer"; }}- onPointerOut={() => { hovered.current = false; document.body.style.cursor = ""; }}>- <BossChair />- </group>- {near && !seated && (- <Html center position={[0, 1.75, 0]} zIndexRange={[24, 0]}>- <span className="office-plate office-seat-prompt" data-office-ui><kbd>E</kbd>{t("society.office.seat_sit")}</span>- </Html>- )}- {seated && (- // In first person this floats just under the monitors, where the eyes are.- <Html center position={[0, 0.86, -0.42]} zIndexRange={[24, 0]}>- <span className="office-plate office-seat-prompt" data-office-ui>{t("society.office.seat_seated_mission")}</span>- </Html>- )}- </group>- );-}--/** Run the live sections within this camera distance of the desk, stop beyond the second (no flicker at the edge). */-const LIVE_NEAR_M = 22;-const LIVE_FAR_M = 26;--/** Should the desk run its live sections, given the camera distance and whether it already does? Pure. */-export function deskLive(distance: number, live: boolean): boolean {- return distance <= (live ? LIVE_FAR_M : LIVE_NEAR_M);-}--/** True while the camera is close enough to `anchor` to read the monitors. */-function useNearCamera(anchor: RefObject<Group | null>): boolean {- const [near, setNear] = useState(false);- const nextCheck = useRef(0);- const at = useMemo(() => new Vector3(), []);- useFrame(({ camera, clock }) => {- if (!anchor.current || clock.elapsedTime < nextCheck.current) return;- nextCheck.current = clock.elapsedTime + 0.3;- anchor.current.getWorldPosition(at);- const next = deskLive(camera.position.distanceTo(at), near);- if (next !== near) setNear(next);- });- return near;-}--/** The glass sits this far in front of a monitor's centre (see Screen). */-const GLASS_Z = 0.0145;--/** A click on a monitor: dive into its glass (`size` metres, `glassZ` in front of its centre), then open its section. */-export function useMonitorDive(section: MonitorSection, size: [number, number] = [MONITOR.w, MONITOR.h], glassZ = GLASS_Z) {- const hovered = useRef(false);- useEffect(() => () => { if (hovered.current) document.body.style.cursor = ""; }, []);- return {- onClick: (event: ThreeEvent<MouseEvent>) => {- if (event.delta > 6) return;- event.stopPropagation();- const monitor = event.eventObject;- const centre = monitor.getWorldPosition(new Vector3());- const normal = new Vector3(0, 0, 1).applyQuaternion(monitor.getWorldQuaternion(new Quaternion()));- const glass = centre.addScaledVector(normal, glassZ);- useOfficeStore.getState().diveToSection(section, [glass.x, glass.y, glass.z], Math.atan2(normal.x, normal.z), size);- },- onPointerOver: (event: ThreeEvent<PointerEvent>) => { event.stopPropagation(); hovered.current = true; document.body.style.cursor = "zoom-in"; },- onPointerOut: (event: ThreeEvent<PointerEvent>) => { event.stopPropagation(); hovered.current = false; document.body.style.cursor = ""; },- };-}--function DeskMonitor({ section, title, detail, live, position, turn = 0 }: {- section: MonitorSection; title: string; detail: string; live: boolean; position: [number, number, number]; turn?: number;-}) {- const card = useLiveScreen(MONITOR_CANVAS.w, MONITOR_CANVAS.h, `${title}|${detail}`, (ctx, w, h) => drawTitleCard(ctx, w, h, title, detail));- const dive = useMonitorDive(section);- return (- <group position={position} rotation={[0, turn, 0]} {...dive}>- <Screen w={MONITOR.w} h={MONITOR.h} material={card} />- {live && <MissionLiveScreen section={section} widthM={MONITOR.w} position={[0, 0, GLASS_Z + 0.002]} />}- </group>- );-}--export function CommandDesk() {- const data = useFloorData();- const labels = useScreenLabels();- const open = useOpenMission();- const anchor = useRef<Group>(null);- const live = useNearCamera(anchor);- // The floor is open: fetch the sections' code now, not when the camera arrives.- useEffect(() => { preloadMissionScreens(); }, []);- const { w, d } = COMMAND_DESK;- const agentCount = `${data.counts.total} ${labels.agents}`;- return (- <group ref={anchor}>- <group {...open}>- {/* Oak top on black steel sled legs, a cable panel at the back and a thin light under the front edge. */}- <Rounded size={[w, 0.04, d]} radius={0.012} position={[0, 0.74, DESK_Z]} material={MAT.deskTop} />- {[-(w / 2 - 0.12), w / 2 - 0.12].map((x) => (- <group key={x}>- <Box size={[0.05, 0.72, d - 0.12]} position={[x, 0.36, DESK_Z]} material={MAT.deskLeg} />- <Box size={[0.07, 0.025, d - 0.06]} position={[x, 0.012, DESK_Z]} material={MAT.deskLeg} />- </group>- ))}- <Box size={[w - 0.4, 0.3, 0.02]} position={[0, 0.5, DESK_Z - d / 2 + 0.06]} material={MAT.deskLeg} />- <Box size={[w - 0.1, 0.01, 0.012]} position={[0, 0.715, DESK_Z + d / 2 - 0.02]} material={CM.ice} cast={false} />- {/* One triple arm: a post at the back and a bar carrying the three monitors, the outer two turned in. */}- <Box size={[0.05, 0.38, 0.05]} position={[0, 0.94, DESK_Z - 0.32]} material={MAT.monitorArm} />- <Box size={[1.7, 0.035, 0.035]} position={[0, MONITOR.y - 0.02, DESK_Z - 0.3]} material={MAT.monitorArm} />- <DeskMonitor section="agents" title={labels.agentsView} detail={labels.title} live={live}- position={[0, MONITOR.y, DESK_Z - 0.26]} />- <DeskMonitor section="costs" title={labels.costs} detail={labels.title} live={live}- position={[-0.76, MONITOR.y, DESK_Z - 0.17]} turn={0.38} />- <DeskMonitor section="agentic-ide" title={labels.ide} detail={agentCount} live={live}- position={[0.76, MONITOR.y, DESK_Z - 0.17]} turn={-0.38} />- {/* On the desk: keyboard, mouse, a mug. */}- <Rounded size={[0.46, 0.018, 0.15]} radius={0.006} position={[0, 0.769, DESK_Z + 0.18]} material={MAT.keyboard} />- <Rounded size={[0.06, 0.022, 0.1]} radius={0.01} position={[0.36, 0.771, DESK_Z + 0.18]} material={MAT.keyboard} />- <mesh geometry={MUG} material={MAT.mug} position={[-0.95, 0.81, DESK_Z + 0.1]} castShadow />- </group>- <ExecutiveChair />- </group>- );-}--/** Mission Control's renderers; merged into OfficeProps' exhaustive table. */-export const COMMAND_RENDERERS = {- commandWall: () => <CommandWall />,- commandDesk: () => <CommandDesk />,-} satisfies Partial<Record<FurnitureKind, (props: { item: Furniture }) => JSX.Element>>;diff --git a/dodaios/ui/web/frontend/src/components/society/office/CourierHud.tsx b/dodaios/ui/web/frontend/src/components/society/office/CourierHud.tsxdeleted file mode 100644index 95a9267d51..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/CourierHud.tsx+++ /dev/null@@ -1,161 +0,0 @@-/**- * The pilot's HUD while the courier flies: speed, height, throttle and boost,- * the flight assist and camera (both switchable here or by key), the landing- * assist, and stepping out once the ship stands on the pad. H shows every- * binding; Escape opens the settings, where any key can be rebound, pitch- * inverted and the engine's volume set. Theme tokens only, so light and dark- * mode both read.- */-import { useEffect, useState } from "react";-import { useT } from "@/i18n";-import { DEFAULT_BINDINGS, FLIGHT_ACTIONS, keyLabel, rebind, type FlightAction } from "./courierControls";-import { FLIGHT } from "./courierFlight";-import { useCourier } from "./courierStore";-import "./courierHud.css";--/** The keys of one action as a pilot reads them, each label once (left and right Shift are both "Shift"). */-function keysLabel(codes: readonly string[]): string {- return [...new Set(codes.map(keyLabel))].join(" / ") || "–";-}--function Meter({ label, value }: { label: string; value: number }) {- return (- <div className="courier-meter">- <span>{label}</span>- <i aria-hidden><b style={{ width: `${Math.round(Math.min(1, Math.max(0, value)) * 100)}%` }} /></i>- </div>- );-}--export function CourierHud() {- const t = useT();- const telemetry = useCourier((s) => s.telemetry);- const assist = useCourier((s) => s.assist);- const view = useCourier((s) => s.view);- const helpOpen = useCourier((s) => s.helpOpen);- const settingsOpen = useCourier((s) => s.settingsOpen);- const bindings = useCourier((s) => s.bindings);- const mouseLocked = useCourier((s) => s.mouseLocked);- const cursorAim = useCourier((s) => s.cursorAim);- const store = useCourier.getState;- const kmh = Math.round(telemetry.speed * 3.6);- const boostShare = Math.min(1, telemetry.speed / FLIGHT.boost);- const keysOf = (action: FlightAction) => keysLabel(bindings[action]);- return (- <>- {/* Placed by the scene each frame: where the pilot aims, and where the nose points. */}- <div id="courier-aim" className="courier-aim" aria-hidden />- <div id="courier-nose" className="courier-nose" aria-hidden />- <div className="courier-hud office-card" data-office-ui role="group" aria-label={t("society.office.flight_hud")}>- <div className="courier-speed" aria-live="off">- <strong>{kmh}</strong><span>km/h</span>- <i className="courier-speed-arc" aria-hidden style={{ ["--share" as string]: boostShare }} />- </div>- <div className="courier-readouts">- <span>{t("society.office.flight_altitude")} <strong>{Math.round(telemetry.altitude)} m</strong></span>- <Meter label={t("society.office.flight_throttle")} value={telemetry.throttle} />- <Meter label={t("society.office.flight_boost")} value={telemetry.charge} />- </div>- <div className="courier-actions">- <button type="button" className="office-chip" aria-pressed={assist === "simulation"}- onClick={() => store().setPrefs({ assist: assist === "arcade" ? "simulation" : "arcade" })}- title={`${t("society.office.flight_assist")} (${keysOf("assist")})`}>- {t(assist === "arcade" ? "society.office.flight_assist_arcade" : "society.office.flight_assist_simulation")}- </button>- <button type="button" className="office-chip" onClick={() => store().setPrefs({ view: view === "chase" ? "cockpit" : "chase" })}- title={keysOf("camera")}>- {t(view === "chase" ? "society.office.flight_view_chase" : "society.office.flight_view_cockpit")}- </button>- {telemetry.landed- ? <button type="button" className="office-chip courier-primary" onClick={() => store().requestExit()}>{t("society.office.flight_leave")}</button>- : telemetry.autopilot- ? <span className="courier-status">{t("society.office.flight_landing")}</span>- : <button type="button" className="office-chip" onClick={() => store().requestLanding()} title={keysOf("land")}>{t("society.office.flight_land")}</button>}- <button type="button" className="office-chip" aria-pressed={helpOpen} onClick={() => store().set({ helpOpen: !helpOpen })}>{t("society.office.flight_help")}</button>- <button type="button" className="office-chip" onClick={() => store().set({ settingsOpen: true })}>{t("society.office.flight_settings")}</button>- </div>- {telemetry.landed- ? <p className="office-hint">{t("society.office.flight_landed_hint").replace("{0}", keysOf("exit"))}</p>- : <p className="office-hint">{t(mouseLocked ? "society.office.flight_mouse_on" : cursorAim ? "society.office.flight_mouse_cursor" : "society.office.flight_mouse_hint")}</p>}- </div>- {helpOpen && !settingsOpen && (- <div className="courier-help office-card" data-office-ui>- <p className="office-subhead">{t("society.office.flight_keys")}</p>- <dl>- {FLIGHT_ACTIONS.map((action) => (- <div key={action}><dt>{t(`society.office.flight_action_${action}`)}</dt><dd><kbd>{keysOf(action)}</kbd></dd></div>- ))}- </dl>- <p className="office-hint">{t("society.office.flight_gamepad")}</p>- </div>- )}- {settingsOpen && <CourierSettings />}- </>- );-}--function CourierSettings() {- const t = useT();- // One selector per choice: the telemetry ticking eight times a second does not redraw the settings.- const assist = useCourier((s) => s.assist);- const view = useCourier((s) => s.view);- const invertPitch = useCourier((s) => s.invertPitch);- const volume = useCourier((s) => s.volume);- const bindings = useCourier((s) => s.bindings);- const store = useCourier.getState;- const [capturing, setCapturing] = useState<FlightAction | null>(null);- useEffect(() => {- if (!capturing) return;- const onKey = (event: KeyboardEvent) => {- event.preventDefault();- event.stopPropagation();- if (event.key !== "Escape") store().setBindings(rebind(store().bindings, capturing, event.code));- setCapturing(null);- };- window.addEventListener("keydown", onKey, true);- return () => window.removeEventListener("keydown", onKey, true);- }, [capturing, store]);- return (- <div className="courier-settings office-card" role="dialog" aria-modal="false" aria-label={t("society.office.flight_settings")} data-office-ui>- <div className="courier-settings-head">- <strong>{t("society.office.flight_settings")}</strong>- <button type="button" className="office-icon-button" aria-label={t("society.office.flight_close")} onClick={() => store().set({ settingsOpen: false })}>×</button>- </div>- <div className="courier-settings-row">- <span>{t("society.office.flight_assist")}</span>- {(["arcade", "simulation"] as const).map((a) => (- <button key={a} type="button" className="office-chip" aria-pressed={assist === a} onClick={() => store().setPrefs({ assist: a })}>- {t(`society.office.flight_assist_${a}`)}- </button>- ))}- </div>- <div className="courier-settings-row">- {(["chase", "cockpit"] as const).map((v) => (- <button key={v} type="button" className="office-chip" aria-pressed={view === v} onClick={() => store().setPrefs({ view: v })}>- {t(`society.office.flight_view_${v}`)}- </button>- ))}- </div>- <label className="courier-settings-row">- <input type="checkbox" checked={invertPitch} onChange={(e) => store().setPrefs({ invertPitch: e.target.checked })} />- <span>{t("society.office.flight_invert")}</span>- </label>- <label className="courier-settings-row">- <span>{t("society.office.flight_volume")}</span>- <input type="range" min={0} max={1} step={0.05} value={volume} onChange={(e) => store().setPrefs({ volume: Number(e.target.value) })} />- </label>- <p className="office-subhead">{t("society.office.flight_keys")}</p>- <div className="courier-bindings">- {FLIGHT_ACTIONS.map((action) => (- <div key={action} className="courier-binding">- <span>{t(`society.office.flight_action_${action}`)}</span>- <button type="button" className="office-chip" aria-pressed={capturing === action} onClick={() => setCapturing(action)}>- {capturing === action ? t("society.office.flight_rebind") : keysLabel(bindings[action])}- </button>- </div>- ))}- </div>- <button type="button" className="office-link" onClick={() => store().setBindings({ ...DEFAULT_BINDINGS })}>{t("society.office.flight_reset")}</button>- </div>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/DeskBusyLights.tsx b/dodaios/ui/web/frontend/src/components/society/office/DeskBusyLights.tsxdeleted file mode 100644index daac4ce477..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/DeskBusyLights.tsx+++ /dev/null@@ -1,97 +0,0 @@-/**- * A busy light on every occupied desk of the coding floor: a small frosted- * lamp on a brass foot at the desk's back corner, lit in the pane's state —- * green while it works, amber blinking while it waits for the person, red- * when it failed, a dim grey when idle. It stays on the desk while its agent- * walks off to the coffee bar, so a glance along a bench tells who needs you.- *- * Two instanced meshes for the whole floor; the lamp colours are rewritten a- * few times a second, not every frame.- */-import { useLayoutEffect, useMemo, useRef } from "react";-import { useFrame } from "@react-three/fiber";-import { Color, CylinderGeometry, InstancedMesh, Matrix4, MeshBasicMaterial, MeshStandardMaterial, Quaternion, Vector3 } from "three";-import type { AgentDotKind } from "@/components/agentic/sidePanel/agentStatus";-import type { PaneOccupant } from "./codingFloor";-import type { DeskSlot } from "./officeLayout";-import { CODING_SCENE } from "./officePalette";--/** Where the lamp stands in the desk's own frame (the agent sits at +z): the back corner beside the monitor. */-const LAMP_LOCAL = new Vector3(-0.6, 0.815, -0.28);-const FOOT = new CylinderGeometry(0.03, 0.034, 0.018, 16);-const LAMP = new CylinderGeometry(0.026, 0.03, 0.07, 16);-/** A moment at which the blinking waiting light is on: the still frame under reduced motion. */-const REST_T = 0.1;--const COLOURS: Record<AgentDotKind, Color> = {- working: new Color(CODING_SCENE.busy.working),- waiting: new Color(CODING_SCENE.busy.waiting),- error: new Color(CODING_SCENE.busy.error),- idle: new Color(CODING_SCENE.busy.idle),-};--/** A desk lamp's colour at time `t` (s): waiting blinks, failed breathes, the others hold. Pure. */-export function busyColour(state: AgentDotKind, t: number, out: Color): Color {- out.copy(COLOURS[state]);- if (state === "waiting") return out.multiplyScalar(Math.sin(t * 6) > 0 ? 1 : 0.2);- if (state === "error") return out.multiplyScalar(0.65 + 0.35 * (0.5 + 0.5 * Math.sin(t * 3)));- return out;-}--const FOOT_MAT = new MeshStandardMaterial({ color: CODING_SCENE.brass, roughness: 0.3, metalness: 0.6 });-/** Unlit, so the lamp reads as light in any scene lighting; each instance's colour is its state. */-const LAMP_MAT = new MeshBasicMaterial({ color: "#ffffff" });--const _m = new Matrix4(), _q = new Quaternion(), _p = new Vector3(), _one = new Vector3(1, 1, 1);-function lampMatrix(desk: DeskSlot, lift: number): Matrix4 {- const turn = desk.facing === "north" ? 0 : Math.PI;- const x = LAMP_LOCAL.x * Math.cos(turn) + LAMP_LOCAL.z * Math.sin(turn);- const z = -LAMP_LOCAL.x * Math.sin(turn) + LAMP_LOCAL.z * Math.cos(turn);- return _m.compose(_p.set(desk.x + x, LAMP_LOCAL.y + lift, desk.z + z), _q.identity(), _one);-}--export function DeskBusyLights({ desks, occupants, animate }: {- desks: readonly DeskSlot[]; occupants: ReadonlyMap<string, PaneOccupant>; animate: boolean;-}) {- const lit = useMemo(() => desks.flatMap((desk) => {- const occupant = desk.agentId ? occupants.get(desk.agentId) : undefined;- return occupant ? [{ desk, state: occupant.dot }] : [];- }), [desks, occupants]);- const foot = useRef<InstancedMesh>(null);- const lamp = useRef<InstancedMesh>(null);- const colour = useMemo(() => new Color(), []);- useLayoutEffect(() => {- lit.forEach(({ desk, state }, i) => {- foot.current?.setMatrixAt(i, lampMatrix(desk, 0));- lamp.current?.setMatrixAt(i, lampMatrix(desk, 0.044));- lamp.current?.setColorAt(i, busyColour(state, REST_T, colour));- });- for (const mesh of [foot.current, lamp.current]) {- if (!mesh) continue;- mesh.count = lit.length;- mesh.instanceMatrix.needsUpdate = true;- if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;- }- }, [lit, colour]);- const next = useRef(0);- useFrame(({ clock }) => {- const mesh = lamp.current;- if (!animate || !mesh || clock.elapsedTime < next.current) return;- next.current = clock.elapsedTime + 0.1;- let changed = false;- lit.forEach(({ state }, i) => {- if (state !== "waiting" && state !== "error") return;- mesh.setColorAt(i, busyColour(state, clock.elapsedTime, colour));- changed = true;- });- if (changed && mesh.instanceColor) mesh.instanceColor.needsUpdate = true;- });- if (lit.length === 0) return null;- // Remount when the count changes: an instanced mesh cannot grow in place.- return (- <group>- <instancedMesh key={`foot${lit.length}`} ref={foot} args={[FOOT, FOOT_MAT, lit.length]} castShadow frustumCulled={false} />- <instancedMesh key={`lamp${lit.length}`} ref={lamp} args={[LAMP, LAMP_MAT, lit.length]} frustumCulled={false} />- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/DeskDressing.tsx b/dodaios/ui/web/frontend/src/components/society/office/DeskDressing.tsxdeleted file mode 100644index aaa451f05a..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/DeskDressing.tsx+++ /dev/null@@ -1,315 +0,0 @@-/**- * Lived-in workstations. The coding floor: desk mats, laptops on stands,- * lamps, succulents, books, bottles, notebooks, headphones on hooks, sticky- * notes, cable trays under the benches, and a walnut planter at each bench- * end. The agents floor: letter trays, documents, tablets with a calendar,- * phone docks, pen cups, framed photos, takeaway coffee, leafy plants, brass- * lamps, pinned pages, and a slatted pale-oak planter at each bench end.- *- * `deskKit.ts` decides what goes where; this draws it as one instanced- * mesh per part type across the whole floor, rebuilt only when the desks- * change. Geometries and materials are module-level singletons.- */-import { useLayoutEffect, useMemo, useRef } from "react";-import {- BufferGeometry, Color, CylinderGeometry, Euler, IcosahedronGeometry, InstancedMesh, Matrix4, MeshStandardMaterial,- PlaneGeometry, Quaternion, TorusGeometry, Vector3, type Material,-} from "three";-import { RoundedBoxGeometry } from "three-stdlib";-import { cachedCanvasTexture } from "./canvasMaterials";-import {- dressDesk, dressOfficeDesk, kitPlacements, leadMarkPlacements, oakPlanterPlacements, officeKitPlacements, planterPlacements,- type DressingPart, type Placement,-} from "./deskKit";-import { GEO, MAT, matte } from "./OfficeFurniture";-import { benchPlanters, type Department, type DeskSlot, type OfficeVariant } from "./officeLayout";--/** A few lines of code in a dark editor, for the laptop screens. */-function drawLaptopScreen(ctx: CanvasRenderingContext2D, w: number, h: number): void {- ctx.fillStyle = "#15181f";- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "#1f2430";- ctx.fillRect(0, 0, w * 0.22, h);- const colours = ["#7dd3c0", "#c4a7f5", "#f0c987", "#8fb8f0", "#9aa3b2"];- let seed = 7;- for (let y = 8, line = 0; y < h - 4; y += 7, line += 1) {- seed = (seed * 1103515245 + 12345) >>> 0;- const indent = 4 + ((seed >>> 8) % 4) * 6;- let x = w * 0.22 + indent;- for (let word = 0; word < 1 + ((seed >>> 4) % 4); word += 1) {- const len = 8 + ((seed >>> (word * 3)) % 22);- ctx.fillStyle = colours[(line + word) % colours.length];- ctx.fillRect(x, y, len, 3);- x += len + 4;- }- }-}--const laptopScreen = (() => {- const map = cachedCanvasTexture("desk:laptop-code", 128, 80, drawLaptopScreen);- return new MeshStandardMaterial({- color: map ? "#ffffff" : "#1a1e27", map, roughness: 0.35,- emissive: "#ffffff", emissiveMap: map, emissiveIntensity: map ? 0.55 : 0,- });-})();--/** A week in a calendar app, for the tablets on the agents floor. */-function drawCalendar(ctx: CanvasRenderingContext2D, w: number, h: number): void {- ctx.fillStyle = "#f7f5f0";- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "#8fa58f";- ctx.fillRect(0, 0, w, 12);- ctx.fillStyle = "#e4dfd4";- const cols = 5, left = 10, colW = (w - left) / cols;- for (let i = 0; i <= cols; i += 1) ctx.fillRect(left + i * colW, 12, 1, h - 12);- for (let y = 22; y < h; y += 10) ctx.fillRect(left, y, w - left, 1);- const tones = ["#c98f6f", "#6f86a6", "#8fa58f", "#d8b36a", "#a58fb8"];- let seed = 11;- for (let col = 0; col < cols; col += 1) {- let y = 14;- while (y < h - 10) {- seed = (seed * 1103515245 + 12345) >>> 0;- y += ((seed >>> 8) % 3) * 10;- const len = 10 + ((seed >>> 4) % 3) * 10;- if (y + len > h - 2) break;- ctx.fillStyle = tones[(seed >>> 12) % tones.length];- ctx.fillRect(left + col * colW + 2, y + 1, colW - 4, len - 2);- y += len + 4;- }- }-}--/** A chat thread, for the phones. */-function drawMessages(ctx: CanvasRenderingContext2D, w: number, h: number): void {- ctx.fillStyle = "#1b1d22";- ctx.fillRect(0, 0, w, h);- let y = 10;- for (let i = 0; y < h - 12; i += 1) {- const mine = i % 3 === 1;- const bw = 22 + ((i * 17) % 18), bh = 8 + (i % 2) * 6;- ctx.fillStyle = mine ? "#7fa88a" : "#3a3e46";- ctx.fillRect(mine ? w - bw - 5 : 5, y, bw, bh);- y += bh + 5;- }-}--/** A printed page: a heading, body lines and a small chart block. */-function drawPage(ctx: CanvasRenderingContext2D, w: number, h: number): void {- ctx.fillStyle = "#fbfaf6";- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "#3a3d42";- ctx.fillRect(7, 8, w * 0.55, 4);- ctx.fillStyle = "#b9b4aa";- for (let y = 18, i = 0; y < h - 8; y += 5, i += 1) {- if (i === 5) {- ctx.fillStyle = "#9db09a";- ctx.fillRect(7, y, w * 0.4, 14);- ctx.fillStyle = "#b9b4aa";- y += 14;- continue;- }- ctx.fillRect(7, y, (w - 14) * (i % 4 === 3 ? 0.6 : 1), 2);- }-}--/** A holiday snapshot: a warm sky over hills and a lake. */-function drawPhoto(ctx: CanvasRenderingContext2D, w: number, h: number): void {- const sky = ctx.createLinearGradient(0, 0, 0, h * 0.6);- sky.addColorStop(0, "#9cc3e0");- sky.addColorStop(1, "#f3d3a8");- ctx.fillStyle = sky;- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "#fff1c9";- ctx.beginPath();- ctx.arc(w * 0.7, h * 0.36, w * 0.09, 0, Math.PI * 2);- ctx.fill();- ctx.fillStyle = "#7d9a78";- ctx.beginPath();- ctx.moveTo(0, h * 0.6);- ctx.quadraticCurveTo(w * 0.3, h * 0.38, w * 0.55, h * 0.56);- ctx.quadraticCurveTo(w * 0.8, h * 0.44, w, h * 0.55);- ctx.lineTo(w, h);- ctx.lineTo(0, h);- ctx.fill();- ctx.fillStyle = "#6d8fa8";- ctx.fillRect(0, h * 0.7, w, h * 0.3);- ctx.fillStyle = "#3a3d42";- ctx.fillRect(w * 0.3, h * 0.6, 3, 9);- ctx.fillRect(w * 0.36, h * 0.62, 3, 7);-}--/** A canvas-drawn face; self-lit when `glow` > 0, on a white base so instance colours tint it. */-function faceMaterial(- key: string, w: number, h: number, draw: (ctx: CanvasRenderingContext2D, w: number, h: number) => void, fallback: string, glow = 0,-): MeshStandardMaterial {- const map = cachedCanvasTexture(key, w, h, draw);- return new MeshStandardMaterial({- color: map ? "#ffffff" : fallback, map, roughness: glow > 0 ? 0.35 : 0.85,- emissive: glow > 0 ? "#ffffff" : "#000000", emissiveMap: glow > 0 ? map : null, emissiveIntensity: map ? glow : 0,- });-}--/** White base for parts coloured per instance. */-const tintedMatte = matte("#ffffff", { roughness: 0.8 });-const tintedGloss = matte("#ffffff", { roughness: 0.4 });-const tintedLeaf = matte("#ffffff", { roughness: 0.75, flatShading: true });-const aluminium = matte("#c7ccd3", { roughness: 0.35, metalness: 0.55 });-const blackMetal = matte("#23262c", { roughness: 0.55, metalness: 0.3 });-const brass = matte("#b8914f", { roughness: 0.32, metalness: 0.75 });-const graphite = matte("#2a2c31", { roughness: 0.4, metalness: 0.3 });--/**- * `cast`: only what is large enough for its shadow to show at the floor's scale (lamp shades, planters and their- * foliage). Every casting part is drawn a second time into the shadow map; a cup's shadow is not worth that.- */-interface PartSpec { geometry: BufferGeometry; material: Material; tinted: boolean; cast: boolean }--const PARTS: Record<DressingPart, PartSpec> = {- mat: { geometry: new RoundedBoxGeometry(0.82, 0.004, 0.34, 1, 0.002), material: tintedMatte, tinted: true, cast: false },- standPlate: { geometry: GEO.box, material: aluminium, tinted: false, cast: false },- standLeg: { geometry: GEO.box, material: aluminium, tinted: false, cast: false },- laptopBase: { geometry: new RoundedBoxGeometry(0.3, 0.012, 0.21, 1, 0.005), material: aluminium, tinted: false, cast: false },- laptopLid: { geometry: new RoundedBoxGeometry(0.3, 0.2, 0.007, 1, 0.003), material: aluminium, tinted: false, cast: false },- laptopScreen: { geometry: new PlaneGeometry(0.28, 0.18), material: laptopScreen, tinted: false, cast: false },- lampBase: { geometry: GEO.cyl, material: tintedGloss, tinted: true, cast: false },- lampArm: { geometry: GEO.cyl, material: tintedGloss, tinted: true, cast: false },- lampShade: { geometry: new CylinderGeometry(0.45, 1, 1, 16), material: tintedGloss, tinted: true, cast: true },- lampBulb: {- geometry: GEO.cyl, tinted: false, cast: false,- material: new MeshStandardMaterial({ color: "#fff2d6", emissive: "#ffd89a", emissiveIntensity: 1.6, toneMapped: false }),- },- pot: { geometry: GEO.potCyl, material: tintedGloss, tinted: true, cast: false },- soil: { geometry: GEO.cyl, material: MAT.soil, tinted: false, cast: false },- succulent: { geometry: new IcosahedronGeometry(1, 0), material: tintedLeaf, tinted: true, cast: false },- book: { geometry: GEO.box, material: tintedMatte, tinted: true, cast: false },- bottle: { geometry: GEO.cyl, material: tintedGloss, tinted: true, cast: false },- bottleCap: { geometry: GEO.cyl, material: blackMetal, tinted: false, cast: false },- notebook: { geometry: GEO.box, material: tintedMatte, tinted: true, cast: false },- notebookBand: { geometry: GEO.box, material: blackMetal, tinted: false, cast: false },- pen: { geometry: GEO.cyl, material: blackMetal, tinted: false, cast: false },- hook: { geometry: GEO.box, material: blackMetal, tinted: false, cast: false },- headband: { geometry: new TorusGeometry(0.08, 0.01, 8, 24, Math.PI), material: tintedMatte, tinted: true, cast: false },- earCup: { geometry: GEO.cyl, material: tintedMatte, tinted: true, cast: false },- note: { geometry: new PlaneGeometry(0.065, 0.065), material: tintedMatte, tinted: true, cast: false },- tray: { geometry: GEO.box, material: blackMetal, tinted: false, cast: false },- snake: { geometry: new CylinderGeometry(1, 1, 1, 10), material: blackMetal, tinted: false, cast: false },- puck: { geometry: GEO.box, material: aluminium, tinted: false, cast: false },- planterBody: { geometry: GEO.box, material: matte("#7a563b", { roughness: 0.7 }), tinted: false, cast: true },- planterPlinth: { geometry: GEO.box, material: blackMetal, tinted: false, cast: false },- planterRail: { geometry: GEO.box, material: MAT.wood, tinted: false, cast: false },- planterSoil: { geometry: GEO.box, material: MAT.soil, tinted: false, cast: false },- foliage: { geometry: GEO.blob, material: tintedLeaf, tinted: true, cast: true },- blade: { geometry: new CylinderGeometry(0.15, 1, 1, 4), material: tintedLeaf, tinted: true, cast: false },- letterTray: { geometry: GEO.box, material: tintedGloss, tinted: true, cast: false },- trayPost: { geometry: GEO.cyl, material: brass, tinted: false, cast: false },- paper: { geometry: GEO.box, material: tintedMatte, tinted: true, cast: false },- page: { geometry: new PlaneGeometry(1, 1), material: faceMaterial("desk:page", 64, 88, drawPage, "#fbfaf6"), tinted: false, cast: false },- folder: { geometry: GEO.box, material: tintedMatte, tinted: true, cast: false },- tabletBody: { geometry: new RoundedBoxGeometry(0.24, 0.17, 0.008, 1, 0.004), material: graphite, tinted: false, cast: false },- tabletScreen: {- geometry: new PlaneGeometry(0.224, 0.154), material: faceMaterial("desk:calendar", 128, 88, drawCalendar, "#e9e5dc", 0.45), tinted: false, cast: false,- },- tabletStand: { geometry: GEO.box, material: brass, tinted: false, cast: false },- phoneBody: { geometry: new RoundedBoxGeometry(0.072, 0.15, 0.008, 1, 0.004), material: graphite, tinted: false, cast: false },- phoneScreen: {- geometry: new PlaneGeometry(0.064, 0.138), material: faceMaterial("desk:messages", 64, 128, drawMessages, "#1b1d22", 0.5), tinted: false, cast: false,- },- dock: { geometry: GEO.box, material: aluminium, tinted: false, cast: false },- penCup: { geometry: GEO.cyl, material: tintedGloss, tinted: true, cast: false },- pencil: { geometry: GEO.cyl, material: tintedGloss, tinted: true, cast: false },- frame: { geometry: GEO.box, material: tintedGloss, tinted: true, cast: false },- photo: { geometry: new PlaneGeometry(1, 1), material: faceMaterial("desk:photo", 64, 84, drawPhoto, "#c9b99c"), tinted: true, cast: false },- cup: { geometry: new CylinderGeometry(1, 0.78, 1, 16), material: tintedMatte, tinted: true, cast: false },- cupLid: { geometry: GEO.cyl, material: tintedGloss, tinted: true, cast: false },- cupSleeve: { geometry: new CylinderGeometry(1, 0.9, 1, 16), material: matte("#b98b5e", { roughness: 0.9 }), tinted: false, cast: false },- oakPlanter: { geometry: GEO.box, material: matte("#d8bd91", { roughness: 0.7 }), tinted: false, cast: true },- oakSlat: { geometry: GEO.box, material: matte("#caa574", { roughness: 0.65 }), tinted: false, cast: false },- brassTrim: { geometry: GEO.box, material: brass, tinted: false, cast: false },- felt: { geometry: GEO.box, material: tintedMatte, tinted: true, cast: false },-};-const PART_KEYS = Object.keys(PARTS) as DressingPart[];--interface Batch { matrices: Matrix4[]; colours: Color[] }--const euler = new Euler(0, 0, 0, "YXZ");-const quat = new Quaternion();-const pos = new Vector3();-const scl = new Vector3();--/** A placement's own transform: where it stands in its space (a desk's, or the world's), turned and sized. */-export function placementMatrix(part: Placement): Matrix4 {- const [rx, ry, rz] = part.r ?? [0, 0, 0];- euler.set(rx, ry, rz, "YXZ");- return new Matrix4().compose(pos.set(...part.p), quat.setFromEuler(euler), scl.set(...(part.s ?? [1, 1, 1])));-}--/**- * Every instance of every part on the floor: desk kits (desk space → world) and planters (already world space).- * The coding floor carries the developer's kit and walnut planters, the agents floor the office kit and oak planters.- */-const NO_SIGNS: ReadonlyMap<string, string> = new Map();--export function buildDressing(- desks: readonly DeskSlot[], departments: readonly Department[], floor: OfficeVariant = "coding",- /** Desk id -> the team's colour, for the desks a team lead sits at: each is marked as the lead's place. */- leadSigns: ReadonlyMap<string, string> = NO_SIGNS,-): Map<DressingPart, Batch> {- const batches = new Map<DressingPart, Batch>(PART_KEYS.map((k) => [k, { matrices: [], colours: [] }]));- const add = (part: Placement, world?: Matrix4) => {- const batch = batches.get(part.part)!;- const local = placementMatrix(part);- batch.matrices.push(world ? world.clone().multiply(local) : local);- batch.colours.push(new Color(part.c ?? "#ffffff"));- };- for (const desk of desks) {- const turn = desk.facing === "north" ? 0 : Math.PI;- const world = new Matrix4().makeRotationY(turn).setPosition(desk.x, 0, desk.z);- const occupied = desk.agentId !== null;- const lead = leadSigns.get(desk.id);- // The lead's name stand takes the front right corner, where a phone would lie.- const kit = floor === "coding" ? kitPlacements(dressDesk(desk.id, occupied))- : officeKitPlacements({ ...dressOfficeDesk(desk.id, occupied), ...(lead === undefined ? {} : { phone: false }) });- for (const part of kit) add(part, world);- if (lead !== undefined) for (const part of leadMarkPlacements(lead)) add(part, world);- }- const planter = floor === "coding" ? planterPlacements : oakPlanterPlacements;- for (const dept of departments) {- for (const { key, rect } of benchPlanters(dept)) for (const part of planter(rect, key)) add(part);- }- return batches;-}--function PartInstances({ spec, batch }: { spec: PartSpec; batch: Batch }) {- const ref = useRef<InstancedMesh>(null);- useLayoutEffect(() => {- const mesh = ref.current;- if (!mesh) return;- batch.matrices.forEach((m, i) => {- mesh.setMatrixAt(i, m);- if (spec.tinted) mesh.setColorAt(i, batch.colours[i]);- });- mesh.count = batch.matrices.length;- mesh.instanceMatrix.needsUpdate = true;- if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;- mesh.computeBoundingSphere();- }, [spec, batch]);- return <instancedMesh ref={ref} args={[spec.geometry, spec.material, batch.matrices.length]} castShadow={spec.cast} receiveShadow frustumCulled={false} />;-}--/** The dressing of every bench desk on the floor and the planters of every department's benches. */-export function DeskDressing({ desks, departments, floor = "coding", leadSigns = NO_SIGNS }: {- desks: readonly DeskSlot[]; departments: readonly Department[]; floor?: OfficeVariant;- /** Desk id -> the team's colour, for the desks a team lead sits at. */- leadSigns?: ReadonlyMap<string, string>;-}) {- const batches = useMemo(() => buildDressing(desks, departments, floor, leadSigns), [desks, departments, floor, leadSigns]);- return (- <group>- {PART_KEYS.map((key) => {- const batch = batches.get(key)!;- // Keyed by count: an InstancedMesh cannot grow in place.- return batch.matrices.length > 0 ? <PartInstances key={`${key}:${batch.matrices.length}`} spec={PARTS[key]} batch={batch} /> : null;- })}- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/DeskInstances.tsx b/dodaios/ui/web/frontend/src/components/society/office/DeskInstances.tsxdeleted file mode 100644index 2e9333037f..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/DeskInstances.tsx+++ /dev/null@@ -1,161 +0,0 @@-/**- * Every workstation on the floor, drawn as instanced meshes: one draw call- * per desk part instead of one per part per desk. The agent sits at local +z- * and looks north at its monitor; a desk facing south is rotated half a turn.- *- * The workstation is a contemporary bench desk: a light-oak top on black- * steel T-legs, a felt privacy screen, a slim monitor on an arm, a white- * pedestal, and an ergonomic mesh-back task chair (OfficeChairs.tsx). The- * felt screen and the seat fabric take the department's zone colour through- * per-instance colours, so a department reads as one team at a glance. A- * coding-floor studio passes a `tone` instead, which swaps whole materials by- * part role.- */-import { useLayoutEffect, useMemo, useRef } from "react";-import {- BufferGeometry, Color, Euler, InstancedMesh, Matrix4, PlaneGeometry, Quaternion, Vector3, type Material, type MeshStandardMaterial,-} from "three";-import { RoundedBoxGeometry } from "three-stdlib";-import type { SocietyAgent } from "../data";-import { CHAIR_MAT, TASK_CHAIR_PARTS, type ChairFinish } from "./OfficeChairs";-import { GEO, MAT, screenMaterial } from "./OfficeFurniture";-import type { DeskSlot } from "./officeLayout";-import { DEPARTMENT_ZONES } from "./officePalette";-import type { ScreenFace } from "./screenTextures";--/** Which zone colour a tinted part takes: the felt screen's panel tone or the seat fabric. */-type Tint = "panel" | "seat";--/** Which surface of a workstation a part is; a desk tone recolours parts by role. */-type PartRole = "top" | "body" | "leg" | "monitor" | "keyboard" | "chair" | "seat" | "chrome" | "mesh";--/** Parts every room keeps as they are: the monitor, keyboard, and the chair's polished base and mesh back. */-type FixedRole = "monitor" | "keyboard" | "chrome" | "mesh";-const FIXED_ROLES: ReadonlySet<PartRole> = new Set<FixedRole>(["monitor", "keyboard", "chrome", "mesh"]);--/** Per-department materials for the parts that carry a room's style. */-export type DeskTone = Partial<Record<Exclude<PartRole, FixedRole>, MeshStandardMaterial>>;--interface Part {- role: PartRole;- geometry: BufferGeometry;- material: Material;- position: [number, number, number];- scale?: [number, number, number];- /** Turn about the part's own vertical axis (radians). */- rotY?: number;- tint?: Tint;- cast: boolean;-}--const CHAIR_Z = 0.62;-const rounded = (w: number, h: number, d: number, r: number) => new RoundedBoxGeometry(w, h, d, 1, r);--/** The task chair's finishes as desk part roles: the frame and fabric follow a desk tone, metal and mesh stay. */-const CHAIR_ROLE: Record<ChairFinish, PartRole> = { frame: "chair", fabric: "seat", metal: "chrome", mesh: "mesh" };-const CHAIR_MATERIAL: Record<ChairFinish, Material> = { frame: MAT.chair, fabric: MAT.tinted, metal: CHAIR_MAT.aluminium, mesh: CHAIR_MAT.mesh };--const PARTS: Part[] = [- // Desk: top surface at 0.77 m, as before, so hands and keyboards line up with the seated pose.- { role: "top", geometry: rounded(1.5, 0.035, 0.8, 0.015), material: MAT.deskTop, position: [0, 0.7525, 0], cast: true },- ...[-0.64, 0.64].flatMap((x): Part[] => [- { role: "leg", geometry: GEO.box, material: MAT.deskLeg, position: [x, 0.36, 0], scale: [0.06, 0.72, 0.05], cast: true },- { role: "leg", geometry: GEO.box, material: MAT.deskLeg, position: [x, 0.015, 0], scale: [0.06, 0.03, 0.72], cast: false },- { role: "leg", geometry: GEO.box, material: MAT.deskLeg, position: [x, 0.72, 0], scale: [0.05, 0.03, 0.68], cast: false },- ]),- { role: "leg", geometry: GEO.box, material: MAT.deskLeg, position: [0, 0.68, -0.2], scale: [1.24, 0.05, 0.04], cast: false },- // Mobile pedestal under the desk's right side.- { role: "body", geometry: rounded(0.4, 0.56, 0.5, 0.03), material: MAT.deskBody, position: [0.44, 0.3, -0.12], cast: true },- // Felt privacy screen between the back-to-back pair.- { role: "body", geometry: rounded(1.46, 0.36, 0.03, 0.012), material: MAT.tinted, position: [0, 0.95, -0.41], tint: "panel", cast: true },- // Slim monitor on an arm clamped to the back edge.- { role: "monitor", geometry: GEO.box, material: MAT.monitorArm, position: [0, 0.795, -0.33], scale: [0.08, 0.05, 0.06], cast: false },- { role: "monitor", geometry: GEO.cyl, material: MAT.monitorArm, position: [0, 0.95, -0.33], scale: [0.018, 0.32, 0.018], cast: true },- { role: "monitor", geometry: GEO.box, material: MAT.monitorArm, position: [0, 1.1, -0.28], scale: [0.04, 0.03, 0.1], cast: false },- { role: "monitor", geometry: rounded(0.72, 0.43, 0.022, 0.012), material: MAT.monitor, position: [0, 1.18, -0.224], cast: true },- // Keyboard, mouse and a mug.- { role: "keyboard", geometry: GEO.box, material: MAT.keyboard, position: [0, 0.777, 0.22], scale: [0.44, 0.014, 0.13], cast: true },- { role: "keyboard", geometry: GEO.box, material: MAT.keyboard, position: [0.33, 0.78, 0.22], scale: [0.05, 0.02, 0.08], cast: false },- { role: "keyboard", geometry: GEO.cyl, material: MAT.mug, position: [-0.52, 0.815, 0.02], scale: [0.035, 0.09, 0.035], cast: true },- // Chair: the ergonomic task chair (seat top 0.52 m) from OfficeChairs, behind the desk.- ...TASK_CHAIR_PARTS.map((part): Part => ({- role: CHAIR_ROLE[part.finish], geometry: part.geometry, material: CHAIR_MATERIAL[part.finish], position: [0, 0, CHAIR_Z],- tint: part.finish === "fabric" ? "seat" : undefined, cast: part.cast,- })),-];--const SCREEN_GEOMETRY = new PlaneGeometry(0.66, 0.38);-const SCREEN_LOCAL: [number, number, number] = [0, 1.18, -0.212];-const FACES: ScreenFace[] = ["working", "idle", "waiting", "paused", "empty"];--function deskMatrix(desk: DeskSlot, local: [number, number, number], scale: [number, number, number] = [1, 1, 1], rotY = 0): Matrix4 {- const turn = desk.facing === "north" ? 0 : Math.PI;- const world = new Matrix4().compose(new Vector3(desk.x, 0, desk.z), new Quaternion().setFromEuler(new Euler(0, turn, 0)), new Vector3(1, 1, 1));- const part = new Matrix4().compose(new Vector3(...local), new Quaternion().setFromEuler(new Euler(0, rotY, 0)), new Vector3(...scale));- return world.multiply(part);-}--const zoneColours = DEPARTMENT_ZONES.map((z) => ({ panel: new Color(z.panel), seat: new Color(z.seat) }));--function PartInstances({ part, desks, zones, material, tinted }: {- part: Part; desks: DeskSlot[]; zones: ReadonlyMap<string, number>; material: Material; tinted: boolean;-}) {- const ref = useRef<InstancedMesh>(null);- useLayoutEffect(() => {- const mesh = ref.current;- if (!mesh) return;- desks.forEach((desk, i) => {- mesh.setMatrixAt(i, deskMatrix(desk, part.position, part.scale, part.rotY));- if (tinted && part.tint) mesh.setColorAt(i, zoneColours[(zones.get(desk.id) ?? 0) % zoneColours.length][part.tint]);- });- mesh.count = desks.length;- mesh.instanceMatrix.needsUpdate = true;- if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;- mesh.computeBoundingSphere();- }, [desks, part, zones, tinted]);- return <instancedMesh ref={ref} args={[part.geometry, material, Math.max(1, desks.length)]} castShadow={part.cast} receiveShadow frustumCulled={false} />;-}--function ScreenInstances({ face, desks }: { face: ScreenFace; desks: DeskSlot[] }) {- const ref = useRef<InstancedMesh>(null);- useLayoutEffect(() => {- const mesh = ref.current;- if (!mesh) return;- desks.forEach((desk, i) => mesh.setMatrixAt(i, deskMatrix(desk, SCREEN_LOCAL)));- mesh.count = desks.length;- mesh.instanceMatrix.needsUpdate = true;- }, [desks]);- // Remount when the capacity must grow; InstancedMesh cannot resize in place.- return <instancedMesh key={Math.max(1, desks.length)} ref={ref} args={[SCREEN_GEOMETRY, screenMaterial(face), Math.max(1, desks.length)]} frustumCulled={false} />;-}--const NO_ZONES: ReadonlyMap<string, number> = new Map();--/**- * All desks with the monitor face each one's agent state calls for; `zones`- * maps a desk id to its department's zone colour (desks without one take the- * first), and `tone` swaps the desk and chair materials by role instead.- */-export function DeskInstances({ desks, agents, zones = NO_ZONES, tone }: {- desks: DeskSlot[]; agents: ReadonlyMap<string, SocietyAgent>; zones?: ReadonlyMap<string, number>; tone?: DeskTone;-}) {- const byFace = useMemo(() => {- const groups = new Map<ScreenFace, DeskSlot[]>(FACES.map((f) => [f, []]));- for (const desk of desks) {- const agent = desk.agentId ? agents.get(desk.agentId) : undefined;- groups.get(agent ? agent.state : "empty")!.push(desk);- }- return groups;- }, [desks, agents]);- return (- <group>- {PARTS.map((part, i) => {- const override = FIXED_ROLES.has(part.role) ? undefined : tone?.[part.role as Exclude<PartRole, FixedRole>];- const material = override ?? part.material;- return <PartInstances key={`${i}:${desks.length}:${material.uuid}`} part={part} desks={desks} zones={zones}- material={material} tinted={!override} />;- })}- {FACES.map((face) => (byFace.get(face)!.length > 0 ? <ScreenInstances key={face} face={face} desks={byFace.get(face)!} /> : null))}- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/ElevatorCallButton.tsx b/dodaios/ui/web/frontend/src/components/society/office/ElevatorCallButton.tsxdeleted file mode 100644index 346ef0f31a..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/ElevatorCallButton.tsx+++ /dev/null@@ -1,115 +0,0 @@-/**- * The elevator's call button, on the shaft to the right of the doors.- *- * Riding needs a press of this button: a click on it (or E while standing at- * the elevator) opens the floor picker; picking a floor lights it, then the- * doors close. The ground floor shows an up arrow, the top floor a down- * arrow, the floors between both. While the person stands at the elevator it- * breathes softly (the HUD's prompt names the press); clicking it from afar- * only walks the character over (see `elevatorCall.ts`).- */-import { useEffect, useMemo, useRef } from "react";-import { useFrame, type ThreeEvent } from "@react-three/fiber";-import { MeshStandardMaterial } from "three";-import { cachedCanvasTexture } from "./canvasMaterials";-import { callButtonPose } from "./elevatorCall";-import type { Furniture } from "./officeLayout";-import { floorLevel, OFFICE_FLOORS, type OfficeFloor } from "./officeStore";--const BUTTON_RADIUS = 0.09;-const IDLE = "#3b3f48";-const LIT = "#f5b83d";--type ArrowDirection = "up" | "down" | "both";--/** Which way the elevator can go from `floor`: up from the bottom, down from the top, both in between. */-export function callDirection(floor: OfficeFloor): ArrowDirection {- const level = floorLevel(floor);- return level <= 0 ? "up" : level >= OFFICE_FLOORS.length - 1 ? "down" : "both";-}--/** White arrows on a transparent square; "up" points to +y, "both" stacks a small up and down arrow. */-function arrowTexture(direction: ArrowDirection) {- return cachedCanvasTexture(`elevator-arrow:${direction}`, 128, 128, (ctx, w, h) => {- ctx.clearRect(0, 0, w, h);- ctx.fillStyle = "#ffffff";- const arrow = (up: boolean, top: number, bottom: number, half: number) => {- ctx.beginPath();- ctx.moveTo(w / 2, up ? top : bottom);- ctx.lineTo(w / 2 - half, up ? bottom : top);- ctx.lineTo(w / 2 + half, up ? bottom : top);- ctx.closePath();- ctx.fill();- };- if (direction === "both") {- arrow(true, h * 0.14, h * 0.44, w * 0.22);- arrow(false, h * 0.56, h * 0.86, w * 0.22);- } else {- arrow(direction === "up", h * 0.24, h * 0.76, w * 0.26);- }- });-}--export function ElevatorCallButton({ shaft, floor, near, lit, animate, onPress }: {- shaft: Furniture;- floor: OfficeFloor;- /** The person stands at the elevator: the button invites a press. */- near: boolean;- /** Pressed: glowing until the ride starts. */- lit: boolean;- animate: boolean;- onPress: () => void;-}) {- const pose = callButtonPose(shaft);- const direction = callDirection(floor);- const button = useMemo(() => new MeshStandardMaterial({ color: IDLE, roughness: 0.35, metalness: 0.3, emissive: LIT, emissiveIntensity: 0 }), []);- const arrow = useMemo(() => new MeshStandardMaterial({- map: arrowTexture(direction), transparent: true, depthWrite: false, roughness: 0.5,- emissive: "#ffffff", emissiveIntensity: 0.25,- }), [direction]);- useEffect(() => () => button.dispose(), [button]);- useEffect(() => () => arrow.dispose(), [arrow]);- useEffect(() => () => { document.body.style.cursor = ""; }, []);-- const pulse = useRef(0);- useFrame((_, delta) => {- if (lit) { button.color.set(LIT); button.emissiveIntensity = 1.1; return; }- button.color.set(IDLE);- if (near && animate) {- pulse.current += delta;- button.emissiveIntensity = 0.25 + (Math.sin(pulse.current * 4) + 1) * 0.2;- } else {- button.emissiveIntensity = near ? 0.45 : 0;- }- });-- const press = (event: ThreeEvent<MouseEvent>) => {- // A drag that ends on the button rotated the camera; only a real click presses.- if (event.delta > 6) return;- event.stopPropagation();- onPress();- };-- return (- <group position={[pose.x, pose.y, pose.z]} rotation={[0, pose.rotationY, 0]} name="elevator-call-button">- {/* The steel plate covers the shaft's painted indicator. */}- <mesh position={[0, 0, -0.005]}>- <boxGeometry args={[0.26, 0.44, 0.02]} />- <meshStandardMaterial color="#c7ccd4" roughness={0.35} metalness={0.3} />- </mesh>- <mesh rotation={[Math.PI / 2, 0, 0]} position={[0, 0, 0.012]} material={button}>- <cylinderGeometry args={[BUTTON_RADIUS, BUTTON_RADIUS, 0.02, 32]} />- </mesh>- <mesh position={[0, 0, 0.0231]} material={arrow} raycast={() => null}>- <planeGeometry args={[BUTTON_RADIUS * 1.6, BUTTON_RADIUS * 1.6]} />- </mesh>- {/* The click target: a see-through pad a little larger than the button, so it is easy to hit from a distance. */}- <mesh position={[0, 0, 0.03]} onClick={press}- onPointerOver={(event) => { event.stopPropagation(); document.body.style.cursor = "pointer"; }}- onPointerOut={() => { document.body.style.cursor = ""; }}>- <planeGeometry args={[0.32, 0.5]} />- <meshBasicMaterial transparent opacity={0} depthWrite={false} />- </mesh>- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/ElevatorDoors.tsx b/dodaios/ui/web/frontend/src/components/society/office/ElevatorDoors.tsxdeleted file mode 100644index 9d5b3572e9..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/ElevatorDoors.tsx+++ /dev/null@@ -1,23 +0,0 @@-/**- * The floor change: the elevator's two brushed-steel doors slide shut over- * the stage, the floor switches behind them, and they slide open on the new- * floor. OfficeStage owns the timing; this only draws the phase it is given.- * Part of the diorama: one palette in light and dark mode. Reduced motion:- * the doors appear and disappear without sliding.- */-import { useT } from "@/i18n";-import { floorLevel, type OfficeFloor } from "./officeStore";--export type DoorsPhase = "closing" | "closed" | "opening";--export function ElevatorDoors({ from, to, phase }: { from: OfficeFloor; to: OfficeFloor; phase: DoorsPhase }) {- const t = useT();- const up = floorLevel(to) > floorLevel(from);- return (- <div className="office-doors" data-phase={phase} role="status" aria-live="polite"- aria-label={t(up ? "society.office.riding_up_to" : "society.office.riding_down_to").replace("{0}", t(`society.office.floor_name_${to}`))}>- <i className="office-doors-leaf" data-side="left" aria-hidden />- <i className="office-doors-leaf" data-side="right" aria-hidden />- </div>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/ElevatorPanel.tsx b/dodaios/ui/web/frontend/src/components/society/office/ElevatorPanel.tsxdeleted file mode 100644index bb380fe1ae..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/ElevatorPanel.tsx+++ /dev/null@@ -1,116 +0,0 @@-/**- * The elevator's floor picker: pressing the call button (click, or E at the- * doors) opens the elevator's button panel. A steel plate with the floor- * indicator on top and one round push button per floor, top floor first,- * each with the floor's name engraved beside it. The floor you are on shows- * in the indicator and cannot be pressed. A pressed button lights its rim- * for a moment, then the panel closes and the doors start to move.- *- * Keys: the floor's number (0 to 3) presses it, arrows move between the- * buttons, Escape (or E) closes. It is a dialog, so the character stands- * still while it is open (`ownsKeyboard`). Part of the diorama: one steel- * palette in light and dark mode.- */-import { useEffect, useRef, useState } from "react";-import { useReducedMotion } from "framer-motion";-import { useT } from "@/i18n";-import { floorLevel, OFFICE_FLOORS, type OfficeFloor } from "./officeStore";--/** The floors as the panel lists them: top floor first, like a real elevator panel. */-export const PANEL_FLOORS: readonly OfficeFloor[] = [...OFFICE_FLOORS].reverse();--/** How long a pressed button stays lit before the panel hands the floor on. */-export const BUTTON_PRESS_MS = 280;--/** The floor a number key picks ("0" = ground floor), or null. */-export function floorForKey(key: string): OfficeFloor | null {- const level = /^[0-9]$/.test(key) ? Number(key) : -1;- return OFFICE_FLOORS[level] ?? null;-}--export function ElevatorPanel({ floor, onPick, onClose }: {- floor: OfficeFloor;- onPick: (floor: OfficeFloor) => void;- onClose: () => void;-}) {- const t = useT();- const reduced = useReducedMotion() ?? false;- const list = useRef<HTMLDivElement>(null);- const [pressed, setPressed] = useState<OfficeFloor | null>(null);- const pressTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);- useEffect(() => () => clearTimeout(pressTimer.current), []);-- // A ref, so the capture-phase key listener always calls the current press without re-subscribing.- const press = useRef<(target: OfficeFloor) => void>(() => undefined);- press.current = (target: OfficeFloor) => {- if (pressed || target === floor) return;- setPressed(target);- if (reduced) { onPick(target); return; }- pressTimer.current = setTimeout(() => onPick(target), BUTTON_PRESS_MS);- };-- // Focus the first floor you can go to, and give focus back to the office when the panel closes.- useEffect(() => {- const before = document.activeElement instanceof HTMLElement ? document.activeElement : null;- list.current?.querySelector<HTMLButtonElement>("button:not(:disabled)")?.focus({ preventScroll: true });- return () => { before?.focus({ preventScroll: true }); };- }, []);-- // Capture phase: the office's own E, Escape and movement keys never see these.- useEffect(() => {- const onKey = (event: KeyboardEvent) => {- if (event.key === "Escape" || event.code === "KeyE") {- event.preventDefault(); event.stopPropagation();- if (!event.repeat) onClose();- return;- }- // Ctrl/Alt/Cmd + a digit belongs to the browser or the app, never to the panel.- const picked = event.ctrlKey || event.metaKey || event.altKey ? null : floorForKey(event.key);- if (picked) {- event.preventDefault(); event.stopPropagation();- if (!event.repeat) press.current(picked);- return;- }- if (event.key === "ArrowUp" || event.key === "ArrowDown") {- event.preventDefault(); event.stopPropagation();- const buttons = [...(list.current?.querySelectorAll<HTMLButtonElement>("button:not(:disabled)") ?? [])];- if (buttons.length === 0) return;- const at = buttons.indexOf(document.activeElement as HTMLButtonElement);- buttons[at < 0 ? 0 : (at + (event.key === "ArrowDown" ? 1 : -1) + buttons.length) % buttons.length].focus();- }- };- document.addEventListener("keydown", onKey, true);- return () => document.removeEventListener("keydown", onKey, true);- }, [onClose]);-- const up = pressed ? floorLevel(pressed) > floorLevel(floor) : null;- return (- <div className="office-lift-backdrop" data-office-ui onPointerDown={(event) => { if (event.target === event.currentTarget) onClose(); }}>- <div className="office-lift" role="dialog" data-state="open" aria-modal="true" aria-label={t("society.office.elevator_choose")}- data-reduced={reduced || undefined}>- <button type="button" className="office-lift-close" onClick={onClose} aria-label={t("society.office.close")}>×</button>- <div className="office-lift-display" aria-hidden>- <svg viewBox="0 0 24 24" className="office-lift-arrow" data-dir={up === null ? undefined : up ? "up" : "down"}>- <path d="M12 4 L21 15 H3 Z" fill="currentColor" />- </svg>- <b>{floorLevel(floor)}</b>- </div>- <div ref={list} className="office-lift-rows">- {PANEL_FLOORS.map((option) => {- const here = option === floor;- return (- <button key={option} type="button" className="office-lift-row" disabled={here || (pressed !== null && pressed !== option)}- aria-current={here ? "location" : undefined} aria-pressed={pressed === option}- aria-keyshortcuts={String(floorLevel(option))} data-here={here || undefined} data-lit={pressed === option || undefined}- onClick={() => press.current(option)}>- <span className="office-lift-button" aria-hidden><span>{floorLevel(option)}</span></span>- <span className="office-lift-label">{t(`society.office.floor_name_${option}`)}</span>- </button>- );- })}- </div>- <p className="office-lift-keys">{t("society.office.elevator_keys")}</p>- </div>- </div>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/GigiFlyer.tsx b/dodaios/ui/web/frontend/src/components/society/office/GigiFlyer.tsxdeleted file mode 100644index 323ee9e2e4..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/GigiFlyer.tsx+++ /dev/null@@ -1,334 +0,0 @@-/**- * The lead agent (Jarvis) as it appears in the office: not a figure but the- * person's pet from My Pets (Gigi when none is chosen), in 3D. Gigi and the- * dragon fly at chest/head height above the walker's ground position; a cat,- * snail, teapot, battery or jelly walks, crawls or hops on the floor- * (`petCompanions.ts`); a pet the person drew floats as a voxel figure.- *- * Motion comes from the pure `gigiFlight.ts` (its `ground` mode for pets on- * the floor), the pet's own limbs from `petRig.ts`. Flyers get a few cheap- * effects: an additive halo, a small glow under the body, a recycled sparkle- * trail while travelling. Every companion casts a soft shadow blob.- */-import { Component, Suspense, useEffect, useMemo, useRef, type ReactNode } from "react";-import { useFrame } from "@react-three/fiber";-import {- AdditiveBlending, BufferAttribute, BufferGeometry, CanvasTexture, CircleGeometry, Color, SRGBColorSpace,- type Group, type Mesh, type MeshBasicMaterial, type PointLight, type Points, type Sprite, type SpriteMaterial, type Texture,-} from "three";-import { CompanionModel } from "../companion/AgentFollower";-import { defaultCompanion } from "../companion/appearance";-import { useCompanionPet } from "../companion/companionPetStore";-import { companionFlies, type CompanionPet } from "../companion/petCompanions";-import { PetModel, VoxelPet, type PetDrive } from "../companion/PetModel";-import type { PetMood } from "../companion/petRig";-import { createGigiFlight, createGigiPose, followAnchor, stepGigiFlight, type GigiFlightMode } from "./gigiFlight";-import { cameraView } from "./officeStore";-import { petBody } from "./walkerRegistry";--/** Gigi's on-screen height in the office. */-export const GIGI_OFFICE_SIZE_M = 0.5;-/** Radius of the little orbs circling Gigi. */-const ORBIT_RADIUS_M = 0.36;-/** The authored model stands on its origin (y 0.014–0.40 of 0.4 m); lift so the flight point is its centre. */-const MODEL_CENTRE_OFFSET = -0.207 * (GIGI_OFFICE_SIZE_M / 0.4);-/** The hover emitter sits at the bottom of the shell. */-const EMITTER_OFFSET = MODEL_CENTRE_OFFSET + 0.02;-const TRAIL_SIZE = 24;-const TRAIL_LIFE_S = 0.8;-const TRAIL_RATE = 30;-const MOVING_SPEED = 0.05;-/** Closer than this to a first-person camera, Gigi would fill the view. */-const FIRST_PERSON_CLEARANCE_M = 2.5;--/** Local effect colours; the diorama keeps one palette in light and dark mode. */-const GLOW_WARM = new Color("#ffd98a");-const GLOW_SPEAK = new Color("#9ff3ff");-const SPARK = new Color("#ffe7a8");--// ---- Shared canvas textures (reference counted; GPU copies freed with the last user) ------interface TextureCache { glow: Texture; shadow: Texture; users: number }-let cache: TextureCache | null = null;--function radialTexture(stops: [number, string][]): Texture {- const canvas = document.createElement("canvas");- canvas.width = canvas.height = 64;- const context = canvas.getContext("2d");- if (context) {- const gradient = context.createRadialGradient(32, 32, 0, 32, 32, 32);- for (const [offset, colour] of stops) gradient.addColorStop(offset, colour);- context.fillStyle = gradient;- context.fillRect(0, 0, 64, 64);- }- const texture = new CanvasTexture(canvas);- texture.colorSpace = SRGBColorSpace;- return texture;-}--function sharedTextures(): TextureCache {- if (!cache) {- cache = {- glow: radialTexture([[0, "rgba(255,255,255,1)"], [0.25, "rgba(255,255,255,0.55)"], [0.6, "rgba(255,255,255,0.12)"], [1, "rgba(255,255,255,0)"]]),- shadow: radialTexture([[0, "rgba(0,0,0,1)"], [0.55, "rgba(0,0,0,0.45)"], [1, "rgba(0,0,0,0)"]]),- users: 0,- };- }- return cache;-}--/** Counted in an effect, so a StrictMode double mount never frees a texture in use. */-function acquireTextures(): void {- sharedTextures().users++;-}--function releaseTextures(): void {- if (!cache) return;- cache.users--;- if (cache.users > 0) return;- // Frees the GPU copies; the tiny canvases stay cached and re-upload on next use,- // so a component still holding them (StrictMode remount) never renders a dead texture.- cache.glow.dispose();- cache.shadow.dispose();-}--/** The pet's mood for its limbs: what Jarvis is doing right now. */-function moodFor(mode: GigiFlightMode, speaking: boolean): PetMood {- if (speaking || mode === "talk" || mode === "wave") return "talk";- if (mode === "work") return "work";- if (mode === "sleep") return "sleep";- return "idle";-}--/** Lift from the flight point (body centre for flyers, the floor for walkers) to the model's origin. */-function bodyOffset(pet: CompanionPet, ground: boolean): number {- if (ground) return 0;- return pet.kind === "gigi" ? MODEL_CENTRE_OFFSET : -pet.heightM / 2;-}--/** The pet's own body: its authored model, its voxel figure, or Gigi (passed in, so each host sizes it). */-export function CompanionBody({ pet, drive, reduced, paused, gigi }: {- pet: CompanionPet; drive: { current: PetDrive }; reduced: boolean; paused: boolean; gigi: ReactNode;-}) {- if (pet.kind === "model") return <PetModel pet={pet} drive={drive} reduced={reduced} paused={paused} />;- if (pet.kind === "voxel") return <VoxelPet pet={pet} reduced={reduced} paused={paused} />;- return <>{gigi}</>;-}--/** A missing or broken GLB hides the companion's body; the glow still marks the lead. */-export class ModelBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {- state = { failed: false };- static getDerivedStateFromError() { return { failed: true }; }- componentDidCatch(error: Error) { console.warn("Companion model unavailable", error.name); }- render() { return this.state.failed ? null : this.props.children; }-}--/** Tiny deterministic generator for sparkle jitter. */-function nextRandom(seed: { value: number }): number {- seed.value = (Math.imul(seed.value, 1664525) + 1013904223) >>> 0;- return seed.value / 4294967296;-}--export function GigiFlyer({ owner, mode, speaking, paused, reduced, clear, children }: {- /** The walker's mover (or, in "follow" mode, the person's character): ground position and facing (0 = +z). */- owner: { current: { x: number; z: number; heading: number } };- mode: GigiFlightMode;- speaking: boolean;- paused: boolean;- reduced: boolean;- /** Free airspace test; "follow" mode keeps Gigi out of walls with it. */- clear?: (x: number, z: number) => boolean;- /** Floor markers and labels share the rendered position, without the body's lift, turn or scale. */- children?: ReactNode;-}) {- const pet = useCompanionPet((s) => s.pet);- const ground = !companionFlies(pet);- const groundRoot = useRef<Group>(null);- // JSX must not reset the animated anchor to a newer target on a React render,- // especially while paused or while switching between following and errands.- const initialPosition = useRef<[number, number, number]>([owner.current.x, 0, owner.current.z]);- const root = useRef<Group>(null);- const body = useRef<Group>(null);- const halo = useRef<Sprite>(null);- const emitter = useRef<Sprite>(null);- const shadow = useRef<Mesh>(null);- const trail = useRef<Points>(null);- const light = useRef<PointLight>(null);- const orbit = useRef<Group>(null);- const flight = useRef(createGigiFlight(owner.current.x, owner.current.z, owner.current.heading, ground));- const pose = useRef(createGigiPose(ground)).current;- const clock = useRef(0);- const last = useRef({ x: owner.current.x, z: owner.current.z });- const emitDebt = useRef(0);- const seed = useRef({ value: 0x9e3779b9 });- const side = useRef<1 | -1>(1);- const tint = useMemo(() => new Color(), []);- const appearance = useMemo(() => ({ ...defaultCompanion("jarvis"), sizeM: GIGI_OFFICE_SIZE_M }), []);- const groundRef = useRef(ground);- groundRef.current = ground;- const drive = useRef<PetDrive>({ speed: 0, mood: "idle" });-- const textures = useMemo(() => sharedTextures(), []);- useEffect(() => { acquireTextures(); return releaseTextures; }, []);-- const particles = useMemo(() => {- const geometry = new BufferGeometry();- const positions = new Float32Array(TRAIL_SIZE * 3);- const colours = new Float32Array(TRAIL_SIZE * 3);- geometry.setAttribute("position", new BufferAttribute(positions, 3));- geometry.setAttribute("color", new BufferAttribute(colours, 3));- const shadowGeometry = new CircleGeometry(0.28, 28);- return { geometry, shadowGeometry, positions, colours, age: new Float32Array(TRAIL_SIZE).fill(TRAIL_LIFE_S), rise: new Float32Array(TRAIL_SIZE), next: 0 };- }, []);- useEffect(() => () => { particles.geometry.dispose(); particles.shadowGeometry.dispose(); }, [particles]);- // The level system's cosmetics follow the pet; nobody draws them once it is gone.- useEffect(() => () => { petBody.active = false; }, []);-- useFrame((_, rawDt) => {- if (paused) return;- const dt = Math.min(rawDt, 0.1);- clock.current += dt;- const m = owner.current;- const travelled = Math.hypot(m.x - last.current.x, m.z - last.current.z);- const moving = dt > 0 && travelled / dt > MOVING_SPEED && travelled < 4;- last.current.x = m.x; last.current.z = m.z;- let targetX = m.x, targetZ = m.z;- if (mode === "follow") {- const anchor = followAnchor(m.x, m.z, m.heading, side.current, clear, groundRef.current);- side.current = anchor.side;- targetX = anchor.x; targetZ = anchor.z;- }- const onFloor = groundRef.current;- stepGigiFlight(flight.current, {- targetX, targetZ, moving, mode, speaking, t: clock.current, dt, heading: m.heading, reduced, clear, ground: onFloor,- }, pose);- drive.current.speed = pose.speed;- drive.current.mood = moodFor(mode, speaking);-- // Gigi hovers at head height beside the person: seated in first person that is right in- // front of the eyes, so close by it steps out of the picture until the person stands up.- const hidden = !onFloor && cameraView.firstPerson && Math.hypot(pose.x - cameraView.x, pose.z - cameraView.z) < FIRST_PERSON_CLEARANCE_M;- if (root.current) root.current.visible = !hidden;- if (shadow.current) shadow.current.visible = !hidden;- // One horizontal transform for the model, shadow and floor annotations.- // The navigation target can lead this spring-smoothed position by a metre.- if (groundRoot.current) groundRoot.current.position.set(pose.x, 0, pose.z);- petBody.x = pose.x; petBody.z = pose.z; petBody.y = onFloor ? pet.heightM / 2 : pose.y;- petBody.top = onFloor ? pet.heightM : pose.y + GIGI_OFFICE_SIZE_M * 0.55;- petBody.sizeM = onFloor ? pet.heightM : GIGI_OFFICE_SIZE_M;- petBody.active = !hidden;- if (root.current) root.current.position.y = pose.y;- if (body.current) {- body.current.rotation.set(pose.pitch, pose.yaw, pose.roll, "YXZ");- body.current.scale.setScalar(pose.scale);- }- tint.copy(GLOW_WARM).lerp(GLOW_SPEAK, speaking ? 1 : mode === "talk" ? 0.5 : 0);- if (halo.current) {- const material = halo.current.material as SpriteMaterial;- material.color.copy(tint);- material.opacity = 0.18 + 0.5 * pose.glow;- halo.current.scale.setScalar(0.75 + 0.35 * pose.glow);- }- if (emitter.current) {- const material = emitter.current.material as SpriteMaterial;- material.color.copy(tint);- material.opacity = 0.3 + 0.5 * pose.glow;- emitter.current.scale.setScalar(0.16 + 0.1 * pose.glow);- }- // A warm light that tints the floor and furniture around Gigi, brighter when it talks.- if (light.current) {- light.current.color.copy(tint);- light.current.intensity = reduced ? 0.5 : 0.45 + 0.9 * pose.glow;- }- // Three small orbs circle Gigi; they spin up while it speaks or works.- if (orbit.current) {- const spin = reduced ? 0 : speaking ? 3.2 : mode === "work" ? 2.2 : 1.1;- orbit.current.rotation.y += spin * dt;- orbit.current.rotation.z = 0.35 * Math.sin(clock.current * 0.7);- orbit.current.children.forEach((child, i) => {- const orb = child as Sprite;- (orb.material as SpriteMaterial).color.copy(tint);- orb.scale.setScalar(0.07 + 0.025 * Math.sin(clock.current * 3 + i * 2.1) + 0.03 * pose.glow);- });- }- if (shadow.current) {- const lift = onFloor ? 0 : Math.max(0, pose.y - 0.4);- (shadow.current.material as MeshBasicMaterial).opacity = Math.max(0.08, 0.34 - lift * 0.22);- // A pet on the floor gets a contact shadow its own size; a flyer's spreads as it rises.- shadow.current.scale.setScalar(onFloor ? Math.max(0.5, pet.heightM * 1.7) : 0.85 + lift * 0.35);- }-- // Sparkle trail: a fixed pool recycled round-robin, faded by age.- const { positions, colours, age, rise } = particles;- if (moving && !reduced && !onFloor && pose.speed > 0.1) {- emitDebt.current += dt * TRAIL_RATE;- while (emitDebt.current >= 1) {- emitDebt.current -= 1;- const i = particles.next;- particles.next = (i + 1) % TRAIL_SIZE;- positions[i * 3] = pose.x + (nextRandom(seed.current) - 0.5) * 0.12;- positions[i * 3 + 1] = pose.y + EMITTER_OFFSET + (nextRandom(seed.current) - 0.5) * 0.06;- positions[i * 3 + 2] = pose.z + (nextRandom(seed.current) - 0.5) * 0.12;- rise[i] = (nextRandom(seed.current) - 0.65) * 0.25;- age[i] = 0;- }- } else emitDebt.current = 0;- let alive = false;- for (let i = 0; i < TRAIL_SIZE; i++) {- if (age[i] >= TRAIL_LIFE_S) { colours[i * 3] = colours[i * 3 + 1] = colours[i * 3 + 2] = 0; continue; }- age[i] += dt;- positions[i * 3 + 1] += rise[i] * dt;- const fade = Math.max(0, 1 - age[i] / TRAIL_LIFE_S);- // Additive blending: fading the colour to black fades the sparkle out.- colours[i * 3] = SPARK.r * fade; colours[i * 3 + 1] = SPARK.g * fade; colours[i * 3 + 2] = SPARK.b * fade;- alive = true;- }- if (trail.current) trail.current.visible = alive;- if (alive) {- particles.geometry.attributes.position.needsUpdate = true;- particles.geometry.attributes.color.needsUpdate = true;- }- });-- return (- <>- <group ref={groundRoot} position={initialPosition.current}>- {children}- <group ref={root} position={[0, pose.y, 0]}>- {!ground && <>- <sprite ref={halo} scale={0.9} renderOrder={1}>- <spriteMaterial map={textures.glow} color={GLOW_WARM} transparent opacity={0.35} blending={AdditiveBlending} depthWrite={false} />- </sprite>- <sprite ref={emitter} position={[0, EMITTER_OFFSET, 0]} scale={0.2} renderOrder={1}>- <spriteMaterial map={textures.glow} color={GLOW_WARM} transparent opacity={0.5} blending={AdditiveBlending} depthWrite={false} />- </sprite>- <pointLight ref={light} color={GLOW_WARM} intensity={0.6} distance={3.2} decay={2} />- <group ref={orbit}>- {[0, 1, 2].map((i) => (- <sprite key={i} position={[Math.cos((i / 3) * Math.PI * 2) * ORBIT_RADIUS_M, 0, Math.sin((i / 3) * Math.PI * 2) * ORBIT_RADIUS_M]} scale={0.08} renderOrder={2}>- <spriteMaterial map={textures.glow} color={GLOW_WARM} transparent opacity={0.9} blending={AdditiveBlending} depthWrite={false} />- </sprite>- ))}- </group>- </>}- <group ref={body}>- <group position={[0, bodyOffset(pet, ground), 0]}>- <ModelBoundary key={pet.id}>- <Suspense fallback={null}>- <CompanionBody pet={pet} drive={drive} reduced={reduced} paused={paused}- gigi={<CompanionModel appearance={appearance} lead />} />- </Suspense>- </ModelBoundary>- </group>- </group>- </group>- <mesh ref={shadow} geometry={particles.shadowGeometry} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.012, 0]} renderOrder={1}>- <meshBasicMaterial map={textures.shadow} color="#000000" transparent opacity={0.3} depthWrite={false} />- </mesh>- </group>- <points ref={trail} geometry={particles.geometry} frustumCulled={false} visible={false} renderOrder={2}>- <pointsMaterial map={textures.glow} size={0.07} sizeAttenuation vertexColors transparent blending={AdditiveBlending} depthWrite={false} />- </points>- </>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/LeadSuite.tsx b/dodaios/ui/web/frontend/src/components/society/office/LeadSuite.tsxdeleted file mode 100644index 4dfa0392b4..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/LeadSuite.tsx+++ /dev/null@@ -1,644 +0,0 @@-/**- * The lead office as an executive suite: a panelled walnut feature wall with- * lit bookcases and a glowing star emblem, an executive desk with three- * monitors and a high-back leather chair, club armchairs for visitors, a- * chesterfield lounge, a bar, a floor globe and warm lamp light.- *- * Same rules as OfficeProps: every piece is built in local space centred on- * the origin, front facing +z, inside its `FURNITURE_SIZE` box, from rounded- * primitives; materials and canvas textures are module-level singletons.- */-import { memo } from "react";-import { Html } from "@react-three/drei";-import type { ThreeEvent } from "@react-three/fiber";-import {- CylinderGeometry, DoubleSide, MeshStandardMaterial, OctahedronGeometry, SphereGeometry, TorusGeometry,-} from "three";-import type { SocietyAgent } from "../data";-import { canvasMaterial } from "./canvasMaterials";-import { Box, matte, MAT, Rounded, screenMaterial } from "./OfficeFurniture";-import { useT } from "@/i18n";-import { TreatJar } from "./dogProps";-import { useLeadSeat } from "./leadSeat";-import { SEAT_OFFSET, seatOf, type DeskSlot, type Furniture, type FurnitureKind, type Point, type Room } from "./officeLayout";-import { useOfficeStore } from "./officeStore";-import { LEAD_SUITE as L } from "./officePalette";-import type { ScreenFace } from "./screenTextures";--type Vec3 = [number, number, number];--// ----------------------------------------------------------------------------// Materials-// -----------------------------------------------------------------------------export const LEAD_MAT = {- walnut: matte(L.walnut, { roughness: 0.6 }),- walnutDark: matte(L.walnutDark, { roughness: 0.65 }),- walnutLight: matte(L.walnutLight, { roughness: 0.6 }),- brass: matte(L.brass, { roughness: 0.32, metalness: 0.75 }),- chrome: matte(L.chrome, { roughness: 0.25, metalness: 0.6 }),- leather: matte(L.leather, { roughness: 0.55 }),- leatherDark: matte(L.leatherDark, { roughness: 0.6 }),- leatherTan: matte(L.leatherTan, { roughness: 0.55 }),- velvet: matte(L.velvetGold, { roughness: 0.95 }),- blackGlass: matte(L.blackGlass, { roughness: 0.15, metalness: 0.2 }),- marble: matte(L.marble, { roughness: 0.3 }),- led: new MeshStandardMaterial({ color: L.led, emissive: L.led, emissiveIntensity: 1.6, roughness: 0.5 }),- backlight: new MeshStandardMaterial({ color: L.backlight, emissive: "#ffb45e", emissiveIntensity: 0.28, roughness: 0.8 }),- shade: new MeshStandardMaterial({ color: L.shade, emissive: "#ffd89a", emissiveIntensity: 0.85, roughness: 0.9 }),- lampGlass: new MeshStandardMaterial({ color: L.lampGlass, emissive: "#3fae6a", emissiveIntensity: 0.55, roughness: 0.3 }),- glass: new MeshStandardMaterial({ color: L.glass, transparent: true, opacity: 0.35, roughness: 0.1, depthWrite: false }),- wallGlass: new MeshStandardMaterial({ color: "#f3d9a4", transparent: true, opacity: 0.16, roughness: 0.1, side: DoubleSide, depthWrite: false }),- mirror: new MeshStandardMaterial({ color: "#6b4a30", emissive: "#ffb766", emissiveIntensity: 0.35, roughness: 0.2, metalness: 0.4 }),- trophy: matte(L.trophy, { roughness: 0.28, metalness: 0.8 }),- bottles: L.bottles.map((c) => new MeshStandardMaterial({ color: c, roughness: 0.15, transparent: true, opacity: 0.85 })),- globeLand: matte(L.globe.land),- rugBorder: matte(L.rug.border, { roughness: 0.95 }),- basket: matte(L.dog.basket, { roughness: 0.95 }),- cushion: matte(L.dog.cushion, { roughness: 0.95 }),-};--const books = ["#7a2c22", "#1d2744", "#2f5a3f", "#c9a24a", "#e9e1d0", "#4a3a6a", "#8a5a36"].map((c) => matte(c));--const GEO = {- cyl: new CylinderGeometry(1, 1, 1, 20),- sphere: new SphereGeometry(1, 24, 16),- star: new OctahedronGeometry(1, 0),- ring: new TorusGeometry(1, 0.035, 8, 48),- rim: new TorusGeometry(1, 0.16, 10, 36),-};--function Cyl({ radius, height, position, material, rotation, cast = true }: {- radius: number; height: number; position: Vec3; material: MeshStandardMaterial; rotation?: Vec3; cast?: boolean;-}) {- return <mesh geometry={GEO.cyl} material={material} position={position} rotation={rotation} scale={[radius, height, radius]} castShadow={cast} receiveShadow />;-}--function Ball({ radius, position, material, cast = true }: { radius: number | Vec3; position: Vec3; material: MeshStandardMaterial; cast?: boolean }) {- return <mesh geometry={GEO.sphere} material={material} position={position} scale={radius} castShadow={cast} receiveShadow />;-}--function Panel({ size, position, material, rotation }: { size: [number, number]; position: Vec3; material: MeshStandardMaterial; rotation?: Vec3 }) {- return <mesh position={position} rotation={rotation} material={material}><planeGeometry args={size} /></mesh>;-}--// ----------------------------------------------------------------------------// Canvas faces-// -----------------------------------------------------------------------------function starPath(ctx: CanvasRenderingContext2D, cx: number, cy: number, outer: number, inner: number): void {- ctx.beginPath();- for (let i = 0; i < 10; i += 1) {- const r = i % 2 === 0 ? outer : inner;- const a = -Math.PI / 2 + (i * Math.PI) / 5;- const x = cx + Math.cos(a) * r, y = cy + Math.sin(a) * r;- if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);- }- ctx.closePath();-}--/** The feature wall's emblem: a gold star in two rings with fine rays on black glass. */-function drawEmblem(ctx: CanvasRenderingContext2D, w: number, h: number): void {- const glow = ctx.createRadialGradient(w / 2, h / 2, 10, w / 2, h / 2, w * 0.55);- glow.addColorStop(0, "#3a2a14");- glow.addColorStop(1, "#0d0e12");- ctx.fillStyle = glow;- ctx.fillRect(0, 0, w, h);- const cx = w / 2, cy = h / 2, r = h * 0.36;- ctx.strokeStyle = "rgba(245,197,90,0.35)";- ctx.lineWidth = 2;- for (let i = 0; i < 48; i += 1) {- const a = (i * Math.PI * 2) / 48;- ctx.beginPath();- ctx.moveTo(cx + Math.cos(a) * r * 1.22, cy + Math.sin(a) * r * 1.22);- ctx.lineTo(cx + Math.cos(a) * r * (i % 2 === 0 ? 1.75 : 1.5), cy + Math.sin(a) * r * (i % 2 === 0 ? 1.75 : 1.5));- ctx.stroke();- }- ctx.strokeStyle = "#f5c55a";- ctx.lineWidth = 7;- ctx.beginPath(); ctx.arc(cx, cy, r * 1.12, 0, Math.PI * 2); ctx.stroke();- ctx.lineWidth = 3;- ctx.beginPath(); ctx.arc(cx, cy, r * 0.98, 0, Math.PI * 2); ctx.stroke();- const gold = ctx.createLinearGradient(cx - r, cy - r, cx + r, cy + r);- gold.addColorStop(0, "#fff0b8");- gold.addColorStop(0.5, "#f5c55a");- gold.addColorStop(1, "#b8862a");- ctx.fillStyle = gold;- starPath(ctx, cx, cy + r * 0.04, r * 0.82, r * 0.34);- ctx.fill();-}--/** Navy rug with a gold border, a burgundy band and a central medallion. */-function drawRug(ctx: CanvasRenderingContext2D, w: number, h: number): void {- ctx.fillStyle = L.rug.field;- ctx.fillRect(0, 0, w, h);- const band = (inset: number, colour: string, width: number) => {- ctx.strokeStyle = colour;- ctx.lineWidth = width;- ctx.strokeRect(inset, inset, w - inset * 2, h - inset * 2);- };- band(14, L.rug.border, 10);- band(34, L.rug.accent, 14);- band(52, L.rug.border, 3);- ctx.fillStyle = L.rug.inner;- ctx.fillRect(60, 60, w - 120, h - 120);- // A lattice of small diamonds in the field.- ctx.fillStyle = "rgba(201,162,74,0.22)";- for (let y = 90; y < h - 80; y += 44) {- for (let x = 90 + ((y / 44) % 2) * 22; x < w - 80; x += 44) {- ctx.beginPath();- ctx.moveTo(x, y - 6); ctx.lineTo(x + 6, y); ctx.lineTo(x, y + 6); ctx.lineTo(x - 6, y);- ctx.fill();- }- }- // Medallion.- const cx = w / 2, cy = h / 2;- ctx.fillStyle = L.rug.field;- ctx.beginPath();- ctx.moveTo(cx, cy - 120); ctx.lineTo(cx + 150, cy); ctx.lineTo(cx, cy + 120); ctx.lineTo(cx - 150, cy);- ctx.closePath();- ctx.fill();- ctx.strokeStyle = L.rug.border;- ctx.lineWidth = 5;- ctx.stroke();- ctx.fillStyle = L.rug.accent;- ctx.beginPath(); ctx.arc(cx, cy, 44, 0, Math.PI * 2); ctx.fill();- ctx.fillStyle = L.rug.border;- starPath(ctx, cx, cy + 2, 32, 13);- ctx.fill();-}--/** A vintage globe: teal seas, parchment continents, a few meridians. */-function drawGlobe(ctx: CanvasRenderingContext2D, w: number, h: number): void {- ctx.fillStyle = L.globe.ocean;- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = L.globe.land;- const blobs: [number, number, number, number][] = [- [0.2, 0.32, 0.1, 0.12], [0.26, 0.62, 0.06, 0.14], [0.5, 0.3, 0.07, 0.08], [0.53, 0.56, 0.07, 0.15],- [0.68, 0.3, 0.14, 0.1], [0.83, 0.68, 0.06, 0.06], [0.15, 0.24, 0.05, 0.05], [0.72, 0.45, 0.05, 0.06],- ];- for (const [x, y, rx, ry] of blobs) {- ctx.beginPath();- ctx.ellipse(x * w, y * h, rx * w, ry * h, 0.3, 0, Math.PI * 2);- ctx.fill();- }- ctx.strokeStyle = L.globe.line;- ctx.globalAlpha = 0.35;- ctx.lineWidth = 1.5;- for (let i = 1; i < 12; i += 1) { ctx.beginPath(); ctx.moveTo((i * w) / 12, 0); ctx.lineTo((i * w) / 12, h); ctx.stroke(); }- for (let i = 1; i < 6; i += 1) { ctx.beginPath(); ctx.moveTo(0, (i * h) / 6); ctx.lineTo(w, (i * h) / 6); ctx.stroke(); }- ctx.globalAlpha = 1;-}--const faces = {- emblem: () => canvasMaterial("lead:emblem", 512, 288, drawEmblem, { glow: 0.95, fallback: "#1a1510", roughness: 0.2 }),- rug: () => canvasMaterial("lead:rug", 512, 512, drawRug, { fallback: L.rug.field, roughness: 0.95 }),- globe: () => canvasMaterial("lead:globe", 256, 128, drawGlobe, { fallback: L.globe.ocean, roughness: 0.5 }),-};--// ----------------------------------------------------------------------------// Feature wall-// -----------------------------------------------------------------------------const WALL = { w: 7.9, h: 2.9, d: 0.38 } as const;-const CASE_W = 2.2;-const SHELF_YS = [0.62, 1.18, 1.74, 2.3] as const;--/** Shelf contents, deterministic per bookcase side: book runs, trophies, a vase, a framed photo. */-function shelfItems(side: number): { kind: "books" | "trophy" | "vase" | "frame"; x: number; shelf: number; n: number }[] {- const out: { kind: "books" | "trophy" | "vase" | "frame"; x: number; shelf: number; n: number }[] = [];- SHELF_YS.forEach((_, shelf) => {- const seed = shelf * 3 + side * 7;- out.push({ kind: "books", x: -0.8 + (seed % 3) * 0.08, shelf, n: 5 + (seed % 4) });- const accent = (["trophy", "vase", "frame", "trophy"] as const)[(shelf + side) % 4];- out.push({ kind: accent, x: 0.6 - (seed % 2) * 0.15, shelf, n: 0 });- if (shelf % 2 === side % 2) out.push({ kind: "books", x: 0.05, shelf, n: 3 + (seed % 3) });- });- return out;-}--function ShelfItem({ item, y }: { item: ReturnType<typeof shelfItems>[number]; y: number }) {- if (item.kind === "books") {- return (- <group position={[item.x, y, 0.02]}>- {Array.from({ length: item.n }, (_, i) => {- const h = 0.3 + ((i * 7 + item.n) % 4) * 0.035;- return <Box key={i} size={[0.055, h, 0.2]} position={[i * 0.062, h / 2, 0]} material={books[(i + item.n) % books.length]} />;- })}- </group>- );- }- if (item.kind === "trophy") {- return (- <group position={[item.x, y, 0.02]}>- <Box size={[0.12, 0.05, 0.12]} position={[0, 0.025, 0]} material={LEAD_MAT.walnutDark} />- <Cyl radius={0.015} height={0.1} position={[0, 0.1, 0]} material={LEAD_MAT.trophy} />- <mesh geometry={GEO.cyl} material={LEAD_MAT.trophy} position={[0, 0.21, 0]} scale={[0.07, 0.13, 0.07]} castShadow />- <mesh geometry={GEO.star} material={LEAD_MAT.trophy} position={[0, 0.33, 0]} scale={[0.04, 0.05, 0.02]} />- </group>- );- }- if (item.kind === "vase") {- return (- <group position={[item.x, y, 0.02]}>- <Ball radius={[0.08, 0.12, 0.08]} position={[0, 0.12, 0]} material={LEAD_MAT.marble} />- <Cyl radius={0.03} height={0.08} position={[0, 0.26, 0]} material={LEAD_MAT.marble} />- </group>- );- }- return (- <group position={[item.x, y, 0.0]} rotation={[-0.12, 0, 0]}>- <Box size={[0.26, 0.2, 0.02]} position={[0, 0.11, 0]} material={LEAD_MAT.brass} />- <Box size={[0.22, 0.16, 0.012]} position={[0, 0.11, 0.008]} material={books[1]} cast={false} />- </group>- );-}--/** One built-in bookcase: walnut carcass, backlit panel, LED-lit shelves and a cabinet base. */-function Bookcase({ x, side }: { x: number; side: number }) {- const items = shelfItems(side);- return (- <group position={[x, 0, 0]}>- <Box size={[CASE_W - 0.1, WALL.h - 0.2, 0.02]} position={[0, (WALL.h - 0.2) / 2 + 0.05, -0.09]} material={LEAD_MAT.backlight} cast={false} />- {[-CASE_W / 2 + 0.03, CASE_W / 2 - 0.03].map((px) => (- <Box key={px} size={[0.06, WALL.h - 0.06, 0.34]} position={[px, (WALL.h - 0.06) / 2, 0.01]} material={LEAD_MAT.walnut} />- ))}- <Box size={[CASE_W, 0.07, 0.36]} position={[0, WALL.h - 0.04, 0.01]} material={LEAD_MAT.walnut} />- {/* Cabinet base with two brass-handled doors. */}- <Box size={[CASE_W - 0.12, 0.56, 0.32]} position={[0, 0.3, 0.02]} material={LEAD_MAT.walnutDark} />- <Box size={[0.012, 0.5, 0.01]} position={[0, 0.3, 0.185]} material={LEAD_MAT.walnut} cast={false} />- {[-0.08, 0.08].map((hx) => <Box key={hx} size={[0.02, 0.14, 0.02]} position={[hx, 0.36, 0.19]} material={LEAD_MAT.brass} cast={false} />)}- {SHELF_YS.map((y) => (- <group key={y}>- <Box size={[CASE_W - 0.12, 0.04, 0.32]} position={[0, y, 0.02]} material={LEAD_MAT.walnut} />- {/* Warm LED strip under the shelf's front edge. */}- <Box size={[CASE_W - 0.2, 0.012, 0.02]} position={[0, y + 0.53, 0.15]} material={LEAD_MAT.led} cast={false} />- </group>- ))}- {items.map((item, i) => <ShelfItem key={i} item={item} y={SHELF_YS[item.shelf] + 0.02} />)}- </group>- );-}--/** The north feature wall: walnut slats around a backlit star emblem, lit bookcases on both sides. */-function LeadWall() {- const slats = 15;- const centreW = WALL.w - CASE_W * 2 - 0.2;- return (- <group>- <Box size={[WALL.w, WALL.h, 0.1]} position={[0, WALL.h / 2, -0.14]} material={LEAD_MAT.walnutDark} />- {Array.from({ length: slats }, (_, i) => (- <Box key={i} size={[0.07, WALL.h - 0.3, 0.04]} position={[-centreW / 2 + 0.1 + (i * (centreW - 0.2)) / (slats - 1), (WALL.h - 0.3) / 2 + 0.15, -0.07]}- material={LEAD_MAT.walnutLight} />- ))}- {/* Emblem: black glass in a brass frame, lit from within. */}- <Box size={[2.3, 1.3, 0.05]} position={[0, 1.62, -0.03]} material={LEAD_MAT.brass} />- <Box size={[2.2, 1.2, 0.02]} position={[0, 1.62, 0.0]} material={LEAD_MAT.blackGlass} cast={false} />- <Panel size={[2.14, 1.14]} position={[0, 1.62, 0.0115]} material={faces.emblem()} />- {/* Cove lights top and bottom of the centre section. */}- <Box size={[centreW, 0.03, 0.05]} position={[0, WALL.h - 0.1, -0.03]} material={LEAD_MAT.led} cast={false} />- <Box size={[centreW, 0.03, 0.05]} position={[0, 0.12, -0.03]} material={LEAD_MAT.led} cast={false} />- {/* Brass pilasters between the sections. */}- {[-1, 1].map((s) => (- <Box key={s} size={[0.08, WALL.h, 0.12]} position={[s * (centreW / 2 + 0.05), WALL.h / 2, -0.03]} material={LEAD_MAT.brass} />- ))}- <Bookcase x={-(WALL.w / 2 - CASE_W / 2)} side={0} />- <Bookcase x={WALL.w / 2 - CASE_W / 2} side={1} />- </group>- );-}--// ----------------------------------------------------------------------------// Seating and lounge-// -----------------------------------------------------------------------------/** Tan leather club armchair for visitors, facing +z. */-function GuestChair() {- return (- <group>- <Rounded size={[0.72, 0.3, 0.7]} radius={0.06} position={[0, 0.2, 0]} material={LEAD_MAT.leatherTan} />- <Rounded size={[0.5, 0.1, 0.52]} radius={0.04} position={[0, 0.4, 0.06]} material={LEAD_MAT.leatherTan} />- <Rounded size={[0.72, 0.5, 0.16]} radius={0.07} position={[0, 0.62, -0.27]} material={LEAD_MAT.leatherTan} />- {[-0.29, 0.29].map((x) => <Rounded key={x} size={[0.14, 0.26, 0.68]} radius={0.06} position={[x, 0.46, 0]} material={LEAD_MAT.leatherTan} />)}- {[[-0.3, -0.3], [0.3, -0.3], [-0.3, 0.3], [0.3, 0.3]].map(([x, z]) => (- <Cyl key={`${x}${z}`} radius={0.025} height={0.05} position={[x, 0.025, z]} material={LEAD_MAT.brass} />- ))}- </group>- );-}--/** Oxblood chesterfield with rolled arms, button tufting and two gold velvet cushions; faces +z. */-function Chesterfield() {- const buttons: Vec3[] = [];- for (let row = 0; row < 2; row += 1) {- for (let i = 0; i < 8; i += 1) buttons.push([-0.8 + i * (1.6 / 7) + (row ? 0.11 : 0), 0.62 + row * 0.14, -0.255]);- }- return (- <group>- <Rounded size={[1.96, 0.34, 0.86]} radius={0.06} position={[0, 0.25, 0]} material={LEAD_MAT.leather} />- {[-0.66, 0, 0.66].map((x) => <Rounded key={x} size={[0.64, 0.12, 0.66]} radius={0.05} position={[x, 0.48, 0.08]} material={LEAD_MAT.leather} />)}- <Rounded size={[1.96, 0.44, 0.2]} radius={0.07} position={[0, 0.62, -0.36]} material={LEAD_MAT.leather} />- {buttons.map((p, i) => <Ball key={i} radius={0.018} position={p} material={LEAD_MAT.leatherDark} cast={false} />)}- {[-0.97, 0.97].map((x) => (- <group key={x}>- <Rounded size={[0.24, 0.46, 0.9]} radius={0.06} position={[x, 0.33, 0]} material={LEAD_MAT.leather} />- <Cyl radius={0.12} height={0.9} position={[x, 0.6, 0]} rotation={[Math.PI / 2, 0, 0]} material={LEAD_MAT.leather} />- </group>- ))}- {[-0.6, 0.6].map((x) => (- <Rounded key={x} size={[0.36, 0.3, 0.1]} radius={0.04} position={[x, 0.66, -0.19]} material={LEAD_MAT.velvet} />- ))}- {[[-0.9, -0.35], [0.9, -0.35], [-0.9, 0.35], [0.9, 0.35]].map(([x, z]) => (- <Box key={`${x}${z}`} size={[0.06, 0.08, 0.06]} position={[x, 0.04, z]} material={LEAD_MAT.brass} />- ))}- </group>- );-}--/** Brass-framed glass coffee table with a marble shelf, a book stack and a vase. */-function LoungeTable() {- return (- <group>- {[[-0.52, -0.29], [0.52, -0.29], [-0.52, 0.29], [0.52, 0.29]].map(([x, z]) => (- <Box key={`${x}${z}`} size={[0.03, 0.42, 0.03]} position={[x, 0.21, z]} material={LEAD_MAT.brass} />- ))}- <Box size={[1.08, 0.025, 0.62]} position={[0, 0.42, 0]} material={LEAD_MAT.glass} cast={false} />- <Box size={[1.06, 0.02, 0.6]} position={[0, 0.405, 0]} material={LEAD_MAT.brass} cast={false} />- <Box size={[1.0, 0.03, 0.54]} position={[0, 0.12, 0]} material={LEAD_MAT.marble} />- <Box size={[0.3, 0.04, 0.22]} position={[-0.22, 0.455, 0.02]} material={books[0]} />- <Box size={[0.26, 0.035, 0.2]} position={[-0.22, 0.49, 0.02]} material={books[3]} />- <Ball radius={[0.06, 0.09, 0.06]} position={[0.26, 0.52, -0.04]} material={LEAD_MAT.marble} />- <Box size={[0.26, 0.05, 0.18]} position={[0.1, 0.16, 0]} material={books[1]} />- </group>- );-}--/** Tall brass floor lamp with a glowing drum shade. */-function FloorLamp() {- return (- <group>- <Cyl radius={0.2} height={0.05} position={[0, 0.025, 0]} material={LEAD_MAT.walnutDark} />- <Cyl radius={0.035} height={1.46} position={[0, 0.77, 0]} material={LEAD_MAT.walnutDark} />- <Cyl radius={0.05} height={0.06} position={[0, 1.44, 0]} material={LEAD_MAT.brass} />- <Cyl radius={0.21} height={0.3} position={[0, 1.6, 0]} material={LEAD_MAT.shade} cast={false} />- </group>- );-}--// ----------------------------------------------------------------------------// Bar and globe-// -----------------------------------------------------------------------------/** Walnut bar cabinet with a marble top, lit mirrored back, glass shelf and bottles; faces +z. */-function ExecutiveBar() {- const bottles = [- { x: -0.7, y: 0.94, h: 0.3 }, { x: -0.52, y: 0.94, h: 0.26 }, { x: -0.36, y: 0.94, h: 0.34 },- { x: 0.42, y: 1.38, h: 0.24 }, { x: 0.58, y: 1.38, h: 0.28 }, { x: 0.74, y: 1.38, h: 0.22 },- { x: -0.6, y: 1.38, h: 0.26 }, { x: -0.44, y: 1.38, h: 0.22 },- ];- return (- <group>- <Box size={[1.9, 0.86, 0.5]} position={[0, 0.45, 0]} material={LEAD_MAT.walnut} />- <Box size={[1.9, 0.04, 0.52]} position={[0, 0.9, 0]} material={LEAD_MAT.marble} />- {[-0.63, 0, 0.63].map((x) => (- <group key={x}>- <Box size={[0.58, 0.7, 0.012]} position={[x, 0.45, 0.253]} material={LEAD_MAT.walnutDark} cast={false} />- <Box size={[0.14, 0.02, 0.02]} position={[x, 0.72, 0.262]} material={LEAD_MAT.brass} cast={false} />- </group>- ))}- {[-0.92, 0.92].map((x) => <Box key={x} size={[0.06, 0.96, 0.3]} position={[x, 1.4, -0.1]} material={LEAD_MAT.walnut} />)}- <Box size={[1.9, 0.06, 0.3]} position={[0, 1.87, -0.1]} material={LEAD_MAT.walnut} />- <Box size={[1.78, 0.9, 0.02]} position={[0, 1.38, -0.24]} material={LEAD_MAT.mirror} cast={false} />- <Box size={[1.78, 0.02, 0.24]} position={[0, 1.37, -0.12]} material={LEAD_MAT.glass} cast={false} />- <Box size={[1.7, 0.012, 0.02]} position={[0, 1.82, -0.02]} material={LEAD_MAT.led} cast={false} />- {bottles.map((b, i) => (- <group key={i} position={[b.x, b.y, b.y > 1 ? -0.12 : 0.05]}>- <Cyl radius={0.045} height={b.h * 0.7} position={[0, (b.h * 0.7) / 2, 0]} material={LEAD_MAT.bottles[i % LEAD_MAT.bottles.length]} />- <Cyl radius={0.016} height={b.h * 0.3} position={[0, b.h * 0.85, 0]} material={LEAD_MAT.bottles[i % LEAD_MAT.bottles.length]} />- </group>- ))}- {/* A decanter and two tumblers on the counter. */}- <Ball radius={[0.1, 0.11, 0.1]} position={[0.35, 1.03, 0.06]} material={LEAD_MAT.bottles[0]} />- <Cyl radius={0.02} height={0.08} position={[0.35, 1.17, 0.06]} material={LEAD_MAT.glass} />- {[0.62, 0.76].map((x) => <Cyl key={x} radius={0.035} height={0.08} position={[x, 0.96, 0.1]} material={LEAD_MAT.glass} cast={false} />)}- </group>- );-}--/** Vintage floor globe on a walnut stand inside a tilted brass meridian. */-function Globe() {- return (- <group>- <Cyl radius={0.3} height={0.05} position={[0, 0.025, 0]} material={LEAD_MAT.walnutDark} />- <Cyl radius={0.035} height={0.4} position={[0, 0.25, 0]} material={LEAD_MAT.walnut} />- <Cyl radius={0.14} height={0.04} position={[0, 0.44, 0]} material={LEAD_MAT.brass} />- <group position={[0, 0.76, 0]} rotation={[0, 0, 0.41]}>- <mesh geometry={GEO.sphere} material={faces.globe()} scale={0.28} castShadow receiveShadow />- <mesh geometry={GEO.ring} material={LEAD_MAT.brass} scale={0.33} castShadow />- </group>- </group>- );-}--/** Navy rug with a gold border and medallion, sized per instance. */-function ExecutiveRug({ w, d }: { w: number; d: number }) {- return (- <group>- <Box size={[w, 0.016, d]} position={[0, 0.008, 0]} material={LEAD_MAT.rugBorder} cast={false} />- <Panel size={[w - 0.08, d - 0.08]} position={[0, 0.018, 0]} rotation={[-Math.PI / 2, 0, 0]} material={faces.rug()} />- </group>- );-}--/** The dog's round basket in the corner; the dog itself is a living figure (OfficeDog.tsx). */-function DogBed() {- return (- <group>- <mesh geometry={GEO.cyl} material={LEAD_MAT.basket} position={[0, 0.07, 0]} scale={[0.43, 0.14, 0.34]} castShadow receiveShadow />- <mesh geometry={GEO.rim} material={LEAD_MAT.basket} position={[0, 0.15, 0]} rotation={[Math.PI / 2, 0, 0]} scale={[0.38, 0.29, 0.5]} castShadow />- <mesh geometry={GEO.cyl} material={LEAD_MAT.cushion} position={[0, 0.15, 0]} scale={[0.36, 0.05, 0.27]} receiveShadow />- </group>- );-}--/** Renderers of the executive-suite furniture kinds; merged into OfficeProps' exhaustive table. */-export const LEAD_RENDERERS = {- leadWall: () => <LeadWall />,- executiveRug: ({ item }: { item: Furniture }) => <ExecutiveRug w={item.size?.w ?? 1} d={item.size?.d ?? 1} />,- guestChair: () => <GuestChair />,- chesterfield: () => <Chesterfield />,- loungeTable: () => <LoungeTable />,- executiveBar: () => <ExecutiveBar />,- globe: () => <Globe />,- floorLamp: () => <FloorLamp />,- dogBed: () => <DogBed />,- treatJar: () => <TreatJar />,-} satisfies Partial<Record<FurnitureKind, (props: { item: Furniture }) => JSX.Element>>;--// ----------------------------------------------------------------------------// Executive desk-// -----------------------------------------------------------------------------/** High-back leather executive chair on a chrome five-star base; the seat top sits at 0.52 m like every chair. */-function ExecutiveChair() {- return (- <group>- <Cyl radius={0.05} height={0.06} position={[0, 0.06, 0]} material={LEAD_MAT.chrome} />- {Array.from({ length: 5 }, (_, i) => (- <group key={i} rotation={[0, (i * Math.PI * 2) / 5, 0]}>- <Box size={[0.04, 0.035, 0.3]} position={[0, 0.06, 0.15]} material={LEAD_MAT.chrome} />- <Ball radius={0.03} position={[0, 0.03, 0.29]} material={MAT.chair} />- </group>- ))}- <Cyl radius={0.028} height={0.34} position={[0, 0.26, 0]} material={LEAD_MAT.chrome} />- <Rounded size={[0.6, 0.12, 0.56]} radius={0.05} position={[0, 0.46, 0]} material={LEAD_MAT.leather} />- <Rounded size={[0.62, 0.84, 0.14]} radius={0.06} position={[0, 0.98, 0.3]} material={LEAD_MAT.leather} />- <Rounded size={[0.46, 0.22, 0.14]} radius={0.06} position={[0, 1.5, 0.32]} material={LEAD_MAT.leather} />- {[0.78, 0.98, 1.18].map((y) => <Box key={y} size={[0.5, 0.015, 0.01]} position={[0, y, 0.228]} material={LEAD_MAT.leatherDark} cast={false} />)}- {[-0.33, 0.33].map((x) => (- <group key={x}>- <Box size={[0.04, 0.2, 0.04]} position={[x, 0.6, 0.02]} material={LEAD_MAT.chrome} />- <Rounded size={[0.08, 0.05, 0.42]} radius={0.02} position={[x, 0.72, 0.02]} material={LEAD_MAT.leatherDark} />- </group>- ))}- </group>- );-}--/**- * An executive desk in the same local frame as a bench desk: the agent sits at- * +z and looks north (-z) at its monitors; the visitor side (-z) shows a- * walnut modesty panel with the brass star. Wide desks get three monitors.- */-function ExecutiveDesk({ w, d, face }: { w: number; d: number; face: ScreenFace }) {- const pedestalX = w / 2 - 0.32;- const triple = w >= 2.2;- const screen = screenMaterial(face);- return (- <group>- <Rounded size={[w, 0.07, d]} radius={0.02} position={[0, 0.735, 0]} material={LEAD_MAT.walnut} />- <Box size={[w - 0.02, 0.025, d - 0.02]} position={[0, 0.69, 0]} material={LEAD_MAT.brass} />- {[-pedestalX, pedestalX].map((x) => (- <group key={x}>- <Box size={[0.56, 0.68, d - 0.06]} position={[x, 0.34, 0]} material={LEAD_MAT.walnutDark} />- {[0.16, 0.38, 0.58].map((y) => <Box key={y} size={[0.16, 0.02, 0.02]} position={[x, y, d / 2 - 0.02]} material={LEAD_MAT.brass} cast={false} />)}- </group>- ))}- {/* Visitor side: modesty panel with brass inlays and the lit star plaque. */}- <Box size={[w - 1.2, 0.56, 0.04]} position={[0, 0.4, -d / 2 + 0.05]} material={LEAD_MAT.walnutDark} />- {[0.2, 0.6].map((y) => <Box key={y} size={[w - 1.2, 0.015, 0.01]} position={[0, y, -d / 2 + 0.025]} material={LEAD_MAT.brass} cast={false} />)}- <Panel size={[0.44, 0.25]} position={[0, 0.4, -d / 2 + 0.028]} rotation={[0, Math.PI, 0]} material={faces.emblem()} />- {/* Leather desk pad, keyboard, mouse. */}- <Box size={[0.95, 0.006, 0.42]} position={[0, 0.773, 0.16]} material={LEAD_MAT.leatherDark} cast={false} />- <Box size={[0.44, 0.02, 0.14]} position={[0, 0.785, 0.24]} material={MAT.keyboard} />- <Rounded size={[0.06, 0.025, 0.1]} radius={0.01} position={[0.34, 0.785, 0.26]} material={MAT.keyboard} />- {/* Monitors: a centre screen, and two angled wings on a wide desk. */}- <Box size={[0.08, 0.2, 0.08]} position={[0, 0.87, -0.24]} material={MAT.monitor} />- <Box size={[0.3, 0.02, 0.18]} position={[0, 0.78, -0.24]} material={MAT.monitor} />- {[0, ...(triple ? [-1, 1] : [])].map((s) => (- <group key={s} position={[s * 0.72, 1.2, -0.26 + Math.abs(s) * 0.1]} rotation={[0, -s * 0.42, 0]}>- <Rounded size={[0.74, 0.44, 0.04]} radius={0.02} position={[0, 0, 0]} material={MAT.monitor} />- <mesh position={[0, 0, 0.0215]} material={screen}><planeGeometry args={[0.68, 0.39]} /></mesh>- </group>- ))}- {triple && [-0.72, 0.72].map((x) => <Box key={x} size={[0.05, 0.4, 0.05]} position={[x, 0.97, -0.18]} material={MAT.monitor} />)}- {/* Banker's lamp, a trophy star and a coffee cup. The lamp stands at the- front-left corner: further back, the angled left wing monitor cuts through its shade. */}- <group position={[-w / 2 + 0.25, 0.77, 0.22]}>- <Cyl radius={0.08} height={0.03} position={[0, 0.015, 0]} material={LEAD_MAT.brass} />- <Cyl radius={0.012} height={0.3} position={[0, 0.16, 0]} material={LEAD_MAT.brass} />- <Rounded size={[0.34, 0.08, 0.14]} radius={0.035} position={[0, 0.33, 0.04]} material={LEAD_MAT.lampGlass} cast={false} />- </group>- <group position={[w / 2 - 0.22, 0.77, -0.2]}>- <Box size={[0.12, 0.06, 0.12]} position={[0, 0.03, 0]} material={LEAD_MAT.walnutDark} />- <mesh geometry={GEO.star} material={LEAD_MAT.trophy} position={[0, 0.17, 0]} scale={[0.07, 0.1, 0.035]} castShadow />- </group>- <Cyl radius={0.04} height={0.09} position={[w / 2 - 0.35, 0.815, 0.22]} material={LEAD_MAT.marble} />- <group position={[0, 0, SEAT_OFFSET]}><ExecutiveChair /></group>- </group>- );-}--/** Monitor centre of a lead desk in world space, and the heading a camera dive looks along. */-function screenOf(desk: DeskSlot): { point: Point & { y: number }; facing: number } {- const turn = desk.facing === "north" ? 0 : Math.PI;- return { point: { x: desk.x - Math.sin(turn) * 0.24, y: 1.2, z: desk.z - Math.cos(turn) * 0.24 }, facing: turn };-}--/** "E - sit down" next to the chair, and once seated, how to open the lead and stand up again. */-function SeatPrompt({ desk }: { desk: DeskSlot }) {- const t = useT();- const seated = useLeadSeat((s) => s.seated === desk.id);- const near = useLeadSeat((s) => s.near === desk.id);- if (!seated && !near) return null;- return (- <Html center position={[0, 1.95, SEAT_OFFSET]} zIndexRange={[24, 0]}>- <span className="office-plate office-seat-prompt" data-office-ui>- {seated ? t("society.office.seat_seated") : <><kbd>E</kbd>{t("society.office.seat_sit")}</>}- </span>- </Html>- );-}--/**- * Every lead desk (the ones that carry their own size) with the monitor face- * its agent's state calls for. The chair can be clicked to walk over and sit;- * the monitors open the lead agent (a camera dive, then the agents view).- */-export const ExecutiveDesks = memo(function ExecutiveDesks({ desks, agents, onOpenScreen }: {- desks: DeskSlot[]; agents: ReadonlyMap<string, SocietyAgent>;- onOpenScreen?: (agentId: string, screen: Point & { y: number }, facing: number) => void;-}) {- return (- <group>- {desks.map((desk) => {- const size = desk.size;- if (!size) return null;- const agent = desk.agentId ? agents.get(desk.agentId) : undefined;- const openScreen = (event: ThreeEvent<MouseEvent>) => {- if (!agent || !onOpenScreen || event.delta > 6) return;- event.stopPropagation();- const { point, facing } = screenOf(desk);- onOpenScreen(agent.agentId, point, facing);- };- const takeSeat = (event: ThreeEvent<MouseEvent>) => {- if (event.delta > 6) return;- event.stopPropagation();- const seat = seatOf(desk);- useLeadSeat.getState().set({ pending: desk.id });- useOfficeStore.getState().requestWalk({ x: seat.x, z: seat.z });- };- const hover = (cursor: string) => () => { document.body.style.cursor = cursor; };- return (- <group key={desk.id} position={[desk.x, 0, desk.z]} rotation={[0, desk.facing === "north" ? 0 : Math.PI, 0]} name={`desk:${desk.id}`}>- <ExecutiveDesk w={size.w} d={size.d} face={agent ? agent.state : "empty"} />- {/* Invisible hit boxes: the monitor bank (clickable from any side) and the chair. */}- {agent && onOpenScreen && (- <mesh position={[0, 1.2, -0.2]} visible={false} onClick={openScreen}- onPointerOver={hover("zoom-in")} onPointerOut={hover("")}>- <boxGeometry args={[size.w >= 2.2 ? 2.1 : 0.8, 0.5, 0.25]} />- </mesh>- )}- <mesh position={[0, 0.75, SEAT_OFFSET + 0.1]} visible={false} onClick={takeSeat}- onPointerOver={hover("pointer")} onPointerOut={hover("")}>- <boxGeometry args={[0.64, 1.5, 0.7]} />- </mesh>- <SeatPrompt desk={desk} />- </group>- );- })}- </group>- );-});--/** Warm light pooled over the executive desk; the suite glows against the cooler open office. */-export function LeadOfficeLight({ room }: { room: Room }) {- const cx = (room.minX + room.maxX) / 2;- return (- <group>- <pointLight position={[cx, 2.7, room.minZ + 2.9]} color="#ffc98a" intensity={9} distance={7.5} decay={2} />- <pointLight position={[room.minX + 0.4, 1.7, room.minZ + 3.1]} color="#ffd9a0" intensity={2.2} distance={3.2} decay={2} />- <pointLight position={[room.maxX - 0.4, 1.7, room.minZ + 2.9]} color="#ffd9a0" intensity={2.2} distance={3.2} decay={2} />- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/LevelHall.tsx b/dodaios/ui/web/frontend/src/components/society/office/LevelHall.tsxdeleted file mode 100644index 19432f58a9..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/LevelHall.tsx+++ /dev/null@@ -1,605 +0,0 @@-/**- * The Level Hall: the agents floor's east wing, a hall of honour. Cream and- * charcoal marble underfoot, walnut and brass, a red runner up the middle,- * and every piece on show is the real one — the same geometry the figures- * wear.- *- * - The rank wall on the north wall: a walnut-framed shadow box holding all- * 24 rank insignia on navy velvet, in two rows like a service chart —- * enlisted and NCO ranks above, officers and generals below. Ranks the- * person holds or held are struck in gold and silver, the current one is- * framed in brass, the ones ahead are pewter silhouettes. A brass plaque- * below reads the person's rank, level, XP and next promotion.- * - The studio dais in front of it: a round walnut platform with a brass- * ring and star inlay. Stepping on it opens the studio.- * - Display cases along the runner, one per uniform piece, lowest unlock at- * the south end: a mannequin in the uniform (wearing the person's own rank- * insignia), a cap on a velvet head form, or ribbons and medals on a slanted- * velvet board — exactly the pieces the figure wears. An unlocked case is- * lit; a locked one stays dim behind smoked glass. A brass plaque on each- * names the piece and the rank that brings it. A click opens it on the- * promotion road.- * - The service guide at the runner's start: a framed, double-sided board- * listing how XP is earned.- *- * Same rules as OfficeProps: every piece is built in local space centred on- * the origin, front facing +z, inside its `FURNITURE_SIZE` box; the lights- * over the dais live in `LevelHallFittings`. The world keeps one palette in- * light and dark mode (office-map.md §2).- */-import { memo, useEffect, useMemo, useRef } from "react";-import { type ThreeEvent } from "@react-three/fiber";-import {- CanvasTexture, CylinderGeometry, DoubleSide, MeshStandardMaterial, RepeatWrapping, Shape, ShapeGeometry, SRGBColorSpace, Vector2,- type Texture,-} from "three";-import { useT } from "@/i18n";-import { Box, matte, Rounded } from "./OfficeFurniture";-import { cachedCanvasTexture, redrawWhenFontsLoad } from "./canvasMaterials";-import { FURNITURE_SIZE, type Furniture, type FurnitureKind } from "./officeLayout";-import { ToyFigure } from "./ToyFigure";-import { TOY, toyLookFor, type ToyLook } from "./toyFigureModel";-import { equippedFor, levelFraction, rewardRoad } from "../progression/cosmetics";-import { RANK_INFO, rankAt, rankOf, slotOf, TITLE_IDS, type RankId, type RewardId } from "../progression/levelCatalog";-import { PERSON_SUBJECT, type XpRuleRow } from "../progression/progressionApi";-import { useProgression } from "../progression/progressionStore";-import { insigniaHeight, RankInsignia3D } from "../progression/regalia/insignia3d";-import { Aiguillette, BreastDecoration } from "../progression/regalia/decorations3d";-import { dressedLook, regaliaFor, type UniformId } from "../progression/regalia/dress";-import { Headwear, type HeadwearId } from "../progression/regalia/headwear3d";--type Ctx = CanvasRenderingContext2D;--// ----------------------------------------------------------------------------// Materials: walnut, brass, navy velvet, glass.-// -----------------------------------------------------------------------------const C = {- walnut: "#4a2f1f",- walnutDark: "#2c1b12",- brass: "#c9a24a",- velvet: "#1a2240",- ink: "#141a2e",- cream: "#efe8d8",-} as const;--const HM = {- walnut: matte(C.walnut, { roughness: 0.45 }),- walnutDark: matte(C.walnutDark, { roughness: 0.4 }),- brass: matte(C.brass, { roughness: 0.3, metalness: 0.7 }),- velvet: matte(C.velvet, { roughness: 1 }),- cream: matte(C.cream, { roughness: 0.5 }),- ink: matte(C.ink, { roughness: 0.5 }),- glass: new MeshStandardMaterial({ color: "#e4f0ff", transparent: true, opacity: 0.12, roughness: 0.05, metalness: 0.1, depthWrite: false, side: DoubleSide }),- /** A locked case: smoked glass. */- smoked: new MeshStandardMaterial({ color: "#20242e", transparent: true, opacity: 0.42, roughness: 0.1, depthWrite: false, side: DoubleSide }),- /** The light panel inside the top of a lit case. */- caseLight: new MeshStandardMaterial({ color: "#fff4dc", emissive: "#fff1d0", emissiveIntensity: 1.6, toneMapped: false }),- caseDark: matte("#191b22", { roughness: 0.8 }),-};--const FONT = '"Inter Variable", "Inter", system-ui, sans-serif';-const SERIF = 'Georgia, "Times New Roman", serif';--// ----------------------------------------------------------------------------// Canvas faces-// -----------------------------------------------------------------------------/**- * A canvas texture redrawn whenever `signature` changes, and once more when- * the hall's font has loaded (canvas text drawn before the face arrives would- * keep the fallback face).- */-function useLiveTexture(w: number, h: number, signature: string, draw: (ctx: Ctx, w: number, h: number) => void): Texture | null {- const canvas = useMemo(() => {- if (typeof document === "undefined") return null;- const el = document.createElement("canvas");- el.width = w;- el.height = h;- return el;- }, [w, h]);- const texture = useMemo(() => {- if (!canvas) return null;- const made = new CanvasTexture(canvas);- made.colorSpace = SRGBColorSpace;- made.anisotropy = 4;- return made;- }, [canvas]);- useEffect(() => () => texture?.dispose(), [texture]);- const drawRef = useRef(draw);- drawRef.current = draw;- useEffect(() => {- let ctx: Ctx | null = null;- try {- ctx = canvas?.getContext("2d") ?? null;- } catch {- // jsdom without the canvas package throws "not implemented": the plaque keeps its plain face, which is honest.- ctx = null;- }- if (!ctx || !texture) return;- const paint = () => { drawRef.current(ctx!, w, h); texture.needsUpdate = true; };- paint();- if (typeof document === "undefined" || !("fonts" in document)) return;- let live = true;- document.fonts.load(`700 48px ${FONT}`).then(() => { if (live) paint(); }, () => {- // A face that fails to load leaves the fallback face already drawn, which stays legible.- });- return () => { live = false; };- }, [signature, canvas, texture, w, h]);- return texture;-}--function fitText(ctx: Ctx, text: string, maxWidth: number): string {- if (ctx.measureText(text).width <= maxWidth) return text;- let cut = text;- while (cut.length > 1 && ctx.measureText(`${cut}…`).width > maxWidth) cut = cut.slice(0, -1);- return `${cut}…`;-}--/** Polished brass: a vertical sheen, a bevelled edge and engraved (dark, inset) text. */-function brassGround(ctx: Ctx, w: number, h: number): void {- const g = ctx.createLinearGradient(0, 0, 0, h);- g.addColorStop(0, "#e6c97f");- g.addColorStop(0.45, "#c9a24a");- g.addColorStop(1, "#9c7a2e");- ctx.fillStyle = g;- ctx.fillRect(0, 0, w, h);- ctx.strokeStyle = "rgba(60,40,8,0.55)";- ctx.lineWidth = Math.max(2, h * 0.04);- ctx.strokeRect(ctx.lineWidth, ctx.lineWidth, w - ctx.lineWidth * 2, h - ctx.lineWidth * 2);-}--function engrave(ctx: Ctx, text: string, x: number, y: number): void {- ctx.fillStyle = "rgba(255,240,200,0.45)";- ctx.fillText(text, x, y + 1.5);- ctx.fillStyle = "#3a2a0c";- ctx.fillText(text, x, y);-}--const plateCache = new Map<string, MeshStandardMaterial>();--/** A brass plaque material with up to two engraved lines, cached by its text. */-function plaqueMaterial(lines: readonly string[], w = 512, h = 128): MeshStandardMaterial {- const key = `hall-plaque:${w}x${h}:${lines.join("|")}`;- const draw = (ctx: Ctx, cw: number, ch: number) => {- brassGround(ctx, cw, ch);- ctx.textAlign = "center";- ctx.textBaseline = "middle";- if (lines.length === 1) {- ctx.font = `700 ${Math.round(ch * 0.42)}px ${SERIF}`;- engrave(ctx, fitText(ctx, lines[0], cw - 40), cw / 2, ch / 2);- } else {- ctx.font = `700 ${Math.round(ch * 0.3)}px ${SERIF}`;- engrave(ctx, fitText(ctx, lines[0], cw - 36), cw / 2, ch * 0.36);- ctx.font = `600 ${Math.round(ch * 0.2)}px ${FONT}`;- engrave(ctx, fitText(ctx, lines[1], cw - 36), cw / 2, ch * 0.72);- }- };- let material = plateCache.get(key);- if (!material) {- const map = cachedCanvasTexture(key, w, h, draw);- redrawWhenFontsLoad(key, map, [`700 40px ${FONT}`], draw);- material = new MeshStandardMaterial({ color: map ? "#ffffff" : C.brass, map, roughness: 0.35, metalness: 0.45 });- plateCache.set(key, material);- }- return material;-}--// ----------------------------------------------------------------------------// The rank wall-// -----------------------------------------------------------------------------const WALL = { w: FURNITURE_SIZE.levelWall.w, h: FURNITURE_SIZE.levelWall.h, d: FURNITURE_SIZE.levelWall.d };-/** The velvet field inside the frame, and the two rows of ranks in it. */-const FIELD = { w: 6.0, h: 1.72, y: 1.83 };-const ROWS: readonly (readonly RankId[])[] = [TITLE_IDS.slice(0, 13), TITLE_IDS.slice(13)];-const CELL = FIELD.w / 13;--function RankCell({ rank, reached, current, x, y, levelAt }: { rank: RankId; reached: boolean; current: boolean; x: number; y: number; levelAt: number }) {- const t = useT();- // As wide as the cell allows, unless that would make a tall chevron set overrun the row.- const fitW = CELL * 0.64, maxH = 0.36;- const width = Math.min(fitW, (fitW * maxH) / insigniaHeight(rank, fitW));- const label = plaqueMaterial([t(`society.level.title.${rank}`), `${RANK_INFO[rank].grade} · ${t("society.level.lv").replace("{0}", String(levelAt))}`], 320, 112);- return (- <group position={[x, y, 0]}>- {current && (- <group>- <Box size={[CELL - 0.03, 0.8, 0.012]} position={[0, -0.02, 0.006]} material={HM.brass} cast={false} />- <Box size={[CELL - 0.07, 0.76, 0.014]} position={[0, -0.02, 0.008]} material={HM.velvet} cast={false} />- </group>- )}- <group position={[0, 0.12, 0.02]}>- {rank === "private"- ? <mesh material={reached ? HM.brass : HM.ink}><torusGeometry args={[0.07, 0.006, 6, 32]} /></mesh>- : <RankInsignia3D rank={rank} width={width} muted={!reached} />}- </group>- <mesh material={label} position={[0, -0.27, 0.018]}>- <planeGeometry args={[CELL - 0.06, (CELL - 0.06) * (112 / 320)]} />- </mesh>- </group>- );-}--interface StatusLines { hall: string; rank: string; grade: string; level: string; xp: string; next: string }--function drawStatus(ctx: Ctx, w: number, h: number, lines: StatusLines, fraction: number): void {- brassGround(ctx, w, h);- ctx.textBaseline = "middle";- ctx.textAlign = "left";- ctx.font = `700 ${Math.round(h * 0.2)}px ${SERIF}`;- engrave(ctx, fitText(ctx, lines.rank, w * 0.5), 40, h * 0.32);- ctx.font = `600 ${Math.round(h * 0.12)}px ${FONT}`;- engrave(ctx, fitText(ctx, `${lines.grade} · ${lines.level}`, w * 0.5), 40, h * 0.62);- // The XP bar: an engraved channel filled with dark enamel.- const bx = w * 0.56, bw = w * 0.4, by = h * 0.26, bh = h * 0.13;- ctx.fillStyle = "rgba(60,40,8,0.35)";- ctx.fillRect(bx, by, bw, bh);- ctx.fillStyle = "#1a2240";- ctx.fillRect(bx + 3, by + 3, Math.max(0, (bw - 6) * fraction), bh - 6);- ctx.textAlign = "right";- ctx.font = `600 ${Math.round(h * 0.12)}px ${FONT}`;- engrave(ctx, fitText(ctx, lines.xp, bw), bx + bw, h * 0.56);- engrave(ctx, fitText(ctx, lines.next, bw), bx + bw, h * 0.78);-}--function RankWall() {- const t = useT();- const person = useProgression((s) => s.subjects[PERSON_SUBJECT]);- const bands = useProgression((s) => s.snapshot?.titles.person);- const level = person?.level ?? 1;- const held = rankAt(bands, level);- const heldIndex = TITLE_IDS.indexOf(held);- const startOf = (rank: RankId) => bands?.find((b) => b.title === rank)?.level ?? 1;- const next = bands?.find((band) => band.level > level);- const fraction = levelFraction(person);- const lines: StatusLines = {- hall: t("society.office.room_levels"),- rank: t(`society.level.title.${held}`),- grade: RANK_INFO[held].grade,- level: t("society.level.level_n").replace("{0}", String(level)),- xp: person && person.xpForNext > 0- ? t("society.level.xp_of").replace("{0}", String(person.xpIntoLevel)).replace("{1}", String(person.xpForNext)) : t("society.level.max"),- next: next ? t("society.level.next_promotion").replace("{0}", t(`society.level.title.${rankOf(next.title)}`)).replace("{1}", String(next.level))- : t("society.hall.top_title"),- };- const status = useLiveTexture(1024, 220, JSON.stringify([lines, Math.round(fraction * 200)]), (ctx, w, h) => drawStatus(ctx, w, h, lines, fraction));- const header = plaqueMaterial([t("society.office.room_levels").toUpperCase()], 768, 112);- return (- <group>- {/* Walnut panelling, then the brass-framed velvet field. */}- <Box size={[WALL.w, WALL.h, 0.18]} position={[0, WALL.h / 2, -WALL.d / 2 + 0.09]} material={HM.walnut} />- <Box size={[WALL.w, 0.12, 0.24]} position={[0, WALL.h - 0.06, -WALL.d / 2 + 0.12]} material={HM.walnutDark} />- <Box size={[WALL.w, 0.16, 0.22]} position={[0, 0.08, -WALL.d / 2 + 0.11]} material={HM.walnutDark} />- <Box size={[FIELD.w + 0.16, FIELD.h + 0.16, 0.08]} position={[0, FIELD.y, 0.0]} material={HM.walnutDark} />- <Box size={[FIELD.w + 0.06, FIELD.h + 0.06, 0.084]} position={[0, FIELD.y, 0.002]} material={HM.brass} />- <Box size={[FIELD.w, FIELD.h, 0.088]} position={[0, FIELD.y, 0.004]} material={HM.velvet} />- <group position={[0, 0, 0.05]}>- {ROWS.map((row, r) => row.map((rank, i) => {- const index = TITLE_IDS.indexOf(rank);- const x = (i - (row.length - 1) / 2) * CELL;- const y = FIELD.y + (r === 0 ? 0.43 : -0.43);- return <RankCell key={rank} rank={rank} reached={index <= heldIndex} current={index === heldIndex} x={x} y={y} levelAt={startOf(rank)} />;- }))}- </group>- {/* The hall's name above, the person's record below. */}- <mesh material={header} position={[0, 2.88, 0.05]}>- <planeGeometry args={[2.2, 2.2 * (112 / 768)]} />- </mesh>- <Box size={[3.0, 0.62, 0.05]} position={[0, 0.56, -0.02]} material={HM.walnutDark} />- <mesh position={[0, 0.56, 0.008]}>- <planeGeometry args={[2.84, 2.84 * (220 / 1024)]} />- {status ? <meshStandardMaterial map={status} roughness={0.35} metalness={0.4} /> : <meshStandardMaterial color={C.brass} roughness={0.35} metalness={0.5} />}- </mesh>- </group>- );-}--// ----------------------------------------------------------------------------// The studio dais-// -----------------------------------------------------------------------------const STAGE_R = FURNITURE_SIZE.studioStage.w / 2 - 0.04;-const GEO = { disc: new CylinderGeometry(1, 1, 1, 64) };--/** The dais's inlaid star, its points `r` from the centre. */-function starShape(r: number): Shape {- return new Shape(Array.from({ length: 10 }, (_, i) => {- const a = -Math.PI / 2 + (i * Math.PI) / 5;- const rr = i % 2 === 0 ? r : r * 0.4;- return new Vector2(Math.cos(a) * rr, Math.sin(a) * rr);- }));-}--const STAR = new ShapeGeometry(starShape(STAGE_R * 0.32));--/** The studio dais; the studio's preview stands its figure on the same one. */-export function StudioStage() {- return (- <group>- {/* Flat on purpose: figures stand at y 0, so nothing here rises above ~0.016 m. */}- <mesh geometry={GEO.disc} material={HM.walnutDark} position={[0, 0.005, 0]} scale={[STAGE_R, 0.01, STAGE_R]} receiveShadow />- <mesh geometry={GEO.disc} material={HM.brass} position={[0, 0.0105, 0]} scale={[STAGE_R * 0.97, 0.001, STAGE_R * 0.97]} />- <mesh geometry={GEO.disc} material={HM.walnut} position={[0, 0.0115, 0]} scale={[STAGE_R * 0.94, 0.002, STAGE_R * 0.94]} receiveShadow />- <mesh geometry={GEO.disc} material={HM.brass} position={[0, 0.0128, 0]} scale={[STAGE_R * 0.56, 0.001, STAGE_R * 0.56]} />- <mesh geometry={GEO.disc} material={HM.walnut} position={[0, 0.0136, 0]} scale={[STAGE_R * 0.54, 0.0012, STAGE_R * 0.54]} receiveShadow />- <mesh geometry={STAR} material={HM.brass} position={[0, 0.0146, 0]} rotation={[-Math.PI / 2, 0, 0]} />- </group>- );-}--// ----------------------------------------------------------------------------// Display cases-// -----------------------------------------------------------------------------const CASE = { w: 0.7, d: 0.7 };--/** A neutral display mannequin: stone-grey, no hair, no face. */-const MANNEQUIN: ToyLook = { ...toyLookFor(null, "hall-mannequin"), skin: "#cfc9bd", hairStyle: "bald", blush: false, eyewear: "none" };-const STILL = { current: { mode: "idle" as const, speed: 0 } };--/** What a case shows: the piece as the person would wear it at their own rank. */-function CaseContent({ reward, rank, open }: { reward: RewardId; rank: RankId; open: boolean }) {- const slot = slotOf(reward);- if (slot === "uniform") {- const regalia = regaliaFor(rank, {});- return (- <group position={[0, 0.3, 0]}>- <ToyFigure look={dressedLook(MANNEQUIN, reward as UniformId, rank)} drive={STILL} paused heightM={1.2} regalia={regalia} mannequin />- {/* The mannequin's stand under its feet. */}- <mesh geometry={GEO.disc} material={HM.walnutDark} position={[0, -0.005, 0]} scale={[0.2, 0.01, 0.2]} />- </group>- );- }- if (slot === "headwear") {- const k = 0.55;- return (- <group position={[0, 0.98, 0]}>- {/* A velvet head form on a turned walnut neck. */}- <mesh material={HM.walnut} position={[0, 0.06, 0]}>- <cylinderGeometry args={[0.035, 0.06, 0.12, 20]} />- </mesh>- <group position={[0, 0.12 - (TOY.head.y - TOY.head.ry) * k, 0]} scale={k}>- <mesh material={HM.velvet} position={[0, TOY.head.y, 0]} scale={[TOY.head.rx, TOY.head.ry, TOY.head.rz]}>- <sphereGeometry args={[1, 32, 20]} />- </mesh>- <Headwear kind={reward as HeadwearId} rank={rank} />- </group>- </group>- );- }- // Decorations lie on a slanted velvet board, three times life size so they read through the glass.- const corded = reward === "decoration_aiguillette" || reward === "decoration_medals";- return (- <group position={[0, 1.2, -0.04]} rotation={[-0.38, 0, 0]}>- <Box size={[0.56, 0.42, 0.03]} position={[0, 0, -0.015]} material={HM.velvet} cast={false} />- <group scale={3} position={[0.02, 0.12, 0.002]}>- <group position={[0.02, 0, 0]}><BreastDecoration decoration={reward} /></group>- {corded && <group position={[-0.085, 0.02, 0]}><Aiguillette span={0.08} /></group>}- </group>- {!open && <Box size={[0.56, 0.42, 0.002]} position={[0, 0, 0.02]} material={HM.smoked} cast={false} />}- </group>- );-}--/** Heights of each case kind: the plinth's top and the glass above it. */-function caseShape(reward: RewardId): { plinth: number; glass: number } {- const slot = slotOf(reward);- if (slot === "uniform") return { plinth: 0.28, glass: 1.42 };- return { plinth: 0.92, glass: 0.72 };-}--function DisplayCase({ item }: { item: Furniture }) {- const t = useT();- const index = Number(item.id.slice("level-pedestal-".length));- const rewards = useProgression((s) => s.snapshot?.rewards);- const level = useProgression((s) => s.subjects[PERSON_SUBJECT]?.level ?? 1);- const bands = useProgression((s) => s.snapshot?.titles.person);- const choices = useProgression((s) => s.choices.person);- const road = useMemo(() => (rewards ? rewardRoad(rewards, "person") : []), [rewards]);- const row = road[index];- const reward = row?.rewardId;- const at = row?.levels.person ?? 0;- const open = !!row && level >= at;- const worn = !!row && !!rewards && equippedFor(rewards, "person", level, choices)[row.slot] === reward;- const rank = rankAt(bands, level);- const onClick = (event: ThreeEvent<MouseEvent>) => {- if (event.delta > 6 || !reward) return;- event.stopPropagation();- useProgression.getState().openPanel("rewards", { subject: "person", reward });- };- const hover = (on: boolean) => (event: ThreeEvent<PointerEvent>) => {- if (!reward) return;- event.stopPropagation();- document.body.style.cursor = on ? "pointer" : "";- };- useEffect(() => () => { document.body.style.cursor = ""; }, []);- if (!reward) return null;- const { plinth, glass } = caseShape(reward);- const top = plinth + glass;- const state = worn ? t("society.hall.equipped") : open ? t("society.hall.unlocked")- : `${t(`society.level.title.${rankAt(bands, at)}`)} · ${t("society.level.lv").replace("{0}", String(at))}`;- const plaque = plaqueMaterial([t(`society.level.reward.${reward}`), state], 448, 128);- return (- <group onClick={onClick} onPointerOver={hover(true)} onPointerOut={hover(false)}>- {/* The walnut plinth with a brass band, a black base and a moulded top. */}- <Rounded size={[CASE.w + 0.06, 0.08, CASE.d + 0.06]} radius={0.02} position={[0, 0.04, 0]} material={HM.walnutDark} />- <Box size={[CASE.w, plinth - 0.1, CASE.d]} position={[0, 0.08 + (plinth - 0.1) / 2, 0]} material={HM.walnut} />- <Box size={[CASE.w + 0.02, 0.025, CASE.d + 0.02]} position={[0, plinth - 0.03, 0]} material={HM.brass} />- <Box size={[CASE.w + 0.04, 0.03, CASE.d + 0.04]} position={[0, plinth - 0.005, 0]} material={HM.walnutDark} />- <mesh material={plaque} position={[0, plinth * 0.55, CASE.d / 2 + 0.002]}>- <planeGeometry args={[0.5, 0.5 * (128 / 448)]} />- </mesh>- {/* The glass, its four brass posts and the lid with its light. */}- <mesh position={[0, plinth + glass / 2, 0]} material={open ? HM.glass : HM.smoked} renderOrder={2}>- <boxGeometry args={[CASE.w - 0.02, glass, CASE.d - 0.02]} />- </mesh>- {[[-1, -1], [1, -1], [-1, 1], [1, 1]].map(([sx, sz]) => (- <Box key={`${sx}${sz}`} size={[0.018, glass, 0.018]} position={[sx * (CASE.w / 2 - 0.01), plinth + glass / 2, sz * (CASE.d / 2 - 0.01)]} material={HM.brass} cast={false} />- ))}- <Box size={[CASE.w + 0.02, 0.05, CASE.d + 0.02]} position={[0, top + 0.025, 0]} material={HM.walnutDark} />- <mesh material={open ? HM.caseLight : HM.caseDark} position={[0, top - 0.002, 0]} rotation={[Math.PI / 2, 0, 0]}>- <planeGeometry args={[CASE.w * 0.6, CASE.d * 0.6]} />- </mesh>- <CaseContent reward={reward} rank={rank} open={open} />- </group>- );-}--// ----------------------------------------------------------------------------// The runner and the service guide-// -----------------------------------------------------------------------------function runnerTexture(): Texture | null {- return cachedCanvasTexture("hall-runner", 256, 256, (ctx, w, h) => {- ctx.fillStyle = "#7a1d25";- ctx.fillRect(0, 0, w, h);- // A fine woven grain.- ctx.fillStyle = "rgba(0,0,0,0.08)";- for (let y = 0; y < h; y += 4) ctx.fillRect(0, y, w, 1);- ctx.fillStyle = "rgba(255,255,255,0.03)";- for (let x = 0; x < w; x += 6) ctx.fillRect(x, 0, 1, h);- // Gold borders with a thin inner line.- ctx.fillStyle = "#c9a24a";- ctx.fillRect(0, 0, 14, h);- ctx.fillRect(w - 14, 0, 14, h);- ctx.fillRect(22, 0, 3, h);- ctx.fillRect(w - 25, 0, 3, h);- });-}--function Runner({ w, d }: { w: number; d: number }) {- const material = useMemo(() => {- const base = runnerTexture();- const map = base ? base.clone() : null;- if (map) {- map.wrapS = RepeatWrapping;- map.wrapT = RepeatWrapping;- map.repeat.set(1, Math.max(1, Math.round(d / w)));- map.needsUpdate = true;- }- return new MeshStandardMaterial({ color: map ? "#ffffff" : "#7a1d25", map, roughness: 0.95 });- }, [d, w]);- useEffect(() => () => { material.map?.dispose(); material.dispose(); }, [material]);- return (- <mesh material={material} position={[0, 0.008, 0]} rotation={[-Math.PI / 2, 0, 0]} receiveShadow>- <planeGeometry args={[w * 0.8, d]} />- </mesh>- );-}--interface GuideLines { title: string; subtitle: string; rows: { xp: string; text: string }[]; footer: string }--/** The guide's face: cream card stock, a navy rule, rows set like a printed order of service. */-function drawGuide(ctx: Ctx, w: number, h: number, lines: GuideLines): void {- ctx.fillStyle = "#f2ecdd";- ctx.fillRect(0, 0, w, h);- ctx.strokeStyle = "#1a2240";- ctx.lineWidth = 6;- ctx.strokeRect(24, 24, w - 48, h - 48);- ctx.lineWidth = 1.5;- ctx.strokeRect(36, 36, w - 72, h - 72);- ctx.textBaseline = "middle";- ctx.textAlign = "center";- ctx.fillStyle = "#1a2240";- ctx.font = `700 58px ${SERIF}`;- ctx.fillText(fitText(ctx, lines.title, w - 140), w / 2, 100);- ctx.fillStyle = "#5b5345";- ctx.font = `500 28px ${FONT}`;- ctx.fillText(fitText(ctx, lines.subtitle, w - 140), w / 2, 150);- ctx.fillStyle = "#b8964f";- ctx.fillRect(w / 2 - 90, 180, 180, 3);- const rowH = 62;- ctx.textAlign = "left";- lines.rows.forEach((row, i) => {- const y = 236 + i * rowH;- ctx.fillStyle = "#1a2240";- ctx.font = `800 32px ${FONT}`;- ctx.fillText(row.xp, 90, y);- ctx.fillStyle = "#2b2a26";- ctx.font = `500 31px ${FONT}`;- ctx.fillText(fitText(ctx, row.text, w - 380), 260, y);- ctx.fillStyle = "rgba(26,34,64,0.12)";- ctx.fillRect(90, y + rowH / 2 - 2, w - 180, 1.5);- });- ctx.textAlign = "center";- ctx.fillStyle = "#5b5345";- ctx.font = `600 26px ${FONT}`;- ctx.fillText(fitText(ctx, lines.footer, w - 140), w / 2, h - 72);-}--const GUIDE = { w: FURNITURE_SIZE.levelGuide.w, h: FURNITURE_SIZE.levelGuide.h, screenW: 3.0, screenH: 1.66, screenY: 1.5 };-/** The guide lists the person's best-paying rules, at most this many. */-const GUIDE_ROWS = 6;-const NO_RULES: XpRuleRow[] = [];--function ServiceGuide() {- const t = useT();- const rules = useProgression((s) => s.snapshot?.rules ?? NO_RULES);- const rows = useMemo(() => rules.filter((r) => r.kind === "person").sort((a, b) => b.xp - a.xp).slice(0, GUIDE_ROWS)- .map((r) => ({ xp: `+${r.xp} XP`, text: t(`society.level.source.${r.source}`) })), [rules, t]);- const lines: GuideLines = {- title: t("society.hall.guide_title"), subtitle: t("society.hall.guide_subtitle"), rows, footer: t("society.hall.guide_footer"),- };- const face = useLiveTexture(1280, 704, JSON.stringify(lines), (ctx, w, h) => drawGuide(ctx, w, h, lines));- const card = face- ? <meshStandardMaterial map={face} roughness={0.8} />- : <meshStandardMaterial color={C.cream} roughness={0.8} />;- return (- <group>- {[-1, 1].map((side) => (- <group key={side} position={[side * (GUIDE.w / 2 - 0.12), 0, 0]}>- <Box size={[0.09, GUIDE.h - 0.05, 0.09]} position={[0, (GUIDE.h - 0.05) / 2, 0]} material={HM.walnutDark} />- <Box size={[0.13, 0.03, 0.13]} position={[0, GUIDE.h - 0.03, 0]} material={HM.brass} />- <Rounded size={[0.24, 0.06, 0.34]} radius={0.02} position={[0, 0.03, 0]} material={HM.walnutDark} />- </group>- ))}- <Box size={[GUIDE.screenW + 0.16, GUIDE.screenH + 0.16, 0.1]} position={[0, GUIDE.screenY, 0]} material={HM.walnut} />- <Box size={[GUIDE.screenW + 0.06, GUIDE.screenH + 0.06, 0.104]} position={[0, GUIDE.screenY, 0]} material={HM.brass} />- {/* The same card on both faces. */}- <mesh position={[0, GUIDE.screenY, 0.054]}><planeGeometry args={[GUIDE.screenW, GUIDE.screenH]} />{card}</mesh>- <mesh position={[0, GUIDE.screenY, -0.054]} rotation={[0, Math.PI, 0]}><planeGeometry args={[GUIDE.screenW, GUIDE.screenH]} />{card}</mesh>- </group>- );-}--/** Renderers of the Level Hall's furniture kinds; merged into OfficeProps' exhaustive table. */-export const LEVEL_HALL_RENDERERS = {- levelWall: () => <RankWall />,- studioStage: () => <StudioStage />,- rewardPedestal: ({ item }: { item: Furniture }) => <DisplayCase item={item} />,- levelRoad: ({ item }: { item: Furniture }) => {- const size = item.size ?? FURNITURE_SIZE.levelRoad;- return <Runner w={size.w} d={size.d} />;- },- levelGuide: () => <ServiceGuide />,-} satisfies Partial<Record<FurnitureKind, (props: { item: Furniture }) => JSX.Element>>;--/**- * What hangs over the hall rather than stands in it: a brass canopy over the- * dais with four spotlights aimed down at it, and warm light on the rank wall- * and the guide.- */-export const LevelHallFittings = memo(function LevelHallFittings({ stage, guide }: { stage: Pick<Furniture, "x" | "z">; guide: Pick<Furniture, "x" | "z"> | null }) {- return (- <>- <group position={[stage.x, 0, stage.z]}>- <mesh material={HM.brass} position={[0, 3.12, 0]}>- <cylinderGeometry args={[0.5, 0.5, 0.04, 40]} />- </mesh>- {[0, 1, 2, 3].map((i) => {- const a = (i / 4) * Math.PI * 2 + Math.PI / 4;- return (- <group key={i} position={[Math.cos(a) * 0.4, 3.0, Math.sin(a) * 0.4]} rotation={[Math.sin(a) * -0.35, 0, Math.cos(a) * 0.35]}>- <mesh material={HM.walnutDark}><cylinderGeometry args={[0.05, 0.065, 0.16, 16]} /></mesh>- <mesh material={HM.caseLight} position={[0, -0.081, 0]} rotation={[Math.PI / 2, 0, 0]}><circleGeometry args={[0.05, 16]} /></mesh>- </group>- );- })}- <pointLight position={[0, 2.6, 0.4]} color="#ffe6bf" intensity={6} distance={7} decay={2} />- </group>- <pointLight position={[stage.x, 2.9, stage.z - 2.6]} color="#ffe2b0" intensity={4} distance={6} decay={2} />- {guide && <pointLight position={[guide.x, 2.8, guide.z - 1.4]} color="#fff1da" intensity={3} distance={6} decay={2} />}- </>- );-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/LiveMonitors.tsx b/dodaios/ui/web/frontend/src/components/society/office/LiveMonitors.tsxdeleted file mode 100644index 35752aa2f5..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/LiveMonitors.tsx+++ /dev/null@@ -1,162 +0,0 @@-/**- * Desk monitors that show the seated agent's live chat. A click on a screen- * zooms the camera into it and then opens that agent's chat view.- */-import { useEffect, useMemo, useRef, useState } from "react";-import { useFrame, type ThreeEvent } from "@react-three/fiber";-import { CanvasTexture, SRGBColorSpace, type Mesh } from "three";-import type { SocietyAgent } from "../data";-import type { DeskSlot, Point } from "./officeLayout";-import type { DeskChat } from "./useDeskChats";-import type { ChatLineKind } from "./deskChat";-import { seatedAtDesk } from "./walkerRegistry";-import { RealChatScreen } from "./RealChatScreen";--/** At most this many monitors run the real chat at once; farther ones keep the light preview. */-const MAX_REAL_CHATS = 3;-/** Start the real chat within this camera distance, stop it beyond the second (no flicker at the edge). */-const REAL_CHAT_NEAR_M = 11;-const REAL_CHAT_FAR_M = 14;--const W = 512, H = 296;-/** Same place as the instanced screen, a hair in front of it. */-const SCREEN_Y = 1.18, SCREEN_Z = -0.2095, SCREEN_W = 0.66, SCREEN_H = 0.38;--const PREFIX: Record<ChatLineKind, { mark: string; colour: string }> = {- user: { mark: "›", colour: "#93c5fd" },- agent: { mark: "●", colour: "#e2e8f0" },- tool: { mark: "⚙", colour: "#fcd34d" },- notice: { mark: "i", colour: "#a7f3d0" },- error: { mark: "!", colour: "#fca5a5" },-};--function wrap(ctx: CanvasRenderingContext2D, text: string, width: number): string[] {- const words = text.split(" ");- const rows: string[] = [];- let row = "";- for (const word of words) {- const next = row ? `${row} ${word}` : word;- if (ctx.measureText(next).width > width && row) { rows.push(row); row = word; } else row = next;- }- if (row) rows.push(row);- return rows;-}--export function drawChatScreen(ctx: CanvasRenderingContext2D, agent: Pick<SocietyAgent, "name" | "state">, chat: DeskChat | undefined): void {- ctx.fillStyle = "#0f1420";- ctx.fillRect(0, 0, W, H);- // Title bar: the agent and its state, like a chat window header.- ctx.fillStyle = "#1c2433";- ctx.fillRect(0, 0, W, 34);- ctx.fillStyle = agent.state === "working" ? "#4ade80" : agent.state === "waiting" ? "#fbbf24" : "#94a3b8";- ctx.beginPath(); ctx.arc(18, 17, 6, 0, Math.PI * 2); ctx.fill();- ctx.fillStyle = "#f8fafc";- ctx.font = "600 17px system-ui, -apple-system, 'Segoe UI', sans-serif";- ctx.textBaseline = "middle";- ctx.fillText(agent.name.length > 34 ? `${agent.name.slice(0, 33)}…` : agent.name, 32, 18);- ctx.font = "15px ui-monospace, 'Cascadia Mono', Menlo, Consolas, monospace";- ctx.textBaseline = "alphabetic";- const lineH = 19, left = 12, textLeft = 30, maxW = W - textLeft - 10;- // Lay out from the newest line upwards, so the latest message is always visible.- const rows: { colour: string; mark: string; text: string }[] = [];- const lines = chat?.lines ?? [];- if (lines.length === 0) rows.push({ colour: "#64748b", mark: "…", text: "" });- for (const line of lines) {- const p = PREFIX[line.kind];- wrap(ctx, line.text, maxW).slice(0, 4).forEach((text, i) => rows.push({ colour: p.colour, mark: i === 0 ? p.mark : "", text }));- }- const fit = Math.floor((H - 44) / lineH);- const visible = rows.slice(-fit);- visible.forEach((row, i) => {- const y = 44 + (i + 1) * lineH - 5;- ctx.fillStyle = row.colour;- ctx.fillText(row.mark, left, y);- ctx.fillText(row.text, textLeft, y);- });- // A blinking-style caret block at the bottom while working.- if (agent.state === "working") { ctx.fillStyle = "#4ade80"; ctx.fillRect(textLeft, H - 12, 9, 4); }-}--function Screen({ desk, agent, chat, real, roster, onOpen }: {- desk: DeskSlot; agent: SocietyAgent; chat: DeskChat | undefined; real: boolean; roster: SocietyAgent[];- onOpen: (agentId: string, screen: Point & { y: number }, facing: number) => void;-}) {- const mesh = useRef<Mesh>(null);- const turn = desk.facing === "north" ? 0 : Math.PI;- const surface = useMemo(() => {- const canvas = typeof document !== "undefined" ? document.createElement("canvas") : null;- const ctx = canvas?.getContext("2d") ?? null;- if (!canvas || !ctx) return null;- canvas.width = W; canvas.height = H;- const texture = new CanvasTexture(canvas);- texture.colorSpace = SRGBColorSpace;- texture.anisotropy = 4;- return { ctx, texture };- }, []);- useEffect(() => () => surface?.texture.dispose(), [surface]);- useEffect(() => {- if (!surface) return;- drawChatScreen(surface.ctx, agent, chat);- surface.texture.needsUpdate = true;- }, [surface, agent.name, agent.state, chat]);- useFrame(() => {- if (mesh.current) mesh.current.visible = seatedAtDesk.has(agent.agentId);- });- if (!surface) return null;- // World position of the screen centre, for the zoom.- const sx = desk.x + Math.sin(turn) * SCREEN_Z, sz = desk.z + Math.cos(turn) * SCREEN_Z;- const click = (event: ThreeEvent<MouseEvent>) => {- if (event.delta > 6) return;- event.stopPropagation();- onOpen(agent.agentId, { x: sx, y: SCREEN_Y, z: sz }, turn);- };- return (- <group position={[desk.x, 0, desk.z]} rotation={[0, turn, 0]}>- <mesh ref={mesh} position={[0, SCREEN_Y, SCREEN_Z]} visible={false} onClick={click}- onPointerOver={() => { document.body.style.cursor = "zoom-in"; }} onPointerOut={() => { document.body.style.cursor = ""; }}>- <planeGeometry args={[SCREEN_W, SCREEN_H]} />- <meshBasicMaterial map={surface.texture} toneMapped={false} />- </mesh>- {real && <RealChatScreen agent={agent} roster={roster} position={[0, SCREEN_Y, SCREEN_Z + 0.002]} />}- </group>- );-}--/** Which seated agents get the real chat: the nearest few to the camera, with hysteresis. Pure. */-export function pickRealChats(candidates: { id: string; distance: number }[], current: ReadonlySet<string>): Set<string> {- const keep = candidates- .filter((c) => c.distance <= (current.has(c.id) ? REAL_CHAT_FAR_M : REAL_CHAT_NEAR_M))- .sort((a, b) => a.distance - b.distance)- .slice(0, MAX_REAL_CHATS);- return new Set(keep.map((c) => c.id));-}--export function LiveMonitors({ desks, agents, chats, onOpen }: {- desks: DeskSlot[]; agents: ReadonlyMap<string, SocietyAgent>; chats: ReadonlyMap<string, DeskChat>;- onOpen: (agentId: string, screen: Point & { y: number }, facing: number) => void;-}) {- const roster = useMemo(() => [...agents.values()], [agents]);- const [real, setReal] = useState<ReadonlySet<string>>(new Set());- const nextCheck = useRef(0);- useFrame(({ camera, clock }) => {- if (clock.elapsedTime < nextCheck.current) return;- nextCheck.current = clock.elapsedTime + 0.3;- const candidates: { id: string; distance: number }[] = [];- for (const desk of desks) {- const agent = desk.agentId ? agents.get(desk.agentId) : undefined;- // The lead's chat is the app's own voice chat; its monitor keeps the preview.- if (!agent || agent.tier === "lead" || !agent.chatSessionId || !seatedAtDesk.has(agent.agentId)) continue;- candidates.push({ id: agent.agentId, distance: Math.hypot(camera.position.x - desk.x, camera.position.y - 1.2, camera.position.z - desk.z) });- }- const next = pickRealChats(candidates, real);- if (next.size !== real.size || [...next].some((id) => !real.has(id))) setReal(next);- });- return (- <group>- {desks.map((desk) => {- const agent = desk.agentId ? agents.get(desk.agentId) : undefined;- return agent ? <Screen key={desk.id} desk={desk} agent={agent} chat={chats.get(agent.agentId)} real={real.has(agent.agentId)} roster={roster} onOpen={onOpen} /> : null;- })}- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/LobbyDecor.test.tsx b/dodaios/ui/web/frontend/src/components/society/office/LobbyDecor.test.tsxdeleted file mode 100644index c4430aa619..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/LobbyDecor.test.tsx+++ /dev/null@@ -1,65 +0,0 @@-/**- * The lobby brand wall's canvas face writes in the bundled interface face.- *- * The bundle ships Inter as "Inter Variable"; a canvas font naming plain- * "Inter" silently drew the wordmark in the system fallback, so the- * wordmark sign looked off-brand. A recording 2D context captures- * every font the face sets and every line of text it draws.- */-import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";-import type { ReactElement } from "react";-import { PRODUCT_NAME } from "@/lib/branding";-import { LOBBY_RENDERERS } from "./LobbyDecor";--// The component is called as a plain function below, so `useT` must not be a real hook.-vi.mock("@/i18n", async () => {- const { default: en } = await import("@/i18n/locales/society/en.json");- const lookup = (key: string) => key.split(".").reduce<unknown>((value, part) => (value as Record<string, unknown>)?.[part], en);- return { useT: () => (key: string) => (typeof lookup(key) === "string" ? lookup(key) as string : key) };-});--const fonts: string[] = [];-const texts: string[] = [];--/** A 2D context that records `font` and `fillText`, and accepts every other call. */-function recordingContext(): CanvasRenderingContext2D {- const gradient = { addColorStop: () => undefined };- const state: Record<string, unknown> = {};- return new Proxy(state, {- get(target, key) {- if (key === "measureText") return (text: string) => ({ width: text.length * 60 });- if (key === "createLinearGradient" || key === "createRadialGradient") return () => gradient;- if (key === "fillText") return (text: string) => { texts.push(text); };- if (key in target) return target[key as string];- return () => undefined;- },- set(target, key, value) {- if (key === "font") fonts.push(String(value));- target[key as string] = value;- return true;- },- }) as unknown as CanvasRenderingContext2D;-}--const realGetContext = HTMLCanvasElement.prototype.getContext;--beforeAll(() => {- HTMLCanvasElement.prototype.getContext = function getContext() {- return recordingContext();- } as unknown as typeof HTMLCanvasElement.prototype.getContext;-});--afterAll(() => {- HTMLCanvasElement.prototype.getContext = realGetContext;-});--describe("lobby brand wall", () => {- it("draws the wordmark and strapline in the bundled Inter face", () => {- const wall = LOBBY_RENDERERS.brandWall() as ReactElement;- // Calling the component builds its materials, which draw the canvas face.- (wall.type as () => ReactElement)();- expect(texts).toEqual(expect.arrayContaining([PRODUCT_NAME.toUpperCase(), "AGENT HEADQUARTERS"]));- expect(fonts.length).toBeGreaterThan(0);- for (const font of fonts) expect(font).toContain("'Inter Variable'");- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/LobbyDecor.tsx b/dodaios/ui/web/frontend/src/components/society/office/LobbyDecor.tsxdeleted file mode 100644index 990353d83b..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/LobbyDecor.tsx+++ /dev/null@@ -1,841 +0,0 @@-/**- * The agents floor's lobby as the arrival at a startup HQ: a brand wall of- * pale oak slats with the Jarvis ghost standing off a sage plaster panel,- * halo-lit from behind, over the wordmark; a waiting lounge (boucle sofa,- * oak-and-cognac armchairs, a travertine coffee table with magazines, a marble- * side table and a tripod lamp on a wool rug), the Agent board as a standing- * touch-screen totem, an entrance mat at the elevator, olive trees in stone- * planters and a lit vitrine of awards.- *- * Its own identity next to the coding floor's walnut and amber: light- * Scandinavian oak, sage, linen and brass. Same rules as OfficeProps: every- * furniture piece is built in local space centred on the origin, front facing- * +z, inside its `FURNITURE_SIZE` box. Repeats (slats, leaves) are merged into- * one geometry per material, and canvas faces are drawn once and shared.- */-import { memo } from "react";-import { useT } from "@/i18n";-import { PRODUCT_NAME } from "@/lib/branding";-import {- BoxGeometry, BufferGeometry, ConeGeometry, CylinderGeometry, DoubleSide, Euler, ExtrudeGeometry, Matrix4,- MeshStandardMaterial, Path, Quaternion, Shape, SphereGeometry, TorusGeometry, Vector3,-} from "three";-import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";-import { cachedCanvasTexture, canvasMaterial, redrawWhenFontsLoad } from "./canvasMaterials";-import { Box, GEO, matte, Rounded } from "./OfficeFurniture";-import { FURNITURE_SIZE, type Furniture, type FurnitureKind } from "./officeLayout";--type Vec3 = [number, number, number];-type Ctx = CanvasRenderingContext2D;--// ----------------------------------------------------------------------------// Materials: pale oak, sage, linen, brass, boucle and cognac leather.-// -----------------------------------------------------------------------------const C = {- oak: "#d2b286",- oakLight: "#e2c9a2",- oakDark: "#a88660",- sage: "#9fae93",- sageDeep: "#74866c",- linen: "#ece5d7",- boucle: "#efe9de",- cognac: "#a8653a",- ink: "#23262b",- stone: "#d9d3c7",- travertine: "#e7ddcc",- marble: "#f1eeea",- clay: "#c4775a",- led: "#ffe6c4",- eye: "#ffd46b",-} as const;--const LM = {- oak: matte(C.oak, { roughness: 0.6 }),- oakLight: matte(C.oakLight, { roughness: 0.6 }),- oakDark: matte(C.oakDark, { roughness: 0.6 }),- sage: matte(C.sage, { roughness: 0.95 }),- sageDeep: matte(C.sageDeep, { roughness: 0.9 }),- linen: matte(C.linen, { roughness: 1 }),- boucle: matte(C.boucle, { roughness: 1 }),- cognac: matte(C.cognac, { roughness: 0.55 }),- ink: matte(C.ink, { roughness: 0.35, metalness: 0.15 }),- // The mascot's satin black: dark enough to read as the logo, glossy enough that the bevel catches the light.- ghost: matte("#1f2124", { roughness: 0.3, metalness: 0.3 }),- pupil: matte("#050505", { roughness: 0.6 }),- // The brand panel's fins: satin brass that stays golden without an environment map to reflect.- fin: matte("#c9a462", { roughness: 0.4, metalness: 0.35 }),- stone: matte(C.stone, { roughness: 0.9 }),- travertine: matte(C.travertine, { roughness: 0.45 }),- marble: matte(C.marble, { roughness: 0.25 }),- clay: matte(C.clay, { roughness: 0.8 }),- brass: matte("#b08d5c", { roughness: 0.3, metalness: 0.7 }),- bronze: matte("#5a4a3a", { roughness: 0.4, metalness: 0.5 }),- charcoal: matte("#2b2f33", { roughness: 0.5, metalness: 0.1 }),- ceramic: matte("#f3efe8", { roughness: 0.35 }),- soil: matte("#3b2f26"),- pebbles: matte("#bdb3a3", { roughness: 1 }),- bark: matte("#7d6b58", { roughness: 0.95 }),- // Lit from within, so they read as light in any scene lighting.- led: new MeshStandardMaterial({ color: C.led, emissive: C.led, emissiveIntensity: 1.3, toneMapped: false }),- eye: new MeshStandardMaterial({ color: C.eye, emissive: C.eye, emissiveIntensity: 1.4, toneMapped: false }),- glass: new MeshStandardMaterial({ color: "#e8f2f4", transparent: true, opacity: 0.22, roughness: 0.05, depthWrite: false }),- crystal: new MeshStandardMaterial({ color: "#dff0f6", transparent: true, opacity: 0.6, roughness: 0.05, metalness: 0.1 }),- shade: new MeshStandardMaterial({ color: "#f3ead8", emissive: "#ffe2b8", emissiveIntensity: 0.35, roughness: 1, side: DoubleSide }),- olive: ["#8c9b76", "#6e805f", "#a7b390"].map((c) => matte(c, { flatShading: true, roughness: 0.8 })),- mags: ["#c4775a", "#2f3d56", "#e9dcc4", "#74866c", "#d9a441"].map((c) => matte(c, { roughness: 0.6 })),-};--// ----------------------------------------------------------------------------// The ghost: the mascot's own outline (MascotGigi's body path), eyes cut out-// -----------------------------------------------------------------------------/** SVG box of the mascot: the figure spans x 58–198 and y 36–208. */-const GHOST_SVG = { cx: 128, hem: 208, height: 172 };-/** Eye centres in the ghost's local space (hem at y = 0, 1 unit tall). */-const GHOST_EYES = [102, 154].map((x) => ({ x: (x - GHOST_SVG.cx) / GHOST_SVG.height, y: (GHOST_SVG.hem - 108) / GHOST_SVG.height }));-const GHOST_EYE = { rx: 10 / GHOST_SVG.height, ry: 14 / GHOST_SVG.height };-/** The mascot's pupils (MascotGigi), in SVG units: a little right of and below each eye's centre. */-const GHOST_PUPIL = { xs: [104, 156], y: 112, rx: 4, ry: 6 };--function ghostPoint(x: number, y: number): [number, number] {- return [(x - GHOST_SVG.cx) / GHOST_SVG.height, (GHOST_SVG.hem - y) / GHOST_SVG.height];-}--/** The ghost's silhouette, one unit tall with its hem on y = 0 and centred on x = 0. */-function ghostShape(): Shape {- const shape = new Shape();- shape.moveTo(...ghostPoint(58, 90));- shape.quadraticCurveTo(...ghostPoint(58, 36), ...ghostPoint(128, 36));- shape.quadraticCurveTo(...ghostPoint(198, 36), ...ghostPoint(198, 90));- for (const [x, y] of [[198, 208], [180, 186], [160, 208], [140, 186], [120, 208], [100, 186], [80, 208], [58, 186]]) {- shape.lineTo(...ghostPoint(x, y));- }- shape.closePath();- for (const eye of GHOST_EYES) {- const hole = new Path();- hole.absellipse(eye.x, eye.y, GHOST_EYE.rx, GHOST_EYE.ry, 0, Math.PI * 2, true);- shape.holes.push(hole);- }- return shape;-}--/** Extruded ghost, 1 unit tall and 0.06 deep (plus a soft bevel), its back face on z = 0. */-export const GHOST_GEOMETRY = (() => {- const geometry = new ExtrudeGeometry(ghostShape(), {- depth: 0.06, bevelEnabled: true, bevelThickness: 0.01, bevelSize: 0.008, bevelSegments: 2, curveSegments: 18,- });- geometry.translate(0, 0, 0.01);- return geometry;-})();--/** The ghost outline as a canvas path (for the screen, mat and rug faces). */-function traceGhost(ctx: Ctx, cx: number, top: number, height: number): void {- const s = height / GHOST_SVG.height;- const p = (x: number, y: number): [number, number] => [cx + (x - GHOST_SVG.cx) * s, top + (y - 36) * s];- ctx.beginPath();- ctx.moveTo(...p(58, 90));- ctx.quadraticCurveTo(...p(58, 36), ...p(128, 36));- ctx.quadraticCurveTo(...p(198, 36), ...p(198, 90));- for (const [x, y] of [[198, 208], [180, 186], [160, 208], [140, 186], [120, 208], [100, 186], [80, 208], [58, 186]]) ctx.lineTo(...p(x, y));- ctx.closePath();-}--/**- * The ghost, `height` px tall with its top at `top`, centred on `cx`: a filled- * body with filled eyes, and the mascot's pupils when a `pupils` colour is given.- */-export function drawGhost(ctx: Ctx, cx: number, top: number, height: number, body: string, eyes: string, pupils?: string): void {- traceGhost(ctx, cx, top, height);- ctx.fillStyle = body;- ctx.fill();- const s = height / GHOST_SVG.height;- const oval = (x: number, y: number, rx: number, ry: number) => {- ctx.beginPath();- ctx.ellipse(cx + (x - GHOST_SVG.cx) * s, top + (y - 36) * s, rx * s, ry * s, 0, 0, Math.PI * 2);- ctx.fill();- };- ctx.fillStyle = eyes;- for (const x of [102, 154]) oval(x, 108, 10, 14);- if (!pupils) return;- ctx.fillStyle = pupils;- for (const x of GHOST_PUPIL.xs) oval(x, GHOST_PUPIL.y, GHOST_PUPIL.rx, GHOST_PUPIL.ry);-}--// ----------------------------------------------------------------------------// Canvas faces-// -----------------------------------------------------------------------------/** Deterministic pseudo-random numbers, so drawn patterns never change between loads. */-function lcg(seed: number): () => number {- let state = seed >>> 0;- return () => {- state = (state * 1664525 + 1013904223) >>> 0;- return state / 0x1_0000_0000;- };-}--function roundRect(ctx: Ctx, x: number, y: number, w: number, h: number, r: number): void {- ctx.beginPath();- ctx.moveTo(x + r, y);- ctx.arcTo(x + w, y, x + w, y + h, r);- ctx.arcTo(x + w, y + h, x, y + h, r);- ctx.arcTo(x, y + h, x, y, r);- ctx.arcTo(x, y, x + w, y, r);- ctx.closePath();-}--/**- * The app's interface face. The bundle ships it as "Inter Variable"; a canvas- * asking for plain "Inter" silently gets the system fallback instead.- */-const FONT = "'Inter Variable', Inter, 'Segoe UI', system-ui, sans-serif";--/** Letter spacing where the canvas supports it (Chromium does; older engines just ignore it). */-function spaced(ctx: Ctx, px: number): void {- (ctx as Ctx & { letterSpacing?: string }).letterSpacing = `${px}px`;-}--/**- * The brand wall's sage panel, in metres on the wall: the plaster face, the- * ghost standing off it and the two lines of type. The canvas faces are drawn- * from the same numbers, so the halo always sits exactly behind the ghost.- */-const BRAND_PANEL = { w: 1.9, h: 2.3, y: 1.52, z: 0.05, d: 0.06 };-const BRAND_FACE = { w: 1.86, h: 2.26, px: 1024 };-const BRAND_GHOST = { hem: 1.3, size: 0.84, z: 0.09 };-const BRAND_TYPE = { wordmark: 1.02, strapline: 0.85 };-const BRAND_FONTS = [`700 120px ${FONT}`, `600 40px ${FONT}`];-const WORDMARK = PRODUCT_NAME.toUpperCase();--/** Wall height (m) → canvas row on a brand face `h` px tall. */-function brandRow(y: number, h: number): number {- return ((BRAND_PANEL.y + BRAND_FACE.h / 2 - y) / BRAND_FACE.h) * h;-}--/** The halo behind the ghost: its silhouette, blurred out in warm light (the ghost itself covers the middle). */-function drawGhostHalo(ctx: Ctx, w: number, h: number, colour: string, blur: number): void {- const height = (BRAND_GHOST.size / BRAND_FACE.h) * h;- ctx.save();- ctx.shadowColor = colour;- ctx.shadowBlur = blur;- ctx.fillStyle = colour;- for (let pass = 0; pass < 2; pass += 1) {- traceGhost(ctx, w / 2, brandRow(BRAND_GHOST.hem + BRAND_GHOST.size, h), height);- ctx.fill();- }- ctx.restore();-}--/**- * The sage panel's face: limestone-smooth plaster washed lighter at the top- * by the cove light, a warm halo where the ghost stands off it, and the- * wordmark and strapline in ink between brass rules.- */-function drawBrandFace(ctx: Ctx, w: number, h: number, strapline: string): void {- const wash = ctx.createLinearGradient(0, 0, 0, h);- wash.addColorStop(0, "#b7c4ad");- wash.addColorStop(0.45, "#a9b89e");- wash.addColorStop(1, "#9aab90");- ctx.fillStyle = wash;- ctx.fillRect(0, 0, w, h);- // Fine plaster grain, too faint to muddy the colour when the texture is minified.- const rand = lcg(2718);- for (let i = 0; i < 14000; i += 1) {- ctx.fillStyle = rand() > 0.5 ? "rgba(255,255,255,0.05)" : "rgba(60,74,56,0.05)";- ctx.fillRect(rand() * w, rand() * h, 1.5, 1.5);- }- const edge = ctx.createRadialGradient(w / 2, h * 0.45, h * 0.3, w / 2, h * 0.45, h * 0.75);- edge.addColorStop(0, "rgba(40,52,38,0)");- edge.addColorStop(1, "rgba(40,52,38,0.14)");- ctx.fillStyle = edge;- ctx.fillRect(0, 0, w, h);- drawGhostHalo(ctx, w, h, "rgba(255,232,192,0.95)", w * 0.065);-- // The wordmark: ink letters fitted to the panel, with a hairline shadow for their stand-off.- ctx.textAlign = "center";- ctx.textBaseline = "middle";- spaced(ctx, w * 0.012);- ctx.font = BRAND_FONTS[0];- const fit = Math.min(1, (w * 0.74) / ctx.measureText(WORDMARK).width);- ctx.font = `700 ${Math.round(120 * fit)}px ${FONT}`;- ctx.save();- ctx.shadowColor = "rgba(24,32,26,0.35)";- ctx.shadowBlur = 4;- ctx.shadowOffsetY = 3;- ctx.fillStyle = "#1b211e";- ctx.fillText(WORDMARK, w / 2 + w * 0.006, brandRow(BRAND_TYPE.wordmark, h));- ctx.restore();-- // The strapline between two brass rules.- const strap = brandRow(BRAND_TYPE.strapline, h);- spaced(ctx, w * 0.011);- ctx.font = BRAND_FONTS[1];- ctx.fillStyle = "rgba(27,33,30,0.82)";- ctx.fillText(strapline, w / 2 + w * 0.008, strap);- const half = ctx.measureText(strapline).width / 2;- const rule = w * 0.07, gap = w * 0.03;- ctx.fillStyle = "#9c7a43";- ctx.fillRect(w / 2 - half - gap - rule, strap - 1.5, rule, 3);- ctx.fillRect(w / 2 + half + gap, strap - 1.5, rule, 3);- spaced(ctx, 0);-}--/** The brand face's light: only the halo, black elsewhere (the emissive map, so the halo glows in any scene light). */-function drawBrandGlow(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#000000";- ctx.fillRect(0, 0, w, h);- drawGhostHalo(ctx, w, h, "rgba(255,214,160,0.9)", w * 0.065);-}--/** The Agent board totem's portrait screen: the ghost header, team counts, agent cards and the add button. */-interface TotemLabels { title: string; hint: string; add: string }--function drawTotem(ctx: Ctx, w: number, h: number, labels: TotemLabels): void {- const bg = ctx.createLinearGradient(0, 0, 0, h);- bg.addColorStop(0, "#1f2925");- bg.addColorStop(1, "#121816");- ctx.fillStyle = bg;- ctx.fillRect(0, 0, w, h);- // Header: the ghost, the title and a sage rule.- drawGhost(ctx, 78, 46, 70, "#f1ebe1", "#1f2925");- ctx.fillStyle = "#f1ebe1";- ctx.textBaseline = "middle";- ctx.font = `700 44px ${FONT}`;- ctx.fillText(labels.title, 138, 72);- ctx.fillStyle = "rgba(241,235,225,0.55)";- ctx.font = `500 24px ${FONT}`;- ctx.fillText(labels.hint, 138, 110);- ctx.fillStyle = C.sage;- ctx.fillRect(40, 148, w - 80, 3);- // Three counts: working, waiting, idle.- const counts: [string, string][] = [["#4ade80", "4"], ["#fbbf24", "1"], ["#aab3c2", "3"]];- counts.forEach(([colour, n], i) => {- const x = 40 + i * ((w - 80) / 3);- ctx.fillStyle = "rgba(255,255,255,0.06)";- roundRect(ctx, x + 4, 172, (w - 80) / 3 - 8, 84, 14);- ctx.fill();- ctx.fillStyle = colour;- ctx.beginPath(); ctx.arc(x + 34, 214, 9, 0, Math.PI * 2); ctx.fill();- ctx.fillStyle = "#f1ebe1";- ctx.font = `700 40px ${FONT}`;- ctx.fillText(n, x + 56, 216);- });- // Agent cards: avatar, name, role, status.- const avatars = ["#c4775a", "#74866c", "#7c8fa8", "#d9a441", "#8b6246", "#9fae93", "#b56a4c"];- const status = ["#4ade80", "#4ade80", "#fbbf24", "#aab3c2", "#4ade80", "#aab3c2", "#4ade80"];- avatars.forEach((colour, i) => {- const y = 286 + i * 86;- ctx.fillStyle = i === 0 ? "rgba(159,174,147,0.18)" : "rgba(255,255,255,0.05)";- roundRect(ctx, 40, y, w - 80, 72, 14);- ctx.fill();- ctx.fillStyle = colour;- ctx.beginPath(); ctx.arc(80, y + 36, 22, 0, Math.PI * 2); ctx.fill();- ctx.fillStyle = "rgba(241,235,225,0.9)";- ctx.fillRect(118, y + 20, 150 + ((i * 47) % 110), 13);- ctx.fillStyle = "rgba(241,235,225,0.38)";- ctx.fillRect(118, y + 44, 90 + ((i * 31) % 70), 9);- ctx.fillStyle = status[i];- ctx.beginPath(); ctx.arc(w - 72, y + 36, 9, 0, Math.PI * 2); ctx.fill();- });- // The add button.- ctx.fillStyle = C.sage;- roundRect(ctx, 40, h - 108, w - 80, 68, 34);- ctx.fill();- ctx.fillStyle = "#16201b";- ctx.font = `700 32px ${FONT}`;- ctx.textAlign = "center";- ctx.fillText(`+ ${labels.add}`, w / 2, h - 73);- ctx.textAlign = "left";-}--/**- * Charcoal coir mat: a ribbed weave, an oat border band with a fine inner- * line, and the mascot in oat with its yellow eyes and pupils in the middle.- */-function drawMat(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#353430";- ctx.fillRect(0, 0, w, h);- // Woven ribs across the mat, then sparse lighter fibres along them.- for (let y = 0; y < h; y += 6) {- ctx.fillStyle = (y / 6) % 2 ? "rgba(0,0,0,0.12)" : "rgba(255,240,215,0.035)";- ctx.fillRect(0, y, w, 3);- }- const rand = lcg(4242);- for (let i = 0; i < 2600; i += 1) {- ctx.fillStyle = "rgba(255,240,215,0.05)";- ctx.fillRect(rand() * w, rand() * h, 5, 1.5);- }- const band = w * 0.045;- ctx.strokeStyle = "#cdbb98";- ctx.lineWidth = band;- ctx.strokeRect(band * 1.1, band * 1.1, w - band * 2.2, h - band * 2.2);- ctx.lineWidth = band * 0.18;- ctx.strokeRect(band * 2.6, band * 2.6, w - band * 5.2, h - band * 5.2);- const height = w * 0.46;- drawGhost(ctx, w / 2, h / 2 - height / 2, height, "#d9c9a6", C.eye, "#2a2926");-}--/** Oat wool rug: a soft weave, a sage band and a fine clay line near the edge. */-function drawLobbyRug(ctx: Ctx, w: number, h: number): void {- const rand = lcg(9001);- ctx.fillStyle = "#e8dfcf";- ctx.fillRect(0, 0, w, h);- for (let i = 0; i < 7000; i += 1) {- ctx.fillStyle = rand() > 0.5 ? "rgba(255,255,255,0.16)" : "rgba(120,100,76,0.08)";- ctx.fillRect(rand() * w, rand() * h, 2, 2);- }- // A sage band inside the edge, then a fine clay line.- ctx.strokeStyle = "rgba(116,134,108,0.55)";- ctx.lineWidth = 18;- ctx.strokeRect(44, 44, w - 88, h - 88);- ctx.strokeStyle = C.clay;- ctx.lineWidth = 4;- ctx.strokeRect(26, 26, w - 52, h - 52);-}--/** A framed certificate: cream paper, a sage seal and lines of text. */-function drawCertificate(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#f6f1e7";- ctx.fillRect(0, 0, w, h);- ctx.strokeStyle = "#c7a15e";- ctx.lineWidth = 4;- ctx.strokeRect(10, 10, w - 20, h - 20);- ctx.fillStyle = "#2f3d56";- ctx.fillRect(w * 0.25, h * 0.22, w * 0.5, 8);- ctx.fillStyle = "rgba(47,61,86,0.45)";- for (let i = 0; i < 3; i += 1) ctx.fillRect(w * 0.18, h * 0.42 + i * 16, w * 0.64, 4);- ctx.fillStyle = C.sage;- ctx.beginPath(); ctx.arc(w * 0.5, h * 0.8, 14, 0, Math.PI * 2); ctx.fill();-}--/** Sharp at a glance: the high camera sees the brand wall and the mat at a steep angle (three clamps it to the GPU's limit). */-const OBLIQUE_ANISOTROPY = 16;--/**- * The brand panel's face: the plaster-and-type canvas lit by the scene, plus- * the halo as its emissive map so the light behind the ghost glows in any- * scene lighting. Sage where no canvas exists.- */-/** One face per strapline, so a language switch paints a new one. */-const brandFaces = new Map<string, MeshStandardMaterial>();-function brandFaceMaterial(strapline: string): MeshStandardMaterial {- const cached = brandFaces.get(strapline);- if (cached) return cached;- const w = BRAND_FACE.px, h = Math.round((BRAND_FACE.px * BRAND_FACE.h) / BRAND_FACE.w);- const key = `lobby:brand-face:${strapline}`;- const draw = (ctx: Ctx, cw: number, ch: number) => drawBrandFace(ctx, cw, ch, strapline);- const map = cachedCanvasTexture(key, w, h, draw);- const glow = cachedCanvasTexture("lobby:brand-glow", w / 4, h / 4, drawBrandGlow);- if (map) map.anisotropy = OBLIQUE_ANISOTROPY;- redrawWhenFontsLoad(key, map, BRAND_FONTS, draw);- const material = new MeshStandardMaterial({- color: map ? "#ffffff" : C.sage, map, roughness: 0.92,- emissive: glow ? "#ffffff" : "#000000", emissiveMap: glow, emissiveIntensity: 0.7,- });- brandFaces.set(strapline, material);- return material;-}--/** A canvas material whose text waits for the interface face (see `FONT`). */-function typedCanvasMaterial(key: string, w: number, h: number, draw: (ctx: Ctx, w: number, h: number) => void,- fonts: readonly string[], options: Parameters<typeof canvasMaterial>[4]): MeshStandardMaterial {- const material = canvasMaterial(key, w, h, draw, options);- redrawWhenFontsLoad(key, material.map, fonts, draw);- return material;-}--/** The entrance mat: high enough resolution that the ghost stays crisp at the camera's grazing angle. */-function matMaterial(): MeshStandardMaterial {- const material = canvasMaterial("lobby:mat", 512, 884, drawMat, { fallback: "#353430", roughness: 1 });- if (material.map) material.map.anisotropy = OBLIQUE_ANISOTROPY;- return material;-}--const faces = {- brand: brandFaceMaterial,- totem: (labels: TotemLabels) => typedCanvasMaterial(`lobby:totem:${labels.title}|${labels.hint}|${labels.add}`, 512, 1024,- (ctx, w, h) => drawTotem(ctx, w, h, labels), [`700 44px ${FONT}`, `500 24px ${FONT}`],- { glow: 0.9, fallback: "#1a2320", roughness: 0.3 }),- mat: matMaterial,- rug: () => canvasMaterial("lobby:rug", 512, 320, drawLobbyRug, { fallback: "#e8dfcf", roughness: 1 }),- certificate: () => canvasMaterial("lobby:certificate", 128, 160, drawCertificate, { fallback: "#f6f1e7", roughness: 0.8 }),-};--// ----------------------------------------------------------------------------// Shared geometry-// -----------------------------------------------------------------------------const LGEO = {- cyl: new CylinderGeometry(1, 1, 1, 24),- sphere: new SphereGeometry(1, 18, 12),- dome: new SphereGeometry(1, 18, 8, 0, Math.PI * 2, Math.PI / 2, Math.PI / 2),- planter: new CylinderGeometry(0.42, 0.34, 0.62, 32),- shade: new CylinderGeometry(0.19, 0.225, 0.3, 32, 1, true),- cup: new CylinderGeometry(0.075, 0.03, 0.13, 24),- handle: new TorusGeometry(0.035, 0.008, 8, 16, Math.PI),- crystal: new ConeGeometry(0.06, 0.22, 4),-};--function Cyl({ radius, height, position, material, rotation, cast = true }: {- radius: number; height: number; position: Vec3; material: MeshStandardMaterial; rotation?: Vec3; cast?: boolean;-}) {- return <mesh geometry={LGEO.cyl} material={material} position={position} rotation={rotation} scale={[radius, height, radius]} castShadow={cast} receiveShadow />;-}--function Panel({ size, position, material, rotation }: { size: [number, number]; position: Vec3; material: MeshStandardMaterial; rotation?: Vec3 }) {- return <mesh position={position} rotation={rotation} material={material}><planeGeometry args={size} /></mesh>;-}--/** The brand wall's oak slats, merged into one geometry. */-const BRAND = { w: FURNITURE_SIZE.brandWall.w, pitch: 0.08 };-const BRAND_SLATS = (() => {- const count = Math.floor((BRAND.w - 0.06) / BRAND.pitch);- const parts = Array.from({ length: count }, (_, i) =>- new BoxGeometry(0.042, 2.64, 0.032).translate(-((count - 1) * BRAND.pitch) / 2 + i * BRAND.pitch, 1.44, -0.002));- const merged = mergeGeometries(parts, false);- parts.forEach((p) => p.dispose());- return merged;-})();--/**- * An olive tree's canopy: small silvery leaf clumps in a loose, lopsided- * crown round three branch tips; merged per leaf tone, three draw calls a tree.- */-const OLIVE_CROWNS: Vec3[] = [[-0.18, 1.9, 0.08], [0.18, 2.05, -0.06], [0.0, 1.72, -0.16], [0.04, 2.14, 0.12]];-const OLIVE_GEOMETRIES: BufferGeometry[] = (() => {- const base = new SphereGeometry(1, 8, 5);- const tones: BufferGeometry[][] = [[], [], []];- const rand = lcg(31337);- const matrix = new Matrix4(), rotation = new Quaternion(), euler = new Euler();- const at = new Vector3(), scale = new Vector3();- for (let i = 0; i < 168; i += 1) {- const [cx, cy, cz] = OLIVE_CROWNS[i % OLIVE_CROWNS.length];- const angle = rand() * Math.PI * 2;- const r = Math.sqrt(rand()) * 0.24;- at.set(cx + Math.cos(angle) * r, cy + (rand() - 0.35) * 0.3, cz + Math.sin(angle) * r);- euler.set((rand() - 0.5) * 0.8, rand() * Math.PI, (rand() - 0.5) * 0.8);- rotation.setFromEuler(euler);- const size = 0.06 + rand() * 0.04;- scale.set(size * 1.4, size * 0.5, size);- matrix.compose(at, rotation, scale);- tones[i % 3].push(base.clone().applyMatrix4(matrix));- }- base.dispose();- return tones.map((parts) => {- const merged = mergeGeometries(parts, false);- parts.forEach((p) => p.dispose());- return merged;- });-})();--// ----------------------------------------------------------------------------// Furniture-// -----------------------------------------------------------------------------/**- * The brand wall: pale oak slats on a linen backing between an oak plinth and- * a cap with a warm cove light; in front a sage plaster panel between brass- * fins. On it the mascot stands off on brass pins in satin black, halo-lit- * from behind, its yellow eyes and dark pupils showing through the cut-outs,- * over the wordmark and strapline printed on the plaster face.- */-function BrandWall() {- const t = useT();- const w = BRAND.w;- const ghost = { y: BRAND_GHOST.hem, size: BRAND_GHOST.size, z: BRAND_GHOST.z };- const front = BRAND_PANEL.z + BRAND_PANEL.d / 2;- return (- <group>- <Box size={[w, 2.84, 0.15]} position={[0, 1.42, -0.1]} material={LM.linen} />- <mesh geometry={BRAND_SLATS} material={LM.oakLight} castShadow receiveShadow />- <Box size={[w, 0.1, 0.3]} position={[0, 0.05, -0.03]} material={LM.oakDark} />- <Box size={[w, 0.06, 0.32]} position={[0, 2.87, -0.02]} material={LM.oakDark} />- <Box size={[w - 0.1, 0.008, 0.02]} position={[0, 2.836, 0.12]} material={LM.led} cast={false} />- {/* The sage panel, its plaster face with the type, and its brass fins. */}- <Rounded size={[BRAND_PANEL.w, BRAND_PANEL.h, BRAND_PANEL.d]} radius={0.02} position={[0, BRAND_PANEL.y, BRAND_PANEL.z]} material={LM.sage} />- <mesh position={[0, BRAND_PANEL.y, front + 0.0006]} material={faces.brand(t("society.office.lobby_strapline"))} receiveShadow>- <planeGeometry args={[BRAND_FACE.w, BRAND_FACE.h]} />- </mesh>- {[-0.99, 0.99].map((x) => <Box key={x} size={[0.025, 2.36, 0.07]} position={[x, BRAND_PANEL.y, 0.055]} material={LM.fin} />)}- {/* The eyes behind the ghost's cut-outs: lit yellow, with the mascot's pupils. */}- {GHOST_EYES.map((eye) => (- <mesh key={eye.x} position={[eye.x * ghost.size, ghost.y + eye.y * ghost.size, front + 0.003]} material={LM.eye}- scale={[GHOST_EYE.rx * ghost.size * 1.3, GHOST_EYE.ry * ghost.size * 1.2, 1]}>- <circleGeometry args={[1, 24]} />- </mesh>- ))}- {GHOST_PUPIL.xs.map((x) => (- <mesh key={x} material={LM.pupil} position={[ghostPoint(x, 0)[0] * ghost.size, ghostPoint(0, GHOST_PUPIL.y)[1] * ghost.size + ghost.y, front + 0.005]}- scale={[(GHOST_PUPIL.rx / GHOST_SVG.height) * ghost.size, (GHOST_PUPIL.ry / GHOST_SVG.height) * ghost.size, 1]}>- <circleGeometry args={[1, 16]} />- </mesh>- ))}- {/* Four brass stand-off pins hold the ghost off the panel. */}- {[[-0.2, 0.35], [0.2, 0.35], [-0.2, 0.8], [0.2, 0.8]].map(([x, y]) => (- <Cyl key={`${x}:${y}`} radius={0.01} height={ghost.z - front + 0.01} position={[x * ghost.size, ghost.y + y * ghost.size, (front + ghost.z + 0.01) / 2]}- rotation={[Math.PI / 2, 0, 0]} material={LM.brass} cast={false} />- ))}- <mesh geometry={GHOST_GEOMETRY} material={LM.ghost} position={[0, ghost.y, ghost.z]} scale={[ghost.size, ghost.size, 0.9]} castShadow receiveShadow />- </group>- );-}--/**- * The Agent board as a standing touch-screen totem: an ink body between pale- * oak cheeks with warm light lines, a portrait screen of the team, the ghost- * in brass on top and an oak plinth.- */-function AgentTotem() {- const t = useT();- const labels: TotemLabels = { title: t("society.office.cp_manage"), hint: t("society.office.lobby_board_hint"), add: t("society.office.lobby_new_agent") };- return (- <group>- <Rounded size={[0.88, 0.06, 0.48]} radius={0.02} position={[0, 0.03, 0]} material={LM.oakDark} />- <Rounded size={[0.76, 1.94, 0.12]} radius={0.03} position={[0, 1.03, -0.02]} material={LM.charcoal} />- {[-0.405, 0.405].map((x) => (- <group key={x}>- <Rounded size={[0.05, 1.96, 0.18]} radius={0.015} position={[x, 1.04, -0.02]} material={LM.oakLight} />- <Box size={[0.008, 1.7, 0.006]} position={[x, 1.1, 0.072]} material={LM.led} cast={false} />- </group>- ))}- <Panel size={[0.66, 1.32]} position={[0, 1.2, 0.0405]} material={faces.totem(labels)} />- <Box size={[0.66, 0.01, 0.01]} position={[0, 1.9, 0.045]} material={LM.brass} cast={false} />- <Box size={[0.4, 0.035, 0.004]} position={[0, 0.34, 0.041]} material={LM.bronze} cast={false} />- <mesh geometry={GHOST_GEOMETRY} material={LM.brass} position={[0, 1.92, -0.03]} scale={[0.1, 0.1, 0.6]} castShadow />- </group>- );-}--/** A low boucle sofa on an oak plinth, deep seat cushions, a sage and a clay pillow. */-function LobbySofa() {- return (- <group>- <Box size={[2.1, 0.06, 0.75]} position={[0, 0.03, 0]} material={LM.charcoal} />- <Rounded size={[2.26, 0.08, 0.9]} radius={0.02} position={[0, 0.1, 0]} material={LM.oak} />- <Rounded size={[2.26, 0.64, 0.24]} radius={0.1} position={[0, 0.46, -0.35]} material={LM.boucle} />- {[-1.07, 1.07].map((x) => <Rounded key={x} size={[0.16, 0.5, 0.9]} radius={0.07} position={[x, 0.39, 0]} material={LM.boucle} />)}- {[-0.51, 0.51].map((x) => (- <group key={x}>- <Rounded size={[1.0, 0.2, 0.68]} radius={0.08} position={[x, 0.24, 0.08]} material={LM.boucle} />- <group position={[x, 0.52, -0.17]} rotation={[-0.14, 0, 0]}>- <Rounded size={[0.98, 0.36, 0.14]} radius={0.06} position={[0, 0, 0]} material={LM.boucle} />- </group>- </group>- ))}- <group position={[-0.72, 0.52, -0.04]} rotation={[-0.25, 0.25, 0.12]}>- <Rounded size={[0.4, 0.36, 0.12]} radius={0.05} position={[0, 0, 0]} material={LM.sage} />- </group>- <group position={[0.74, 0.5, -0.04]} rotation={[-0.22, -0.3, -0.1]}>- <Rounded size={[0.36, 0.32, 0.11]} radius={0.05} position={[0, 0, 0]} material={LM.clay} />- </group>- </group>- );-}--/** An oak lounge chair with cognac leather cushions and a tilted back. */-function LobbyArmchair() {- return (- <group>- {[-0.33, 0.33].flatMap((x) => [-0.33, 0.33].map((z) => (- <Box key={`${x}:${z}`} size={[0.045, 0.58, 0.045]} position={[x, 0.29, z]} material={LM.oak} />- )))}- {[-0.34, 0.34].map((x) => <Rounded key={x} size={[0.075, 0.035, 0.8]} radius={0.012} position={[x, 0.595, 0]} material={LM.oak} />)}- <Box size={[0.62, 0.05, 0.66]} position={[0, 0.3, 0]} material={LM.oak} />- <Rounded size={[0.6, 0.12, 0.62]} radius={0.05} position={[0, 0.385, 0.04]} material={LM.cognac} />- <group position={[0, 0.36, -0.25]} rotation={[-0.22, 0, 0]}>- <Rounded size={[0.58, 0.42, 0.1]} radius={0.045} position={[0, 0.21, 0]} material={LM.cognac} />- <Box size={[0.62, 0.04, 0.05]} position={[0, 0.43, -0.03]} material={LM.oak} />- </group>- </group>- );-}--/** An oval travertine coffee table on two oak drums, magazines, a sage bowl and an olive sprig. */-function LobbyTable() {- return (- <group>- <mesh geometry={LGEO.cyl} material={LM.travertine} position={[0, 0.3825, 0]} scale={[0.59, 0.035, 0.365]} castShadow receiveShadow />- {[-0.26, 0.26].map((x) => <Cyl key={x} radius={0.1} height={0.365} position={[x, 0.1825, 0]} material={LM.oak} />)}- {/* A stack of magazines and one fanned out beside it. */}- <group position={[-0.2, 0.4, 0.04]} rotation={[0, 0.22, 0]}>- {[0, 1, 2].map((i) => (- <Box key={i} size={[0.22 - i * 0.01, 0.009, 0.29 - i * 0.01]} position={[0, 0.0045 + i * 0.009, 0]} material={LM.mags[i]} cast={false} />- ))}- </group>- <group position={[-0.02, 0.4, -0.08]} rotation={[0, -0.5, 0]}>- <Box size={[0.21, 0.008, 0.28]} position={[0, 0.004, 0]} material={LM.mags[3]} cast={false} />- </group>- <mesh geometry={LGEO.dome} material={LM.sageDeep} position={[0.26, 0.47, 0.05]} scale={[0.1, 0.07, 0.1]} castShadow />- {[[-0.03, 0.01], [0.03, -0.02], [0.0, 0.035]].map(([x, z], i) => (- <mesh key={i} geometry={LGEO.sphere} material={LM.mags[4]} position={[0.26 + x, 0.435, 0.05 + z]} scale={0.028} />- ))}- <Cyl radius={0.025} height={0.09} position={[0.38, 0.445, -0.12]} material={LM.ceramic} />- {[-0.3, 0.1, 0.4].map((tilt, i) => (- <group key={i} position={[0.38, 0.49, -0.12]} rotation={[tilt * 0.3, i * 1.9, tilt]}>- <Box size={[0.005, 0.07, 0.005]} position={[0, 0.035, 0]} material={LM.bark} cast={false} />- <mesh geometry={GEO.blob} material={LM.olive[i]} position={[0, 0.06, 0]} scale={[0.022, 0.012, 0.022]} />- </group>- ))}- </group>- );-}--/** A round marble side table on a brass stem, a book and a glass. */-function SideTable() {- return (- <group>- <Cyl radius={0.18} height={0.02} position={[0, 0.01, 0]} material={LM.brass} />- <Cyl radius={0.018} height={0.52} position={[0, 0.28, 0]} material={LM.brass} />- <Cyl radius={0.235} height={0.025} position={[0, 0.5525, 0]} material={LM.marble} />- <Box size={[0.16, 0.025, 0.22]} position={[-0.05, 0.5775, 0.02]} material={LM.mags[1]} cast={false} />- <Box size={[0.15, 0.02, 0.2]} position={[-0.05, 0.6, 0.02]} material={LM.mags[2]} cast={false} />- <Cyl radius={0.03} height={0.08} position={[0.12, 0.605, -0.06]} material={LM.glass} cast={false} />- </group>- );-}--/** Tripod floor lamp: three oak legs, a brass neck and a glowing linen drum. */-const LAMP_LEG = { spread: 0.2, apex: 1.24 };-/** Height of the bulb inside the shade; the lounge's light sits there. */-const LAMP_LIGHT_Y = 1.5;-function LobbyLamp() {- const tilt = Math.atan2(LAMP_LEG.spread, LAMP_LEG.apex);- const length = Math.hypot(LAMP_LEG.spread, LAMP_LEG.apex);- return (- <group>- {[0, 1, 2].map((i) => (- <group key={i} rotation={[0, (i * Math.PI * 2) / 3 + 0.4, 0]}>- <Cyl radius={0.014} height={length} position={[LAMP_LEG.spread / 2, LAMP_LEG.apex / 2, 0]} rotation={[0, 0, tilt]} material={LM.oak} />- </group>- ))}- <Cyl radius={0.012} height={0.26} position={[0, 1.36, 0]} material={LM.brass} />- <mesh geometry={LGEO.shade} material={LM.shade} position={[0, 1.56, 0]} castShadow />- <mesh geometry={LGEO.sphere} material={LM.led} position={[0, LAMP_LIGHT_Y, 0]} scale={0.045} />- </group>- );-}--/** The three branches from the trunk's fork to the crowns, as placed cylinders. */-const OLIVE_BRANCHES = OLIVE_CROWNS.map(([x, y, z]) => {- const from = new Vector3(0.04, 1.3, -0.02);- const dir = new Vector3(x, y - 0.1, z).sub(from);- const length = dir.length();- return {- position: from.clone().addScaledVector(dir, 0.5).toArray() as Vec3,- quaternion: new Quaternion().setFromUnitVectors(new Vector3(0, 1, 0), dir.normalize()),- scale: [0.028, length, 0.028] as Vec3,- };-});--/** An olive tree in a pale stone planter: a twisting trunk, three branches and a silvery crown. */-function OliveTree() {- return (- <group>- <mesh geometry={LGEO.planter} material={LM.stone} position={[0, 0.31, 0]} castShadow receiveShadow />- <Cyl radius={0.43} height={0.03} position={[0, 0.62, 0]} material={LM.stone} />- <Cyl radius={0.39} height={0.01} position={[0, 0.631, 0]} material={LM.pebbles} cast={false} />- <Cyl radius={0.07} height={0.62} position={[0.02, 0.93, 0]} rotation={[0.06, 0, -0.08]} material={LM.bark} />- <Cyl radius={0.05} height={0.5} position={[0.06, 1.38, -0.02]} rotation={[-0.1, 0, 0.18]} material={LM.bark} />- {OLIVE_BRANCHES.map((branch, i) => (- <mesh key={i} geometry={LGEO.cyl} material={LM.bark} position={branch.position} quaternion={branch.quaternion} scale={branch.scale} castShadow />- ))}- {OLIVE_GEOMETRIES.map((geometry, i) => <mesh key={i} geometry={geometry} material={LM.olive[i]} castShadow receiveShadow />)}- </group>- );-}--/** A brass cup on a round foot with two handles. */-function Cup({ position, scale = 1 }: { position: Vec3; scale?: number }) {- return (- <group position={position} scale={scale}>- <Cyl radius={0.05} height={0.03} position={[0, 0.015, 0]} material={LM.oakDark} />- <Cyl radius={0.012} height={0.08} position={[0, 0.07, 0]} material={LM.brass} />- <mesh geometry={LGEO.cup} material={LM.brass} position={[0, 0.175, 0]} castShadow />- {[-1, 1].map((side) => (- <mesh key={side} geometry={LGEO.handle} material={LM.brass} position={[side * 0.07, 0.18, 0]} rotation={[0, 0, side * -Math.PI / 2]} />- ))}- </group>- );-}--/**- * A lit oak vitrine of awards: glass shelves on a sage back behind a glass- * front — brass cups, a crystal obelisk, a framed certificate and the ghost- * in brass on an oak block.- */-function AwardCase() {- const shelves = [0.56, 0.98, 1.4];- return (- <group>- <Box size={[1.3, 0.12, 0.42]} position={[0, 0.06, 0]} material={LM.oakDark} />- <Box size={[1.3, 1.83, 0.03]} position={[0, 1.035, -0.195]} material={LM.oak} />- <Box size={[1.22, 1.72, 0.01]} position={[0, 1.02, -0.175]} material={LM.sage} />- {[-0.63, 0.63].map((x) => <Box key={x} size={[0.04, 1.83, 0.42]} position={[x, 1.035, 0]} material={LM.oak} />)}- <Box size={[1.3, 0.04, 0.42]} position={[0, 1.93, 0]} material={LM.oak} />- <Box size={[1.18, 0.008, 0.02]} position={[0, 1.905, 0.12]} material={LM.led} cast={false} />- {shelves.map((y) => <Box key={y} size={[1.22, 0.012, 0.36]} position={[0, y, -0.01]} material={LM.glass} cast={false} />)}- <Box size={[1.22, 1.78, 0.008]} position={[0, 1.01, 0.2]} material={LM.glass} cast={false} />- {/* Floor level: the big cup and a certificate leaning back. */}- <Cup position={[-0.3, 0.12, 0]} scale={1.3} />- <group position={[0.25, 0.12, -0.08]} rotation={[-0.14, 0, 0]}>- <Box size={[0.3, 0.37, 0.02]} position={[0, 0.185, 0]} material={LM.oakDark} />- <Panel size={[0.25, 0.32]} position={[0, 0.185, 0.0105]} material={faces.certificate()} />- </group>- {/* First shelf: two cups. */}- <Cup position={[-0.35, shelves[0] + 0.006, 0]} />- <Cup position={[0.1, shelves[0] + 0.006, -0.02]} scale={0.85} />- <Box size={[0.2, 0.05, 0.1]} position={[0.4, shelves[0] + 0.031, 0]} material={LM.oakDark} />- <Box size={[0.14, 0.03, 0.004]} position={[0.4, shelves[0] + 0.031, 0.051]} material={LM.brass} cast={false} />- {/* Second shelf: the crystal obelisk and the brass ghost. */}- <mesh geometry={LGEO.crystal} material={LM.crystal} position={[-0.25, shelves[1] + 0.116, 0]} rotation={[0, Math.PI / 4, 0]} />- <Box size={[0.14, 0.05, 0.1]} position={[0.22, shelves[1] + 0.031, 0]} material={LM.oakDark} />- <mesh geometry={GHOST_GEOMETRY} material={LM.brass} position={[0.22, shelves[1] + 0.056, -0.02]} scale={[0.16, 0.16, 0.5]} castShadow />- {/* Top shelf: books and a small cup. */}- {[0.04, 0.03, 0.045, 0.035].map((w, i) => (- <Box key={i} size={[w, 0.22 + (i % 2) * 0.03, 0.17]} position={[-0.45 + i * 0.05, shelves[2] + 0.12 + (i % 2) * 0.015, -0.03]} material={LM.mags[i]} />- ))}- <Cup position={[0.3, shelves[2] + 0.006, 0]} scale={0.8} />- </group>- );-}--/** A flat textured floor piece (mat, rug), sized per instance. */-function FloorPiece({ w, d, material, lift }: { w: number; d: number; material: MeshStandardMaterial; lift: number }) {- return <Box size={[w, lift, d]} position={[0, lift / 2, 0]} material={material} cast={false} />;-}--/** Renderers of the lobby's furniture kinds; merged into OfficeProps' exhaustive table. */-export const LOBBY_RENDERERS = {- brandWall: () => <BrandWall />,- agentTotem: () => <AgentTotem />,- lobbySofa: () => <LobbySofa />,- lobbyArmchair: () => <LobbyArmchair />,- lobbyTable: () => <LobbyTable />,- sideTable: () => <SideTable />,- lobbyLamp: () => <LobbyLamp />,- oliveTree: () => <OliveTree />,- awardCase: () => <AwardCase />,- entranceMat: ({ item }: { item: Furniture }) => {- const size = item.size ?? FURNITURE_SIZE.entranceMat;- return <FloorPiece w={size.w} d={size.d} material={faces.mat()} lift={0.014} />;- },- lobbyRug: ({ item }: { item: Furniture }) => {- const size = item.size ?? FURNITURE_SIZE.lobbyRug;- return <FloorPiece w={size.w} d={size.d} material={faces.rug()} lift={0.016} />;- },-} satisfies Partial<Record<FurnitureKind, (props: { item: Furniture }) => JSX.Element>>;--// ----------------------------------------------------------------------------// Fittings: the lounge's light-// -----------------------------------------------------------------------------/**- * The lounge's one real light: warm, from inside the tripod lamp's linen- * shade, so the pool of light round the sofa has a visible source. (The lobby- * has no ceiling to hang a pendant from; one floating in the night read as a- * hoop in mid-air from the high camera.)- */-export const LobbyFittings = memo(function LobbyFittings({ lamp }: { lamp: Furniture }) {- return <pointLight position={[lamp.x, LAMP_LIGHT_Y, lamp.z]} color="#ffd9ad" intensity={4} distance={6} decay={2} />;-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/MissionControlPanel.tsx b/dodaios/ui/web/frontend/src/components/society/office/MissionControlPanel.tsxdeleted file mode 100644index c2dd096729..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/MissionControlPanel.tsx+++ /dev/null@@ -1,411 +0,0 @@-/**- * Mission Control, the screen in the middle of the coding floor: start new- * coding agents, and message several running ones at once.- *- * "Start an agent" opens panes through the IDE's own `POST /terminals`- * (workspace, CLI, how many) and, when a task is given, waits for each pane to- * come up and hands it the task through `/terminals/{name}/prompt` — the path- * voice and the grid use, so every prompt is recorded and receipted the same- * way. Files dropped on the launcher are held until each pane is live and- * then go through the pane's own `/terminals/{name}/attach`. "New workspace"- * opens a folder as another workspace through the IDE's `POST /session`,- * with the new agents as its panes. "Message several agents" sends one- * message to every picked session. The office adds no backend contract of- * its own.- */-import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";-import { Minus, Paperclip, Plus, X } from "lucide-react";-import { useT } from "@/i18n";-import {- attachToTerminal, fetchIdeAgents, fetchIdeProjects, fetchIdeState, fetchWorkspacePanes, interruptTerminal,- openIdeWorkspace, openTerminal, promptTerminal, startTerminal,- type AgentStatus, type DropAttachment, type IdeProject, type WorkspaceCard,-} from "@/lib/agenticIdeApi";-import { openProject } from "@/lib/chatLibraryApi";-import { useWorkspacePanesStore } from "@/store/workspacePanes";-import { AgentMark } from "@/components/agentic/AgentMark";-import { BrandedSelect } from "@/components/ui/select";-import { paneOccupants, type PaneOccupant } from "./codingFloor";-import { NewWorkspaceFields, type NewWorkspaceTarget } from "./NewWorkspaceFields";-import { briefWithFiles, heldPayload, useSpawnFiles, type HeldFile } from "./spawnFiles";-import "./missionControl.css";--/** At most this many agents per launch; the IDE caps the workspace on its own too. */-export const MAX_LAUNCH = 4;-/** A new pane gets this long to start before its first task is given up on. */-const START_TIMEOUT_MS = 30_000;-const START_POLL_MS = 600;-const START_JITTER_MS = 300;--/** The workspace picker's value for "open a new workspace". */-export const NEW_WORKSPACE = "__new__";--type LaunchLine = { tone: "busy" | "ok" | "warn" | "error"; text: string };--/** Coding CLIs a new agent can run: installed, and not a plain shell. Pure. */-export function launchableAgents(agents: readonly AgentStatus[]): AgentStatus[] {- return agents.filter((a) => a.installed && (a.kind ?? "cli") !== "shell");-}--/** Projects a new workspace can open in: real, reachable folders the user connected. Pure. */-export function workspaceProjects(projects: readonly IdeProject[]): IdeProject[] {- return projects.filter((p) => !p.scratch && !p.archived && p.exists);-}--/** Every session on the floor, or none: the one bulk pick the list offers. Pure. */-export function pickAll(occupants: readonly PaneOccupant[], picked: ReadonlySet<string>): Set<string> {- const everyone = occupants.every((o) => picked.has(o.agent.agentId));- return everyone ? new Set() : new Set(occupants.map((o) => o.agent.agentId));-}--/** Wait until the pane `name` of `workspaceId` is live; false when it failed or the clock ran out. */-async function waitLive(workspaceId: string, name: string): Promise<boolean> {- const deadline = Date.now() + START_TIMEOUT_MS;- for (;;) {- try {- const { panes } = await fetchWorkspacePanes();- const row = panes.find((p) => p.workspace_id === workspaceId && p.name === name);- if (row?.status === "live") return true;- if (row && row.status !== "pending") return false;- } catch (err) {- // One failed poll is not an answer; the next one decides.- console.warn("Mission Control: pane poll failed", err);- }- if (Date.now() >= deadline) return false;- await new Promise((resolve) => setTimeout(resolve, START_POLL_MS + Math.random() * START_JITTER_MS));- }-}--function errorText(err: unknown): string {- return err instanceof Error ? err.message : String(err);-}--/** What a launch read once and every pane shares: the attached files, as references and analysis. */-type Handover = { references: string[]; analysis: DropAttachment[] };--/** Start coding agents: CLI, workspace (or a new one), how many, an optional first task and files. Also the coding floor's spawn point. */-export function StartAgent() {- const t = useT();- const [workspaces, setWorkspaces] = useState<WorkspaceCard[] | null>(null);- const [projects, setProjects] = useState<IdeProject[]>([]);- const [agents, setAgents] = useState<AgentStatus[] | null>(null);- const [loadError, setLoadError] = useState<string | null>(null);- const [workspaceId, setWorkspaceId] = useState("");- const [newTarget, setNewTarget] = useState<NewWorkspaceTarget | null>(null);- const [newName, setNewName] = useState("");- const [agentName, setAgentName] = useState("");- const [count, setCount] = useState(1);- const [task, setTask] = useState("");- const [sharpen, setSharpen] = useState(false);- const [running, setRunning] = useState(false);- const [lines, setLines] = useState<LaunchLine[]>([]);- const files = useSpawnFiles();- const fileInput = useRef<HTMLInputElement>(null);-- const loadProjects = useCallback(() => fetchIdeProjects()- .then((listing) => setProjects(workspaceProjects(listing.projects)))- // Only the new-workspace picker lists these; without them it still offers "choose a folder".- .catch((err) => console.warn("Mission Control: projects did not load", err)), []);-- useEffect(() => {- let alive = true;- Promise.all([fetchIdeState(), fetchIdeAgents(true)])- .then(([state, list]) => {- if (!alive) return;- setWorkspaces(state.workspaces);- setWorkspaceId((current) => current || state.active_id || state.workspaces[0]?.id || NEW_WORKSPACE);- const usable = launchableAgents(list.agents);- setAgents(usable);- setAgentName((current) => current || usable[0]?.name || "");- })- .catch((err) => { if (alive) setLoadError(errorText(err)); });- void loadProjects();- return () => { alive = false; };- }, [loadProjects]);-- const setLine = (index: number, line: LaunchLine) =>- setLines((prev) => { const next = [...prev]; next[index] = line; return next; });-- /** Wait for one new pane, then hand it the files and the task. */- const settle = async (- i: number, name: string, wsId: string, brief: string, held: readonly HeldFile[], shared: { handover?: Handover },- ) => {- if (!brief && held.length === 0) {- setLine(i, { tone: "ok", text: t("society.office.mission_done_open").replace("{0}", name) });- return;- }- setLine(i, { tone: "busy", text: t("society.office.mission_waiting").replace("{0}", name) });- try {- // A pane starts when a viewer first attaches, and nobody views it from here.- await startTerminal(name, wsId);- } catch (err) {- // The wait below decides; a viewer opening the pane still starts it.- console.warn("Mission Control: pane start request failed", err);- }- if (!(await waitLive(wsId, name))) {- setLine(i, { tone: "warn", text: t("society.office.mission_not_started").replace("{0}", name) });- return;- }- let text = brief;- let attachments: DropAttachment[] = [];- if (held.length > 0) {- setLine(i, { tone: "busy", text: t("society.office.mission_files_handing").replace("{0}", name) });- let handover: Handover;- try {- if (!brief) {- // Files alone: typed into the pane's input, as a drop on the pane itself would be.- await attachToTerminal(name, heldPayload(held));- setLine(i, { tone: "ok", text: t("society.office.mission_files_typed").replace("{0}", name) });- return;- }- // Read once per launch: every pane shares the workspace and the CLI, so- // the references are the same, and describing a picture again for each- // pane would bill the user again for the same answer.- handover = shared.handover ??= await attachToTerminal(name, { ...heldPayload(held), analyze: true, deliver: false })- .then((result) => ({ references: result.references, analysis: result.analysis ?? [] }));- } catch (err) {- setLine(i, { tone: "error", text: t("society.office.mission_files_failed").replace("{0}", name).replace("{1}", errorText(err)) });- return;- }- attachments = handover.analysis;- text = briefWithFiles(brief, handover.references, attachments);- }- setLine(i, { tone: "busy", text: t("society.office.mission_briefing").replace("{0}", name) });- try {- const result = await promptTerminal(name, text, { compose: sharpen, workspaceId: wsId, attachments });- setLine(i, result.submitted === true- ? { tone: "ok", text: t("society.office.mission_done_briefed").replace("{0}", name) }- : { tone: "warn", text: result.detail || t("society.office.cmd_unconfirmed") });- } catch (err) {- setLine(i, { tone: "error", text: errorText(err) });- }- };-- const creating = workspaceId === NEW_WORKSPACE;- const ready = Boolean(agentName) && (creating ? newTarget !== null : Boolean(workspaceId));-- const launch = async () => {- if (running || !ready) return;- setRunning(true);- setLines([]);- const brief = task.trim();- const held = files.held;- const shared: { handover?: Handover } = {};- let opened = 0;- if (creating && newTarget) {- setLine(0, { tone: "busy", text: t("society.office.mission_ws_creating") });- try {- const project = newTarget.projectId ? { id: newTarget.projectId, path: newTarget.path } : await openProject(newTarget.path);- const { session, state } = await openIdeWorkspace(- project.path, Array.from({ length: count }, () => ({ agent: agentName })),- { projectId: project.id, name: newName.trim() || undefined },- );- // The next launch lands beside these agents, not in yet another new workspace.- setWorkspaces(state.workspaces);- setWorkspaceId(session.id);- setNewTarget(null);- setNewName("");- void loadProjects();- void useWorkspacePanesStore.getState().load();- opened = session.terminals.length;- for (const [i, term] of session.terminals.entries()) await settle(i, term.name, session.id, brief, held, shared);- } catch (err) {- setLine(0, { tone: "error", text: t("society.office.mission_failed").replace("{0}", errorText(err)) });- }- } else {- for (let i = 0; i < count; i += 1) {- setLine(i, { tone: "busy", text: t("society.office.mission_opening") });- let name = "";- try {- name = (await openTerminal({ workspace_id: workspaceId, agent: agentName })).name;- } catch (err) {- setLine(i, { tone: "error", text: t("society.office.mission_failed").replace("{0}", errorText(err)) });- break;- }- opened += 1;- void useWorkspacePanesStore.getState().load();- await settle(i, name, workspaceId, brief, held, shared);- }- }- // Kept for another try when not a single agent opened.- if (opened > 0) {- if (brief) setTask("");- files.release(held);- }- void useWorkspacePanesStore.getState().load();- setRunning(false);- };-- if (loadError) return <p className="office-mc-note" role="alert">{loadError}</p>;- if (!workspaces || !agents) return <p className="office-mc-note" role="status">{t("society.office.mission_loading")}</p>;- return (- <div className="office-mc-block office-mc-dropzone" data-dragging={files.dragging || undefined} {...files.handlers}>- {agents.length === 0 ? <p className="office-mc-note">{t("society.office.mission_no_agents")}</p> : (- <div className="office-mc-agents" role="radiogroup" aria-label={t("society.office.mission_agent")}>- {agents.map((a) => (- <button key={a.name} type="button" role="radio" aria-checked={agentName === a.name} disabled={running}- title={a.description || a.display_name} onClick={() => setAgentName(a.name)}>- <AgentMark agent={a.name} label={a.display_name} logoUrl={a.logo_url || undefined} size="sm" />- <span>{a.display_name}</span>- </button>- ))}- </div>- )}-- {workspaces.length === 0 ? <p className="office-mc-note">{t("society.office.mission_no_workspace")}</p> : (- <div className="office-mc-row">- <span>{t("society.office.mission_workspace")}</span>- <BrandedSelect value={workspaceId} onValueChange={setWorkspaceId} disabled={running}- ariaLabel={t("society.office.mission_workspace")} className="office-mc-select px-2 py-1.5 text-xs"- options={[- ...workspaces.map((w) => ({ value: w.id, label: w.name, hint: w.branch || undefined })),- { value: NEW_WORKSPACE, label: t("society.office.mission_ws_new") },- ]} />- </div>- )}- {creating && (- <NewWorkspaceFields projects={projects} target={newTarget} onTarget={setNewTarget}- name={newName} onName={setNewName} disabled={running} />- )}-- <textarea className="office-mc-task" rows={3} value={task} maxLength={8000} disabled={running}- placeholder={t("society.office.mission_task_placeholder")} aria-label={t("society.office.mission_task")}- onChange={(e) => setTask(e.target.value)} onPaste={files.onPaste}- onKeyDown={(e) => { if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) { e.preventDefault(); void launch(); } }} />- {files.held.length > 0 && (- <ul className="office-mc-files" aria-label={t("society.office.mission_files_attach")}>- {files.held.map((h) => (- <li key={h.key} title={h.path ?? h.name}>- <span>{h.name}</span>- <button type="button" disabled={running} onClick={() => files.remove(h.key)}- aria-label={t("society.office.mission_files_remove").replace("{0}", h.name)}><X aria-hidden /></button>- </li>- ))}- </ul>- )}- <div className="office-mc-tools">- <button type="button" className="office-mc-link office-mc-attach" disabled={running} onClick={() => fileInput.current?.click()}>- <Paperclip aria-hidden />{t("society.office.mission_files_attach")}- </button>- <input ref={fileInput} type="file" multiple hidden tabIndex={-1}- onChange={(e) => { files.addFiles(Array.from(e.target.files ?? [])); e.target.value = ""; }} />- {task.trim() && (- <label className="office-cmd-check">- <input type="checkbox" checked={sharpen} disabled={running} onChange={(e) => setSharpen(e.target.checked)} />- <span>{t("society.office.cmd_sharpen")}</span>- </label>- )}- </div>-- <div className="office-mc-go">- <div className="office-mc-stepper" role="group" aria-label={t("society.office.mission_count")}>- <button type="button" disabled={running || count <= 1} onClick={() => setCount((n) => n - 1)}- aria-label={t("society.office.mission_fewer")}><Minus aria-hidden /></button>- <output aria-live="polite">{count}</output>- <button type="button" disabled={running || count >= MAX_LAUNCH} onClick={() => setCount((n) => n + 1)}- aria-label={t("society.office.mission_more")}><Plus aria-hidden /></button>- </div>- <button type="button" className="office-mc-primary" disabled={running || !ready} onClick={() => void launch()}>- {count === 1 ? t("society.office.mission_start_one") : t("society.office.mission_start_many").replace("{0}", String(count))}- </button>- </div>-- {lines.length > 0 && (- <ul className="office-mc-log" aria-live="polite">- {lines.map((line, i) => <li key={i} data-tone={line.tone}><i aria-hidden />{line.text}</li>)}- </ul>- )}- {files.dragging && <div className="office-mc-drophint" aria-hidden>{t("society.office.mission_files_drop")}</div>}- </div>- );-}--function MessageSeveral() {- const t = useT();- const panes = useWorkspacePanesStore((s) => s.panes);- const occupants = useMemo(() => paneOccupants(panes), [panes]);- const [picked, setPicked] = useState<Set<string>>(() => new Set());- const [message, setMessage] = useState("");- const [sending, setSending] = useState(false);- const [result, setResult] = useState<{ tone: "ok" | "warn"; text: string } | null>(null);- const chosen = occupants.filter((o) => picked.has(o.agent.agentId));- const chosenWorking = chosen.filter((o) => o.dot === "working");-- const toggle = (id: string) => setPicked((prev) => {- const next = new Set(prev);- if (next.has(id)) next.delete(id); else next.add(id);- return next;- });-- const broadcast = useCallback(async (kind: "send" | "stop") => {- const text = message.trim();- if (sending || chosen.length === 0 || (kind === "send" && !text)) return;- setSending(true);- setResult(null);- const targets = kind === "stop" ? chosenWorking : chosen;- const outcomes = await Promise.allSettled(targets.map(async (o) => {- if (kind === "stop") { await interruptTerminal(o.pane.name, o.pane.workspace_id); return true; }- if (o.pane.status !== "live" || !o.pane.accepts_prompts) throw new Error(t("society.office.cmd_not_running"));- const res = await promptTerminal(o.pane.name, text, { workspaceId: o.pane.workspace_id });- if (res.submitted !== true) throw new Error(res.detail || t("society.office.cmd_unconfirmed"));- return true;- }));- const missed = targets.filter((_, i) => outcomes[i].status === "rejected").map((o) => o.agent.name);- const reached = targets.length - missed.length;- const summary = t("society.office.fleet_result").replace("{0}", String(reached)).replace("{1}", String(targets.length));- setResult({ tone: missed.length ? "warn" : "ok", text: missed.length ? `${summary} ${t("society.office.fleet_result_missed").replace("{0}", missed.join(", "))}` : summary });- if (kind === "send" && missed.length === 0) setMessage("");- void useWorkspacePanesStore.getState().load();- setSending(false);- }, [chosen, chosenWorking, message, sending, t]);-- if (occupants.length === 0) return <p className="office-mc-note">{t("society.office.fleet_empty")}</p>;- const everyone = occupants.every((o) => picked.has(o.agent.agentId));- return (- <div className="office-mc-block">- <ul className="office-mc-fleet">- {occupants.map((o) => (- <li key={o.agent.agentId}>- <label>- <input type="checkbox" checked={picked.has(o.agent.agentId)} onChange={() => toggle(o.agent.agentId)} />- <span className="office-mc-fleet-name" title={o.pane.recap || o.pane.last_prompt}>{o.agent.name}</span>- <span className="office-mc-fleet-state"><i className="office-dot" data-state={o.agent.state} data-dot={o.dot} aria-hidden />{t(`society.office.pane_state_${o.stateKey}`)}</span>- </label>- </li>- ))}- </ul>- <button type="button" className="office-mc-link" onClick={() => setPicked(pickAll(occupants, picked))}>- {t(everyone ? "society.office.fleet_select_none" : "society.office.fleet_select_all")}- </button>- <textarea className="office-mc-task" rows={2} value={message} maxLength={8000} disabled={sending}- placeholder={t("society.office.fleet_placeholder")} aria-label={t("society.office.fleet_placeholder")}- onChange={(e) => setMessage(e.target.value)}- onKeyDown={(e: KeyboardEvent<HTMLTextAreaElement>) => { if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) { e.preventDefault(); void broadcast("send"); } }} />- <div className="office-mc-go">- <button type="button" className="office-mc-secondary" disabled={sending || chosenWorking.length === 0} onClick={() => void broadcast("stop")}>- {t("society.office.fleet_stop").replace("{0}", String(chosenWorking.length))}- </button>- <button type="button" className="office-mc-primary" disabled={sending || chosen.length === 0 || !message.trim()} onClick={() => void broadcast("send")}>- {t("society.office.fleet_send").replace("{0}", String(chosen.length))}- </button>- </div>- {result && <p className="office-mc-note" role="status" data-tone={result.tone}>{result.text}</p>}- </div>- );-}--export function MissionControlPanel() {- const t = useT();- return (- <div className="office-mc">- <section aria-labelledby="office-mc-start">- <h3 id="office-mc-start" className="office-mc-heading">{t("society.office.mission_new_title")}</h3>- <StartAgent />- </section>- <details className="office-mc-more">- <summary className="office-mc-heading">{t("society.office.fleet_title")}</summary>- <MessageSeveral />- </details>- </div>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/MissionScreens.tsx b/dodaios/ui/web/frontend/src/components/society/office/MissionScreens.tsxdeleted file mode 100644index c1019bd226..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/MissionScreens.tsx+++ /dev/null@@ -1,274 +0,0 @@-/**- * Mission Control's desk monitors run three REAL app sections, live, as they- * would run in the app: Spend (left), the Agents view (centre) and the Agentic- * IDE (right). Each is the section's own components laid out at a normal- * window size and drawn onto the screen plane with drei's <Html>.- *- * Display only: clicks fall through to the monitor underneath, which dives- * the camera into the glass and then opens that section.- *- * Two sections are reduced to what can run twice without side effects:- * - Agents: the real roster rail and one agent's real chat on its OWN chat- * store (never the lead's: its chat is the app's own voice chat, and a- * second panel on it would disconnect the app when the monitor unmounts).- * - Agentic IDE: the real terminals, read from the same read-only screen feed- * the desk monitors use. Mounting the real IDE would attach a second xterm- * to every PTY and resize the user's live terminals to monitor size.- */-import { Suspense, lazy, useContext, useEffect, useMemo, useState, type CSSProperties, type ReactNode } from "react";-import { CanvasActivity } from "@/hooks/useCanvasAwake";-import { Html } from "@react-three/drei";-import { QueryClientProvider, useQueryClient } from "@tanstack/react-query";-import { useT } from "@/i18n";-import { useThemeValue } from "@/hooks/useTheme";-import { createAgentChatStore } from "@/store/agentChat";-import { useWorkspacePanesStore } from "@/store/workspacePanes";-import { fetchPaneScreens, MAX_PANE_SCREENS, type PaneScreen } from "@/lib/paneScreensApi";-import { PANE_BRAND, PANE_CHROME, PANE_SOLID, storedTerminalAppearance, themeFor } from "@/components/agentic/terminalThemes";-import { Folder } from "lucide-react";-import { WorkspaceTerminalHeader } from "@/components/agentic/WorkspaceTerminalHeader";-import type { PaneEdgeState } from "@/components/agentic/terminalThemes";-import { RosterRail } from "@/components/society/roster/RosterRail";-import { useSocietyRoster, type SocietyAgent } from "../data";-import { chatGroupsKnown, useSocietyChatGroups } from "@/lib/societyChatGroups";-import { paneLabel, paneOccupants, type PaneOccupant } from "./codingFloor";-import { PaneScreenView } from "./PaneLiveScreen";-import { screenChanged } from "./terminalScreen";-import type { MonitorSection } from "./officeStore";-import { useBlendingCanvasLayer } from "./blendingLayer";-import "./paneCommand.css";-import "./missionScreens.css";--const loadCosts = () => import("@/views/CostsView");-const loadChat = () => import("../chat/AgentChatPanel");-const CostsView = lazy(() => loadCosts().then((m) => ({ default: m.CostsView })));-const AgentChatPanel = lazy(() => loadChat().then((m) => ({ default: m.AgentChatPanel })));--/**- * Fetch the sections' code before the camera gets close, so walking up to the- * desk shows the screens at once instead of a blank glass while chunks load.- */-export function preloadMissionScreens(): void {- void loadCosts().catch((err) => console.warn("Mission Control: Spend preload failed", err));- void loadChat().catch((err) => console.warn("Mission Control: chat preload failed", err));-}--/** The sections are laid out at this window size, then scaled onto the monitor. */-export const MISSION_SCREEN_PX = { w: 1240, h: 723 } as const;--const SCREEN_Z_RANGE: [number, number] = [10, 0];--/** One terminal poll for every tile at once, jittered (AP-33). */-const POLL_MIN_MS = 900;-const POLL_JITTER_MS = 300;-/** The IDE monitor shows at most this many panes of the front workspace. */-const MAX_TILES = 6;--// ----------------------------------------------------------------------------// Agents-// -----------------------------------------------------------------------------/** Whose chat the Agents monitor shows: a working agent first, never the lead. Pure. */-export function pickShownAgent(agents: readonly SocietyAgent[]): SocietyAgent | null {- const chatty = agents.filter((a) => a.tier !== "lead" && a.chatSessionId);- return chatty.find((a) => a.state === "working") ?? chatty.find((a) => a.state === "waiting") ?? chatty[0] ?? null;-}--function AgentsScreen() {- const t = useT();- const roster = useSocietyRoster();- const agents = useMemo(() => roster.data?.agents ?? [], [roster.data]);- const sample = roster.data?.sample ?? true;- const groupsQuery = useSocietyChatGroups(!sample);- const groups = groupsQuery.data ?? [];- const shown = pickShownAgent(agents);- const shownId = shown?.agentId ?? null;- const store = useMemo(() => (shownId ? createAgentChatStore("society", `office-mission:${shownId}`) : null), [shownId]);- // Leaving the monitor closes its socket; the chat itself keeps running on the server.- useEffect(() => () => store?.getState().disconnect(), [store]);- return (- <div className="grid h-full min-h-0 grid-cols-[300px_minmax(0,1fr)] bg-card">- <RosterRail agents={agents} groups={groups} loading={roster.isLoading} teamsPending={!sample && !chatGroupsKnown(groupsQuery)} sample={sample}- activeAgentId={shownId} onOpen={() => undefined} onCreate={() => undefined}- side="left" className="w-full border-0 jarvis-nav-surface" />- <section className="flex min-h-0 flex-col overflow-hidden rounded-tl-[12px] border-l border-border bg-background">- {shown && store ? (- <Suspense fallback={null}>- <AgentChatPanel key={shown.agentId} agent={shown} roster={agents} chatStore={store} />- </Suspense>- ) : (- <p className="m-auto text-sm text-muted-foreground">{t("society.office.mission_screen_none")}</p>- )}- </section>- </div>- );-}--// ----------------------------------------------------------------------------// Agentic IDE-// -----------------------------------------------------------------------------/** The panes the IDE monitor shows: the front workspace's coding panes, in grid order. Pure. */-export function idePanes(occupants: readonly PaneOccupant[]): { workspace: string; tiles: PaneOccupant[] } {- const front = occupants.find((o) => o.pane.workspace_active) ?? occupants[0];- if (!front) return { workspace: "", tiles: [] };- const tiles = occupants.filter((o) => o.pane.workspace_id === front.pane.workspace_id).slice(0, MAX_TILES);- return { workspace: front.pane.workspace_id, tiles };-}--/** Columns × rows for `n` tiles, the way the IDE splits a workspace: side by side up to three, then two rows. Pure. */-export function ideGrid(n: number): { cols: number; rows: number } {- if (n <= 3) return { cols: Math.max(1, n), rows: 1 };- if (n === 4) return { cols: 2, rows: 2 };- return { cols: 3, rows: 2 };-}--/** The IDE sidebar's tree: each project folder with its workspaces, their pane counts and whether one works. Pure. */-export function ideTree(occupants: readonly PaneOccupant[]): { folder: string; name: string; workspaces: { id: string; name: string; count: number; working: boolean }[] }[] {- const projects = new Map<string, { folder: string; name: string; workspaces: Map<string, { id: string; name: string; count: number; working: boolean }> }>();- for (const { pane, agent } of occupants) {- const folder = pane.folder || pane.workspace_name;- const project = projects.get(folder) ?? { folder, name: folder.split(/[\\/]/).filter(Boolean).pop() ?? folder, workspaces: new Map() };- const ws = project.workspaces.get(pane.workspace_id) ?? { id: pane.workspace_id, name: pane.workspace_name, count: 0, working: false };- ws.count += 1;- ws.working ||= agent.state === "working";- project.workspaces.set(pane.workspace_id, ws);- projects.set(folder, project);- }- return [...projects.values()].map((p) => ({ folder: p.folder, name: p.name, workspaces: [...p.workspaces.values()] }));-}--const EDGE: Record<string, PaneEdgeState> = { pending: "connecting", live: "live", exited: "exited", error: "error" };-const noop = () => undefined;--function usePaneScreenBatch(panes: { workspaceId: string; key: string }[]): Map<string, PaneScreen> | null {- const [screens, setScreens] = useState<Map<string, PaneScreen> | null>(null);- const signature = panes.map((p) => `${p.workspaceId}:${p.key}`).join("|");- useEffect(() => {- const wanted = panes.slice(0, MAX_PANE_SCREENS);- let alive = true;- let failing = false;- let timer: ReturnType<typeof setTimeout>;- const tick = async () => {- try {- const next = await fetchPaneScreens(wanted);- if (!alive) return;- failing = false;- setScreens((prev) => {- const map = new Map(next.map((s) => [`${s.workspace_id}:${s.key}`, s]));- if (prev && map.size === prev.size && [...map].every(([k, s]) => !screenChanged(prev.get(k), s))) return prev;- return map;- });- } catch (err) {- // The last good screens stay up; only the first failure of a streak is worth a line.- if (!failing) console.warn("Mission Control: IDE screens unavailable", err);- failing = true;- }- if (alive) timer = setTimeout(() => void tick(), POLL_MIN_MS + Math.random() * POLL_JITTER_MS);- };- timer = setTimeout(() => void tick(), Math.random() * POLL_JITTER_MS);- return () => { alive = false; clearTimeout(timer); };- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [signature]);- return screens;-}--function IdeScreen() {- const t = useT();- const panes = useWorkspacePanesStore((s) => s.panes);- const occupants = useMemo(() => paneOccupants(panes), [panes]);- const { workspace, tiles } = idePanes(occupants);- const tree = useMemo(() => ideTree(occupants), [occupants]);- const screens = usePaneScreenBatch(tiles.map((o) => ({ workspaceId: o.pane.workspace_id, key: o.pane.key })));- const appTheme = useThemeValue();- // The IDE's pane appearance: the reader's stored choice, else the app's theme.- const appearance = storedTerminalAppearance() ?? appTheme;- const brand = PANE_BRAND[appearance], chrome = PANE_CHROME[appearance], ansi = themeFor(appearance);- const vars = {- "--pane-ink": brand.ink, "--pane-ink-muted": brand.inkMuted, "--pane-ink-faint": brand.inkFaint,- "--pane-chip": brand.chip, "--pane-rule": chrome.border,- "--pane-ground": PANE_SOLID[appearance], "--pane-caret": ansi.cursor ?? brand.ink,- } as CSSProperties;- const { cols, rows } = ideGrid(tiles.length);- return (- <div className="office-ide-monitor jarvis-nav-surface" style={vars}>- {/* The IDE's sidebar: every project folder with its workspaces, the front one highlighted. */}- <aside className="office-ide-side">- <div className="office-ide-side-title">{t("nav.agentic_ide")}</div>- {tree.map((project) => (- <div key={project.folder}>- <div className="office-ide-project"><Folder aria-hidden />{project.name}</div>- {project.workspaces.map((ws) => (- <div key={ws.id} className="office-ide-ws" data-active={ws.id === workspace || undefined}>- <i style={{ background: ws.working ? ansi.green : brand.inkFaint }} />- <span>{ws.name}</span>- <b>{ws.count}</b>- </div>- ))}- </div>- ))}- </aside>- {tiles.length === 0 ? (- <p className="office-ide-empty">{t("society.office.mission_screen_none")}</p>- ) : (- <div className="office-ide-grid" style={{ gridTemplateColumns: `repeat(${cols}, minmax(0, 1fr))`, gridTemplateRows: `repeat(${rows}, minmax(0, 1fr))` }}>- {tiles.map((o) => {- const key = `${o.pane.workspace_id}:${o.pane.key}`;- const edge = EDGE[o.pane.status] ?? "live";- return (- // The IDE's own pane: its header component, its edge colour, the live terminal under it.- <article key={key} className="office-ide-tile" style={{ borderColor: chrome.edge[edge === "connecting" ? "live" : edge] }}>- <WorkspaceTerminalHeader name={o.pane.name} workspaceId={o.pane.workspace_id} agent={o.pane.agent}- displayName={o.pane.display_name || o.pane.agent} status={edge} appearance={appearance}- onToggleMaximize={noop} onAdd={noop} onClose={noop} onFork={noop} />- <PaneScreenView screen={screens ? (screens.get(key) ?? null) : undefined} label={paneLabel(o.pane)}- loadingText={t("society.office.cmd_screen_loading")} emptyText={t("society.office.cmd_screen_empty")}- className="office-pane-screen office-ide-screen" />- </article>- );- })}- </div>- )}- </div>- );-}--// ----------------------------------------------------------------------------// The screen-// -----------------------------------------------------------------------------const SECTIONS: Record<MonitorSection, () => ReactNode> = {- costs: () => <CostsView />,- agents: () => <AgentsScreen />,- "agentic-ide": () => <IdeScreen />,-};--/** `section`, live, on a monitor `widthM` metres wide whose glass sits at `position`. */-type MissionLiveScreenProps = {- section: MonitorSection; widthM: number; position: [number, number, number];-};--export function MissionLiveScreen(props: MissionLiveScreenProps) {- const active = useContext(CanvasActivity);- return active ? <ActiveMissionLiveScreen {...props} /> : null;-}--function ActiveMissionLiveScreen({ section, widthM, position }: MissionLiveScreenProps) {- // drei renders <Html> content in a separate React root: the app's data client- // must be handed over, or the sections' queries throw and the screen stays blank.- const client = useQueryClient();- // drei maps one CSS pixel to distanceFactor / 400 metres in transform mode.- const distanceFactor = (widthM * 400) / MISSION_SCREEN_PX.w;- // Another <Html> mounting later would drop the canvas under this screen (see blendingLayer).- useBlendingCanvasLayer(SCREEN_Z_RANGE);- return (- <Html transform occlude="blending" position={position} distanceFactor={distanceFactor} zIndexRange={SCREEN_Z_RANGE}- style={{ width: MISSION_SCREEN_PX.w, height: MISSION_SCREEN_PX.h, pointerEvents: "none" }}>- <div className="office-mission-screen" data-office-ui>- <QueryClientProvider client={client}>- <Suspense fallback={null}>{SECTIONS[section]()}</Suspense>- </QueryClientProvider>- </div>- </Html>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/NewWorkspaceFields.tsx b/dodaios/ui/web/frontend/src/components/society/office/NewWorkspaceFields.tsxdeleted file mode 100644index ab4c48e221..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/NewWorkspaceFields.tsx+++ /dev/null@@ -1,95 +0,0 @@-/**- * A new workspace, chosen at the spawn point: which folder, and what the tab- * is called. Only the CHOICE is made here. The workspace itself is opened by- * the launch, with the new agents already in it, so a spawn point closed- * halfway leaves no empty workspace and no half-registered project behind.- */-import { lazy, Suspense, useState } from "react";-import * as Dialog from "@radix-ui/react-dialog";-import { X } from "lucide-react";-import { useT } from "@/i18n";-import type { IdeProject } from "@/lib/agenticIdeApi";-import { BrandedSelect } from "@/components/ui/select";--const FolderPicker = lazy(() => import("@/components/agentic/FolderPicker").then((module) => ({ default: module.FolderPicker })));--/** Where the new workspace opens: a connected project, or a folder that is not one yet. */-export interface NewWorkspaceTarget {- path: string;- label: string;- projectId?: string;-}--const PICK = "__pick__";--const samePath = (a: string, b: string) =>- a.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase() === b.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();--/** A picked folder as a target: the connected project it already is, if any. Pure. */-export function folderTarget(path: string, projects: readonly IdeProject[]): NewWorkspaceTarget {- const project = projects.find((p) => samePath(p.path, path));- if (project) return { path: project.path, label: project.name, projectId: project.id };- return { path, label: path.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || path };-}--export function NewWorkspaceFields({ projects, target, onTarget, name, onName, disabled }: {- projects: readonly IdeProject[];- target: NewWorkspaceTarget | null;- onTarget: (target: NewWorkspaceTarget) => void;- name: string;- onName: (name: string) => void;- disabled: boolean;-}) {- const t = useT();- const [picking, setPicking] = useState(false);- const [candidate, setCandidate] = useState<string | null>(null);- const value = target ? target.projectId ?? `folder:${target.path}` : "";-- return (- <>- <div className="office-mc-row" title={target?.path}>- <span>{t("society.office.mission_ws_folder")}</span>- <BrandedSelect value={value} disabled={disabled} ariaLabel={t("society.office.mission_ws_folder")}- placeholder={t("society.office.mission_ws_pick")} className="office-mc-select px-2 py-1.5 text-xs"- options={[- ...projects.map((p) => ({ value: p.id, label: p.name, searchText: p.path })),- ...(target && !target.projectId ? [{ value, label: target.label, searchText: target.path }] : []),- { value: PICK, label: t("society.office.mission_ws_choose") },- ]}- onValueChange={(next) => {- // Picking "choose a folder" leaves the select on what it showed- // before, so closing the window without a choice changes nothing.- if (next === PICK) { setCandidate(target?.path ?? null); setPicking(true); return; }- const project = projects.find((p) => p.id === next);- if (project) onTarget({ path: project.path, label: project.name, projectId: project.id });- }} />- </div>- <label className="office-mc-row">- <span>{t("society.office.mission_ws_name")}</span>- <input className="office-mc-input" value={name} maxLength={80} disabled={disabled}- placeholder={target?.label ?? ""} onChange={(e) => onName(e.target.value)} />- </label>-- <Dialog.Root open={picking} onOpenChange={setPicking}>- <Dialog.Portal>- <Dialog.Overlay className="fixed inset-0 z-[90] bg-[rgb(var(--scrim-rgb)/0.4)]" />- <Dialog.Content onEscapeKeyDown={(e) => { if (e.target instanceof Element && e.target.closest("[data-escape-local]")) e.preventDefault(); }} className="fixed left-1/2 top-1/2 z-[91] flex max-h-[85vh] w-[min(680px,calc(100vw-24px))] -translate-x-1/2 -translate-y-1/2 flex-col rounded-xl border border-border bg-popover p-4 text-foreground shadow-float">- <Dialog.Title className="pr-8 text-sm font-semibold">{t("society.office.mission_ws_choose_title")}</Dialog.Title>- <Dialog.Description className="mt-1 text-xs text-muted-foreground">{t("society.office.mission_ws_choose_hint")}</Dialog.Description>- <Dialog.Close aria-label={t("society.office.mission_ws_close")} className="absolute right-3 top-3 rounded p-1 hover:bg-secondary"><X className="h-4 w-4" /></Dialog.Close>- <div className="my-3 min-h-0 overflow-auto">- <Suspense fallback={<p className="text-xs text-muted-foreground">{t("society.office.mission_loading")}</p>}>- {picking && <FolderPicker selected={candidate} onSelect={setCandidate} className="p-0" />}- </Suspense>- </div>- <button type="button" disabled={!candidate}- onClick={() => { if (candidate) onTarget(folderTarget(candidate, projects)); setPicking(false); }}- className="self-end rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground disabled:opacity-40">- {t("society.office.mission_ws_use")}- </button>- </Dialog.Content>- </Dialog.Portal>- </Dialog.Root>- </>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeAgents.groundAnchor.test.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeAgents.groundAnchor.test.tsxdeleted file mode 100644index c13a67fc79..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeAgents.groundAnchor.test.tsx+++ /dev/null@@ -1,187 +0,0 @@-import { readFileSync } from "node:fs";-import { resolve } from "node:path";-import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";-import { act, createRoot, extend, type ReconcilerRoot, type RootState } from "@react-three/fiber";-import * as THREE from "three";-import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";-import { OfficeAgents, type WalkerContext } from "./OfficeAgents";-import type { SocietyAgent } from "../data";-import { BUILTIN_COMPANIONS } from "../companion/petCompanions";-import { useCompanionPet } from "../companion/companionPetStore";-import { buildOfficeLayout } from "./officeLayout";-import { SpotBook } from "./officeBehavior";-import { player, useOfficeStore } from "./officeStore";-import { useEventStore } from "@/store/events";--let model: THREE.Group;-vi.mock("@react-three/drei", async (original) => ({- ...await original<typeof import("@react-three/drei")>(),- // Load the shipped GLB below; keep the real R3F tree and all frame callbacks.- useGLTF: () => ({ scene: model }),- Html: () => null,-}));-// The pet's vinyl gets a studio reflection that is rendered into GPU targets; the renderer double below has-// none, and where the pet stands on the floor does not depend on it. The reflection is a plain texture here.-vi.mock("three", async (original) => {- const actual = await original<typeof import("three")>();- class FlatReflection {- fromScene() { return { texture: new actual.Texture() }; }- dispose() { /* nothing was allocated */ }- }- return { ...actual, PMREMGenerator: FlatReflection };-});--extend(THREE);-let root: ReconcilerRoot<HTMLCanvasElement> | null = null;-const originalPlayer = { ...player };-const originalPet = useCompanionPet.getState().pet;-const originalVoice = useEventStore.getState().voiceState;--beforeAll(async () => {- const bytes = readFileSync(resolve(__dirname, "../../../assets/society/companions/pets/miso.glb"));- const buffer = new Uint8Array(bytes).buffer;- model = (await new GLTFLoader().parseAsync(buffer, "")).scene;-});--beforeEach(() => {- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);- Object.assign(player, { x: 0, z: 0, heading: 0, path: [], moving: false });- useOfficeStore.setState({ summons: {} });- useCompanionPet.setState({ pet: { id: "miso", ...BUILTIN_COMPANIONS.miso } });-});--afterEach(async () => {- await act(async () => root?.unmount());- root = null;- Object.assign(player, originalPlayer);- useOfficeStore.setState({ summons: {} });- useCompanionPet.setState({ pet: originalPet });- useEventStore.setState({ voiceState: originalVoice });- vi.restoreAllMocks();- vi.unstubAllGlobals();-});--/** R3F scene graph test double; no browser, GPU or inference calls. */-function fakeRenderer(canvas: HTMLCanvasElement) {- const noop = () => undefined;- return {- domElement: canvas, render: noop, setSize: noop, setPixelRatio: noop, setAnimationLoop: noop, dispose: noop,- getPixelRatio: () => 1, shadowMap: { enabled: false, type: 0, needsUpdate: false },- xr: { enabled: false, isPresenting: false, addEventListener: noop, removeEventListener: noop, setAnimationLoop: noop },- outputColorSpace: "srgb", toneMapping: 0, toneMappingExposure: 1,- info: { render: {}, memory: {} },- };-}--const lead = {- agentId: "jarvis", name: "George", tier: "lead", state: "idle", figure: null,- palette: { primary: "#f2a65a" }, provider: "", chatSessionId: null,-} as SocietyAgent;-const agents = new Map([[lead.agentId, lead]]);--async function mount(reduced: boolean) {- const canvas = document.createElement("canvas");- const current = createRoot(canvas);- root = current;- let state!: RootState;- const scene = new THREE.Scene();- // Check real geometry and animation without GPU reflection baking.- scene.environment = new THREE.Texture();- current.configure({- scene,- gl: fakeRenderer(canvas) as unknown as NonNullable<Parameters<typeof current.configure>[0]>["gl"],- frameloop: "never", size: { width: 100, height: 100, top: 0, left: 0 },- onCreated: (value) => { state = value; },- });- const ctx: WalkerContext = {- layout: buildOfficeLayout([]), book: new SpotBook(), colleagues: () => [], spawn: { x: 0, z: 0 },- // An open floor isolates presentation from obstacle routing.- grid: { cell: 1, cols: 40, rows: 40, originX: -20, originZ: -20, blocked: new Uint8Array(1600) },- };- const render = async (awake = true, selectedId: string | null = null) => {- await act(async () => {- current.render(- <group position={[7, 2, -4]} rotation={[0, 0.7, 0]} scale={1.6}>- <OfficeAgents agents={agents} desks={[]} ctx={ctx} newcomers={new Set()} awake={awake}- reduced={reduced} selectedId={selectedId} onSelect={() => undefined} />- </group>,- );- });- };- await render();- let time = 0;- return {- scene: state.scene, render,- frame: async (dt: number) => { time += dt; await act(async () => state.advance(time)); state.scene.updateMatrixWorld(true); },- };-}--function groundObjects(scene: THREE.Scene) {- const cat = scene.getObjectByName("Pet_miso");- let ring: THREE.Mesh | undefined;- scene.traverse((object) => {- const mesh = object as THREE.Mesh;- if (mesh.isMesh && mesh.geometry.type === "RingGeometry") ring = mesh;- });- if (!cat || !ring) throw new Error("The lead's cat and floor ring must both mount");- return { cat, ring };-}--function expectCentered(scene: THREE.Scene) {- const { cat, ring } = groundObjects(scene);- const torso = cat.getObjectByName("miso_Torso");- if (!torso) throw new Error("The shipped cat must have its authored torso");- const at = new THREE.Box3().setFromObject(torso).getCenter(new THREE.Vector3());- const centre = ring.getWorldPosition(new THREE.Vector3());- expect(Math.hypot(at.x - centre.x, at.z - centre.z), "cat torso projection versus ring centre").toBeLessThan(1e-6);- // The parent floor is y=2 at scale 1.6; body hops and pulses cannot lift or resize the marker.- expect(centre.y).toBeCloseTo(2 + 0.015 * 1.6, 6);- expect(ring.getWorldScale(new THREE.Vector3()).x).toBeCloseTo(1.6, 6);- expect(ring.visible, "a ground pet keeps its floor marker").toBe(true);-}--describe("the lead pet's floor anchor", () => {- it("starts on the floor instead of descending from a flyer's hover height", async () => {- const view = await mount(false);- view.scene.updateMatrixWorld(true);- const { cat } = groundObjects(view.scene);- expect(cat.getWorldPosition(new THREE.Vector3()).y).toBeCloseTo(2, 6);- await view.frame(1 / 60);- expect(cat.getWorldPosition(new THREE.Vector3()).y).toBeCloseTo(2, 6);- });-- it.each([1 / 144, 1 / 30, 0.25])("keeps the real cat centred through motion and turns at dt=%s", async (dt) => {- const view = await mount(false);- // Straight travel, a right turn, a reversal, then standing still.- for (let i = 0; i < 100; i++) {- if (i < 25) player.z += 1.2 * Math.min(dt, 0.1);- else if (i < 50) { player.x += 1.2 * Math.min(dt, 0.1); player.heading = Math.PI / 2; }- else if (i < 75) { player.x -= 1.2 * Math.min(dt, 0.1); player.heading = -Math.PI / 2; }- await view.frame(dt);- expectCentered(view.scene);- }- await view.render(true, lead.agentId);- await act(async () => useEventStore.setState({ voiceState: "speaking" }));- for (let i = 0; i < 20; i++) { await view.frame(dt); expectCentered(view.scene); }- await view.render(false, lead.agentId);- const before = groundObjects(view.scene).cat.getWorldPosition(new THREE.Vector3());- player.x += 3;- await view.frame(dt);- expectCentered(view.scene);- expect(groundObjects(view.scene).cat.getWorldPosition(new THREE.Vector3()).toArray()).toEqual(before.toArray());- });-- it.each([false, true])("keeps the marker on the cat during summons and return to following (reduced=%s)", async (reduced) => {- const view = await mount(reduced);- view.scene.updateMatrixWorld(true);- expectCentered(view.scene);- await view.frame(1 / 60);- expectCentered(view.scene);- useOfficeStore.setState({ summons: { jarvis: { target: { x: 4, z: 3 }, untilMs: Date.now() + 60000 } } });- for (let i = 0; i < 3; i++) { await view.frame(1 / 60); expectCentered(view.scene); }- useOfficeStore.setState({ summons: {} });- player.x = -6; player.z = -5; player.heading = Math.PI;- for (let i = 0; i < 3; i++) { await view.frame(1 / 60); expectCentered(view.scene); }- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeAgents.teamwork.test.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeAgents.teamwork.test.tsxdeleted file mode 100644index cf6da54868..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeAgents.teamwork.test.tsx+++ /dev/null@@ -1,307 +0,0 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { act, createRoot, extend, type ReconcilerRoot, type RootState } from "@react-three/fiber";-import * as THREE from "three";-import { OfficeAgents, type WalkerContext } from "./OfficeAgents";-import type { AgentRunState, SocietyAgent } from "../data";-import { allDesks, seatOf, type OfficeLayout } from "./officeLayout";-import { buildNavGrid, isWalkable } from "./officeNav";-import { PERSON_CROWD_M, PERSON_SPACE_M, SpotBook } from "./officeBehavior";-import { huddlePlaces, studioOfTeam } from "./officeTeams";-import { player, useOfficeStore } from "./officeStore";-import { emptyRound, useTeamwork, type Handoff } from "./teamwork";-import { agentPositions, seatedAtDesk, walkerDebug } from "./walkerRegistry";-import { campusOf, type Campus } from "./officeFixtures";--vi.mock("@react-three/drei", async (original) => ({- ...await original<typeof import("@react-three/drei")>(),- // The walkers' choreography is under test, not their models or their DOM labels.- useGLTF: () => ({ scene: new THREE.Group() }),- Html: () => null,-}));--// The little symbol pets behind the agents need their shipped models; they are not what is tested here.-vi.mock("../companion/AgentFollower", () => ({ AgentFollower: () => null }));-// The store is driven by hand here; the hook that feeds it from the network has its own tests.-vi.mock("./useTeamRounds", () => ({ useTeamRounds: () => undefined }));--extend(THREE);-let root: ReconcilerRoot<HTMLCanvasElement> | null = null;-const originalPlayer = { ...player };--beforeEach(() => {- vi.useFakeTimers({ toFake: ["Date"] });- vi.setSystemTime(1_000_000);- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);- vi.spyOn(console, "warn").mockImplementation(() => undefined);- // The person stands far away from everything that happens.- Object.assign(player, { x: 500, z: 500, heading: 0, path: [], moving: false });- useOfficeStore.setState({ summons: {} });- useTeamwork.getState().reset();-});--afterEach(async () => {- await act(async () => root?.unmount());- root = null;- Object.assign(player, originalPlayer);- useTeamwork.getState().reset();- agentPositions.clear();- seatedAtDesk.clear();- walkerDebug.clear();- vi.restoreAllMocks();- vi.unstubAllGlobals();- vi.useRealTimers();-});--/** R3F scene graph test double; no browser, GPU or network. */-function fakeRenderer(canvas: HTMLCanvasElement) {- const noop = () => undefined;- return {- domElement: canvas, render: noop, setSize: noop, setPixelRatio: noop, setAnimationLoop: noop, dispose: noop,- getPixelRatio: () => 1, shadowMap: { enabled: false, type: 0, needsUpdate: false },- xr: { enabled: false, isPresenting: false, addEventListener: noop, removeEventListener: noop, setAnimationLoop: noop },- outputColorSpace: "srgb", toneMapping: 0, toneMappingExposure: 1,- info: { render: {}, memory: {} },- };-}--function societyAgents(campus: Campus, states: Record<string, AgentRunState> = {}): Map<string, SocietyAgent> {- return new Map(campus.roster.map((a) => [a.agentId, {- agentId: a.agentId, name: a.name, tier: "specialist", state: states[a.agentId] ?? "idle", figure: null,- palette: { primary: "#f2a65a" }, provider: "", chatSessionId: null, checkpoint: "desk",- } as unknown as SocietyAgent]));-}--async function mount(campus: Campus) {- const canvas = document.createElement("canvas");- const current = createRoot(canvas);- root = current;- let state!: RootState;- current.configure({- gl: fakeRenderer(canvas) as unknown as NonNullable<Parameters<typeof current.configure>[0]>["gl"],- frameloop: "never", size: { width: 100, height: 100, top: 0, left: 0 },- onCreated: (value) => { state = value; },- });- const book = new SpotBook();- let agents = societyAgents(campus);- let layout: OfficeLayout = campus.layout;- let grid = campus.grid;- const context = (): WalkerContext => {- const desks = allDesks(layout);- return {- layout, grid, book, spawn: layout.arrival,- colleagues: () => desks.filter((d) => d.agentId && agents.get(d.agentId)?.state === "working").map((d) => ({ agentId: d.agentId as string, desk: d })),- };- };- let ctx = context();- const render = async () => {- await act(async () => {- current.render(- <OfficeAgents agents={agents} desks={allDesks(layout)} ctx={ctx} newcomers={new Set()} awake reduced={false} selectedId={null} onSelect={() => undefined} />,- );- });- };- await render();- let time = 0;- let closest = Infinity;- /** Run the office for `seconds`, 30 frames each; keeps the smallest gap between any two figures on the move. */- const run = async (seconds: number) => {- await act(async () => {- for (let i = 0; i < seconds * 30; i += 1) {- time += 1000 / 30;- vi.setSystemTime(1_000_000 + time);- // R3F takes the frame time in seconds.- state.advance(time / 1000);- for (const a of walkerDebug.values()) {- if (a.phase !== "travel") continue;- for (const b of walkerDebug.values()) {- if (a.id !== b.id) closest = Math.min(closest, Math.hypot(a.at.x - b.at.x, a.at.z - b.at.z));- }- }- }- });- };- return {- run, book,- closest: () => closest,- walker: (id: string) => walkerDebug.get(id)!,- setStates: async (states: Record<string, AgentRunState>) => { agents = societyAgents(campus, states); await render(); },- swapFloor: async (next: Campus) => { layout = next.layout; grid = buildNavGrid(next.layout); book.retain(new Set(layout.spots.map((s) => s.id))); ctx = context(); await render(); },- grid: () => grid,- };-}--const TEAM = "team-0";--describe("teamwork on the floor", () => {- it("gathers a team's free members at their studio board while its round runs, and sends them back when it ends", async () => {- const campus = campusOf(12, [5]);- const office = await mount(campus);- const studio = studioOfTeam(campus.layout, TEAM)!;- const members = studio.members;- const places = huddlePlaces(campus.layout, campus.grid, studio);- await office.run(1);- for (const id of members) expect(office.walker(id)).toMatchObject({ team: TEAM, role: "none" });- expect(members.every((id) => office.walker(id).plan !== "huddle" || office.walker(id).phase === "dwell")).toBe(true);-- // A round opens; one member is working on something else.- await office.setStates({ [members[4]]: "working" });- act(() => useTeamwork.getState().setRound({ ...emptyRound(TEAM), running: true, members: [...members], loaded: true }));- await office.run(40);- const free = members.slice(0, 4);- for (const id of free) {- const w = office.walker(id);- expect(w, id).toMatchObject({ plan: "huddle", phase: "dwell", role: "gather" });- const place = places.find((p) => p.id === w.spot)!;- expect(Math.hypot(w.at.x - place.x, w.at.z - place.z), id).toBeLessThan(1e-6);- }- expect(new Set(free.map((id) => office.walker(id).spot)).size).toBe(4);- // The busy member never left its screen.- const seat = seatOf(allDesks(campus.layout).find((d) => d.agentId === members[4])!);- expect(office.walker(members[4])).toMatchObject({ plan: "work", role: "busy", at: { x: seat.x, z: seat.z } });-- // The member contributing now reads "working" and stays at the board, as the speaker.- act(() => useTeamwork.getState().setRound({ ...useTeamwork.getState().rounds[TEAM], speakerId: members[1] }));- await office.setStates({ [members[4]]: "working", [members[1]]: "working" });- await office.run(12);- expect(office.walker(members[1])).toMatchObject({ plan: "huddle", phase: "dwell", role: "speaker" });-- // The round settles: everyone goes back to their own desk first.- act(() => useTeamwork.getState().setRound({ ...useTeamwork.getState().rounds[TEAM], running: false, speakerId: null }));- await office.setStates({ [members[4]]: "working" });- await office.run(1);- for (const id of free) expect(office.walker(id), id).toMatchObject({ plan: "desk", role: "none" });- await office.run(30);- for (const id of free) {- const own = seatOf(allDesks(campus.layout).find((d) => d.agentId === id)!);- const w = office.walker(id);- if (w.plan === "desk") expect([w.at.x, w.at.z], id).toEqual([own.x, own.z]);- }- // On the way there and back nobody walked through anybody, and nobody had to be placed.- expect(office.closest()).toBeGreaterThan(0.5);- expect(members.reduce((n, id) => n + office.walker(id).rescues, 0)).toBe(0);- });-- it("makes room when the person walks into the group at the board, and takes no place on the person's toes", async () => {- const campus = campusOf(12, [5]);- const office = await mount(campus);- const studio = studioOfTeam(campus.layout, TEAM)!;- const places = huddlePlaces(campus.layout, campus.grid, studio);- // The person already stands on the best place when the round opens.- Object.assign(player, { x: places[0].x, z: places[0].z });- act(() => useTeamwork.getState().setRound({ ...emptyRound(TEAM), running: true, members: [...studio.members], loaded: true }));- await office.run(40);- const gap = (id: string) => Math.hypot(office.walker(id).at.x - player.x, office.walker(id).at.z - player.z);- for (const id of studio.members) {- expect(office.walker(id), id).toMatchObject({ plan: "huddle", phase: "dwell" });- expect(gap(id), id).toBeGreaterThanOrEqual(PERSON_SPACE_M - 0.01);- }- // Now the person steps right up to one of them.- const neighbour = studio.members[2];- const was = office.walker(neighbour).spot;- Object.assign(player, { x: office.walker(neighbour).at.x + 0.7, z: office.walker(neighbour).at.z });- expect(gap(neighbour)).toBeLessThan(PERSON_CROWD_M);- await office.run(12);- expect(office.walker(neighbour)).toMatchObject({ plan: "huddle", phase: "dwell" });- expect(office.walker(neighbour).spot).not.toBe(was);- expect(gap(neighbour)).toBeGreaterThanOrEqual(PERSON_SPACE_M - 0.01);- // Everybody still has a place of their own, more than a metre from the next.- const at = studio.members.map((id) => office.walker(id).at);- for (const [i, p] of at.entries()) for (const q of at.slice(i + 1)) expect(Math.hypot(p.x - q.x, p.z - q.z)).toBeGreaterThan(1);- });-- it("hurries a working agent back to its screen, at the pace the walker reports", async () => {- const campus = campusOf(12, [5]);- const office = await mount(campus);- // Idle life spreads the floor out; then an agent away from its desk gets work.- await office.run(40);- const desks = allDesks(campus.layout);- const away = campus.roster.map((a) => a.agentId).filter((id) => {- const seat = seatOf(desks.find((d) => d.agentId === id)!);- return Math.hypot(office.walker(id).at.x - seat.x, office.walker(id).at.z - seat.z) > 8;- });- expect(away.length).toBeGreaterThan(0);- const id = away[0];- const seat = seatOf(desks.find((d) => d.agentId === id)!);- await office.setStates({ [id]: "working" });- await office.run(2);- const start = office.walker(id);- expect(start).toMatchObject({ plan: "work", phase: "travel" });- const metres = start.remainingM + start.walkS * start.speed;- // By its own clock it walks briskly: well above the stroll, never above the brisk pace.- expect(start.speed).toBeGreaterThan(1.5);- expect(start.speed).toBeLessThanOrEqual(2.1 + 1e-6);- // And it is seated within the time that pace gives, plus the turns.- await office.run(Math.ceil(metres / 1.6) + 2);- expect(office.walker(id)).toMatchObject({ plan: "work", phase: "dwell", at: { x: seat.x, z: seat.z }, speed: 0, walkS: 0 });- });-- it("walks a message from its sender to the receiver, and delivers it once", async () => {- const campus = campusOf(12, [5]);- const office = await mount(campus);- const studio = studioOfTeam(campus.layout, TEAM)!;- const receiver = studio.members[0];- const sender = campus.roster.find((a) => !studio.members.includes(a.agentId))!.agentId;- await office.setStates({ [receiver]: "working" });- await office.run(1);- const handoff: Handoff = {- id: "ev-1", from: sender, to: receiver, toName: "Agent 0", text: "Here are the numbers you asked for.", msgType: "ANSWER",- atMs: Date.now(), phase: "queued", untilMs: Date.now() + 90_000,- };- act(() => useTeamwork.getState().addHandoff(handoff));- await office.run(1);- expect(office.walker(sender)).toMatchObject({ plan: "handoff", with: receiver });- // It arrives beside the receiver's chair and stays a moment.- let delivered = false;- for (let i = 0; i < 60 && !delivered; i += 1) {- await office.run(1);- delivered = useTeamwork.getState().handoffs[0]?.phase === "delivering";- }- expect(delivered).toBe(true);- const seat = seatOf(allDesks(campus.layout).find((d) => d.agentId === receiver)!);- const at = office.walker(sender).at;- // Beside the chair, or a step away when both places beside it are taken.- expect(Math.hypot(at.x - seat.x, at.z - seat.z)).toBeLessThan(1.7);- expect(Math.hypot(at.x - seat.x, at.z - seat.z)).toBeGreaterThan(0.6);- // The receiver kept working at its screen throughout.- expect(office.walker(receiver)).toMatchObject({ plan: "work", at: { x: seat.x, z: seat.z } });- await office.run(10);- expect(useTeamwork.getState().handoffs).toEqual([]);- expect(office.walker(sender).plan).not.toBe("handoff");- });-- it("keeps a working sender at its screen: the message is not walked over", async () => {- const campus = campusOf(12, [5]);- const office = await mount(campus);- const [a, b] = studioOfTeam(campus.layout, TEAM)!.members;- await office.setStates({ [a]: "working" });- await office.run(1);- act(() => useTeamwork.getState().addHandoff({ id: "ev-2", from: a, to: b, toName: "Agent 1", text: "Take this over", msgType: "ASSIGN", atMs: Date.now(), phase: "queued", untilMs: Date.now() + 90_000 }));- await office.run(5);- expect(office.walker(a).plan).toBe("work");- expect(useTeamwork.getState().handoffs[0].phase).toBe("queued");- });-- it("keeps everyone on their feet when the floor plan is rebuilt under them", async () => {- const before = campusOf(14, [5]);- const office = await mount(before);- // Let the idle floor spread out, then build a second team's studio mid-walk.- await office.run(25);- const after = campusOf(14, [5, 5]);- await office.swapFloor(after);- await office.run(60);- const grid = office.grid();- for (const agent of after.roster) {- const w = office.walker(agent.agentId);- expect(w.plan, agent.agentId).not.toBeNull();- // Standing people stand on the floor; seated ones on a seat that exists on the new plan.- const seated = w.phase === "dwell" && ["desk", "couch", "beanbag", "meeting", "work", "nap"].includes(w.plan!);- if (w.phase === "dwell" && !seated) expect(isWalkable(grid, w.at), `${agent.agentId} ${w.plan}`).toBe(true);- if (w.plan === "desk" && w.phase === "dwell") {- const own = seatOf(allDesks(after.layout).find((d) => d.agentId === agent.agentId)!);- expect([w.at.x, w.at.z], agent.agentId).toEqual([own.x, own.z]);- }- expect(w.team, agent.agentId).toBe(after.teams.find((t) => t.members.includes(agent.agentId))?.id ?? null);- }- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeAgents.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeAgents.tsxdeleted file mode 100644index b024a800ac..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeAgents.tsx+++ /dev/null@@ -1,695 +0,0 @@-/**- * Agents living in the office. Working agents sit at their screens, waiting- * agents stand and wave at their desk, paused agents nap, and idle agents- * live round their team's studio: their desk, the studio board, a teammate's- * desk, now and then a coffee or the couch. A running round of a team brings- * its free members to their studio board, and a message one agent sent- * another is walked over (teamwork.ts): both are real, nothing is staged.- *- * The office is a projection of the roster: run state comes from the backend,- * everything else is client-side choreography that costs no tokens and never- * starts or stops work.- */-import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";-import { Html } from "@react-three/drei";-import { useFrame } from "@react-three/fiber";-import { DoubleSide, Vector3, type Group, type Mesh, type MeshBasicMaterial } from "three";-import { useT } from "@/i18n";-import type { SocietyAgent } from "../data";-import type { FigureDrive, FigureMode } from "../figures/FigureRig";-import { ToyFigure } from "./ToyFigure";-import { GigiFlyer } from "./GigiFlyer";-import { followAnchor, type GigiFlightMode } from "./gigiFlight";-import { useEventStore } from "@/store/events";-import { SEAT_HEIGHT, toyLookFor } from "./toyFigureModel";-import { OFFICE } from "./officePalette";-import type { DeskSlot, OfficeLayout, Point } from "./officeLayout";-import { findPath, isWalkable, type NavGrid } from "./officeNav";-import { AgentFollower } from "../companion/AgentFollower";-import { useCompanionPet } from "../companion/companionPetStore";-import { companionFlies } from "../companion/petCompanions";-import { resolveCompanion } from "../companion/appearance";-import type { TrailPoint } from "../companion/trail";-import { clearOfBodies, hurryPaceFor, stepMover, turnToward, WALK_SPEED, type Mover } from "./officeMotion";-import { advanceWalk, beginWalk, type Walk } from "./officeWalk";-import {- createRng, dwellAfter, HANDOFF_DWELL_MS, PERSON_CROWD_M, planFor, planStillValid, shownActivity, type ActivityKind, type Plan, type Pose, type SpotBook,-} from "./officeBehavior";-import { homeStudio, mateDesks, studiosOf } from "./officeTeams";-import { boardWatch, pendingHandoff, roundFor, roundRole, steadyRole, useTeamwork, type RoleMemory } from "./teamwork";-import { useTeamRounds } from "./useTeamRounds";-import { StudioBoards } from "./StudioBoards";-import { player, useOfficeStore, type Summon } from "./officeStore";-import { agentPositions, bodiesNear, companions, placeAgent, seatedAtDesk, walkerDebug } from "./walkerRegistry";-import { AgentBubble } from "./OfficeBubbles";-import type { ChatLine } from "./deskChat";-import type { DeskChat } from "./useDeskChats";-import { officeTalkChat, useOfficeTalk } from "./officeTalk";-import { deliverySpot, ERRAND_SPEED, useErrandFeed, useGigiErrands } from "./gigiErrands";-import { isPaneAgentId, plateTitle } from "./codingFloor";-import { agentLogoAsset } from "@/components/agentic/AgentMark";-import { LevelChip } from "../progression/LevelHud";-import { plateDetail, type PlateDetail } from "./namePlate";-import type { Camera } from "three";-import { useThree } from "@react-three/fiber";-import { joinPlates, plateSeating, reportPlate, type ScreenRect } from "./plateCrowd";-import { isSpeaking, lastSpokeBy, SPOKE_LINGER_MS } from "./teamwork";-import { agentSubject, petSubject } from "../progression/progressionApi";-import { useProgression } from "../progression/progressionStore";-import { useDressedFigure } from "../progression/regalia/dress";--/** The agent's symbol walks behind it as a little pet, about a fifth of its height. */-export const PET_SIZE_M = 0.26;-const PET_FOLLOW_M = 0.7;--/** The person's character as a mover for Gigi to follow (the body object itself, mutated every frame). */-const PLAYER_OWNER = { current: player };-/** Farther than this from the person's shoulder and Gigi flies back first instead of hovering beside them. */-const FOLLOW_CATCH_M = 1;--/** Height of the lead's nameplate: above a flying companion, or low above a pet on the floor. */-const LEAD_PLATE_FLYING_M = 1.75;-const LEAD_PLATE_ON_FLOOR_M = 0.85;--/** The person's pet keeps this far from every agent while it follows the person. */-const PET_CLEAR_M = 0.5;-/** Bodies further than this from a walker play no part in its steering or its detours. */-const BODY_RANGE_M = 7;--// Dev-only: what every walker, team round and studio board is doing right now.-// __officeLife.walkers() one row per agent: team, role in a running round, plan, phase, target, stuck seconds,-// walkS / speed (seconds and average m/s on the current walk, by the frame time the-// walker really got: with the frame loop running, __officeStep's dtMs is not that time),-// and how often it took a detour (replans), was placed (rescues), gave a walk up (blocked)-// or had its route repaired (repaths)-// __officeLife.walker(id) the same for one agent-// __officeLife.stuck() the walkers that needed a detour or a placement, or gave a walk up, so far-// __officeLife.teamwork() rounds by team (running, speaker, lines) and the messages still to be walked over-// __officeLife.boards() the team ids whose studio board is live (near the camera)-if (import.meta.env.DEV && typeof window !== "undefined") {- Object.assign(window, { __officeLife: {- walkers: () => [...walkerDebug.values()],- walker: (id: string) => walkerDebug.get(id) ?? null,- stuck: () => [...walkerDebug.values()].filter((w) => w.replans + w.rescues + w.blocked > 0),- teamwork: () => { const { rounds, handoffs } = useTeamwork.getState(); return { rounds, handoffs }; },- boards: () => [...boardWatch.near()],- store: useTeamwork,- } });-}--/** Every figure shares one toy scale, so desks and couches read the same everywhere. */-export const OFFICE_FIGURE_HEIGHT_M = 1.3;--/** Pose → animation clip. Seated work uses the seated clip; the monitor shows the typing. */-export const POSE_CLIP: Record<Pose, FigureMode> = { sit: "sit", work: "sit", stand: "idle", wave: "wave", talk: "talk", sleep: "sleep" };--/** The seat-top height under a seated agent, per activity; the figure puts its hips exactly there. */-export function seatHeightFor(kind: ActivityKind): number {- if (kind === "couch" || kind === "nap") return SEAT_HEIGHT.couch;- if (kind === "beanbag") return SEAT_HEIGHT.beanbag;- if (kind === "meeting") return SEAT_HEIGHT.meeting;- return SEAT_HEIGHT.chair;-}--/** Nameplate scale by camera distance: readable up close, compact in the overview, never huge. */-export function plateScale(distance: number): number {- return Math.min(1.05, Math.max(0.8, 24 / Math.max(1, distance)));-}--const RING_COLOUR = { working: OFFICE.ringWorking, idle: OFFICE.ringIdle, waiting: OFFICE.ringWaiting, paused: OFFICE.ringPaused } as const;--/** Jarvis is not a person in the office: it is the person's pet (Gigi by default), flying or on the floor. */-function gigiModeFor(pose: Pose | null, travelling: boolean): GigiFlightMode {- if (travelling || !pose) return "idle";- if (pose === "sit" || pose === "work") return "work";- if (pose === "stand") return "idle";- return pose;-}--function Nameplate({ agent, activity, selected, onSelect, height = OFFICE_FIGURE_HEIGHT_M + 0.35 }: {- agent: SocietyAgent; activity: ActivityKind | null; selected: boolean; onSelect: (id: string) => void; height?: number;-}) {- const t = useT();- const plate = useRef<HTMLButtonElement>(null);- const wrap = useRef<HTMLSpanElement>(null);- const anchor = useRef<Group>(null);- const last = useRef(0);- const world = useMemo(() => new Vector3(), []);- const [open, setOpen] = useState(false);- // The pointer on the figure itself counts like the pointer on its plate.- const pointedAt = useOfficeStore((s) => s.hover?.kind === "agent" && s.hover.id === agent.agentId);- const shown = useRef<PlateDetail>("dot");- // What the distance rule alone says (it has its own memory); a crowd may still keep the plate a dot.- const ruled = useRef<PlateDetail>("dot");- const wanted = useRef({ pointed: false, selected: false });- wanted.current = { pointed: open || pointedAt, selected };- // Whoever speaks in a team round keeps its plate in a crowd, with room for the bubble above it.- const speaking = useTeamwork((s) => isSpeaking(s.rounds, agent.agentId));- const spokeAt = useTeamwork((s) => lastSpokeBy(s.rounds, agent.agentId)?.atMs ?? 0);- const voice = useRef({ speaking, spokeAt });- voice.current = { speaking, spokeAt };- const measured = useRef({ w: 0, h: 0, tick: 0 });- const scene = useThree((s) => s.scene);- const onScreen = useMemo(() => new Vector3(), []);- // Plates are seated per stage (two offices can be awake at once); this one leaves its stage's seating on unmount.- useEffect(() => joinPlates(scene), [scene]);- useFrame(({ camera, size, clock }) => {- if (!anchor.current || !plate.current || !wrap.current) return;- anchor.current.getWorldPosition(world);- const cameraDistance = camera.position.distanceTo(world);- const personDistance = Math.hypot(world.x - player.x, world.z - player.z);- const scale = plateScale(cameraDistance);- // Far away the agent is a dot; the plate opens near the camera or the person, and for the one pointed at or selected.- ruled.current = plateDetail(ruled.current, { cameraDistance, personDistance, ...wanted.current });- let detail = ruled.current;- if (detail === "full") {- // In a crowd only the plates that do not cover one another open (plateCrowd.ts); the rest stay dots.- const m = measured.current;- if (m.w === 0 || m.tick % PLATE_MEASURE_FRAMES === 0) {- m.w = plate.current.offsetWidth || PLATE_FALLBACK_PX.w;- m.h = plate.current.offsetHeight || PLATE_FALLBACK_PX.h;- }- m.tick += 1;- onScreen.copy(world).project(camera);- if (onScreen.z < 1) {- const pinned = wanted.current.pointed || wanted.current.selected;- const taken = () => personPlate(camera, size);- if (!pinned && !plateSeating(scene, clock.elapsedTime, taken).has(agent.agentId)) detail = "dot";- reportPlate(scene, {- id: agent.agentId, x: (onScreen.x * 0.5 + 0.5) * size.width, y: (0.5 - onScreen.y * 0.5) * size.height,- w: m.w * scale, h: m.h * scale, pinned, distance: personDistance, shown: shown.current === "full",- speaker: voice.current.speaking || Date.now() - voice.current.spokeAt < SPOKE_LINGER_MS,- });- }- }- if (detail !== shown.current || wrap.current.dataset.detail !== detail) {- shown.current = detail;- wrap.current.dataset.detail = detail;- }- if (Math.abs(scale - last.current) < 0.02) return;- last.current = scale;- plate.current.style.transform = `scale(${scale.toFixed(2)})`;- });- const detail = agent.state !== "idle" ? t(`society.office.state_${agent.state}`) : activity ? t(`society.office.activity_${activity}`) : "";- const pane = isPaneAgentId(agent.agentId);- const logo = pane ? agentLogoAsset(agent.provider) : null;- const state = (- <span className="office-plate-state" title={t(`society.office.state_${agent.state}`)}>- <i aria-hidden />{detail ? <em>{detail}</em> : null}- </span>- );- return (- <group ref={anchor} position={[0, height, 0]}>- {/* Hover/focus raises a plate above its neighbours. Only the dot and the open plate take the pointer: the- wrapper is as wide as the plate even while it shows a dot, and must not swallow clicks meant for the floor. */}- <Html center zIndexRange={open ? [40, 30] : [20, 0]} style={PLATE_PASS_THROUGH}>- <span ref={wrap} className="office-plate-wrap" data-office-ui data-state={agent.state} data-detail={shown.current}- onPointerEnter={() => setOpen(true)} onPointerLeave={() => setOpen(false)}>- <i className="office-plate-dot" aria-hidden onClick={(event) => { event.stopPropagation(); onSelect(agent.agentId); }} />- <button ref={plate} type="button" className="office-plate" data-state={agent.state} data-selected={selected || undefined}- data-pane={pane || undefined} data-open={pane || open || undefined}- onClick={(event) => { event.stopPropagation(); onSelect(agent.agentId); }}- onFocus={() => setOpen(true)} onBlur={() => setOpen(false)}- aria-label={t("society.office.open_agent").replace("{0}", agent.name)}>- {pane && logo ? <PaneLogo url={logo.url} ground={logo.ground} /> : (- <span className="office-plate-badge" style={{ background: agent.palette.primary }} aria-hidden>- {agent.tier === "lead" ? "★" : (pane ? agent.provider : agent.name).slice(0, 1).toUpperCase()}- </span>- )}- {pane ? <PanePlateText agent={agent} state={state} /> : (- <>- <span className="office-plate-name" title={agent.name}>{agent.name}</span>- <PlateLevel agent={agent} />- {state}- </>- )}- </button>- </span>- </Html>- </group>- );-}--/** The plate's wrapper never takes the pointer itself; the dot and the open plate inside it do. */-const PLATE_PASS_THROUGH = { pointerEvents: "none" } as const;-/** A plate's size on screen is read from the DOM now and then, not every frame; before the first reading it is assumed. */-const PLATE_MEASURE_FRAMES = 45;-const PLATE_FALLBACK_PX = { w: 150, h: 22 } as const;-/** The person's own plate (OfficePlayer draws it) is always there: agents' plates keep clear of it. */-const PERSON_PLATE_PX = { w: 150, h: 26 } as const;-const personAt = new Vector3();--function personPlate(camera: Camera, size: { width: number; height: number }): ScreenRect[] {- personAt.set(player.x, OFFICE_FIGURE_HEIGHT_M + 0.35, player.z).project(camera);- if (personAt.z >= 1) return [];- return [{ x: (personAt.x * 0.5 + 0.5) * size.width, y: (0.5 - personAt.y * 0.5) * size.height, ...PERSON_PLATE_PX }];-}--/** An agent's level on its plate; the lead shows its pet's level, since the lead IS the pet. */-function PlateLevel({ agent }: { agent: SocietyAgent }) {- const lead = agent.tier === "lead";- const level = useProgression((s) => {- if (!s.snapshot) return null;- return s.subjects[lead ? petSubject(s.petId) : agentSubject(agent.agentId)]?.level ?? 1;- });- return level === null ? null : <LevelChip kind={lead ? "pet" : "agent"} level={level} />;-}--/**- * The coding CLI's own mark in front of a pane's plate, instead of a lettered- * hexagon: a floor of Claude panes read "C", "C", "C", which named nothing.- * Drawn here rather than with `AgentMark`, whose `ink` marks follow the app- * theme's text colour — the plate is dark in both themes, so a light-mode ink- * mark would vanish on it. An `ink` mark is masked in the plate's own white;- * a full-colour lockup keeps its colours on a dark tile it can sit on.- */-function PaneLogo({ url, ground }: { url: string; ground: "ink" | "dark" | "any" }) {- if (ground === "ink") {- const mask = { WebkitMaskImage: `url("${url}")`, maskImage: `url("${url}")` };- return <span className="office-plate-logo" data-ground="ink" aria-hidden><i style={mask} /></span>;- }- return <span className="office-plate-logo" data-ground={ground} aria-hidden><img src={url} alt="" draggable={false} /></span>;-}--/**- * A coding pane's plate shows only its whole title (subject, then result) and- * run state. The logo in front already names the CLI, so neither its- * call-sign nor the opening of the last prompt is repeated here.- */-function PanePlateText({ agent, state }: { agent: SocietyAgent; state: ReactNode }) {- const { subject, result } = plateTitle(agent.name);- return (- <span className="office-plate-text">- <span className="office-plate-name">{subject}</span>- <span className="office-plate-line">- {result ? <span className="office-plate-result">{result}</span> : null}- {state}- </span>- </span>- );-}--/** The sealed envelope Gigi carries on an errand, bobbing under it. */-function ErrandEnvelope() {- const env = useRef<Group>(null);- useFrame(({ clock }) => {- if (!env.current) return;- env.current.position.y = 0.62 + Math.sin(clock.elapsedTime * 5) * 0.04;- env.current.rotation.y = clock.elapsedTime * 1.6;- });- return (- <group ref={env}>- <mesh castShadow>- <boxGeometry args={[0.26, 0.17, 0.02]} />- <meshStandardMaterial color="#fffaf0" roughness={0.6} />- </mesh>- <mesh position={[0, 0.02, 0.012]} rotation={[0, 0, Math.PI / 4]}>- <boxGeometry args={[0.13, 0.13, 0.004]} />- <meshStandardMaterial color="#efe3c8" roughness={0.7} />- </mesh>- <mesh position={[0, -0.01, 0.016]}>- <circleGeometry args={[0.03, 16]} />- <meshStandardMaterial color="#c0392b" roughness={0.4} />- </mesh>- </group>- );-}--export interface WalkerContext {- layout: OfficeLayout;- grid: NavGrid;- book: SpotBook;- /** Busy colleagues someone idle may visit, refreshed with the roster. */- colleagues: () => { agentId: string; desk: DeskSlot }[];- spawn: Point;-}--function Walker({ agent, desk, ctx, deskOf, arrivesByElevator, awake, reduced, selected, lines, onSelect }: {- agent: SocietyAgent; desk: DeskSlot | null; ctx: WalkerContext; deskOf: ReadonlyMap<string, DeskSlot>; arrivesByElevator: boolean;- awake: boolean; reduced: boolean; selected: boolean; lines: readonly ChatLine[] | undefined; onSelect: (id: string) => void;-}) {- const look = useMemo(() => toyLookFor(agent.figure, agent.agentId), [agent.figure, agent.agentId]);- const group = useRef<Group>(null);- const body = useRef<Group>(null);- const ring = useRef<Mesh>(null);- const drive = useRef<FigureDrive>({ mode: "idle", speed: 0 });- const dressed = useDressedFigure("agent", agentSubject(agent.agentId), look);- const rng = useMemo(() => createRng(agent.agentId), [agent.agentId]);- const mover = useRef<Mover>({ ...(arrivesByElevator ? ctx.spawn : { x: 0, z: 0 }), heading: Math.PI, path: [] });- const plan = useRef<Plan | null>(null);- const phase = useRef<"travel" | "dwell">("dwell");- const dwellUntil = useRef(0);- const placed = useRef(arrivesByElevator);- const planState = useRef("");- // The desk the current plan was made for: a roster change can move an agent to another desk.- const planDesk = useRef<string | null>(null);- const summonKey = useRef("");- // The walk in progress (its route, stuck watch and time budget), and the floor plan the current plan was made on.- const walk = useRef<Walk | null>(null);- const planGrid = useRef<NavGrid | null>(null);- // Team life: the studio the agent belongs to, its part in a running round, and the message it is walking over.- const home = useMemo(() => homeStudio(ctx.layout, agent.agentId, desk), [ctx.layout, agent.agentId, desk]);- const roleMemory = useRef<RoleMemory>({ role: "none", busySinceMs: null });- const roundKey = useRef("");- const handoffKey = useRef("");- const nearby = useRef<Point[]>([]);- const tally = useRef({ replans: 0, rescues: 0, repaths: 0, near: 0, blocked: 0, lost: 0 });- // Walks in a row that were given up because the way stayed closed.- const givenUp = useRef(0);- // The keys a plan is made for, built when the desk or the call changes and not on every frame.- const deskKey = useMemo(() => (desk ? `${desk.id}@${desk.x.toFixed(2)},${desk.z.toFixed(2)}` : null), [desk]);- const called = useRef<{ summon: Summon | undefined; key: string }>({ summon: undefined, key: "" });- // Seconds the person has stood right beside this agent at a board (negative: it just made room, give it a moment).- const crowded = useRef(0);- const [activity, setActivity] = useState<ActivityKind | null>(null);- const [seatHeight, setSeatHeight] = useState<number>(SEAT_HEIGHT.chair);- const isGigi = agent.tier === "lead";- const [gigiPose, setGigiPose] = useState<{ pose: Pose | null; travelling: boolean }>({ pose: null, travelling: false });- const speaking = useEventStore((s) => isGigi && s.voiceState === "speaking");- const errandKey = useRef("");- const carrying = useGigiErrands((s) => isGigi && s.current?.phase === "fly");- const [following, setFollowing] = useState(false);- const followingRef = useRef(false);- const gigiSide = useRef<1 | -1>(1);- const airClear = useMemo(() => (x: number, z: number) => isWalkable(ctx.grid, { x, z }), [ctx.grid]);- // Where the pet keeps the person company: free floor that is nobody's, so it never sits in a seated agent or on a chair.- const petSpot = useMemo(() => {- const around: Point[] = [];- return (x: number, z: number) => isWalkable(ctx.grid, { x, z }) && clearOfBodies({ x, z }, bodiesNear(agent.agentId, { x, z }, 1, null, around), PET_CLEAR_M);- }, [ctx.grid, agent.agentId]);- // The lead is drawn as the person's pet; one that walks takes floor routes instead of flying over desks.- const petOnFloor = useCompanionPet((s) => isGigi && !companionFlies(s.pet));- const onFloorRef = useRef(petOnFloor);- onFloorRef.current = petOnFloor;- const routeGoal = useRef<Point | null>(null);-- // Leaving the office releases the agent's spot and its registry entry.- useEffect(() => () => {- ctx.book.release(agent.agentId);- agentPositions.delete(agent.agentId);- seatedAtDesk.delete(agent.agentId);- companions.delete(agent.agentId);- walkerDebug.delete(agent.agentId);- }, [ctx.book, agent.agentId]);- const pet = useMemo(() => ({ ...resolveCompanion(agent.agentId, agent.figure?.companion), sizeM: PET_SIZE_M, followDistanceM: PET_FOLLOW_M }),- [agent.agentId, agent.figure?.companion]);- const petClear = useMemo(() => (point: TrailPoint, radius: number) =>- isWalkable(ctx.grid, { x: point[0] - radius, z: point[2] }) && isWalkable(ctx.grid, { x: point[0] + radius, z: point[2] })- && isWalkable(ctx.grid, { x: point[0], z: point[2] - radius }) && isWalkable(ctx.grid, { x: point[0], z: point[2] + radius }), [ctx.grid]);-- useFrame((_, rawDt) => {- const dt = Math.min(rawDt, 0.1);- const now = Date.now();- const m = mover.current;- // A flyer heads straight for its goal; a pet on the floor walks a route, re-planned only when the goal moves.- const headFor = (goal: Point) => {- if (!onFloorRef.current) { m.path = [goal]; return; }- const last = routeGoal.current;- if (last && m.path.length > 0 && Math.hypot(last.x - goal.x, last.z - goal.z) < 0.4) return;- routeGoal.current = { x: goal.x, z: goal.z };- m.path = findPath(ctx.grid, m, goal) ?? [goal];- };- // Gigi on an errand: fly straight to the recipient, hover and deliver, then back to its day.- const errand = isGigi ? useGigiErrands.getState().current : null;- const recipient = errand ? agentPositions.get(errand.to) : undefined;- if (errand && !recipient) useGigiErrands.getState().finish(errand.id);- if (errand && recipient) {- if (followingRef.current) { followingRef.current = false; setFollowing(false); }- companions.delete(agent.agentId);- const key = `${errand.id}:${errand.phase}`;- if (errand.phase === "fly") {- const spot = deliverySpot(recipient, m);- if (errandKey.current !== key) routeGoal.current = null;- if (onFloorRef.current) headFor(spot);- else {- const end = m.path[m.path.length - 1];- if (errandKey.current !== key || !end || Math.hypot(end.x - spot.x, end.z - spot.z) > 0.4) m.path = [spot];- }- if (reduced) { m.x = spot.x; m.z = spot.z; m.path = []; }- const { arrived } = stepMover(m, ERRAND_SPEED, dt);- if (arrived) useGigiErrands.getState().arrive(errand.id);- } else {- m.heading = turnToward(m.heading, Math.atan2(recipient.x - m.x, recipient.z - m.z), 8 * dt);- if (now >= errand.untilMs) useGigiErrands.getState().finish(errand.id);- }- if (errandKey.current !== key) {- errandKey.current = key;- setGigiPose({ pose: errand.phase === "deliver" ? "talk" : null, travelling: errand.phase === "fly" });- }- // The day resumes from wherever the errand ended.- plan.current = null;- placeAgent(agent.agentId, m.x, m.z);- seatedAtDesk.delete(agent.agentId);- if (group.current) group.current.position.set(m.x, 0, m.z);- return;- }- errandKey.current = "";- const summon = useOfficeStore.getState().summons[agent.agentId];- const calledTo = summon && summon.untilMs > now ? summon.target : null;- if (isGigi && !calledTo) {- // Gigi keeps the person company, as on the coding floor; an errand or a summons still takes it away.- const anchor = followAnchor(player.x, player.z, player.heading, gigiSide.current, petSpot, onFloorRef.current);- gigiSide.current = anchor.side;- const far = Math.hypot(anchor.x - m.x, anchor.z - m.z) > FOLLOW_CATCH_M;- if (!placed.current || reduced || !far) {- m.x = anchor.x; m.z = anchor.z; m.path = [];- placed.current = true;- } else if (awake) {- // Back from an errand or a meeting: fly (or run) over to the person, then fall in beside them.- headFor(anchor);- stepMover(m, ERRAND_SPEED, dt);- }- const nowFollowing = Math.hypot(anchor.x - m.x, anchor.z - m.z) <= FOLLOW_CATCH_M;- if (nowFollowing) { m.heading = player.heading; companions.add(agent.agentId); } else companions.delete(agent.agentId);- if (followingRef.current !== nowFollowing || plan.current) {- followingRef.current = nowFollowing;- setFollowing(nowFollowing);- setGigiPose({ pose: null, travelling: !nowFollowing });- setActivity(null);- }- // The day resumes from wherever the person leaves Gigi (a summons).- plan.current = null;- summonKey.current = "";- placeAgent(agent.agentId, m.x, m.z);- seatedAtDesk.delete(agent.agentId);- if (group.current) group.current.position.set(m.x, 0, m.z);- return;- }- if (followingRef.current) { followingRef.current = false; setFollowing(false); }- companions.delete(agent.agentId);- const calledSeat = calledTo ? summon.spotId ?? null : null;- if (called.current.summon !== summon) {- called.current = { summon, key: summon ? `${summon.target.x.toFixed(2)},${summon.target.z.toFixed(2)},${summon.spotId ?? ""}` : "" };- }- const sKey = calledTo ? called.current.key : "";- // Team life, from what is real right now: a running round of the agent's team, and a message it sent a colleague.- const teamwork = useTeamwork.getState();- const round = isGigi ? undefined : roundFor(teamwork.rounds, agent.agentId, home?.teamId ?? null);- const role = steadyRole(roleMemory.current, roundRole(agent, round), now);- const inRound = !!round && !calledTo && (role === "gather" || role === "speaker");- const rKey = inRound && round ? round.teamId : "";- // The stay with the receiver is over: the message has been delivered.- if (plan.current?.kind === "handoff" && handoffKey.current && phase.current === "dwell" && now >= dwellUntil.current) {- teamwork.finishHandoff(handoffKey.current);- }- // Only a free agent walks a message over; a working one keeps its screen (its bubble still says what it sent).- const handoff = isGigi || reduced || agent.state !== "idle" || calledTo || inRound- ? null : pendingHandoff(useTeamwork.getState().handoffs, agent.agentId, now);- const hKey = handoff ? handoff.id : "";- // A rebuilt floor plan: the plan holds only if its place still exists there, and its spot is still this agent's.- let stale = false;- if (plan.current && planGrid.current !== ctx.grid) {- const held = plan.current;- stale = !planStillValid(held, ctx.layout, ctx.grid) || (held.spotId !== null && !ctx.book.claim(held.spotId, agent.agentId));- planGrid.current = ctx.grid;- }- // The person walked into the group at the board: the agent beside them makes room (another place in the arc).- let makeRoom = false;- if (plan.current?.kind === "huddle" && phase.current === "dwell" && Math.hypot(player.x - m.x, player.z - m.z) < PERSON_CROWD_M) {- crowded.current += dt;- if (crowded.current > 0.4) { makeRoom = true; crowded.current = -3; }- } else if (crowded.current > 0) crowded.current = 0;- else crowded.current = Math.min(0, crowded.current + dt);- const needsPlan = !plan.current || planState.current !== agent.state || summonKey.current !== sKey- || planDesk.current !== deskKey || roundKey.current !== rKey || handoffKey.current !== hKey || stale || makeRoom- || (phase.current === "dwell" && now >= dwellUntil.current);- if (needsPlan) {- const seatedMates = home ? mateDesks(ctx.layout, home, agent.agentId).filter((d) => seatedAtDesk.has(d.agentId as string)) : [];- const next = planFor({- agentId: agent.agentId, state: agent.state, desk, layout: ctx.layout, grid: ctx.grid, rng, book: ctx.book,- previous: plan.current?.kind ?? null, workingColleagues: ctx.colleagues().filter((c) => c.agentId !== agent.agentId), calledTo, calledSeat,- position: placed.current ? { x: m.x, z: m.z } : null,- // The member contributing right now reads "working"; it is the one working member a round places.- round: inRound && round ? { speaker: role === "speaker" || agent.state === "working", teamId: round.teamId } : null,- // A receiver that works is at its screen, or on its way there: its desk is where to find it.- handoff: handoff ? {- to: handoff.to, desk: deskOf.get(handoff.to) ?? null, at: agentPositions.get(handoff.to) ?? null,- seated: seatedAtDesk.has(handoff.to) || ctx.colleagues().some((c) => c.agentId === handoff.to),- } : null,- matesAtDesk: seatedMates.map((d) => ({ agentId: d.agentId as string, desk: d })),- backToDesk: roundKey.current !== "" && rKey === "",- bodies: bodiesNear(agent.agentId, m, Infinity, player, nearby.current),- person: player,- });- // Reduced motion: no idle wandering — a placement holds until the state changes.- if (reduced && !calledTo) next.dwellMs = Infinity;- plan.current = next;- planState.current = agent.state;- planDesk.current = deskKey;- summonKey.current = sKey;- roundKey.current = rKey;- handoffKey.current = hKey;- planGrid.current = ctx.grid;- walk.current = null;- if (!placed.current || reduced) {- // First sight (or reduced motion): already there, no walk across the floor.- m.x = next.target.x; m.z = next.target.z; m.path = [];- if (next.facing !== null) m.heading = next.facing;- placed.current = true;- phase.current = "dwell";- } else if (isGigi) {- m.path = findPath(ctx.grid, m, next.target) ?? [];- // Gigi flies: after an errand it may hover over a desk, where no floor path starts.- if (m.path.length === 0 && !onFloorRef.current && Math.hypot(next.target.x - m.x, next.target.z - m.z) > 0.05) m.path = [next.target];- if (m.path.length === 0) { m.x = next.target.x; m.z = next.target.z; }- phase.current = m.path.length > 0 ? "travel" : "dwell";- } else {- walk.current = beginWalk(ctx.grid, m, next.target, bodiesNear(agent.agentId, m, BODY_RANGE_M, player, nearby.current));- // No way there on this floor plan: the agent is simply there.- if (!walk.current) { m.x = next.target.x; m.z = next.target.z; m.path = []; }- phase.current = m.path.length > 0 ? "travel" : "dwell";- }- if (phase.current === "dwell") {- dwellUntil.current = now + next.dwellMs;- if (next.kind === "handoff" && hKey) teamwork.deliverHandoff(hKey, now, HANDOFF_DWELL_MS);- }- // The plate says "at the team board" only for a gathering that is real: a running round, or a meeting the person called.- const shown = shownActivity(next.kind, inRound || calledTo !== null);- if (shown !== activity) setActivity(shown);- if (isGigi) setGigiPose({ pose: next.pose, travelling: phase.current === "travel" });- const nextSeat = seatHeightFor(next.kind);- if (nextSeat !== seatHeight) setSeatHeight(nextSeat);- }- const p = plan.current!;- if (phase.current === "travel") {- // Walkers steer round other people and never through them or the furniture; Gigi flies over everyone.- let moved = 0, arrived = false;- const going = walk.current;- if (!awake) { /* A sleeping stage holds every walk where it is. */ }- else if (isGigi || !going) ({ moved, arrived } = stepMover(m, WALK_SPEED, dt));- else {- // Nobody is moved across the floor, with one exception: a place the agent's real state demands (its screen- // while it works, the board while its round runs) that it failed to reach twice.- const step = advanceWalk(going, m, ctx.grid, dt, bodiesNear(agent.agentId, m, BODY_RANGE_M, player, nearby.current),- { far: givenUp.current >= 2 && !Number.isFinite(p.dwellMs), ...(p.kind === "work" ? { speed: hurryPaceFor(going.remaining) } : {}) });- ({ moved, arrived } = step);- if (step.event === "replan") tally.current.replans += 1;- else if (step.event === "rescue") tally.current.rescues += 1;- else if (step.event === "repath") tally.current.repaths += 1;- else if (step.event === "near") tally.current.near += 1;- else if (step.event === "lost" || step.event === "blocked") {- // No way to this place (a new floor plan walled it off, or the way stays closed): plan again next frame.- if (step.event === "lost") tally.current.lost += 1;- else { tally.current.blocked += 1; givenUp.current += 1; }- plan.current = null;- }- }- // Waiting for someone to pass is standing, not walking on the spot.- drive.current.mode = moved > 1e-4 ? "walk" : "idle";- drive.current.speed = moved / Math.max(dt, 1e-3);- if (arrived) {- phase.current = "dwell";- givenUp.current = 0;- // A long way earns a long stay, so a large floor shows people being somewhere.- dwellUntil.current = now + dwellAfter(p, going?.length ?? 0);- if (p.kind === "handoff" && handoffKey.current) teamwork.deliverHandoff(handoffKey.current, now, HANDOFF_DWELL_MS);- if (isGigi) setGigiPose({ pose: p.pose, travelling: false });- }- } else {- if (p.facing !== null) m.heading = turnToward(m.heading, p.facing, 8 * dt);- // At the board the member contributing right now talks; everyone else listens.- drive.current.mode = POSE_CLIP[p.kind === "huddle" && role === "speaker" ? "talk" : p.pose];- drive.current.speed = 0;- }- if (import.meta.env.DEV) {- walkerDebug.set(agent.agentId, {- id: agent.agentId, name: agent.name, state: agent.state, team: home?.teamId ?? null, studio: home?.deptId ?? null, role,- plan: plan.current?.kind ?? null, phase: phase.current, target: plan.current?.target ?? null, spot: plan.current?.spotId ?? null,- with: plan.current?.with ?? null, at: { x: m.x, z: m.z }, pathLength: m.path.length, remainingM: walk.current?.remaining ?? 0,- stuckS: phase.current === "travel" ? walk.current?.watch.idleS ?? 0 : 0,- walkS: phase.current === "travel" ? walk.current?.elapsedS ?? 0 : 0,- speed: phase.current === "travel" && walk.current && walk.current.elapsedS > 0- ? (walk.current.length - walk.current.remaining) / walk.current.elapsedS : 0,- ...tally.current,- });- }- placeAgent(agent.agentId, m.x, m.z);- if (plan.current && phase.current === "dwell" && (p.kind === "work" || p.kind === "desk")) seatedAtDesk.add(agent.agentId);- else seatedAtDesk.delete(agent.agentId);- if (group.current) group.current.position.set(m.x, 0, m.z);- if (body.current) body.current.rotation.y = m.heading;- if (ring.current) {- const material = ring.current.material as MeshBasicMaterial;- material.opacity = agent.state === "working" && awake && !reduced ? 0.55 + Math.sin(now / 330) * 0.3 : 0.8;- ring.current.visible = isGigi ? onFloorRef.current : phase.current === "dwell" || selected;- }- });-- // A pet on the floor carries its name low, just above its head; a flyer's sits above its hover height.- const leadPlate = petOnFloor ? LEAD_PLATE_ON_FLOOR_M : LEAD_PLATE_FLYING_M;- const presentation = (- // The lead inherits GigiFlyer's rendered ground anchor. Only ordinary- // walkers bind the group that the navigation frame positions directly.- <group ref={isGigi ? undefined : group} userData={{ agentId: agent.agentId }}>- <mesh ref={ring} visible={!isGigi || petOnFloor} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.015, 0]}>- <ringGeometry args={[selected ? 0.4 : 0.46, 0.54, 40]} />- <meshBasicMaterial color={selected ? "#93c5fd" : RING_COLOUR[agent.state]} transparent opacity={0.8} side={DoubleSide} depthWrite={false} />- </mesh>- <group ref={body}- onClick={(event) => { event.stopPropagation(); onSelect(agent.agentId); }}- onPointerOver={() => { document.body.style.cursor = "pointer"; useOfficeStore.getState().setHover({ kind: "agent", id: agent.agentId }); }}- onPointerOut={() => {- document.body.style.cursor = "";- const hover = useOfficeStore.getState().hover;- if (hover?.kind === "agent" && hover.id === agent.agentId) useOfficeStore.getState().setHover(null);- }}>- {!isGigi && <ToyFigure look={dressed.look} drive={drive} paused={!awake} heightM={OFFICE_FIGURE_HEIGHT_M} seatHeight={seatHeight}- regalia={dressed.regalia} />}- </group>- <Nameplate agent={agent} activity={activity} selected={selected} onSelect={onSelect} height={isGigi ? leadPlate : undefined} />- <AgentBubble agent={agent} lines={lines} selected={selected} onSelect={onSelect} listening={activity === "huddle"}- height={(isGigi ? leadPlate : OFFICE_FIGURE_HEIGHT_M + 0.35) + 0.14} />- {carrying && <ErrandEnvelope />}- </group>- );- return isGigi- // One flyer for both roles, so switching keeps its flight state instead of re-spawning it.- ? <GigiFlyer owner={following ? PLAYER_OWNER : mover} mode={following ? "follow" : gigiModeFor(gigiPose.pose, gigiPose.travelling)}- speaking={speaking} paused={!awake} reduced={reduced} clear={following ? airClear : undefined}>- {presentation}- </GigiFlyer>- : <>{presentation}<AgentFollower owner={group} appearance={pet} paused={!awake || reduced} clear={petClear} /></>;-}--export function OfficeAgents({ desks, agents, ctx, newcomers, awake, reduced, selectedId, chats, onSelect }: {- desks: DeskSlot[]; agents: ReadonlyMap<string, SocietyAgent>; ctx: WalkerContext; newcomers: ReadonlySet<string>;- awake: boolean; reduced: boolean; selectedId: string | null; chats?: ReadonlyMap<string, DeskChat>; onSelect: (id: string) => void;-}) {- const deskOf = useMemo(() => new Map(desks.filter((d) => d.agentId).map((d) => [d.agentId as string, d])), [desks]);- useErrandFeed(agents, awake);- // Team rounds and messages between agents exist only where there are team studios (the agents floor).- const studios = studiosOf(ctx.layout);- useTeamRounds(studios, agents, awake && studios.length > 0);- // Leaving the office hangs up: the talk socket closes, the chat keeps running on the server.- useEffect(() => () => { officeTalkChat.getState().disconnect(); useOfficeTalk.getState().setAgent(null); }, []);- return (- <group>- {[...agents.values()].map((agent) => (- <Walker key={agent.agentId} agent={agent} desk={deskOf.get(agent.agentId) ?? null} ctx={ctx} deskOf={deskOf}- arrivesByElevator={newcomers.has(agent.agentId)} awake={awake} reduced={reduced}- selected={selectedId === agent.agentId} lines={chats?.get(agent.agentId)?.lines} onSelect={onSelect} />- ))}- {studios.length > 0 && <StudioBoards layout={ctx.layout} agents={agents} awake={awake} />}- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeBubbles.memory.test.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeBubbles.memory.test.tsxdeleted file mode 100644index 2c6cfa2d95..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeBubbles.memory.test.tsx+++ /dev/null@@ -1,124 +0,0 @@-/**- * The lead pet's thought bubble shows its memory receipts end to end: a- * `MemoryFileWrite` payload in the store becomes "Updating memory · MEMORY.md",- * then "Saved to MEMORY.md" — and nothing claims "saved" without a receipt.- */-import type { ReactNode } from "react";-import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";-import { act, createRoot, extend, type ReconcilerRoot } from "@react-three/fiber";-import { cleanup, render, screen } from "@testing-library/react";-import * as THREE from "three";-import { loadLocaleChunk, setUiLanguage } from "@/i18n";-import { useMemoryWrites } from "@/store/memoryWrites";-import type { SocietyAgent } from "../data";-import { AgentBubble } from "./OfficeBubbles";-import { useOfficeTalk } from "./officeTalk";--/** What the in-world `<Html>` would put on screen, captured per render. */-const shown: { current: ReactNode } = { current: null };-vi.mock("@react-three/drei", async (original) => ({- ...await original<typeof import("@react-three/drei")>(),- Html: ({ children }: { children: ReactNode }) => { shown.current = children; return null; },-}));--extend(THREE);-let root: ReconcilerRoot<HTMLCanvasElement> | null = null;--function fakeRenderer(canvas: HTMLCanvasElement) {- const noop = () => undefined;- return {- domElement: canvas, render: noop, setSize: noop, setPixelRatio: noop, setAnimationLoop: noop, dispose: noop,- getPixelRatio: () => 1, shadowMap: { enabled: false, type: 0, needsUpdate: false },- xr: { enabled: false, isPresenting: false, addEventListener: noop, removeEventListener: noop, setAnimationLoop: noop },- outputColorSpace: "srgb", toneMapping: 0, toneMappingExposure: 1,- info: { render: {}, memory: {} },- };-}--const lead = { agentId: "jarvis", name: "George", tier: "lead", state: "idle", chatSessionId: null } as SocietyAgent;-const scout = { agentId: "scout", name: "Scout", tier: "specialist", state: "idle", chatSessionId: null } as SocietyAgent;--async function bubbleOf(agent: SocietyAgent, lines: { kind: "agent" | "tool"; text: string }[] = []) {- shown.current = null;- const canvas = document.createElement("canvas");- root = root ?? createRoot(canvas);- root.configure({- gl: fakeRenderer(canvas) as unknown as NonNullable<Parameters<ReconcilerRoot<HTMLCanvasElement>["configure"]>[0]>["gl"],- frameloop: "never", size: { width: 100, height: 100, top: 0, left: 0 },- });- await act(async () => {- root?.render(<AgentBubble agent={agent} lines={lines as never} selected={false} height={1} onSelect={() => undefined} />);- });- cleanup();- if (shown.current) render(<>{shown.current}</>);- return shown.current;-}--function receipt(phase: string, file = "MEMORY.md", id = "u1", agent = "jarvis") {- act(() => useMemoryWrites.getState().receive({ update_id: id, agent_id: agent, file, phase, operation: "add" }));-}--beforeAll(async () => {- setUiLanguage("en");- await loadLocaleChunk("society");-});--beforeEach(() => {- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);- useMemoryWrites.getState().reset();- useOfficeTalk.setState({ agentId: null });-});--afterEach(async () => {- await act(async () => root?.unmount());- root = null;- cleanup();- useMemoryWrites.getState().reset();- vi.restoreAllMocks();- vi.unstubAllGlobals();-});--describe("the lead's memory receipt", () => {- it("names the file while writing and claims saved only after the receipt", async () => {- receipt("pending");- await bubbleOf(lead);- const row = screen.getByRole("status");- expect(row.dataset.phase).toBe("pending");- expect(row.textContent).toMatch(/MEMORY\.md/);- expect(row.textContent).toBe("Updating memory · MEMORY.md");-- receipt("saved");- await bubbleOf(lead);- expect(screen.getByRole("status").dataset.phase).toBe("saved");- expect(screen.getByRole("status").textContent).toBe("Saved to MEMORY.md");- });-- it("shows a failed write as failed", async () => {- receipt("pending", "SOUL.md");- receipt("failed", "SOUL.md");- await bubbleOf(lead);- expect(screen.getByRole("status").dataset.phase).toBe("failed");- expect(screen.getByRole("status").textContent).toMatch(/SOUL\.md/);- });-- it("keeps the agent's own thought and adds the memory line under it", async () => {- receipt("pending", "USER.md");- await bubbleOf({ ...lead, state: "working" }, [{ kind: "agent", text: "Checking the calendar" }]);- expect(screen.getByText(/Checking the calendar/)).toBeTruthy();- expect(screen.getByRole("status").textContent).toMatch(/USER\.md/);- });-- it("leaves the bubble empty again when the write changed nothing", async () => {- receipt("pending");- receipt("unchanged");- expect(await bubbleOf(lead)).toBeNull();- });-- it("never draws a memory line over another agent", async () => {- receipt("pending", "MEMORY.md", "u2", "scout");- expect(await bubbleOf(scout)).toBeNull();- receipt("pending", "MEMORY.md", "u3", "jarvis");- expect(await bubbleOf(scout)).toBeNull();- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeBubbles.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeBubbles.tsxdeleted file mode 100644index 46198e3983..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeBubbles.tsx+++ /dev/null@@ -1,230 +0,0 @@-/**- * Comic bubbles over heads in the office: a thought cloud while an agent- * works, a speech bubble with its reply, a "?" bubble when it waits for the- * person — and the person's own words over their character.- *- * In-world, like the nameplates: one dark look in both themes, scaled by- * camera distance. Ambient bubbles (agents nobody is talking to) hide when- * the camera is far away, so the overview never turns into a wall of text.- */-import { useMemo, useRef, useState } from "react";-import { Html } from "@react-three/drei";-import { useFrame } from "@react-three/fiber";-import { AlertTriangle, Check, LoaderCircle } from "lucide-react";-import { Vector3, type Group } from "three";-import { useT } from "@/i18n";-import { useCanvasInterval } from "@/hooks/useCanvasInterval";-import { useEventStore } from "@/store/events";-import { memoryNoteFor, useMemoryWrites, type MemoryWrite } from "@/store/memoryWrites";-import type { SocietyAgent } from "../data";-import type { ChatLine } from "./deskChat";-import { player } from "./officeStore";-import { plateScale } from "./OfficeAgents";-import { useGigiErrands } from "./gigiErrands";-import { memoryLine, type MemoryLabels, type MemoryLine } from "./memoryBubble";-import { isSpeaking, lastSpokeBy, teamBubble, teamBubbleLive, useTeamwork } from "./teamwork";-import {- ambientBubble, bubbleText, conversationBubble, itemsFor, PLAYER_LINE_MS, REPLY_LINGER_MS, talkStoreFor, useOfficeTalk,- type Bubble, type BubbleLabels,-} from "./officeTalk";--/** Ambient bubbles only show within this camera distance (metres). */-const AMBIENT_RANGE_M = 20;-/** What a team says and hands over is the floor's real news: readable from a little further away. */-const TEAM_RANGE_M = 34;--export function useBubbleLabels(): BubbleLabels {- const t = useT();- return useMemo(() => ({- thinking: t("society.office.bubble_thinking"),- tool: t("society.office.bubble_tool"),- failed: t("society.office.bubble_failed"),- cancelled: t("society.office.bubble_cancelled"),- done: t("society.office.bubble_done"),- approval: t("society.office.bubble_approval"),- waiting: t("society.office.bubble_waiting"),- }), [t]);-}--export function useMemoryLabels(): MemoryLabels {- const t = useT();- return useMemo(() => ({- updating: t("society.office.memory_updating"),- updatingFile: t("society.office.memory_updating_file"),- saved: t("society.office.memory_saved"),- savedFile: t("society.office.memory_saved_file"),- failed: t("society.office.memory_failed"),- failedFile: t("society.office.memory_failed_file"),- }), [t]);-}--const NO_WRITES: Record<string, MemoryWrite> = {};--/**- * The lead's memory receipt (George writing MEMORY.md, USER.md, SOUL.md …)- * as one bubble line. Only the lead shows it; other agents keep their bubbles.- */-function useMemoryLine(agent: SocietyAgent): MemoryLine | null {- const labels = useMemoryLabels();- const writes = useMemoryWrites((s) => (agent.tier === "lead" ? s.writes : NO_WRITES));- const own = useMemo(() => Object.values(writes).filter((w) => w.agentId === agent.agentId), [writes, agent.agentId]);- const now = useClock(own.length > 0);- if (own.length === 0) return null;- // A receipt that arrived after the last tick is newer than `now`: it counts as just now.- const note = memoryNoteFor(writes, agent.agentId, Math.max(now, ...own.map((w) => w.atMs)));- return note ? memoryLine(note, labels) : null;-}--const MEMORY_ICON = { pending: LoaderCircle, saved: Check, failed: AlertTriangle } as const;--/** Gigi's side of an errand ("on my way to Nora", then the task) and the recipient's "Got it". */-function useErrandBubble(agent: SocietyAgent): Bubble | null {- const t = useT();- const errand = useGigiErrands((s) => s.current);- if (!errand) return null;- if (agent.tier === "lead") {- return errand.phase === "fly"- ? { kind: "thought", text: t("society.office.errand_flying").replace("{0}", errand.toName || "…"), live: true, atMs: 0 }- : { kind: "speech", text: bubbleText(errand.text || t("society.office.errand_task"), 180), live: false, atMs: 0 };- }- if (agent.agentId === errand.to && errand.phase === "deliver") {- return { kind: "speech", text: t("society.office.errand_ack"), live: false, atMs: 0 };- }- return null;-}--/**- * Real teamwork over an agent's head: the line it just said in its team's- * round, a thought while it is the round's speaker, and the message it sent- * (or is walking over to) a colleague. See teamwork.ts.- */-function useTeamBubble(agent: SocietyAgent): Bubble | null {- const t = useT();- const spoke = useTeamwork((s) => lastSpokeBy(s.rounds, agent.agentId));- const speaking = useTeamwork((s) => isSpeaking(s.rounds, agent.agentId));- const handoff = useTeamwork((s) => s.handoffs.find((h) => h.from === agent.agentId) ?? null);- // The clock runs only while a line or a message is still on its way out; a line said long ago needs none.- const now = useClock(teamBubbleLive(spoke, handoff, Date.now()));- if (!spoke && !speaking && !handoff) return null;- return teamBubble({- spoke, speaking, handoff, now: Math.max(now, spoke?.atMs ?? 0, handoff?.atMs ?? 0), short: bubbleText,- labels: { thinking: t("society.office.bubble_thinking"), to: t("society.office.handoff_to") },- });-}--/** Re-renders once a second while `active`, so a settled bubble can expire. */-function useClock(active: boolean): number {- const [now, setNow] = useState(() => Date.now());- useCanvasInterval(() => setNow(Date.now()), 1000, active);- return now;-}--/** The bubble itself, anchored `height` metres above its parent group. */-export function BubbleView({ bubble, height, range = Infinity, onClick, memory }: {- bubble: Bubble; height: number; range?: number; onClick?: () => void;- /** The lead's memory receipt, shown as its own line under the bubble text. */- memory?: MemoryLine | null;-}) {- const anchor = useRef<Group>(null);- const box = useRef<HTMLDivElement>(null);- const world = useMemo(() => new Vector3(), []);- const last = useRef({ scale: 0, hidden: false });- useFrame(({ camera }) => {- if (!anchor.current || !box.current) return;- const distance = camera.position.distanceTo(anchor.current.getWorldPosition(world));- const hidden = distance > range;- const scale = plateScale(distance);- if (hidden !== last.current.hidden) {- last.current.hidden = hidden;- box.current.style.visibility = hidden ? "hidden" : "visible";- }- if (Math.abs(scale - last.current.scale) < 0.02) return;- last.current.scale = scale;- box.current.style.transform = `translateX(-50%) scale(${scale.toFixed(2)})`;- });- return (- <group ref={anchor} position={[0, height, 0]}>- <Html zIndexRange={[22, 0]} style={{ pointerEvents: "none" }}>- <div ref={box} className="office-bubble" data-kind={bubble.kind} data-live={bubble.live || undefined} data-office-ui- role={onClick ? "button" : undefined} onClick={onClick ? (e) => { e.stopPropagation(); onClick(); } : undefined}- style={{ pointerEvents: onClick ? "auto" : "none" }}>- {bubble.text- ? <p>{bubble.text}{bubble.live && bubble.kind !== "ask" ? <span className="office-bubble-dots" aria-hidden><i /><i /><i /></span> : null}</p>- : null}- {memory ? <MemoryRow line={memory} /> : null}- {bubble.kind === "thought"- ? <span className="office-bubble-puffs" aria-hidden><i /><i /></span>- : <span className="office-bubble-tail" aria-hidden />}- </div>- </Html>- </group>- );-}--function MemoryRow({ line }: { line: MemoryLine }) {- const Icon = MEMORY_ICON[line.phase];- return (- <span className="office-bubble-memory" data-phase={line.phase} role="status" aria-live="polite">- <Icon aria-hidden strokeWidth={2.4} />- <span className="office-bubble-memory-text">{line.text}</span>- </span>- );-}--/**- * The agent's bubble: its live conversation when the person talks to it,- * otherwise what it is busy with (from the desk-monitor tail).- */-export function AgentBubble({ agent, lines, selected, height, onSelect, listening = false }: {- agent: SocietyAgent; lines: readonly ChatLine[] | undefined; selected: boolean; height: number; onSelect: (id: string) => void;- /** The agent stands at its team's board in a running round: there only the member who has the word carries a bubble. */- listening?: boolean;-}) {- const labels = useBubbleLabels();- const talking = useOfficeTalk((s) => s.agentId === agent.agentId);- const useStore = talkStoreFor(agent);- const timeline = useStore((s) => (talking ? s.timeline : null));- const activeSessionId = useStore((s) => (talking ? s.activeSessionId : null));- const talk = useMemo(() => {- if (!timeline) return null;- return conversationBubble(itemsFor(agent, activeSessionId, timeline), timeline.pendingApprovals.length, labels);- }, [timeline, activeSessionId, agent, labels]);- const lingering = !!talk && !talk.live && !selected;- const now = useClock(lingering);- const open = () => onSelect(agent.agentId);- const errand = useErrandBubble(agent);- const team = useTeamBubble(agent);- const memory = useMemoryLine(agent);- if (errand) return <BubbleView bubble={errand} height={height} onClick={open} memory={memory} />;- if (talk && (talk.live || selected || now - talk.atMs < REPLY_LINGER_MS)) {- return <BubbleView bubble={talk} height={height} onClick={open} memory={memory} />;- }- if (team) return <BubbleView bubble={team} height={height} range={memory ? Infinity : TEAM_RANGE_M} onClick={open} memory={memory} />;- // A listener at the board says nothing: its own work bubble would read as a second voice in the round.- if (listening && !memory) return null;- const ambient = listening ? null : ambientBubble(agent.state, lines, labels);- if (ambient) return <BubbleView bubble={ambient} height={height} range={memory ? Infinity : AMBIENT_RANGE_M} onClick={open} memory={memory} />;- // Nothing else to say: the memory receipt alone fills the thought cloud.- return memory- ? <BubbleView bubble={{ kind: "thought", text: "", live: false, atMs: 0 }} height={height} onClick={open} memory={memory} />- : null;-}--/** The person's own words over their character: the live transcript while speaking, then the sent line. */-export function PlayerBubble({ height }: { height: number }) {- const t = useT();- const group = useRef<Group>(null);- const listening = useOfficeTalk((s) => s.listening);- const line = useOfficeTalk((s) => s.playerLine);- const interim = useEventStore((s) => (listening ? s.dictationText : ""));- const now = useClock(!!line && !listening);- useFrame(() => { group.current?.position.set(player.x, 0, player.z); });- let bubble: Bubble | null = null;- if (listening) bubble = { kind: "speech", text: interim || t("society.office.bubble_listening"), live: true, atMs: 0 };- else if (line && now - line.atMs < PLAYER_LINE_MS) bubble = { kind: "speech", text: line.text, live: false, atMs: line.atMs };- return (- <group ref={group}>- {bubble ? <BubbleView bubble={bubble} height={height} /> : null}- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeCameraRig.follow.test.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeCameraRig.follow.test.tsxdeleted file mode 100644index d106238c17..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeCameraRig.follow.test.tsx+++ /dev/null@@ -1,145 +0,0 @@-import { useEffect, useImperativeHandle } from "react";-import { act, cleanup, render } from "@testing-library/react";-import { afterEach, beforeEach, expect, it, vi } from "vitest";-import { PerspectiveCamera, Vector3 } from "three";-import { CanvasActivity } from "@/hooks/useCanvasAwake";-import { FOLLOW_DISTANCE, OfficeCameraRig } from "./OfficeCameraRig";-import { cameraLimitsFor } from "./officeCamera";-import { officeSession, player, useOfficeStore } from "./officeStore";-import { campusOf } from "./officeFixtures";-import { boundsWithPad } from "./skyPad";--const state = vi.hoisted(() => ({- frames: new Set<(frame: unknown, dt: number) => void>(),- renderer: null as unknown as { camera: PerspectiveCamera; size: { width: number; height: number }; gl: { domElement: HTMLCanvasElement }; scene: object; events: { connected: undefined } },- controls: null as unknown as { target: Vector3; enabled: boolean; update: () => void; mouseButtons: { LEFT: number }; zoomSpeed: number; maxDistance: number },-}));--vi.mock("@react-three/fiber", () => ({- useThree: (select: (value: typeof state.renderer) => unknown) => select(state.renderer),- useFrame: (frame: (frame: unknown, dt: number) => void) => {- useEffect(() => { state.frames.add(frame); return () => { state.frames.delete(frame); }; }, [frame]);- },-}));-vi.mock("@react-three/drei", async () => {- const { forwardRef } = await import("react");- return {- OrbitControls: forwardRef(({ enabled, maxDistance }: { enabled: boolean; maxDistance: number }, ref) => {- state.controls.enabled = enabled;- state.controls.maxDistance = maxDistance;- useImperativeHandle(ref, () => state.controls);- return null;- }),- };-});--const campus = campusOf(40, [8, 7, 6, 5]);-const originalPlayer = { ...player };--beforeEach(() => {- state.renderer = {- camera: new PerspectiveCamera(35, 1.6, 0.2, 800), size: { width: 1280, height: 800 },- gl: { domElement: document.createElement("canvas") }, scene: {}, events: { connected: undefined },- };- state.controls = { target: new Vector3(), enabled: true, update: () => undefined, mouseButtons: { LEFT: 0 }, zoomSpeed: 1, maxDistance: 0 };- officeSession.camera = null;- Object.assign(player, { x: campus.layout.spawn.x, z: campus.layout.spawn.z, heading: 0, path: [], moving: false });- useOfficeStore.setState({ zoom: null, focus: null, follow: true });-});--afterEach(() => {- cleanup();- state.frames.clear();- Object.assign(player, originalPlayer);- officeSession.camera = null;-});--const tree = (overview: number) => (- <CanvasActivity.Provider value><OfficeCameraRig layout={campus.layout} overview={overview} /></CanvasActivity.Provider>-);-const frames = (count: number) => act(() => { for (let i = 0; i < count; i += 1) for (const step of state.frames) step(null, 1 / 30); });-const orbit = () => state.renderer.camera.position.distanceTo(state.controls.target);-const offTarget = () => Math.hypot(state.controls.target.x - player.x, state.controls.target.z - player.z);--it("comes back to the walking view when following resumes after the overview", () => {- const view = render(tree(0));- frames(5);- expect(orbit()).toBeCloseTo(FOLLOW_DISTANCE, 1);- const angle = () => { const c = state.renderer.camera.position, t = state.controls.target; return Math.atan2(c.x - t.x, c.z - t.z); };-- view.rerender(tree(1));- frames(5);- // The overview stands a campus away and looks at the middle of the floor.- expect(orbit()).toBeGreaterThan(60);- expect(useOfficeStore.getState().follow).toBe(false);- const from = orbit();- const yaw = angle();-- act(() => useOfficeStore.getState().setFollow(true));- frames(3);- // A glide, not a cut: on its way after a tenth of a second.- expect(orbit()).toBeLessThan(from);- expect(orbit()).toBeGreaterThan(FOLLOW_DISTANCE + 5);- frames(40);- expect(orbit()).toBeCloseTo(FOLLOW_DISTANCE, 1);- expect(offTarget()).toBeLessThan(0.05);- // Only the distance changed: the direction the person looks from stays.- expect(angle()).toBeCloseTo(yaw, 2);-});--it("keeps a distance the person zoomed to by hand in the overview", () => {- const view = render(tree(0));- frames(5);- view.rerender(tree(1));- frames(5);- const chosen = orbit();- act(() => { state.renderer.gl.domElement.dispatchEvent(new WheelEvent("wheel", { deltaY: 100 })); });- // Far out a notch zooms further than up close.- expect(state.controls.zoomSpeed).toBeGreaterThan(4);- act(() => useOfficeStore.getState().setFollow(true));- frames(40);- expect(orbit()).toBeCloseTo(chosen, 1);- expect(offTarget()).toBeLessThan(0.05);-});--it("lets the wheel reach the overview of this floor", () => {- render(tree(0));- // The floor and the sky pad beside it.- expect(state.controls.maxDistance).toBe(cameraLimitsFor(boundsWithPad(campus.layout.bounds, campus.layout.skyPad), 1280 / 800).maxDistance);- expect(state.controls.maxDistance).toBeGreaterThan(100);-});--it("does not restore a remembered view of a place the floor no longer has", () => {- officeSession.camera = { position: [900, 20, 900], target: [880, 0.8, 880] };- officeSession.follow = false;- render(tree(0));- frames(2);- // The view starts from the character instead.- expect(offTarget()).toBeLessThan(0.05);- expect(orbit()).toBeCloseTo(FOLLOW_DISTANCE, 1);- expect(useOfficeStore.getState().follow).toBe(true);-});--it("leaves the view where it is when the floor plan is rebuilt (a team was created)", () => {- // A view remembered from an earlier visit; restoring it again now would be a jump.- officeSession.camera = { position: [30, 25, 30], target: [10, 0.8, 10] };- officeSession.follow = false;- const view = render(tree(0));- frames(3);- // The person turns and pans to a view of their own.- act(() => {- state.renderer.camera.position.set(-12, 18, 4);- state.controls.target.set(-20, 0.8, -6);- useOfficeStore.getState().setFollow(false);- });- frames(2);- const position = state.renderer.camera.position.toArray();- const target = state.controls.target.toArray();- // Same floor, new plan: one more team, so a fresh layout object with a fresh `spawn`.- const rebuilt = campusOf(40, [8, 7, 6, 5, 4]);- view.rerender(<CanvasActivity.Provider value><OfficeCameraRig layout={rebuilt.layout} overview={0} /></CanvasActivity.Provider>);- frames(5);- expect(state.renderer.camera.position.toArray()).toEqual(position);- expect(state.controls.target.toArray()).toEqual(target);- expect(useOfficeStore.getState().follow).toBe(false);-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeCameraRig.lifecycle.test.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeCameraRig.lifecycle.test.tsxdeleted file mode 100644index 7b54a240eb..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeCameraRig.lifecycle.test.tsx+++ /dev/null@@ -1,75 +0,0 @@-import { useEffect, useImperativeHandle } from "react";-import { act, cleanup, render } from "@testing-library/react";-import { afterEach, beforeEach, expect, it, vi } from "vitest";-import { PerspectiveCamera, Vector3 } from "three";-import { CanvasActivity } from "@/hooks/useCanvasAwake";-import { OfficeCameraRig } from "./OfficeCameraRig";-import { buildOfficeLayout } from "./officeLayout";-import { officeSession, useOfficeStore } from "./officeStore";--const state = vi.hoisted(() => ({- frames: new Set<(_state: unknown, dt: number) => void>(),- renderer: null as unknown as { camera: PerspectiveCamera; size: { width: number; height: number }; gl: { domElement: HTMLCanvasElement }; scene: object; events: { connected: undefined } },- controls: null as unknown as { target: Vector3; enabled: boolean; update: () => void; mouseButtons: { LEFT: number } },-}));--vi.mock("@react-three/fiber", () => ({- useThree: (select: (value: typeof state.renderer) => unknown) => select(state.renderer),- useFrame: (frame: (_state: unknown, dt: number) => void) => {- useEffect(() => { state.frames.add(frame); return () => { state.frames.delete(frame); }; }, [frame]);- },-}));-vi.mock("@react-three/drei", async () => {- const { forwardRef } = await import("react");- return {- OrbitControls: forwardRef(({ enabled }: { enabled: boolean }, ref) => {- state.controls.enabled = enabled;- useImperativeHandle(ref, () => state.controls);- return null;- }),- };-});--beforeEach(() => {- vi.useFakeTimers();- state.renderer = {- camera: new PerspectiveCamera(35, 1.6, 0.2, 800), size: { width: 1280, height: 800 },- gl: { domElement: document.createElement("canvas") }, scene: {}, events: { connected: undefined },- };- state.controls = { target: new Vector3(), enabled: true, update: () => undefined, mouseButtons: { LEFT: 0 } };- officeSession.camera = null;- useOfficeStore.setState({ zoom: null, focus: null, follow: true });-});--afterEach(() => {- cleanup();- state.frames.clear();- vi.useRealTimers();-});--it.each([2, 14])("returns from a hidden monitor dive after %i frames without replaying it", (frames) => {- const layout = buildOfficeLayout([]);- const tree = (active: boolean) => <CanvasActivity.Provider value={active}><OfficeCameraRig layout={layout} overview={0} /></CanvasActivity.Provider>;- const view = render(tree(true));- const initialPosition = state.renderer.camera.position.toArray();- const initialTarget = state.controls.target.toArray();- act(() => {- useOfficeStore.getState().zoomInto([4, 1, 7], 0);- for (let i = 0; i < frames; i += 1) for (const step of state.frames) step(null, 0.1);- });- expect(state.renderer.camera.position.toArray()).not.toEqual(initialPosition);- expect(state.controls.enabled).toBe(false);-- view.rerender(tree(false));- expect(state.renderer.camera.position.toArray()).toEqual(initialPosition);- expect(state.controls.target.toArray()).toEqual(initialTarget);- expect(vi.getTimerCount()).toBe(0);- act(() => vi.advanceTimersByTime(3_000));- expect(state.controls.enabled).toBe(false);-- view.rerender(tree(true));- act(() => { for (const step of state.frames) step(null, 0.1); });- expect(state.renderer.camera.position.toArray()).toEqual(initialPosition);- expect(state.controls.target.toArray()).toEqual(initialTarget);- expect(state.controls.enabled).toBe(true);-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsxdeleted file mode 100644index ff73ff46fc..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeCameraRig.tsx+++ /dev/null@@ -1,521 +0,0 @@-/**- * One camera for walking and for the overview. OrbitControls always own- * rotate and zoom; in follow mode the orbit target glides after the- * character, so zooming out turns the same view into an overview without a- * mode switch. A right-drag pan or a fly-to leaves follow mode; moving the- * character re-enters it. Seated at Mission Control's desk the camera glides- * into the character's eyes (first person onto the monitors) and back out- * when it stands up; asking for the overview or a fly-to stands it up.- *- * The zoom limits and the overview follow the floor's size, so a campus of- * any extent can be framed whole. While the character stands inside a walled- * room, the walls the camera looks in through drop to a kerb (wallCutaway.ts).- *- * A press that turned the camera never ends in a click, and the wheel zooms- * by how far it turned (see officeCamera.ts).- */-import { useContext, useEffect, useMemo, useRef } from "react";-import { useReducedMotion } from "framer-motion";-import { CanvasActivity } from "@/hooks/useCanvasAwake";-import { OrbitControls } from "@react-three/drei";-import { useFrame, useThree } from "@react-three/fiber";-import { MOUSE, Vector3, type Object3D, type PerspectiveCamera } from "three";-import type { OrbitControls as OrbitControlsImpl } from "three-stdlib";-import {- cameraLimitsFor, campusOverview, CAMERA_LIMITS, depthNear, DRAG_CLICK_PX, FOLLOW_CATCH_UP_M, FOLLOW_DISTANCE_M, followBlend, followDistanceAfterOverview,- HOME_PITCH_RAD, HOME_YAW_RAD, settleView, wheelZoomSpeed, type CameraPose,-} from "./officeCamera";-import { seatOf, wallRect, type OfficeLayout, type WallSegment } from "./officeLayout";-import { cutawayStep, cutawayWalls, wallKey } from "./wallCutaway";-import { useLeadSeat } from "./leadSeat";-import { cameraView, officeSession, player, useOfficeStore } from "./officeStore";-import { courierSession } from "./courierStore";-import { boundsWithPad } from "./skyPad";-import "./officeCameraRig.css";--/** Where the camera starts: close behind the character, south-east, looking down. */-export const FOLLOW_DISTANCE = FOLLOW_DISTANCE_M;-const TARGET_HEIGHT = 0.8;-/** How often the scene is searched for wall objects, and how often the cutaway is decided (seconds). */-const WALL_SCAN_S = 1;-const CUTAWAY_CHECK_S = 0.12;-/** How long the glide back to a far-away character takes when following resumes. */-const CATCH_UP_SECONDS = 0.6;-/** How long the dive into a monitor takes before the chat opens. */-export const ZOOM_SECONDS = 1.15;-/** Monitor screen size in metres (see LiveMonitors): the dive ends with it filling the view. */-const SCREEN_W = 0.66, SCREEN_H = 0.38;-/**- * First person at Mission Control: eye height, how far behind the seat centre- * the eyes sit, the height looked at, a wider lens so all three monitors fit,- * and how long the glide in and out takes.- */-const FIRST_PERSON = { eyeY: 1.2, back: 0.3, lookY: 1.08, lookAhead: 0.2, fov: 64, seconds: 0.7 };--/** How far in front of a screen the camera must stand for the screen to fill the view. */-export function screenFillDistance(fovDeg: number, aspect: number, width = SCREEN_W, height = SCREEN_H): number {- const v = Math.tan((fovDeg * Math.PI) / 360);- return Math.max(height / 2 / v, width / 2 / (v * Math.max(0.2, aspect)));-}--export function OfficeCameraRig({ layout, overview }: { layout: OfficeLayout; overview: number }) {- const active = useContext(CanvasActivity);- const activeRef = useRef(active);- activeRef.current = active;- const controls = useRef<OrbitControlsImpl>(null);- const camera = useThree((s) => s.camera);- const size = useThree((s) => s.size);- const gl = useThree((s) => s.gl);- const scene = useThree((s) => s.scene);- // The element R3F and the orbit controls listen on (the canvas wrapper, which also holds the <Html> labels).- const connected = useThree((s) => s.events.connected) as HTMLElement | undefined;- const reduced = useReducedMotion() ?? false;- // The wheel may back away far enough to frame this floor whole, however large it is.- const aspect = size.width / Math.max(1, size.height);- // The camera frames the slab and the sky pad beside it.- const viewBounds = useMemo(() => boundsWithPad(layout.bounds, layout.skyPad), [layout.bounds, layout.skyPad]);- const limits = useMemo(() => cameraLimitsFor(viewBounds, aspect), [viewBounds, aspect]);- const lastFocus = useRef(0);- const lastZoom = useRef(0);- // Following resumed far from the character: glide over instead of snapping across the floor.- // The glide can also bring the camera back to a walking distance (after the overview).- const catchUp = useRef<{ from: Vector3; t: number; fromDistance: number; toDistance: number } | null>(null);- const wasFollowing = useRef(false);- // The orbit distance before the overview took the camera away; cleared once the person zooms by hand.- const beforeOverview = useRef<number | null>(null);- // A remembered view is only restored where it still makes sense on this floor plan.- const wallRects = useMemo(() => layout.walls.map(wallRect), [layout.walls]);- const settle = (pose: CameraPose) => settleView(pose, viewBounds, wallRects);- const backOff = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);- useEffect(() => () => clearTimeout(backOff.current), []);- const dive = useRef<{ fromEye: Vector3; toEye: Vector3; fromTarget: Vector3; toTarget: Vector3; t: number } | null>(null);- const flight = useRef<{ from: Vector3; to: Vector3; t: number } | null>(null);- const desired = useRef(new Vector3());- // First person: 0 = the normal view, 1 = the character's eyes; the view it left is kept to glide back to.- const seated = useRef<{ blend: number; before: { position: Vector3; target: Vector3; fov: number } | null }>({ blend: 0, before: null });- const eye = useRef(new Vector3());- const look = useRef(new Vector3());- const delta = useRef(new Vector3());- const shownFirstPerson = useRef(false);-- // First person for the rest of the scene: Gigi steps aside (cameraView), and the floating labels- // of the rest of the floor hide over the monitors (officeCameraRig.css keys on the attribute).- const publishFirstPerson = (on: boolean) => {- cameraView.firstPerson = on;- if (shownFirstPerson.current === on) return;- shownFirstPerson.current = on;- const viewport = gl.domElement.closest(".office-viewport");- if (on) viewport?.setAttribute("data-first-person", "");- else viewport?.removeAttribute("data-first-person");- };- useEffect(() => () => {- if (activeRef.current) cameraView.firstPerson = false;- gl.domElement.closest(".office-viewport")?.removeAttribute("data-first-person");- }, [gl]);-- // Out of first person at once, back to the view it left: the person asked for another view.- const leaveFirstPerson = () => {- const c = controls.current;- const fp = seated.current;- const desk = layout.command;- if (desk && useLeadSeat.getState().seated === desk.id) useLeadSeat.getState().set({ seated: null, standUp: true });- const lensCam = camera as PerspectiveCamera;- if (fp.before) {- camera.position.copy(fp.before.position);- c?.target.copy(fp.before.target);- lensCam.fov = fp.before.fov;- lensCam.updateProjectionMatrix();- }- fp.before = null;- fp.blend = 0;- if (c) { c.enabled = true; c.update(); }- };-- // Remember the view when leaving: the pose before a dive, never the inside of a monitor,- // and the view before sitting down, never the character's eyes.- const preDive = useRef<{ position: [number, number, number]; target: [number, number, number] } | null>(null);- useEffect(() => {- const store = useOfficeStore.getState();- lastZoom.current = store.zoom?.seq ?? 0;- lastFocus.current = store.focus?.seq ?? 0;- if (active) return;- clearTimeout(backOff.current);- dive.current = null;- flight.current = null;- const c = controls.current;- const beforeSeat = seated.current.before;- const saved = beforeSeat- ? { position: beforeSeat.position.toArray() as [number, number, number], target: beforeSeat.target.toArray() as [number, number, number] }- : preDive.current;- if (saved) {- camera.position.set(...saved.position);- c?.target.set(...saved.target);- }- if (beforeSeat) {- (camera as PerspectiveCamera).fov = beforeSeat.fov;- (camera as PerspectiveCamera).updateProjectionMatrix();- }- seated.current = { blend: 0, before: null };- preDive.current = null;- if (c) {- c.enabled = false;- c.update();- officeSession.camera = { position: camera.position.toArray() as [number, number, number], target: c.target.toArray() as [number, number, number] };- }- officeSession.follow = store.follow;- shownFirstPerson.current = false;- gl.domElement.closest(".office-viewport")?.removeAttribute("data-first-person");- }, [active, camera, gl]);- useEffect(() => () => {- // An inactive retained rig already saved its pose; another visible office may own the session now.- if (!activeRef.current) return;- const c = controls.current;- const beforeSeat = seated.current.before;- officeSession.camera = beforeSeat- ? { position: beforeSeat.position.toArray() as [number, number, number], target: beforeSeat.target.toArray() as [number, number, number] }- : preDive.current ?? (c- ? { position: camera.position.toArray() as [number, number, number], target: c.target.toArray() as [number, number, number] }- : null);- officeSession.follow = useOfficeStore.getState().follow;- // The camera belongs to the canvas and can outlive this rig: hand it back with its own lens.- if (beforeSeat) { (camera as PerspectiveCamera).fov = beforeSeat.fov; (camera as PerspectiveCamera).updateProjectionMatrix(); }- }, [camera]);-- // Start where the last visit left off, or close to the character. This runs when the map comes on screen and- // when the floor changes (an elevator ride), never because the floor plan was rebuilt: creating or renaming a- // team while the person looks at the map must leave the view where it is.- const floorKey = layout.variant;- const startedOn = useRef<string | null>(null);- useEffect(() => {- if (!active) { startedOn.current = null; return; }- if (import.meta.env.DEV) (window as unknown as Record<string, unknown>).__office = { camera, controls: controls.current, gl, scene };- // The remembered view belongs to the floor the map was left on: after a ride the view starts from the character.- const rode = startedOn.current !== null && startedOn.current !== floorKey;- startedOn.current = floorKey;- // The floor plan may have been rebuilt since the view was remembered: a view of a place that is gone- // starts from the character instead, and a camera that would stand in a wall backs out of it.- const saved = !rode && officeSession.camera ? settle(officeSession.camera) : null;- if (saved) {- camera.position.set(...saved.position);- controls.current?.target.set(...saved.target);- controls.current?.update();- useOfficeStore.getState().setFollow(officeSession.follow);- return;- }- const target = new Vector3(player.x, TARGET_HEIGHT, player.z);- const horizontal = Math.cos(HOME_PITCH_RAD) * FOLLOW_DISTANCE;- camera.position.set(target.x + Math.sin(HOME_YAW_RAD) * horizontal, Math.sin(HOME_PITCH_RAD) * FOLLOW_DISTANCE + TARGET_HEIGHT,- target.z + Math.cos(HOME_YAW_RAD) * horizontal);- controls.current?.target.copy(target);- controls.current?.update();- useOfficeStore.getState().setFollow(true);- // `settle` reads the plan of the render that runs this effect; a rebuilt plan alone must not run it again.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [camera, gl, scene, floorKey, active]);-- // "Overview": frame the whole floor and stop following.- useEffect(() => {- if (!active || overview === 0) return;- // Seated in first person the glide would keep the camera in the chair: stand up first.- if (seated.current.blend > 0 || (layout.command && useLeadSeat.getState().seated === layout.command.id)) leaveFirstPerson();- const home = campusOverview(viewBounds, size.width / Math.max(1, size.height));- // "Follow me" comes back to the view the person walked in, not to a view from across the campus.- if (controls.current) beforeOverview.current ??= camera.position.distanceTo(controls.current.target);- flight.current = null;- catchUp.current = null;- useOfficeStore.getState().setFollow(false);- camera.position.set(...home.position);- controls.current?.target.set(...home.target);- controls.current?.update();- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [overview]);-- // A right-drag (or Ctrl-drag) pans: the person takes the camera, so stop following.- // Shift is the sprint key, so a Shift-drag must still rotate: OrbitControls- // turns Shift+left into a pan, which slid the view off a running character- // while the follow kept dragging it back. Flipping the left button to "pan"- // for that press makes the controls' own Shift inversion land on "rotate".- // (Capture phase: this runs before the controls read the button.) It listens- // where the controls listen, not on the canvas: a press that started on a- // floating label skipped it and kept the last Shift press's "pan", so a- // plain drag slid the view while the follow dragged it back.- useEffect(() => {- if (!active) return;- const el = connected ?? gl.domElement;- const down = (event: PointerEvent) => {- const c = controls.current;- const sprintDrag = event.shiftKey && !event.ctrlKey && !event.metaKey;- if (c) c.mouseButtons.LEFT = sprintDrag ? MOUSE.PAN : MOUSE.ROTATE;- if (event.button === 2 || event.ctrlKey || event.metaKey) useOfficeStore.getState().setFollow(false);- };- el.addEventListener("pointerdown", down, true);- return () => el.removeEventListener("pointerdown", down, true);- }, [connected, gl, active]);-- // A drag turns the camera and nothing else. R3F still delivers a click when- // the press ends on the object it started on, so a small turn over the- // Mission Control wall, a place token or an agent opened it (a handler's own- // `delta` check only sees start to end, and many had none). The click is- // swallowed here, in the capture phase, before R3F or a label sees it.- // The wheel zooms by how far it turned, not a fixed step per event.- useEffect(() => {- if (!active) return;- const el = connected ?? gl.domElement;- let origin: { x: number; y: number } | null = null;- let dragged = false;- const down = (event: PointerEvent) => {- origin = { x: event.clientX, y: event.clientY };- dragged = false;- // A pinch zoom uses the same speed; only the wheel sets it per event.- if (controls.current) controls.current.zoomSpeed = 1;- };- const move = (event: PointerEvent) => {- if (origin && !dragged && Math.hypot(event.clientX - origin.x, event.clientY - origin.y) > DRAG_CLICK_PX) dragged = true;- };- const up = () => { origin = null; };- const click = (event: MouseEvent) => {- if (!dragged) return;- dragged = false;- event.stopImmediatePropagation();- event.preventDefault();- };- const wheel = (event: WheelEvent) => {- const c = controls.current;- if (!c) return;- // Far out a notch covers more of the way, so a large floor zooms in a few notches.- c.zoomSpeed = wheelZoomSpeed(event.deltaY, event.deltaMode, camera.position.distanceTo(c.target));- // The person chose a distance: following keeps it from here on.- beforeOverview.current = null;- };- el.addEventListener("pointerdown", down, true);- window.addEventListener("pointermove", move, true);- window.addEventListener("pointerup", up, true);- el.addEventListener("click", click, true);- el.addEventListener("wheel", wheel, { capture: true, passive: true });- return () => {- el.removeEventListener("pointerdown", down, true);- window.removeEventListener("pointermove", move, true);- window.removeEventListener("pointerup", up, true);- el.removeEventListener("click", click, true);- el.removeEventListener("wheel", wheel, true);- };- }, [connected, gl, active]);-- // Inside a walled room the walls between camera and character drop to a kerb, so the room stays readable.- // Walls are whatever the scene tags with `userData.officeWall`; an untagged wall is simply never moved.- const walls = useRef<{ object: Object3D; key: string }[]>([]);- const wallScan = useRef(0);- const cutCheck = useRef(0);- const cut = useRef<Set<string>>(new Set());- useEffect(() => {- // A new floor plan brings new wall objects: look again at once.- wallScan.current = 0;- cutCheck.current = 0;- return () => {- for (const wall of walls.current) wall.object.scale.y = 1;- walls.current = [];- };- }, [layout]);- useFrame((frame, rawDt) => {- if (!active || typeof (scene as Partial<Object3D>).traverse !== "function") return;- const t = frame.clock.elapsedTime;- if (t >= wallScan.current) {- wallScan.current = t + WALL_SCAN_S;- const found: { object: Object3D; key: string }[] = [];- scene.traverse((object) => {- const wall = object.userData?.officeWall as WallSegment | undefined;- if (wall && typeof wall.x1 === "number") found.push({ object, key: wallKey(wall) });- });- walls.current = found;- }- if (walls.current.length === 0) return;- if (t >= cutCheck.current) {- cutCheck.current = t + CUTAWAY_CHECK_S;- // First person looks out of the room from inside it: nothing is in the way.- cut.current = cameraView.firstPerson ? new Set() : cutawayWalls(layout.rooms, layout.walls, player, { x: camera.position.x, z: camera.position.z });- }- const dt = Math.min(rawDt, 0.1);- for (const wall of walls.current) {- const next = cutawayStep(wall.object.scale.y, cut.current.has(wall.key), dt, reduced);- if (next !== wall.object.scale.y) wall.object.scale.y = next;- }- });- useEffect(() => {- if (!import.meta.env.DEV || !active) return;- // Dev-only: the walls lowered right now, how many wall objects are tagged, and this floor's zoom limits.- (window as unknown as Record<string, unknown>).__officeCamera = {- cut: () => [...cut.current], walls: () => walls.current.length, limits: () => limits,- };- }, [active, limits]);-- const wasFlying = useRef(false);- // The near plane follows the zoom, or coplanar layers (oak over slab) fight in bands when zoomed out.- useFrame(() => {- if (!active || courierSession.flying) return;- const c = controls.current;- const lens = camera as PerspectiveCamera;- if (!c || !lens.isPerspectiveCamera) return;- const near = depthNear(camera.position.distanceTo(c.target));- if (Math.abs(near - lens.near) < lens.near * 0.05) return;- lens.near = near;- lens.updateProjectionMatrix();- });-- useFrame((_, rawDt) => {- if (!active) return;- const c = controls.current;- if (!c) return;- // The courier flies the camera itself; on stepping out the orbit picks up behind the person beside the ship.- if (courierSession.flying) { c.enabled = false; wasFlying.current = true; return; }- if (wasFlying.current) {- wasFlying.current = false;- c.enabled = true;- c.target.set(player.x, 0.9, player.z);- camera.position.set(player.x - 9, 8, player.z + 9);- c.update();- }- // Publish the view for the minimap: where the camera stands and which way it looks.- const lens = camera as unknown as { fov: number; aspect: number };- cameraView.x = camera.position.x; cameraView.z = camera.position.z;- cameraView.yaw = Math.atan2(c.target.x - camera.position.x, c.target.z - camera.position.z);- cameraView.halfWidth = Math.atan(Math.tan(((lens.fov ?? 35) * Math.PI) / 360) * (lens.aspect ?? 1.6));- cameraView.ready = true;- const dt = Math.min(rawDt, 0.1);- const store = useOfficeStore.getState();- // Seated at Mission Control: glide into first person, and back out on standing up.- const desk = layout.command;- const fp = seated.current;- // A fly-to (an agent picked from a list, the minimap) is a request for another view: stand up for it,- // or it would wait until the person stands up and then fly somewhere stale.- const flyTo = !!store.focus && store.focus.seq !== lastFocus.current;- if (flyTo && !dive.current && (fp.blend > 0 || (!!desk && useLeadSeat.getState().seated === desk.id))) leaveFirstPerson();- const inSeat = !!desk && useLeadSeat.getState().seated === desk.id;- publishFirstPerson(inSeat || fp.blend > 0);- // A monitor dive from the chair runs as usual, starting from the eyes.- const diving = !!dive.current || (!!store.zoom && store.zoom.seq !== lastZoom.current);- if (desk && (inSeat || fp.blend > 0) && !diving) {- const lensCam = camera as PerspectiveCamera;- if (inSeat && !fp.before) fp.before = { position: camera.position.clone(), target: c.target.clone(), fov: lensCam.fov };- fp.blend = Math.min(1, Math.max(0, fp.blend + ((inSeat ? 1 : -1) * dt) / FIRST_PERSON.seconds));- const e = fp.blend < 0.5 ? 4 * fp.blend ** 3 : 1 - (-2 * fp.blend + 2) ** 3 / 2;- const before = fp.before;- if (before) {- const seat = seatOf(desk);- const dx = Math.sin(seat.facing), dz = Math.cos(seat.facing);- eye.current.set(seat.x - dx * FIRST_PERSON.back, FIRST_PERSON.eyeY, seat.z - dz * FIRST_PERSON.back);- look.current.set(desk.x + dx * FIRST_PERSON.lookAhead, FIRST_PERSON.lookY, desk.z + dz * FIRST_PERSON.lookAhead);- camera.position.lerpVectors(before.position, eye.current, e);- c.target.lerpVectors(before.target, look.current, e);- lensCam.fov = before.fov + (FIRST_PERSON.fov - before.fov) * e;- lensCam.updateProjectionMatrix();- camera.lookAt(c.target);- }- // Orbit limits would pull the camera out of the chair; the controls rest until the glide back ends.- c.enabled = false;- if (fp.blend === 0) {- if (before) { lensCam.fov = before.fov; lensCam.updateProjectionMatrix(); }- fp.before = null;- c.enabled = true;- c.update();- }- return;- }- if (store.zoom && store.zoom.seq !== lastZoom.current) {- lastZoom.current = store.zoom.seq;- flight.current = null;- // A second dive within the last one's wait: that wait must not yank the camera back mid-dive.- clearTimeout(backOff.current);- // End squarely in front of the screen, far enough back that it exactly fills the view.- const lens = camera as unknown as { fov: number; aspect: number };- const reach = screenFillDistance(lens.fov ?? 35, lens.aspect ?? 1.6, ...(store.zoom.size ?? [SCREEN_W, SCREEN_H])) * 1.02;- const [tx, ty, tz] = store.zoom.target;- // Still set while the last dive's wait runs: the view to come back to is the one before the first dive.- preDive.current ??= { position: camera.position.toArray() as [number, number, number], target: c.target.toArray() as [number, number, number] };- dive.current = { fromEye: camera.position.clone(),- toEye: new Vector3(tx + Math.sin(store.zoom.facing) * reach, ty, tz + Math.cos(store.zoom.facing) * reach),- fromTarget: c.target.clone(), toTarget: new Vector3(tx, ty, tz), t: 0 };- // Orbit limits (minimum distance, pitch) would stop the camera short of the glass.- c.enabled = false;- }- if (dive.current) {- // Dive: the look turns to the screen first, then the camera glides in (smooth in and out).- const d = dive.current;- d.t = Math.min(1, d.t + dt / ZOOM_SECONDS);- const ease = d.t < 0.5 ? 4 * d.t ** 3 : 1 - (-2 * d.t + 2) ** 3 / 2;- const look = Math.min(1, d.t / 0.45);- c.target.lerpVectors(d.fromTarget, d.toTarget, 1 - (1 - look) ** 3);- camera.position.lerpVectors(d.fromEye, d.toEye, ease);- camera.lookAt(c.target);- if (d.t >= 1) {- dive.current = null;- // If the chat does not take over (no handler), return to the view before the dive.- backOff.current = setTimeout(() => {- // Back to the view before the dive, unless the floor plan changed under it meanwhile.- const back = preDive.current ? settle(preDive.current) : null;- if (back) { camera.position.set(...back.position); c.target.set(...back.target); }- else camera.position.copy(c.target).add(camera.position.clone().sub(c.target).setLength(CAMERA_LIMITS.minDistance + 1));- preDive.current = null;- c.enabled = true;- c.update();- }, 2500);- }- return;- }- if (store.focus && store.focus.seq !== lastFocus.current) {- lastFocus.current = store.focus.seq;- flight.current = { from: c.target.clone(), to: new Vector3(store.focus.point.x, TARGET_HEIGHT, store.focus.point.z), t: 0 };- }- // Set while a glide also brings the camera back to a walking distance.- let zoomTo: number | null = null;- if (flight.current) {- const f = flight.current;- f.t = Math.min(1, f.t + dt / 0.7);- const ease = f.t < 0.5 ? 2 * f.t * f.t : 1 - (-2 * f.t + 2) ** 2 / 2;- desired.current.copy(f.from).lerp(f.to, ease);- if (f.t >= 1) flight.current = null;- } else if (store.follow) {- desired.current.set(player.x, TARGET_HEIGHT, player.z);- // Following resumed (the "follow me" button, a step after a pan) far from the character: one eased glide over.- if (!wasFollowing.current) {- const orbit = camera.position.distanceTo(c.target);- const back = beforeOverview.current;- beforeOverview.current = null;- if (back !== null || desired.current.distanceTo(c.target) > FOLLOW_CATCH_UP_M) {- catchUp.current = { from: c.target.clone(), t: 0, fromDistance: orbit, toDistance: back !== null ? followDistanceAfterOverview(back) : orbit };- }- }- const glide = catchUp.current;- if (glide) {- glide.t = Math.min(1, glide.t + dt / CATCH_UP_SECONDS);- const ease = glide.t < 0.5 ? 2 * glide.t * glide.t : 1 - (-2 * glide.t + 2) ** 2 / 2;- desired.current.lerpVectors(glide.from, desired.current, ease);- zoomTo = glide.fromDistance + (glide.toDistance - glide.fromDistance) * ease;- if (glide.t >= 1) catchUp.current = null;- } else {- // Exponential, so the motion is the same at any frame rate and eases out when the character stops.- desired.current.lerpVectors(c.target, desired.current, followBlend(dt));- }- } else {- wasFollowing.current = false;- catchUp.current = null;- return;- }- wasFollowing.current = store.follow && !flight.current;- // Move camera and target together: rotation and zoom stay what the person chose.- delta.current.copy(desired.current).sub(c.target);- c.target.add(delta.current);- camera.position.add(delta.current);- if (zoomTo !== null) {- // Along the line of sight, so the angle the person chose stays.- delta.current.copy(camera.position).sub(c.target).setLength(zoomTo);- camera.position.copy(c.target).add(delta.current);- }- c.update();- });-- return (- <OrbitControls ref={controls} makeDefault enabled={active} enableDamping dampingFactor={0.12} screenSpacePanning={false}- minPolarAngle={CAMERA_LIMITS.minPolar} maxPolarAngle={CAMERA_LIMITS.maxPolar}- minDistance={limits.minDistance} maxDistance={limits.maxDistance} />- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeChairs.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeChairs.tsxdeleted file mode 100644index a6af8ba5d9..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeChairs.tsx+++ /dev/null@@ -1,340 +0,0 @@-/**- * The office's chairs, built once as merged geometry so every copy costs a- * handful of draw calls however much detail a chair carries.- *- * - The desk task chair is an ergonomic mesh chair: a sculpted seat with a- * waterfall front edge, a curved mesh back in- * a black frame with a lumbar pad, T-arms with soft pads, a gas lift in its- * sleeve and a polished five-star base on twin-wheel casters. It is exported- * as a part list (`TASK_CHAIR_PARTS`) that `DeskInstances` instances per desk.- * - The meeting chair is a soft-pad conference chair: stitched leather pads- * slung between polished side rails on a four-star base.- *- * Both keep the seat top where the seated pose expects it (0.52 m at a desk,- * 0.50 m at the table) and stay inside a chair's 0.29 m reach from the column.- */-import {- BoxGeometry, BufferGeometry, CatmullRomCurve3, CylinderGeometry, DoubleSide, Euler, ExtrudeGeometry, Float32BufferAttribute,- Matrix4, MeshStandardMaterial, PlaneGeometry, Quaternion, RepeatWrapping, Shape, TubeGeometry, Vector3,-} from "three";-import { mergeVertices, RoundedBoxGeometry } from "three-stdlib";-import { cachedCanvasTexture } from "./canvasMaterials";-import { MAT, matte } from "./OfficeFurniture";-import { OFFICE } from "./officePalette";--/** Chair-only finishes: polished aluminium and the meeting chairs' cognac leather. */-const CHAIR_COLOURS = { aluminium: "#d3d6db", leather: "#9c5f38" } as const;--// ----------------------------------------------------------------------------// Geometry helpers-// -----------------------------------------------------------------------------type Vec3 = [number, number, number];--function at(position: Vec3, rotation: Vec3 = [0, 0, 0], scale: Vec3 = [1, 1, 1]): Matrix4 {- // YXZ: a part's tilt (x) is applied before its turn about the column (y).- const q = new Quaternion().setFromEuler(new Euler(rotation[0], rotation[1], rotation[2], "YXZ"));- return new Matrix4().compose(new Vector3(...position), q, new Vector3(...scale));-}--/** Bakes transformed pieces into one non-indexed geometry (positions and normals only). */-function merged(pieces: Array<[BufferGeometry, Matrix4]>): BufferGeometry {- const positions: number[] = [];- const normals: number[] = [];- for (const [source, matrix] of pieces) {- const piece = source.clone().applyMatrix4(matrix);- const flat = piece.index ? piece.toNonIndexed() : piece;- const p = flat.getAttribute("position").array;- const n = flat.getAttribute("normal").array;- for (let i = 0; i < p.length; i += 1) { positions.push(p[i]); normals.push(n[i]); }- piece.dispose();- if (flat !== piece) flat.dispose();- }- const out = new BufferGeometry();- out.setAttribute("position", new Float32BufferAttribute(positions, 3));- out.setAttribute("normal", new Float32BufferAttribute(normals, 3));- out.computeBoundingSphere();- return out;-}--/** Welds a geometry's seams and recomputes normals, so a bevelled cushion shades soft instead of faceted. */-function smooth(geometry: BufferGeometry): BufferGeometry {- geometry.deleteAttribute("uv");- const welded = mergeVertices(geometry, 1e-4);- welded.clearGroups();- welded.computeVertexNormals();- return welded;-}--/** A round tube along a smooth curve through `points`; callers squash it with a scale to make a blade. */-function tube(points: Vec3[], radius: number, closed = false, segments = 14): BufferGeometry {- const curve = new CatmullRomCurve3(points.map((p) => new Vector3(...p)), closed, "centripetal");- return new TubeGeometry(curve, segments, radius, 5, closed);-}--const rounded = (w: number, h: number, d: number, r: number) => new RoundedBoxGeometry(w, h, d, 1, r);--// ----------------------------------------------------------------------------// Shared base pieces-// -----------------------------------------------------------------------------/** One tapered, flattened spoke, thin end at +y; laid down by the caller. */-const SPOKE = new CylinderGeometry(0.015, 0.026, 1, 8);-const CASTER_WHEEL = new CylinderGeometry(0.03, 0.03, 0.017, 16);--/** A star base: hub, `count` spokes sloping down to `reach`, and a socket at each tip. */-function starBase(count: number, reach: number, hubY: number): Array<[BufferGeometry, Matrix4]> {- const pieces: Array<[BufferGeometry, Matrix4]> = [[new CylinderGeometry(0.048, 0.064, 0.075, 20), at([0, hubY, 0])]];- const length = reach - 0.03;- const tilt = 0.11;- for (let i = 0; i < count; i += 1) {- const a = (i * 2 * Math.PI) / count;- const mid = 0.03 + length / 2;- pieces.push([SPOKE, at([Math.sin(a) * mid, hubY - 0.012, Math.cos(a) * mid], [Math.PI / 2 + tilt, a, 0], [1, length, 0.62])]);- pieces.push([new CylinderGeometry(0.019, 0.021, 0.03, 12), at([Math.sin(a) * reach, hubY - 0.035, Math.cos(a) * reach])]);- }- return pieces;-}--/** Twin-wheel casters under the tips of a star base, wheels across the spoke. */-function casters(count: number, reach: number): Array<[BufferGeometry, Matrix4]> {- const pieces: Array<[BufferGeometry, Matrix4]> = [];- for (let i = 0; i < count; i += 1) {- const a = (i * 2 * Math.PI) / count;- const turn = new Matrix4().makeRotationY(a);- const place = (local: Vec3, rotation: Vec3, geometry: BufferGeometry) =>- pieces.push([geometry, turn.clone().multiply(at(local, rotation))]);- // Trailing slightly outboard of the socket, like a real swivel caster.- for (const x of [-0.013, 0.013]) place([x, 0.03, reach + 0.012], [0, 0, Math.PI / 2], CASTER_WHEEL);- place([0, 0.052, reach + 0.006], [0, 0, 0], rounded(0.038, 0.03, 0.05, 0.012));- }- return pieces;-}--// ----------------------------------------------------------------------------// Desk task chair (local: seat centre on the floor, sitter faces -z, back towards +z)-// -----------------------------------------------------------------------------/** Sculpted seat pan: side profile with a dished middle and a waterfall front edge, extruded across. */-function seatCushion(): BufferGeometry {- // Profile in (z, y): z runs front (-) to back (+).- const s = new Shape();- s.moveTo(0.19, 0.466);- s.lineTo(-0.16, 0.466);- s.quadraticCurveTo(-0.228, 0.47, -0.236, 0.498);- s.quadraticCurveTo(-0.232, 0.522, -0.18, 0.522);- s.quadraticCurveTo(-0.02, 0.5, 0.12, 0.508);- s.quadraticCurveTo(0.196, 0.514, 0.198, 0.494);- s.lineTo(0.19, 0.466);- const depth = 0.43;- const g = new ExtrudeGeometry(s, { depth, bevelEnabled: true, bevelThickness: 0.028, bevelSize: 0.012, bevelSegments: 1, curveSegments: 5 });- // Extruded along z; turn it so the profile's first axis becomes local z and the width runs along x.- g.applyMatrix4(new Matrix4().makeRotationY(-Math.PI / 2));- g.translate(depth / 2, 0, 0);- // Round the pan's corners in plan: the sides pull in a little towards the front and back edges.- const pos = g.getAttribute("position");- for (let i = 0; i < pos.count; i += 1) {- const z = pos.getZ(i);- pos.setX(i, pos.getX(i) * (1 - 0.07 * (z / 0.24) ** 2));- }- return smooth(g);-}--/** The backrest surface: a cone segment wrapping the sitter, wider and reclined at the shoulders, rounded corners. */-const BACK = { yb: 0.61, h: 0.5, rb: 0.5, rt: 0.6, arc: 0.84, zb: 0.212 } as const;-function backPoint(s: number, t: number, inset = 0): Vector3 {- const { yb, h, rb, rt, arc, zb } = BACK;- const axisZ = zb - rb;- const theta = (s * arc) / 2;- const r = rb + (rt - rb) * t - inset;- const y = yb + t * h - 0.06 * t * s ** 4 + 0.035 * (1 - t) * s ** 4;- return new Vector3(r * Math.sin(theta), y, axisZ + r * Math.cos(theta));-}--function backPanel(): BufferGeometry {- const g = new PlaneGeometry(1, 1, 6, 4);- const pos = g.getAttribute("position");- for (let i = 0; i < pos.count; i += 1) {- const p = backPoint(pos.getX(i) * 2, pos.getY(i) + 0.5);- pos.setXYZ(i, p.x, p.y, p.z);- }- g.computeVertexNormals();- g.computeBoundingSphere();- return g;-}--function backFrame(): BufferGeometry {- const points: Vec3[] = [];- const edge = (from: [number, number], to: [number, number], n: number) => {- for (let i = 0; i < n; i += 1) {- const k = i / n;- const p = backPoint(from[0] + (to[0] - from[0]) * k, from[1] + (to[1] - from[1]) * k);- points.push([p.x, p.y, p.z]);- }- };- edge([-1, 0], [1, 0], 6);- edge([1, 0], [1, 1], 6);- edge([1, 1], [-1, 1], 6);- edge([-1, 1], [-1, 0], 6);- return tube(points, 0.015, true, 36);-}--/** A rounded box bent round the backrest's curve at height `t`, standing `inset` in front of the mesh. */-function bentPad(w: number, h: number, d: number, t: number, inset: number): BufferGeometry {- const g = rounded(w, h, d, Math.min(h, d) / 2.2);- const pos = g.getAttribute("position");- const centre = backPoint(0, t, inset);- const r = BACK.rb + (BACK.rt - BACK.rb) * t - inset;- const axisZ = BACK.zb - BACK.rb;- for (let i = 0; i < pos.count; i += 1) {- const theta = pos.getX(i) / r;- const rr = r - pos.getZ(i);- pos.setXYZ(i, rr * Math.sin(theta), centre.y + pos.getY(i), axisZ + rr * Math.cos(theta));- }- g.computeVertexNormals();- return g;-}--/** Fine woven mesh for the backrest, drawn once. */-function meshWeave() {- const texture = cachedCanvasTexture("chair:mesh-weave", 64, 64, (ctx, w, h) => {- ctx.fillStyle = "#ffffff";- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "rgba(0,0,0,0.34)";- for (let y = 0; y < h; y += 4) ctx.fillRect(0, y, w, 1);- ctx.fillStyle = "rgba(0,0,0,0.18)";- for (let x = 0; x < w; x += 4) ctx.fillRect(x, 0, 1, h);- });- if (texture) {- texture.wrapS = texture.wrapT = RepeatWrapping;- texture.repeat.set(9, 10);- }- return texture;-}--export const CHAIR_MAT = {- aluminium: matte(CHAIR_COLOURS.aluminium, { roughness: 0.26, metalness: 0.65 }),- /** The backrest mesh: see-through weave, both faces lit (the backrest is a single curved sheet). */- mesh: new MeshStandardMaterial({ color: OFFICE.chairMesh, map: meshWeave(), roughness: 0.9, side: DoubleSide }),- leather: matte(CHAIR_COLOURS.leather, { roughness: 0.5 }),-};--/** Which finish a task-chair part takes; `DeskInstances` maps frame and fabric onto a desk tone's chair/seat roles. */-export type ChairFinish = "frame" | "fabric" | "metal" | "mesh";--export interface ChairPart {- finish: ChairFinish;- geometry: BufferGeometry;- cast: boolean;-}--const TASK_FRAME = merged([- // Gas-lift sleeve and the tilt mechanism with its paddle.- [new CylinderGeometry(0.029, 0.036, 0.23, 16), at([0, 0.225, 0])],- [rounded(0.22, 0.05, 0.24, 0.015), at([0, 0.438, 0.02])],- [rounded(0.09, 0.012, 0.024, 0.005), at([0.14, 0.43, -0.04], [0, -0.3, 0])],- // T-arms: a bar under the seat, a post, and a soft pad on top.- ...[-1, 1].flatMap((side): Array<[BufferGeometry, Matrix4]> => [- [rounded(0.2, 0.024, 0.05, 0.008), at([side * 0.175, 0.428, 0.06])],- [rounded(0.034, 0.25, 0.05, 0.012), at([side * 0.272, 0.54, 0.06])],- [rounded(0.078, 0.032, 0.26, 0.014), at([side * 0.272, 0.675, 0.03])],- ]),- // The backrest's frame, and the spine that carries it from the mechanism.- [backFrame(), new Matrix4()],- [tube([[0, 0.44, 0.1], [0, 0.46, 0.2], [0, 0.55, 0.245], [0, 0.7, 0.245]], 0.022), at([0, 0, 0], [0, 0, 0], [1.9, 1, 1])],- ...casters(5, 0.262),-]);--const TASK_METAL = merged([- ...starBase(5, 0.262, 0.105),- // Chrome piston between the sleeve and the mechanism.- [new CylinderGeometry(0.014, 0.014, 0.09, 12), at([0, 0.38, 0])],-]);--/** The ergonomic desk chair, one entry per draw call. */-export const TASK_CHAIR_PARTS: ChairPart[] = [- { finish: "metal", geometry: TASK_METAL, cast: true },- // The frame is arms, spine and casters: the seat and the back panel already throw the chair's shadow.- { finish: "frame", geometry: TASK_FRAME, cast: false },- { finish: "fabric", geometry: seatCushion(), cast: true },- // Lumbar pad in the seat fabric across the small of the back.- { finish: "fabric", geometry: bentPad(0.34, 0.07, 0.022, 0.2, 0.014), cast: false },- { finish: "mesh", geometry: backPanel(), cast: true },-];--/** The task chair outside the instanced desks (a single desk, a showroom): same parts, plain meshes. */-export function TaskChair({ fabric = MAT.chairSeat }: { fabric?: MeshStandardMaterial }) {- const finishes: Record<ChairFinish, MeshStandardMaterial> = { frame: MAT.chair, fabric, metal: CHAIR_MAT.aluminium, mesh: CHAIR_MAT.mesh };- return (- <group>- {TASK_CHAIR_PARTS.map((part, i) => (- <mesh key={i} geometry={part.geometry} material={finishes[part.finish]} castShadow={part.cast} receiveShadow />- ))}- </group>- );-}--// ----------------------------------------------------------------------------// Meeting chair (local: seat centre on the floor, facing +z, backrest on the -z side)-// -----------------------------------------------------------------------------const RAIL_X = 0.238;-/** The side rail's path: along the seat edge, then sweeping up behind the back pads. */-const RAIL: Vec3[] = [[0, 0.478, 0.235], [0, 0.46, 0.13], [0, 0.455, -0.1], [0, 0.49, -0.215], [0, 0.64, -0.255], [0, 0.82, -0.285], [0, 0.975, -0.31]];-/** Back pads lean with the rail: bottom at (y 0.56, z -0.235), top at (y 0.95, z -0.3). */-const BACK_TILT = Math.atan2(0.065, 0.39);--function meetingPads(): BufferGeometry {- const pad = rounded(0.44, 0.056, 0.138, 0.026);- const pieces: Array<[BufferGeometry, Matrix4]> = [- // Three seat pads; the front one rolls down a touch, a waterfall edge for the knees.- [pad, at([0, 0.468, 0.145], [0.16, 0, 0])],- [pad, at([0, 0.472, 0.0])],- [pad, at([0, 0.47, -0.143], [-0.05, 0, 0])],- ];- const backPad = rounded(0.44, 0.1, 0.05, 0.022);- for (let i = 0; i < 4; i += 1) {- const t = (i + 0.5) / 4;- pieces.push([backPad, at([0, 0.56 + t * 0.39, -0.235 - t * 0.065 + 0.02], [BACK_TILT, 0, 0])]);- }- return smooth(merged(pieces));-}--const MEETING_METAL = merged([- ...starBase(4, 0.29, 0.1),- [new CylinderGeometry(0.024, 0.024, 0.32, 16), at([0, 0.27, 0])],- // Side rails, flattened into blades, and the spreaders that tie them together.- ...[-1, 1].map((side): [BufferGeometry, Matrix4] => [tube(RAIL, 0.02, false, 24), at([side * RAIL_X, 0, 0], [0, 0, 0], [0.55, 1, 1])]),- [new BoxGeometry(RAIL_X * 2, 0.02, 0.05), at([0, 0.44, -0.02])],- [new BoxGeometry(RAIL_X * 2, 0.03, 0.02), at([0, 0.8, -0.3], [BACK_TILT, 0, 0])],- // Arm posts rising off the rails.- ...[-1, 1].map((side): [BufferGeometry, Matrix4] => [- tube([[0, 0.46, -0.1], [0, 0.56, -0.08], [0, 0.645, -0.03]], 0.014, false, 16), at([side * (RAIL_X + 0.018), 0, 0], [0, 0, 0], [0.7, 1, 1]),- ]),-]);--const MEETING_DARK = merged([- // Backing sheet behind the pads (it shows as the seams between them) and the tilt housing.- [new BoxGeometry(0.45, 0.012, 0.44), at([0, 0.445, 0])],- [new BoxGeometry(0.45, 0.4, 0.012), at([0, 0.755, -0.281], [BACK_TILT, 0, 0])],- [rounded(0.16, 0.05, 0.18, 0.015), at([0, 0.42, -0.01])],- // Arm pads and the glides under the base.- ...[-1, 1].map((side): [BufferGeometry, Matrix4] => [rounded(0.07, 0.03, 0.27, 0.013), at([side * (RAIL_X + 0.018), 0.655, 0.02])]),- ...Array.from({ length: 4 }, (_, i): [BufferGeometry, Matrix4] => {- const a = (i * Math.PI) / 2;- return [new CylinderGeometry(0.024, 0.03, 0.05, 14), at([Math.sin(a) * 0.29, 0.025, Math.cos(a) * 0.29])];- }),-]);--const MEETING_PADS = meetingPads();--/** A soft-pad conference chair centred on its seat, facing +z (backrest on the -z side). */-export function MeetingChair() {- return (- <group>- <mesh geometry={MEETING_METAL} material={CHAIR_MAT.aluminium} castShadow receiveShadow />- <mesh geometry={MEETING_DARK} material={MAT.chair} castShadow receiveShadow />- <mesh geometry={MEETING_PADS} material={CHAIR_MAT.leather} castShadow receiveShadow />- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeDog.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeDog.tsxdeleted file mode 100644index 3c386afb9d..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeDog.tsx+++ /dev/null@@ -1,505 +0,0 @@-/**- * The lead office's dog as a living figure: a chunky black-and-tan rottweiler- * in the toy-office style with a jointed body (legs with knees, head, ears,- * tail, tongue) whose pose blends between standing, trotting, sniffing,- * sitting, lying and sleeping. Its day comes from dogLife.ts; it walks on the- * office navigation grid, and the person can pet it (E or a click).- */-import { useEffect, useMemo, useRef, useState } from "react";-import { Billboard, Html } from "@react-three/drei";-import { useFrame, type ThreeEvent } from "@react-three/fiber";-import {- CylinderGeometry, ExtrudeGeometry, MeshStandardMaterial, OctahedronGeometry, Shape, SphereGeometry, TorusGeometry,- type Group, type Mesh,-} from "three";-import { useT } from "@/i18n";-import { Rounded } from "./OfficeFurniture";-import { createRng } from "./officeBehavior";-import {- DOG_CHEW_MS, DOG_FOLLOW_FAR, DOG_FOLLOW_NEAR, DOG_PET_RANGE, DOG_PETTED_MS, DOG_POSE, DOG_RUN_SPEED, DOG_TRICK_MS,- DOG_WALK_SPEED, TREAT_JAR_RANGE, followPoint, insideRoom, nextDogStep, pickOtherBasket, useOfficeDog,- type DogActivity, type DogPose,-} from "./dogLife";-import { TreatBone } from "./dogProps";-import type { Furniture, Point, Rect, Room } from "./officeLayout";-import { findPath, randomWalkablePoint, type NavGrid } from "./officeNav";-import { stepMoverAvoiding, turnToward, type Mover } from "./officeMotion";-import { player, useOfficeStore } from "./officeStore";-import { bodiesExcept, extraBodies } from "./walkerRegistry";-import { isWalkable } from "./officeNav";--// ----------------------------------------------------------------------------// Model-// -----------------------------------------------------------------------------const C = { black: "#1d1a19", tan: "#a8612c", collar: "#7a4a2a", tongue: "#e8768a", eye: "#2a1a10", heart: "#ff5a7a" } as const;-const DM = {- black: new MeshStandardMaterial({ color: C.black, roughness: 0.75 }),- tan: new MeshStandardMaterial({ color: C.tan, roughness: 0.8 }),- collar: new MeshStandardMaterial({ color: C.collar, roughness: 0.6 }),- brass: new MeshStandardMaterial({ color: "#d8ae52", roughness: 0.3, metalness: 0.75 }),- tongue: new MeshStandardMaterial({ color: C.tongue, roughness: 0.5 }),- eye: new MeshStandardMaterial({ color: C.eye, roughness: 0.2 }),- shine: new MeshStandardMaterial({ color: "#ffffff", emissive: "#ffffff", emissiveIntensity: 0.6 }),- heart: new MeshStandardMaterial({ color: C.heart, emissive: C.heart, emissiveIntensity: 0.55, roughness: 0.4, transparent: true }),-};-const DG = {- sphere: new SphereGeometry(1, 20, 14),- cyl: new CylinderGeometry(1, 1, 1, 14),- taper: new CylinderGeometry(0.75, 1, 1, 14),- collar: new TorusGeometry(1, 0.16, 8, 28),-};--function heartGeometry(): ExtrudeGeometry {- const s = new Shape();- s.moveTo(0, -0.5);- s.bezierCurveTo(-0.1, -0.35, -0.55, -0.15, -0.5, 0.15);- s.bezierCurveTo(-0.45, 0.45, -0.1, 0.5, 0, 0.25);- s.bezierCurveTo(0.1, 0.5, 0.45, 0.45, 0.5, 0.15);- s.bezierCurveTo(0.55, -0.15, 0.1, -0.35, 0, -0.5);- const g = new ExtrudeGeometry(s, { depth: 0.18, bevelEnabled: true, bevelSize: 0.06, bevelThickness: 0.06, bevelSegments: 2 });- g.center();- return g;-}-const HEART = heartGeometry();--type Vec3 = [number, number, number];-function Ball({ r, p, m, cast = true }: { r: number | Vec3; p: Vec3; m: MeshStandardMaterial; cast?: boolean }) {- return <mesh geometry={DG.sphere} material={m} position={p} scale={r} castShadow={cast} />;-}-function Bone({ radius, length, m, y = 0, geometry = DG.cyl }: { radius: number; length: number; m: MeshStandardMaterial; y?: number; geometry?: CylinderGeometry }) {- return <mesh geometry={geometry} material={m} position={[0, y - length / 2, 0]} scale={[radius, length, radius]} castShadow />;-}--/** Joint handles the animator writes every frame. */-interface DogRig {- body: Group | null; torso: Group | null; head: Group | null; tail: Group | null; tongue: Mesh | null;- eyesOpen: Group | null; eyesShut: Group | null; mouthBone: Group | null;- legs: { hip: Group | null; knee: Group | null }[];-}--/** One leg: an upper bone from the hip, a tan lower bone and paw from the knee. */-function Leg({ at, rig, index, thigh }: { at: Vec3; rig: DogRig; index: number; thigh: number }) {- return (- <group position={at} ref={(g) => { rig.legs[index].hip = g; }}>- <Bone radius={thigh} length={0.19} m={DM.black} geometry={DG.taper} />- <group position={[0, -0.18, 0]} ref={(g) => { rig.legs[index].knee = g; }}>- <Bone radius={0.036} length={0.1} m={DM.black} />- <Bone radius={0.034} length={0.07} m={DM.tan} y={-0.09} />- <Ball r={[0.045, 0.028, 0.06]} p={[0, -0.165, 0.02]} m={DM.tan} />- </group>- </group>- );-}--/**- * The rottweiler, facing +z, paws on y = 0 when standing. `body` pivots at the- * hind hips so sitting tips the front up; legs counter-rotate to stay planted.- */-function DogModel({ rig }: { rig: DogRig }) {- return (- <group>- <group position={[0, 0.36, -0.2]} ref={(g) => { rig.body = g; }}>- <group ref={(g) => { rig.torso = g; }}>- {/* Barrel, chest and rump, with the tan chest patch. */}- <Rounded size={[0.3, 0.27, 0.56]} radius={0.12} position={[0, 0.07, 0.2]} material={DM.black} />- <Ball r={[0.16, 0.16, 0.14]} p={[0, 0.05, 0.42]} m={DM.black} />- <Ball r={[0.15, 0.14, 0.12]} p={[0, 0.07, -0.03]} m={DM.black} />- <Ball r={[0.09, 0.07, 0.03]} p={[0, 0.0, 0.54]} m={DM.tan} cast={false} />- </group>- {/* Stub tail. */}- <group position={[0, 0.14, -0.12]} ref={(g) => { rig.tail = g; }}>- <mesh geometry={DG.cyl} material={DM.black} position={[0, 0.04, -0.03]} rotation={[-0.9, 0, 0]} scale={[0.028, 0.1, 0.028]} />- </group>- {/* Neck, collar and head. */}- <Ball r={[0.11, 0.12, 0.11]} p={[0, 0.16, 0.5]} m={DM.black} />- <group position={[0, 0.15, 0.52]} rotation={[Math.PI / 2 - 0.6, 0, 0]}>- <mesh geometry={DG.collar} material={DM.collar} scale={[0.115, 0.115, 0.9]} />- <Ball r={0.018} p={[0, -0.12, -0.02]} m={DM.brass} cast={false} />- </group>- <group position={[0, 0.25, 0.6]} scale={1.25} ref={(g) => { rig.head = g; }}>- <Ball r={[0.13, 0.12, 0.14]} p={[0, 0.03, 0.02]} m={DM.black} />- {/* Muzzle: tan sides and chin, black bridge and nose. */}- <Rounded size={[0.13, 0.09, 0.13]} radius={0.04} position={[0, -0.03, 0.14]} material={DM.tan} />- <Rounded size={[0.08, 0.03, 0.12]} radius={0.012} position={[0, 0.02, 0.14]} material={DM.black} />- <Ball r={[0.035, 0.028, 0.025]} p={[0, 0.01, 0.21]} m={DM.black} />- {[-1, 1].map((s) => (- <group key={s}>- <Ball r={[0.045, 0.04, 0.035]} p={[s * 0.06, -0.04, 0.09]} m={DM.tan} cast={false} />- <Ball r={[0.022, 0.013, 0.012]} p={[s * 0.052, 0.095, 0.105]} m={DM.tan} cast={false} />- {/* Floppy triangular ears. */}- <mesh geometry={DG.sphere} material={DM.black} position={[s * 0.115, 0.07, 0.0]} rotation={[0.2, 0, s * 0.5]} scale={[0.02, 0.075, 0.055]} castShadow />- </group>- ))}- <group ref={(g) => { rig.eyesOpen = g; }}>- {[-1, 1].map((s) => (- <group key={s}>- <Ball r={0.02} p={[s * 0.05, 0.06, 0.13]} m={DM.eye} cast={false} />- <Ball r={0.006} p={[s * 0.047, 0.066, 0.148]} m={DM.shine} cast={false} />- </group>- ))}- </group>- <group ref={(g) => { rig.eyesShut = g; }} visible={false}>- {[-1, 1].map((s) => (- <mesh key={s} geometry={DG.cyl} material={DM.eye} position={[s * 0.05, 0.058, 0.135]} rotation={[0, 0, Math.PI / 2]} scale={[0.004, 0.035, 0.004]} />- ))}- </group>- <group ref={(g) => { rig.mouthBone = g; }} position={[0, -0.06, 0.2]} visible={false}><TreatBone scale={0.75} /></group>- <mesh ref={(m) => { rig.tongue = m; }} geometry={DG.sphere} material={DM.tongue} position={[0, -0.085, 0.17]} scale={[0.028, 0.008, 0.045]} visible={false} />- </group>- <Leg at={[-0.09, 0.0, 0.4]} rig={rig} index={0} thigh={0.05} />- <Leg at={[0.09, 0.0, 0.4]} rig={rig} index={1} thigh={0.05} />- <Leg at={[-0.1, 0.0, 0.0]} rig={rig} index={2} thigh={0.065} />- <Leg at={[0.1, 0.0, 0.0]} rig={rig} index={3} thigh={0.065} />- </group>- </group>- );-}--/** The dog's id among the solid bodies on the floor. */-const DOG_ID = "office-dog";--// ----------------------------------------------------------------------------// Pose blending-// -----------------------------------------------------------------------------interface Pose { pitch: number; hipY: number; front: number; frontKnee: number; hind: number; hindKnee: number; head: number }--const POSES: Record<DogPose, Pose> = {- stand: { pitch: 0, hipY: 0.36, front: 0, frontKnee: 0, hind: 0, hindKnee: 0, head: 0 },- sniff: { pitch: 0.08, hipY: 0.36, front: -0.1, frontKnee: 0.15, hind: 0, hindKnee: 0, head: 0.75 },- // Front up on straight front legs; thighs forward along the floor, hocks folded back.- sit: { pitch: -0.62, hipY: 0.14, front: 0.62, frontKnee: 0, hind: -1.05, hindKnee: 1.7, head: -0.2 },- // Sphinx: body low, forelegs stretched forward, hind legs tucked.- lie: { pitch: 0, hipY: 0.15, front: -1.45, frontKnee: 0.1, hind: -1.25, hindKnee: 1.9, head: 0.05 },- sleep: { pitch: 0, hipY: 0.14, front: -1.45, frontKnee: 0.1, hind: -1.25, hindKnee: 1.9, head: 0.55 },- // Begging: up on the hind legs, front paws tucked against the chest.- beg: { pitch: -1.2, hipY: 0.2, front: 0.5, frontKnee: -1.6, hind: -0.35, hindKnee: 1.35, head: -0.45 },-};--const damp = (from: number, to: number, k: number) => from + (to - from) * k;--// ----------------------------------------------------------------------------// The living dog-// -----------------------------------------------------------------------------export interface OfficeDogProps {- /** Every dog basket on the floor; the dog lives in the room of the one it last slept in. */- beds: Furniture[];- rooms: Room[];- /** The treat jar that hands out bones, when the floor has one. */- jar: Furniture | null;- grid: NavGrid;- awake: boolean;- reduced: boolean;-}--/** The part of a room the dog roams: its floor, a little in from the walls. */-function roamArea(room: Room): Rect {- return { minX: room.minX + 0.4, maxX: room.maxX - 0.4, minZ: room.minZ + 0.5, maxZ: room.maxZ - 0.4 };-}--export function OfficeDog({ beds, rooms, jar, grid, awake, reduced }: OfficeDogProps) {- const t = useT();- const root = useRef<Group>(null);- const spin = useRef<Group>(null);- const rig = useMemo<DogRig>(() => ({- body: null, torso: null, head: null, tail: null, tongue: null, eyesOpen: null, eyesShut: null, mouthBone: null,- legs: [0, 1, 2, 3].map(() => ({ hip: null, knee: null })),- }), []);- const rng = useMemo(() => createRng("office-dog"), []);- const roomOf = useMemo(() => (bed: Furniture) => rooms.find((r) => r.kind === bed.room) ?? null, [rooms]);- // Facing out of its corner, towards the middle of the basket's room.- const headingAt = useMemo(() => (bed: Furniture) => {- const room = roomOf(bed);- return room ? Math.atan2((room.minX + room.maxX) / 2 - bed.x, (room.minZ + room.maxZ) / 2 - bed.z) : 0;- }, [roomOf]);- const basketKey = beds.map((b) => `${b.id}:${b.x.toFixed(2)}:${b.z.toFixed(2)}`).join("|");- const first = beds[0];- const mover = useRef<Mover>({ x: first.x, z: first.z, heading: headingAt(first), path: [] });- const brain = useRef({- activity: "sleep" as DogActivity, until: Date.now() + 8000, roamsLeft: 0, basket: 0, bone: false, startedAt: 0,- lastPet: useOfficeDog.getState().petSeq, lastTreat: useOfficeDog.getState().treatSeq, repathAt: 0,- });- const pose = useRef<Pose>({ ...POSES.sleep });- const gait = useRef(0);- const [activity, setActivity] = useState<DogActivity>("sleep");- const [hearts, setHearts] = useState(0);- const [sparkles, setSparkles] = useState(0);- const near = useOfficeDog((s) => s.near);- const nearJar = useOfficeDog((s) => s.nearJar);- const hasBone = useOfficeDog((s) => s.hasBone);-- // A changed floor plan (someone joined) puts the dog back in its first basket.- useEffect(() => {- const bed = beds[0];- mover.current = { x: bed.x, z: bed.z, heading: headingAt(bed), path: [] };- Object.assign(brain.current, { activity: "sleep", basket: 0, bone: false, until: Date.now() + 8000 });- setActivity("sleep");- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [basketKey, headingAt]);- useEffect(() => () => {- useOfficeDog.getState().set({ near: false, nearJar: false, pending: null });- extraBodies.delete(DOG_ID);- }, []);- // Dev-only handle for runtime checks (hold the dog still, read where it is).- useEffect(() => {- if (!import.meta.env.DEV) return;- const w = window as unknown as Record<string, unknown>;- w.__officeDog = { get brain() { return brain.current; }, get mover() { return mover.current; } };- return () => { delete w.__officeDog; };- }, []);-- const begin = (next: DogActivity, durationMs: number) => {- const b = brain.current, m = mover.current;- // Moving house: pick another basket; the walk there is the activity.- if (next === "move") b.basket = pickOtherBasket(b.basket, beds.length, rng);- const bed = beds[b.basket] ?? beds[0];- const room = roomOf(bed);- b.activity = next;- b.until = Date.now() + durationMs;- b.startedAt = Date.now();- m.path = [];- if (reduced) {- // No walking with reduced motion: the dog stays where it is and just changes pose.- if (next === "roam" || next === "home" || next === "move") { b.activity = "sleep"; b.until = Infinity; }- } else if (next === "roam" && room) {- const target = randomWalkablePoint(grid, rng, roamArea(room));- m.path = (target && findPath(grid, m, target)) ?? [];- } else if (next === "home" || next === "move") {- m.path = findPath(grid, m, bed) ?? [];- }- setActivity(b.activity);- };-- const walkable = useMemo(() => (q: Point) => isWalkable(grid, q), [grid]);- const others = () => Array.from(bodiesExcept(DOG_ID, player));-- useFrame(({ clock }, rawDt) => {- if (!awake) return;- const dt = Math.min(rawDt, 0.1);- const now = Date.now();- const b = brain.current, m = mover.current, dog = useOfficeDog.getState();- const bed = beds[b.basket] ?? beds[0];- const room = roomOf(bed);-- // A bone beats everything; a pet wakes it and turns it to the person.- if (dog.treatSeq !== b.lastTreat) {- b.lastTreat = dog.treatSeq;- b.bone = true;- begin("trick", DOG_TRICK_MS);- setSparkles((n) => n + 1);- } else if (dog.petSeq !== b.lastPet) {- b.lastPet = dog.petSeq;- if (b.activity !== "trick") begin("petted", DOG_PETTED_MS);- setHearts((h) => h + 1);- }- const toPerson = Math.hypot(player.x - m.x, player.z - m.z);- const isNear = toPerson <= DOG_PET_RANGE;- if (isNear !== dog.near) dog.set({ near: isNear });- const atJar = !!jar && Math.hypot(player.x - jar.x, player.z - jar.z) <= TREAT_JAR_RANGE;- if (atJar !== dog.nearJar) dog.set({ nearJar: atJar });- if (dog.pending === "pet") {- if (isNear) dog.interact();- else if (player.path.length === 0) dog.set({ pending: null });- } else if (dog.pending === "jar") {- if (atJar) dog.takeBone();- else if (player.path.length === 0) dog.set({ pending: null });- }-- // Movement and the schedule.- let moved = 0;- const advance = () => {- const next = nextDogStep(b.activity, b.roamsLeft, rng, beds.length);- b.roamsLeft = next.roamsLeft;- begin(next.activity, next.durationMs);- };- if (b.activity === "follow") {- // It follows inside its own room only; when the person leaves, it goes back to bed.- if (now >= b.until || !room || !insideRoom(room, player)) begin("home", Infinity);- else {- if (toPerson > DOG_FOLLOW_FAR && now >= b.repathAt) {- b.repathAt = now + 600;- m.path = findPath(grid, m, followPoint(player, m)) ?? [];- } else if (toPerson < DOG_FOLLOW_NEAR) m.path = [];- moved = stepMoverAvoiding(m, toPerson > 4 ? DOG_RUN_SPEED : DOG_WALK_SPEED * 1.4, dt, others(), walkable).moved;- if (moved === 0) m.heading = turnToward(m.heading, Math.atan2(player.x - m.x, player.z - m.z), 6 * dt);- }- } else if (b.activity === "roam" || b.activity === "home" || b.activity === "move") {- const step = stepMoverAvoiding(m, b.activity === "move" ? DOG_WALK_SPEED * 1.2 : DOG_WALK_SPEED, dt, others(), walkable);- moved = step.moved;- if (step.arrived) {- if (b.activity !== "roam") { m.x = bed.x; m.z = bed.z; }- // Carrying the bone home: settle down and chew on it.- if (b.activity === "home" && b.bone) begin("chew", DOG_CHEW_MS);- else advance();- }- } else {- if (b.activity === "petted" || b.activity === "trick") m.heading = turnToward(m.heading, Math.atan2(player.x - m.x, player.z - m.z), 8 * dt);- if ((b.activity === "sleep" || b.activity === "chew") && m.x === bed.x && m.z === bed.z) m.heading = turnToward(m.heading, headingAt(bed), 4 * dt);- if (now >= b.until) {- if (b.activity === "chew") b.bone = false;- advance();- }- }-- // A solid body for everyone else: nobody walks through the dog.- extraBodies.set(DOG_ID, { x: m.x, z: m.z });-- // Place the figure; it lies a little higher on the basket's cushion.- const inBed = beds.some((d) => Math.hypot(m.x - d.x, m.z - d.z) < 0.05);- const trickT = b.activity === "trick" ? (now - b.startedAt) / 1000 : -1;- // The trick: beg (0–0.9 s), catch, then two spins in the air (0.9–2.7 s), land and sit proud.- const spinning = trickT >= 0.9 && trickT < 2.7 && !reduced;- const hop = spinning ? Math.abs(Math.sin(((trickT - 0.9) / 0.9) * Math.PI)) * 0.35 : 0;- if (root.current) {- root.current.position.set(m.x, (inBed ? 0.1 : 0) + hop, m.z);- root.current.rotation.y = m.heading;- }- if (spin.current) spin.current.rotation.y = spinning ? ((trickT - 0.9) / 1.8) * Math.PI * 4 : 0;-- // Blend the pose, then layer the gait, breathing, wag and head life on top.- const walking = moved > 1e-4;- const trickPose: DogPose = trickT < 0 ? DOG_POSE[b.activity] : trickT < 0.9 ? "beg" : spinning ? "stand" : "sit";- const target = POSES[walking ? "stand" : trickPose];- const k = 1 - Math.exp(-(spinning ? 14 : 8) * dt), p = pose.current;- (Object.keys(p) as (keyof Pose)[]).forEach((key) => { p[key] = damp(p[key], target[key], k); });- const speed = moved / Math.max(dt, 1e-3);- gait.current += dt * (walking ? 5 + speed * 3.2 : 0);- const swing = walking ? Math.sin(gait.current) * Math.min(0.6, 0.25 + speed * 0.12) : spinning ? -0.5 : 0;- const time = clock.elapsedTime;- const sleeping = b.activity === "sleep";- const chewing = b.activity === "chew";- const happy = b.activity === "petted" || b.activity === "follow" || b.activity === "trick" || chewing;-- if (rig.body) {- rig.body.position.y = p.hipY + (walking ? Math.abs(Math.sin(gait.current)) * 0.02 : 0);- rig.body.rotation.x = p.pitch;- }- if (rig.torso) {- const breath = 1 + Math.sin(time * (sleeping ? 1.4 : 2.6)) * (sleeping ? 0.03 : 0.012);- rig.torso.scale.set(breath, breath, 1);- }- // Diagonal pairs swing together: front-left with hind-right. Mid-spin all legs tuck.- const phase = spinning ? [swing, swing, -swing, -swing] : [swing, -swing, -swing, swing];- rig.legs.forEach((leg, i) => {- const front = i < 2;- if (leg.hip) leg.hip.rotation.x = (front ? p.front : p.hind) + phase[i];- if (leg.knee) leg.knee.rotation.x = (front ? p.frontKnee : p.hindKnee) + (walking ? Math.max(0, -phase[i]) * (front ? -0.6 : 0.9) : 0);- });- if (rig.head) {- const sniffBob = b.activity === "sniff" ? Math.sin(time * 9) * 0.08 : 0;- const chew = chewing ? Math.sin(time * 7) * 0.08 : 0;- rig.head.rotation.x = p.head + sniffBob + chew + (sleeping ? Math.sin(time * 1.4) * 0.02 : 0);- const look = happy && !walking && !chewing ? Math.sin(time * 1.3) * 0.25 : b.activity === "sniff" ? Math.sin(time * 1.7) * 0.4 : 0;- rig.head.rotation.y = damp(rig.head.rotation.y, look, k);- rig.head.rotation.z = damp(rig.head.rotation.z, b.activity === "petted" || chewing ? 0.22 : 0, k);- }- if (rig.tail) rig.tail.rotation.y = Math.sin(time * (happy ? 22 : 6)) * (sleeping ? 0.05 : happy ? 0.7 : walking ? 0.35 : 0.15);- // The bone sits in its mouth from the catch until the chewing is done.- const holding = b.bone && (trickT < 0 || trickT >= 0.7);- if (rig.mouthBone) rig.mouthBone.visible = holding;- if (rig.tongue) rig.tongue.visible = !holding && (happy || (walking && speed > 2) || b.activity === "sit");- if (rig.eyesOpen) rig.eyesOpen.visible = !sleeping;- if (rig.eyesShut) rig.eyesShut.visible = sleeping;- });-- const onClick = (event: ThreeEvent<MouseEvent>) => {- if (event.delta > 6) return;- event.stopPropagation();- const dog = useOfficeDog.getState();- if (dog.near) { dog.interact(); return; }- dog.set({ pending: "pet" });- const m = mover.current;- const dx = player.x - m.x, dz = player.z - m.z, d = Math.hypot(dx, dz) || 1;- useOfficeStore.getState().requestWalk({ x: m.x + (dx / d) * 0.95, z: m.z + (dz / d) * 0.95 });- };- const onJarClick = (event: ThreeEvent<MouseEvent>) => {- if (event.delta > 6 || !jar) return;- event.stopPropagation();- const dog = useOfficeDog.getState();- if (dog.hasBone) return;- if (dog.nearJar) { dog.takeBone(); return; }- dog.set({ pending: "jar" });- // The jar faces +z (turned by its rotation): stand in front of it.- useOfficeStore.getState().requestWalk({ x: jar.x + Math.sin(jar.rotationY) * 0.8, z: jar.z + Math.cos(jar.rotationY) * 0.8 });- };- const hover = (cursor: string) => () => { document.body.style.cursor = cursor; };- const busy = activity === "petted" || activity === "trick";-- return (- <>- <group ref={root} name="office-dog">- <group ref={spin}><DogModel rig={rig} /></group>- {/* Generous invisible hit box: the dog is small from the usual camera distance. */}- <mesh position={[0, 0.35, 0.1]} visible={false} onClick={onClick} onPointerOver={hover("pointer")} onPointerOut={hover("")}>- <boxGeometry args={[0.6, 0.7, 1.1]} />- </mesh>- {hearts > 0 && <Burst key={`h${hearts}`} kind="heart" animate={!reduced} />}- {sparkles > 0 && <Burst key={`s${sparkles}`} kind="spark" animate={!reduced} />}- {near && !busy && (- <Html center position={[0, 1.0, 0]} zIndexRange={[24, 0]}>- <span className="office-plate office-seat-prompt" data-office-ui>- <kbd>E</kbd>{t(hasBone ? "society.office.dog_treat" : "society.office.dog_pet")}- </span>- </Html>- )}- </group>- {jar && (- <group position={[jar.x, 0, jar.z]}>- <mesh position={[0, 0.6, 0]} visible={false} onClick={onJarClick} onPointerOver={hover("pointer")} onPointerOut={hover("")}>- <boxGeometry args={[0.6, 1.2, 0.6]} />- </mesh>- {nearJar && !hasBone && (- <Html center position={[0, 1.55, 0]} zIndexRange={[24, 0]}>- <span className="office-plate office-seat-prompt" data-office-ui><kbd>E</kbd>{t("society.office.dog_take_bone")}</span>- </Html>- )}- </group>- )}- </>- );-}--const SPARK = new OctahedronGeometry(1, 0);-const SPARK_MAT = new MeshStandardMaterial({ color: "#ffd44d", emissive: "#ffb300", emissiveIntensity: 1.2, roughness: 0.3, transparent: true });--/** Hearts float up from the dog's head (petting); gold sparks burst around it (the treat trick). */-function Burst({ kind, animate }: { kind: "heart" | "spark"; animate: boolean }) {- const group = useRef<Group>(null);- const start = useRef(-1);- const material = useMemo(() => (kind === "heart" ? DM.heart : SPARK_MAT).clone(), [kind]);- useEffect(() => () => material.dispose(), [material]);- const count = kind === "heart" ? 3 : 12;- const life = kind === "heart" ? 3.2 : 2.6;- useFrame(({ clock }) => {- if (start.current < 0) start.current = clock.elapsedTime;- const age = clock.elapsedTime - start.current;- const g = group.current;- if (!g) return;- g.children.forEach((child, i) => {- if (kind === "heart") {- const a = Math.max(0, age - i * 0.35);- child.position.set(Math.sin(a * 3 + i * 2) * 0.12 + (i - 1) * 0.12, 0.75 + (animate ? a * 0.45 : 0.1 * i), 0.25);- child.scale.setScalar(a > 0 ? Math.min(1, a * 4) * 0.09 : 0);- } else {- // Sparks fly out in a ring from mid-trick and drift down.- const a = Math.max(0, age - 0.9);- const angle = (i / count) * Math.PI * 2;- const r = animate ? 0.2 + a * 0.9 : 0.5;- child.position.set(Math.cos(angle) * r, 0.55 + (animate ? a * 0.6 - a * a * 0.35 : 0.2), Math.sin(angle) * r);- child.rotation.set(age * 4, age * 3, 0);- child.scale.setScalar(a > 0 ? 0.035 * Math.min(1, a * 5) : 0);- }- });- material.opacity = Math.max(0, 1 - Math.max(0, age - (life - 1.2)) / 1.2);- g.visible = age < life;- });- return (- <group ref={group}>- {Array.from({ length: count }, (_, i) => (kind === "heart"- ? <Billboard key={i}><mesh geometry={HEART} material={material} /></Billboard>- : <mesh key={i} geometry={SPARK} material={material} />))}- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeFrameDriver.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeFrameDriver.tsxdeleted file mode 100644index 8f11f8a207..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeFrameDriver.tsx+++ /dev/null@@ -1,18 +0,0 @@-import { useEffect } from "react";-import { useThree } from "@react-three/fiber";-import { startOfficeFrameBudget } from "./officeFrameBudget";--/** The narrow IDE companion animates at 30 fps; the full view stays unrestricted. */-export function OfficeFrameDriver({ enabled }: { enabled: boolean }) {- const invalidate = useThree((state) => state.invalidate);- // Dev-only handle for runtime checks of the draw-call and memory budget (renderer.info).- const gl = useThree((state) => state.gl);- useEffect(() => {- if (import.meta.env.DEV && typeof window !== "undefined") Object.assign(window, { __officeGl: gl });- }, [gl]);- useEffect(() => {- if (!enabled) return;- return startOfficeFrameBudget(invalidate, 30);- }, [enabled, invalidate]);- return null;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeFullMap.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeFullMap.tsxdeleted file mode 100644index adbb30f71a..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeFullMap.tsx+++ /dev/null@@ -1,356 +0,0 @@-/**- * The full office map, game style: "M" (or the minimap's Map button) opens a- * dialog over most of the stage with the whole floor fitted north-up, a light- * lettered grid (columns A–H, rows 1–N), room and checkpoint names, every- * agent with its name, and the person's arrow. A click anywhere sets a- * waypoint (the character walks there) and closes the map; Escape or M closes.- *- * The painted floor, grid and labels are drawn once per size/layout/theme into- * an offscreen canvas; the agents and the arrow repaint at ≤ 20 Hz while open.- * The chrome (header, grid letters, readout) uses theme tokens.- */-import { useCallback, useEffect, useId, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent, type PointerEvent as ReactPointerEvent } from "react";-import { X } from "lucide-react";-import { useReducedMotion } from "framer-motion";-import { useT } from "@/i18n";-import type { CampusZoneKind, CheckpointKind, OfficeLayout, Rect, RoomKind } from "./officeLayout";-import { cameraView, player, useOfficeStore } from "./officeStore";-import { agentPositions } from "./walkerRegistry";-import { ownsKeyboard } from "./OfficePlayer";-import {- MAP_PAINT, clampToRect, columnLabel, drawAgentToken, drawCheckpointBadge, drawFloorArt, drawMapLabel, drawPlayerArrow,- drawViewCone, fitSheet, fitTransform, gridLabel, mapGrid, mapToWorld, placeAt, worldToMap, type AgentToken, type MapPoint, type MapTransform,-} from "./minimap";-import {- agentColour, context2d, offscreenLayer, useElementSize, usePixelRatio, useThemeVersion, useThrottledFrames, type OfficeMapAgent,-} from "./mapHooks";-import { courierSession } from "./courierStore";-import { boundsWithPad } from "./skyPad";--export interface OfficeFullMapProps {- open: boolean;- onOpen: () => void;- onClose: () => void;- layout: OfficeLayout;- agents: ReadonlyMap<string, OfficeMapAgent>;- selectedId: string | null;-}--const FRAME_MS = 50;-/** Room around the grid for the column letters and row numbers (CSS px). */-const GRID_PAD = 30;-const GRID_COLUMNS = 8;--function typingIn(target: EventTarget | null): boolean {- if (!(target instanceof HTMLElement)) return false;- const tag = target.tagName;- return target.isContentEditable || tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT";-}--/** M toggles the map; Escape closes it before the office (or the view behind it) sees the key. */-function useMapKeys(open: boolean, onOpen: () => void, onClose: () => void): void {- const live = useRef({ open, onOpen, onClose });- live.current = { open, onOpen, onClose };- useEffect(() => {- const onKey = (event: KeyboardEvent) => {- if (event.ctrlKey || event.metaKey || event.altKey) return;- const { open: isOpen, onOpen: show, onClose: hide } = live.current;- if (isOpen) {- if (event.key === "Escape" || (event.code === "KeyM" && !typingIn(event.target))) {- event.preventDefault();- event.stopPropagation();- hide();- }- return;- }- // The full map stays shut while the courier flies.- if (event.code !== "KeyM" || event.repeat || ownsKeyboard(event.target) || courierSession.flying) return;- event.preventDefault();- show();- };- // Window capture runs before the office's and the workspace's document listeners.- window.addEventListener("keydown", onKey, true);- return () => window.removeEventListener("keydown", onKey, true);- }, []);-}--export function OfficeFullMap({ open, onOpen, onClose, layout, agents, selectedId }: OfficeFullMapProps) {- useMapKeys(open, onOpen, onClose);- if (!open) return null;- return <FullMapDialog onClose={onClose} layout={layout} agents={agents} selectedId={selectedId} />;-}--interface Readout { cell: string; place: string }--function FullMapDialog({ onClose, layout, agents, selectedId }: Omit<OfficeFullMapProps, "open" | "onOpen">) {- const t = useT();- const reduced = useReducedMotion() ?? false;- const titleId = useId();- const hintId = useId();- const backdropRef = useRef<HTMLDivElement>(null);- const headRef = useRef<HTMLElement>(null);- const dialogRef = useRef<HTMLDivElement>(null);- const closeRef = useRef<HTMLButtonElement>(null);- const bodyRef = useRef<HTMLDivElement>(null);- const canvasRef = useRef<HTMLCanvasElement>(null);- const layerRef = useRef<HTMLCanvasElement | null>(null);- const [readout, setReadout] = useState<Readout | null>(null);- const size = useElementSize(bodyRef);- const dpr = usePixelRatio();- const themeVersion = useThemeVersion();-- // The sheet reaches out over the sky pad too, so the courier is on the map.- const grid = useMemo(() => mapGrid(boundsWithPad(layout.bounds, layout.skyPad), GRID_COLUMNS), [layout]);- const gridRect = useMemo<Rect>(() => ({- minX: grid.originX, maxX: grid.originX + grid.columns * grid.cell, minZ: grid.originZ, maxZ: grid.originZ + grid.rows * grid.cell,- }), [grid]);- // The sheet takes the plan's shape: a floor that is nearly square or taller than wide leaves no empty band beside it.- const outer = useElementSize(backdropRef);- const head = useElementSize(headRef);- const sheet = useMemo(() => {- // The backdrop pads 3 % of its width on every side.- const inset = outer.width * 0.03;- const availW = outer.width - inset * 2, availH = outer.height - inset * 2;- return availW > 200 && availH > 200 ? fitSheet(gridRect, availW, availH, GRID_PAD, head.height || 46) : null;- }, [outer, head.height, gridRect]);- const transform = useMemo<MapTransform | null>(- () => (size.width > GRID_PAD * 2 && size.height > GRID_PAD * 2 ? fitTransform(gridRect, size.width, size.height, GRID_PAD) : null),- [gridRect, size],- );-- const checkpointLabels: Record<CheckpointKind, string> = {- spawn: t("society.office.cp_spawn"),- launch: t("society.office.cp_launch"),- create: t("society.office.cp_create"),- manage: t("society.office.cp_manage"),- team: t("society.office.cp_team"),- wardrobe: t("society.office.cp_wardrobe"),- lead: t("society.office.cp_lead"),- break: t("society.office.cp_break"),- elevator: t("society.office.cp_elevator"),- mission: t("society.office.cp_mission"),- studio: t("society.office.cp_studio"),- levels: t("society.office.cp_levels"),- ship: t("society.office.cp_ship"),- };- const roomLabels: Record<RoomKind, string> = {- lead: t("society.office.room_lead"),- team: t("society.office.room_team"),- wardrobe: t("society.office.room_wardrobe"),- reception: t("society.office.room_reception"),- break: t("society.office.room_break"),- command: t("society.office.room_command"),- server: t("society.office.room_server"),- arcade: t("society.office.room_arcade"),- classics: t("society.office.room_classics"),- puzzle: t("society.office.room_puzzle"),- action: t("society.office.room_action"),- foyer: t("society.office.room_foyer"),- prizes: t("society.office.room_prizes"),- snack: t("society.office.room_snack"),- levels: t("society.office.room_levels"),- };- // Agents floor: the campus between the studios. The pool studio has no team name; the map gives it one.- const zoneLabels: Record<CampusZoneKind, string> = {- boulevard: t("society.office.zone_boulevard"),- plaza: t("society.office.zone_boulevard"),- atrium: t("society.office.zone_atrium"),- plot: t("society.office.zone_plot"),- garden: t("society.office.zone_garden"),- booths: t("society.office.zone_booths"),- library: t("society.office.zone_library"),- cafe: t("society.office.zone_cafe"),- };- const openSpace = t(layout.variant === "agents" ? "society.office.studio_pool" : "society.office.open_space");- const youLabel = t("society.office.minimap_you");- const labelKey = JSON.stringify([checkpointLabels, roomLabels, zoneLabels, openSpace]);- const labels = useRef({ checkpointLabels, roomLabels, zoneLabels, openSpace, youLabel });- labels.current = { checkpointLabels, roomLabels, zoneLabels, openSpace, youLabel };-- // Focus moves into the dialog and returns to where it was on close.- useEffect(() => {- const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null;- closeRef.current?.focus();- return () => { if (previous && previous.isConnected) previous.focus(); };- }, []);-- const live = useRef({ agents, selectedId, transform, reduced });- live.current = { agents, selectedId, transform, reduced };-- const draw = useCallback((now: number) => {- const canvas = canvasRef.current;- const ctx = context2d(canvas);- const { agents: roster, selectedId: sel, transform: tr, reduced: still } = live.current;- if (!canvas || !ctx || !tr) return;- const ratio = canvas.width / tr.width;- ctx.setTransform(ratio, 0, 0, ratio, 0, 0);- ctx.globalAlpha = 1;- ctx.fillStyle = MAP_PAINT.space;- ctx.fillRect(0, 0, tr.width, tr.height);- if (layerRef.current) ctx.drawImage(layerRef.current, 0, 0, tr.width, tr.height);-- const me = worldToMap(tr, player);- if (cameraView.ready) drawViewCone(ctx, me, cameraView.yaw, cameraView.halfWidth, Math.max(40, tr.scale * 9));- const radius = Math.max(6, Math.min(9, tr.scale * 0.5));- const pulse = still ? null : (now % 1400) / 1400;- let selected: AgentToken | null = null;- const tokens: AgentToken[] = [];- for (const agent of roster.values()) {- const pos = agentPositions.get(agent.agentId);- if (!pos) continue;- const token: AgentToken = {- id: agent.agentId, name: agent.name, state: agent.state, colour: agentColour(agent), selected: agent.agentId === sel,- ...worldToMap(tr, pos),- };- if (token.selected) selected = token; else tokens.push(token);- }- if (selected) tokens.push(selected);- for (const token of tokens) {- drawAgentToken(ctx, token, radius, token.selected ? pulse : null);- drawMapLabel(ctx, token.name, token.x, token.y + radius * (token.selected ? 1.3 : 1) + 11, 10, 700);- }- drawPlayerArrow(ctx, me.x, me.y, player.heading, 11);- drawMapLabel(ctx, labels.current.youLabel, me.x, me.y + 18, 10, 800);- }, []);-- // Static layer: painted floor, grid, room/department names and checkpoints.- useEffect(() => {- const canvas = canvasRef.current;- if (!canvas || !transform) return;- canvas.width = Math.round(transform.width * dpr);- canvas.height = Math.round(transform.height * dpr);- const off = offscreenLayer(transform.width, transform.height, dpr);- if (!off) {- layerRef.current = null;- return;- }- const ctx = off.ctx;- const nw = mapToWorld(transform, { x: 0, y: 0 });- const se = mapToWorld(transform, { x: transform.width, y: transform.height });- drawFloorArt(ctx, layout, transform, { minX: nw.x, maxX: se.x, minZ: nw.z, maxZ: se.z });-- // The lettered grid: light lines over the painting, like a game's big map.- const g0 = worldToMap(transform, { x: gridRect.minX, z: gridRect.minZ });- const g1 = worldToMap(transform, { x: gridRect.maxX, z: gridRect.maxZ });- ctx.strokeStyle = "rgba(255,255,255,0.38)";- ctx.lineWidth = 1;- ctx.beginPath();- for (let c = 0; c <= grid.columns; c += 1) {- const x = Math.round(g0.x + c * grid.cell * transform.scale) + 0.5;- ctx.moveTo(x, g0.y);- ctx.lineTo(x, g1.y);- }- for (let r = 0; r <= grid.rows; r += 1) {- const y = Math.round(g0.y + r * grid.cell * transform.scale) + 0.5;- ctx.moveTo(g0.x, y);- ctx.lineTo(g1.x, y);- }- ctx.stroke();-- const { roomLabels: rooms, checkpointLabels: cps, zoneLabels: zoneNames, openSpace: spare } = labels.current;- const roomPx = Math.max(11, Math.min(15, transform.scale * 0.75));- // The campus's own places, quieter than rooms and studios; the streets need no name.- for (const zone of layout.zones ?? []) {- if (zone.kind === "boulevard" || zone.kind === "plaza") continue;- // Along the zone's south edge: its seats and tables stay readable, and the atrium's name sits under the spawn point.- const c = worldToMap(transform, { x: (zone.minX + zone.maxX) / 2, z: zone.maxZ - 0.9 });- drawMapLabel(ctx, zoneNames[zone.kind], c.x, c.y, roomPx * 0.8, 700, (zone.maxX - zone.minX - 0.6) * transform.scale);- }- for (const room of layout.rooms) {- const c = worldToMap(transform, { x: (room.minX + room.maxX) / 2, z: room.minZ + 1.1 });- drawMapLabel(ctx, rooms[room.kind].toLocaleUpperCase(), c.x, c.y, roomPx, 800);- }- // A studio's name stands on the street behind its name wall, clear of everyone working inside, and never- // wider than the studio itself.- for (const dept of layout.departments) {- const c = worldToMap(transform, { x: (dept.minX + dept.maxX) / 2, z: dept.minZ - 1.0 });- drawMapLabel(ctx, (dept.label || spare).toLocaleUpperCase(), c.x, c.y, roomPx * 0.85, 800, (dept.maxX - dept.minX - 0.6) * transform.scale);- }- const badge = Math.max(14, Math.min(22, transform.scale * 1.1));- for (const cp of layout.checkpoints) {- const m = worldToMap(transform, cp);- drawCheckpointBadge(ctx, m.x, m.y, badge, cp.id);- drawMapLabel(ctx, cps[cp.id], m.x, m.y - badge / 2 - 8, 10, 700);- }- layerRef.current = off.canvas;- draw(performance.now());- // labelKey stands in for the translated names (read through a ref), which are new objects every render.- }, [layout, transform, grid, gridRect, dpr, themeVersion, labelKey, draw]);-- useThrottledFrames(draw, FRAME_MS, transform !== null);-- const mapPoint = (event: { clientX: number; clientY: number }): MapPoint | null => {- const canvas = canvasRef.current;- if (!canvas || !transform) return null;- const rect = canvas.getBoundingClientRect();- if (rect.width <= 0 || rect.height <= 0) return null;- return { x: ((event.clientX - rect.left) / rect.width) * transform.width, y: ((event.clientY - rect.top) / rect.height) * transform.height };- };-- const onClick = (event: ReactMouseEvent<HTMLCanvasElement>) => {- const at = mapPoint(event);- if (!at || !transform) return;- useOfficeStore.getState().requestWalk(clampToRect(mapToWorld(transform, at), layout.floor));- onClose();- };-- const onPointerMove = (event: ReactPointerEvent<HTMLCanvasElement>) => {- const at = mapPoint(event);- if (!at || !transform) return;- const world = mapToWorld(transform, at);- const place = placeAt(layout, world);- const name = place?.kind === "checkpoint" ? checkpointLabels[place.id]- : place?.kind === "room" ? roomLabels[place.id]- : place?.kind === "department" ? place.label || openSpace- : place?.kind === "zone" ? zoneLabels[place.id] : "";- const next = { cell: gridLabel(grid, world), place: name };- setReadout((prev) => (prev && prev.cell === next.cell && prev.place === next.place ? prev : next));- };-- // Tab stays inside the dialog: the close button is its only control.- const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {- if (event.key !== "Tab") return;- event.preventDefault();- closeRef.current?.focus();- };-- const g0 = transform ? worldToMap(transform, { x: gridRect.minX, z: gridRect.minZ }) : null;- const cellPx = transform ? grid.cell * transform.scale : 0;-- return (- <div ref={backdropRef} className="office-fullmap-backdrop" data-office-ui onMouseDown={(event) => { if (event.target === event.currentTarget) onClose(); }}>- <div ref={dialogRef} className="office-card office-fullmap" role="dialog" aria-modal="true" data-state="open"- aria-labelledby={titleId} aria-describedby={hintId} onKeyDown={onKeyDown}- style={sheet ? { width: sheet.width, height: sheet.height } : undefined}>- <header ref={headRef} className="office-fullmap-head">- <div className="office-fullmap-heading">- <h2 id={titleId}>{t("society.office.map_title")}</h2>- <span id={hintId}>{t("society.office.map_hint")}</span>- </div>- <span className="office-fullmap-readout" aria-live="off">- {readout ? (readout.place ? `${readout.cell} · ${readout.place}` : readout.cell) : ""}- </span>- <button ref={closeRef} type="button" className="office-icon-button office-fullmap-close" onClick={onClose}- aria-label={t("society.office.map_close")} title={t("society.office.map_close")} aria-keyshortcuts="Escape M">- <X aria-hidden size={16} />- </button>- </header>- <div ref={bodyRef} className="office-fullmap-body">- <canvas ref={canvasRef} className="office-fullmap-canvas" aria-label={t("society.office.map_aria")} role="img"- style={transform ? { width: transform.width, height: transform.height } : undefined}- onClick={onClick} onPointerMove={onPointerMove} onPointerLeave={() => setReadout(null)} />- {g0 && Array.from({ length: grid.columns }, (_, c) => (- <span key={`c${c}`} className="office-fullmap-axis" aria-hidden style={{ left: g0.x + (c + 0.5) * cellPx, top: g0.y - 14 }}>- {columnLabel(c)}- </span>- ))}- {g0 && Array.from({ length: grid.rows }, (_, r) => (- <span key={`r${r}`} className="office-fullmap-axis" aria-hidden style={{ left: g0.x - 14, top: g0.y + (r + 0.5) * cellPx }}>- {r + 1}- </span>- ))}- </div>- </div>- </div>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeFurniture.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeFurniture.tsxdeleted file mode 100644index 6d1345d41b..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeFurniture.tsx+++ /dev/null@@ -1,295 +0,0 @@-/**- * The office kit: every piece is a few rounded primitives with flat, matte- * colours in a contemporary-workplace palette — light oak on black steel,- * felt, ceramic planters and lots of green. It needs no authored meshes; the- * few surface patterns (felt fluting, sign faces) are canvas textures.- * Geometries and materials are module-level singletons shared by every copy.- */-import { useMemo } from "react";-import {- BoxGeometry, CylinderGeometry, DoubleSide, IcosahedronGeometry, OctahedronGeometry, MeshStandardMaterial, RepeatWrapping, type Texture,-} from "three";-import { RoundedBoxGeometry } from "three-stdlib";-import { cachedCanvasTexture } from "./canvasMaterials";-import { DEPARTMENT_ZONES, OFFICE } from "./officePalette";-import { screenTexture, type ScreenFace } from "./screenTextures";--export const matte = (color: string, extra: Partial<ConstructorParameters<typeof MeshStandardMaterial>[0]> = {}) =>- new MeshStandardMaterial({ color, roughness: 0.85, metalness: 0, ...extra });--export const MAT = {- deskTop: matte(OFFICE.deskTop, { roughness: 0.6 }),- deskEdge: matte(OFFICE.deskEdge, { roughness: 0.6 }),- deskBody: matte(OFFICE.deskBody),- deskLeg: matte(OFFICE.deskLeg, { roughness: 0.45, metalness: 0.35 }),- chair: matte(OFFICE.chair, { roughness: 0.5, metalness: 0.2 }),- chairSeat: matte(OFFICE.chairSeat),- chairMesh: matte(OFFICE.chairMesh, { roughness: 0.95 }),- /** White base for parts tinted per instance (seat fabric, desk screens): the instance colour is the colour. */- tinted: matte("#ffffff", { roughness: 0.95 }),- monitor: matte(OFFICE.monitor, { roughness: 0.35, metalness: 0.2 }),- monitorArm: matte(OFFICE.monitorArm, { roughness: 0.3, metalness: 0.6 }),- keyboard: matte(OFFICE.keyboard, { roughness: 0.5 }),- mug: matte(OFFICE.mug, { roughness: 0.35 }),- steel: matte(OFFICE.steel, { roughness: 0.45, metalness: 0.35 }),- railing: matte(OFFICE.railing, { roughness: 0.4, metalness: 0.3 }),- glass: new MeshStandardMaterial({ color: OFFICE.glass, transparent: true, opacity: 0.14, roughness: 0.05, side: DoubleSide, depthWrite: false }),- wall: matte(OFFICE.wallWhite),- sign: matte(OFFICE.signBoard, { roughness: 0.6 }),- wood: matte(OFFICE.wood, { roughness: 0.65 }),- woodDark: matte(OFFICE.woodDark, { roughness: 0.65 }),- couch: matte(OFFICE.couch, { roughness: 1 }),- cushion: matte(OFFICE.couchCushion, { roughness: 1 }),- couchAccents: OFFICE.couchAccent.map((c) => matte(c, { roughness: 1 })),- pot: matte(OFFICE.plantPot, { roughness: 0.7 }),- planterLight: matte(OFFICE.planterLight, { roughness: 0.7 }),- soil: matte("#3b2f26"),- leaf: matte(OFFICE.leaf, { flatShading: true }),- leafDark: matte(OFFICE.leafDark, { flatShading: true }),- leafLight: matte(OFFICE.leafLight, { flatShading: true }),- trunk: matte(OFFICE.trunk),- rug: matte(OFFICE.rug, { roughness: 1 }),- books: OFFICE.book.map((c) => matte(c)),-};--export const GEO = {- box: new BoxGeometry(1, 1, 1),- cyl: new CylinderGeometry(1, 1, 1, 16),- potCyl: new CylinderGeometry(1, 0.8, 1, 16),- // One subdivision: foliage reads as soft clusters rather than faceted low-poly rocks.- blob: new IcosahedronGeometry(1, 1),- // Twenty faces: for foliage that is flat-shaded anyway, and for anything drawn by the hundred.- facet: new IcosahedronGeometry(1, 0),- // A blade of grass: a slim four-sided spindle, eight faces.- blade: new OctahedronGeometry(1, 0),-};--export function Box({ size, position, material, cast = true }: {- size: [number, number, number]; position: [number, number, number]; material: MeshStandardMaterial; cast?: boolean;-}) {- return <mesh geometry={GEO.box} material={material} position={position} scale={size} castShadow={cast} receiveShadow />;-}--/**- * Rounded boxes are cached by size: every desk shares the same few geometries. One bevel segment: the corners are- * a few centimetres at most, and a second segment tripled the triangles of every piece of furniture on the floor.- */-const roundedCache = new Map<string, RoundedBoxGeometry>();-export function Rounded({ size, radius, position, material, cast = true }: {- size: [number, number, number]; radius: number; position: [number, number, number]; material: MeshStandardMaterial; cast?: boolean;-}) {- const key = `${size.join("x")}:${radius}`;- let geometry = roundedCache.get(key);- if (!geometry) {- geometry = new RoundedBoxGeometry(size[0], size[1], size[2], 1, radius);- roundedCache.set(key, geometry);- }- return <mesh geometry={geometry} material={material} position={position} castShadow={cast} receiveShadow />;-}--const screenMaterials = new Map<ScreenFace, MeshStandardMaterial>();-export function screenMaterial(face: ScreenFace): MeshStandardMaterial {- let material = screenMaterials.get(face);- if (!material) {- const map = screenTexture(face);- const lit = face !== "empty" && face !== "paused";- material = new MeshStandardMaterial({- color: "#ffffff", map, roughness: 0.4,- emissive: lit ? "#ffffff" : "#000000", emissiveMap: lit ? map : null, emissiveIntensity: lit ? 0.9 : 0,- });- screenMaterials.set(face, material);- }- return material;-}--/**- * A potted plant; `size` scales the whole plant (1 ≈ 1.45 m tall): a tall- * charcoal planter under a full, leafy crown.- */-export function Plant({ position, size = 1 }: { position: [number, number, number]; size?: number }) {- return (- <group position={position} scale={size}>- <mesh geometry={GEO.cyl} material={MAT.pot} position={[0, 0.25, 0]} scale={[0.21, 0.5, 0.21]} castShadow receiveShadow />- <mesh geometry={GEO.cyl} material={MAT.soil} position={[0, 0.501, 0]} scale={[0.19, 0.01, 0.19]} />- <mesh geometry={GEO.cyl} material={MAT.trunk} position={[0, 0.64, 0]} scale={[0.025, 0.3, 0.025]} castShadow />- <mesh geometry={GEO.blob} material={MAT.leaf} position={[0, 1.0, 0]} scale={[0.33, 0.3, 0.33]} castShadow />- <mesh geometry={GEO.blob} material={MAT.leafDark} position={[0.15, 0.86, 0.1]} scale={0.19} castShadow />- <mesh geometry={GEO.blob} material={MAT.leafLight} position={[-0.15, 0.92, -0.08]} scale={0.19} castShadow />- <mesh geometry={GEO.blob} material={MAT.leafDark} position={[-0.06, 0.8, 0.16]} scale={0.17} castShadow />- <mesh geometry={GEO.blob} material={MAT.leaf} position={[0.1, 1.12, -0.14]} scale={0.18} castShadow />- <mesh geometry={GEO.blob} material={MAT.leafLight} position={[0.04, 1.28, 0.04]} scale={[0.2, 0.15, 0.2]} castShadow />- <mesh geometry={GEO.blob} material={MAT.leafDark} position={[-0.13, 1.16, 0.1]} scale={0.15} castShadow />- </group>- );-}--/** Open shelving: black steel uprights, light-oak boards, books, a plant and a few ceramics. */-export function Bookshelf({ position, rotationY = 0 }: { position: [number, number, number]; rotationY?: number }) {- const books = useMemo(() => Array.from({ length: 13 }, (_, i) => {- const shelf = i < 6 ? 0 : i < 10 ? 1 : 2;- const inShelf = shelf === 0 ? i : shelf === 1 ? i - 6 : i - 10;- const start = shelf === 0 ? -0.8 : shelf === 1 ? 0.12 : -0.78;- return {- x: start + inShelf * 0.1,- y: [0.05, 0.5, 0.95][shelf],- h: 0.26 + ((i * 7) % 4) * 0.03,- m: MAT.books[(i * 3) % MAT.books.length],- };- }), []);- return (- <group position={position} rotation={[0, rotationY, 0]}>- {/* Boards are shallower than the uprights and the top board sits below their tops:- coplanar faces where steel meets oak would z-fight and flicker as the camera moves. */}- {[-0.88, 0, 0.88].map((x) => <Box key={x} size={[0.03, 1.4, 0.34]} position={[x, 0.7, 0]} material={MAT.steel} />)}- {[0.035, 0.485, 0.935, 1.37].map((y) => <Box key={y} size={[1.8, 0.03, 0.32]} position={[0, y, 0]} material={MAT.wood} />)}- {books.map((b, i) => <Box key={i} size={[0.07, b.h, 0.24]} position={[b.x, b.y + b.h / 2, 0]} material={b.m} />)}- {/* A small planter, two ceramic vases and a trailing plant. */}- <mesh geometry={GEO.cyl} material={MAT.planterLight} position={[0.45, 0.58, 0]} scale={[0.08, 0.14, 0.08]} castShadow />- <mesh geometry={GEO.blob} material={MAT.leaf} position={[0.45, 0.71, 0]} scale={[0.12, 0.1, 0.12]} castShadow />- <mesh geometry={GEO.cyl} material={MAT.planterLight} position={[-0.45, 1.05, 0]} scale={[0.06, 0.2, 0.06]} castShadow />- <mesh geometry={GEO.cyl} material={MAT.pot} position={[-0.3, 1.02, 0.02]} scale={[0.05, 0.14, 0.05]} castShadow />- <mesh geometry={GEO.cyl} material={MAT.pot} position={[0.55, 1.0, 0]} scale={[0.07, 0.1, 0.07]} castShadow />- <mesh geometry={GEO.blob} material={MAT.leafDark} position={[0.55, 1.1, 0]} scale={[0.1, 0.1, 0.1]} castShadow />- </group>- );-}--/** A low modular lounge sofa facing +z: plinth on slim legs, loose cushions, two accent pillows. */-export function Couch({ position, rotationY = 0 }: { position: [number, number, number]; rotationY?: number }) {- return (- <group position={position} rotation={[0, rotationY, 0]}>- {[-1.05, 1.05].flatMap((x) => [-0.36, 0.36].map((z) => (- <mesh key={`${x}:${z}`} geometry={GEO.cyl} material={MAT.steel} position={[x, 0.04, z]} scale={[0.03, 0.08, 0.03]} />- )))}- <Rounded size={[2.3, 0.34, 0.88]} radius={0.06} position={[0, 0.25, 0]} material={MAT.couch} />- <Rounded size={[2.3, 0.42, 0.22]} radius={0.08} position={[0, 0.62, -0.33]} material={MAT.couch} />- <Rounded size={[0.16, 0.3, 0.88]} radius={0.06} position={[-1.1, 0.55, 0]} material={MAT.couch} />- <Rounded size={[0.16, 0.3, 0.88]} radius={0.06} position={[1.1, 0.55, 0]} material={MAT.couch} />- <Rounded size={[1.0, 0.14, 0.64]} radius={0.05} position={[-0.51, 0.49, 0.08]} material={MAT.cushion} />- <Rounded size={[1.0, 0.14, 0.64]} radius={0.05} position={[0.51, 0.49, 0.08]} material={MAT.cushion} />- <group position={[-0.72, 0.7, -0.17]} rotation={[-0.25, 0.15, 0]}>- <Rounded size={[0.38, 0.3, 0.1]} radius={0.04} position={[0, 0, 0]} material={MAT.couchAccents[0]} />- </group>- <group position={[0.74, 0.7, -0.17]} rotation={[-0.25, -0.12, 0]}>- <Rounded size={[0.38, 0.3, 0.1]} radius={0.04} position={[0, 0, 0]} material={MAT.couchAccents[1]} />- </group>- </group>- );-}--/** A frameless glass balustrade from (x1,z1) to (x2,z2): a black base shoe, the pane and a slim cap. */-export function Railing({ from, to, height = 1.05 }: { from: [number, number]; to: [number, number]; height?: number }) {- const [x1, z1] = from;- const [x2, z2] = to;- const length = Math.hypot(x2 - x1, z2 - z1);- const angle = Math.atan2(z2 - z1, x2 - x1);- return (- <group position={[(x1 + x2) / 2, 0, (z1 + z2) / 2]} rotation={[0, -angle, 0]}>- <Box size={[length, 0.08, 0.08]} position={[0, 0.04, 0]} material={MAT.railing} />- <Box size={[length, height - 0.1, 0.02]} position={[0, (height - 0.1) / 2 + 0.07, 0]} material={MAT.glass} cast={false} />- <Box size={[length, 0.03, 0.05]} position={[0, height, 0]} material={MAT.railing} />- </group>- );-}--/** A department name plate: white type on charcoal, with a short rule in the zone's colour. */-function signTexture(label: string, accent: string): Texture | null {- const text = label.length > 22 ? `${label.slice(0, 21)}…` : label;- return cachedCanvasTexture(`dept-sign:${accent}:${text}`, 512, 112, (ctx, w, h) => {- ctx.fillStyle = OFFICE.signBoard;- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = accent;- ctx.fillRect(30, h - 24, 48, 6);- ctx.fillStyle = OFFICE.signText;- ctx.textAlign = "left";- ctx.textBaseline = "middle";- let size = 50;- const font = (px: number) => `600 ${px}px system-ui, -apple-system, 'Segoe UI', sans-serif`;- ctx.font = font(size);- while (size > 30 && ctx.measureText(text).width > w - 60) {- size -= 2;- ctx.font = font(size);- }- ctx.fillText(text, 30, h / 2 - 8);- });-}--/** Acoustic felt with vertical fluting, drawn once per colour and repeated along the wall. */-function feltTexture(colour: string): Texture | null {- const texture = cachedCanvasTexture(`felt:${colour}`, 64, 64, (ctx, w, h) => {- ctx.fillStyle = colour;- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "rgba(0,0,0,0.16)";- for (let x = 0; x < w; x += 16) ctx.fillRect(x, 0, 3, h);- ctx.fillStyle = "rgba(255,255,255,0.07)";- for (let x = 6; x < w; x += 16) ctx.fillRect(x, 0, 4, h);- });- if (texture) {- texture.wrapS = texture.wrapT = RepeatWrapping;- texture.anisotropy = 4;- }- return texture;-}--const feltMaterials = new Map<string, MeshStandardMaterial>();-function feltMaterial(colour: string, width: number): MeshStandardMaterial {- const key = `${colour}:${width.toFixed(2)}`;- let material = feltMaterials.get(key);- if (!material) {- const base = feltTexture(colour);- let map: Texture | null = null;- if (base) {- map = base.clone();- // Four flutes per texture repeat, one repeat every 20 cm.- map.repeat.set(width / 0.2, 1);- map.needsUpdate = true;- }- material = new MeshStandardMaterial({ color: map ? "#ffffff" : colour, map, roughness: 1 });- feltMaterials.set(key, material);- }- return material;-}--/**- * A department's back wall: a white partition faced with fluted acoustic felt- * in the zone's colour, a charcoal name plate with white type, and on a wide- * wall two slim oak ledges with small planters.- */-export function SignWall({ label, width, position, zone = 0, tone }: {- label: string; width: number; position: [number, number, number]; zone?: number;- /** A coding-floor studio's own wall and panel materials, in place of the zone colours. */- tone?: { wall: MeshStandardMaterial; slat: MeshStandardMaterial };-}) {- const colours = DEPARTMENT_ZONES[zone % DEPARTMENT_ZONES.length];- const panel = tone ? `#${tone.slat.color.getHexString()}` : colours.panel;- const texture = signTexture(label, tone ? panel : colours.rug);- const plateW = Math.min(2.6, width * 0.46);- const ledgeX = width / 2 - 0.9;- return (- <group position={position}>- <Box size={[width, 1.9, 0.12]} position={[0, 0.95, -0.01]} material={tone?.wall ?? MAT.wall} />- <Box size={[width - 0.06, 1.6, 0.03]} position={[0, 0.98, 0.06]} material={feltMaterial(panel, width - 0.06)} cast={false} />- <Box size={[plateW + 0.06, (plateW * 112) / 512 + 0.06, 0.03]} position={[0, 1.36, 0.09]} material={MAT.sign} />- {texture && (- <mesh position={[0, 1.36, 0.106]}>- <planeGeometry args={[plateW, (plateW * 112) / 512]} />- <meshStandardMaterial map={texture} roughness={0.7} />- </mesh>- )}- {ledgeX > plateW / 2 + 0.55 && [-ledgeX, ledgeX].map((x) => (- <group key={x} position={[x, 0, 0]}>- <Box size={[0.9, 0.03, 0.12]} position={[0, 1.2, 0.13]} material={MAT.wood} />- <mesh geometry={GEO.cyl} material={MAT.planterLight} position={[-0.2, 1.28, 0.13]} scale={[0.05, 0.13, 0.05]} castShadow />- <mesh geometry={GEO.blob} material={MAT.leaf} position={[-0.2, 1.4, 0.13]} scale={[0.09, 0.08, 0.09]} castShadow />- <mesh geometry={GEO.cyl} material={MAT.pot} position={[0.18, 1.26, 0.13]} scale={[0.045, 0.09, 0.045]} castShadow />- <mesh geometry={GEO.blob} material={MAT.leafDark} position={[0.18, 1.35, 0.13]} scale={[0.07, 0.06, 0.07]} castShadow />- </group>- ))}- </group>- );-}--/** A flat rug under the lounge. */-export function Rug({ position, size }: { position: [number, number, number]; size: [number, number] }) {- return <Box size={[size[0], 0.02, size[1]]} position={position} material={MAT.rug} cast={false} />;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeHud.test.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeHud.test.tsxdeleted file mode 100644index 62d5833156..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeHud.test.tsx+++ /dev/null@@ -1,265 +0,0 @@-import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";-import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from "vitest";-import { loadLocaleChunk, useT } from "@/i18n";-import { buildOfficeLayout, type OfficeLayout, type Studio } from "./officeLayout";-import { useOfficeStore } from "./officeStore";-import { ControlHints, OfficeTools, StationPrompt, stationAction, stationLabel } from "./OfficeHud";-import { stationsFor } from "./stations";-import { DEFAULT_OFFICE_SETTINGS, loadOfficeSettings, useOfficeSettings } from "./officeSettings";--const layout = buildOfficeLayout([- { agentId: "a1", name: "Ada", tier: "specialist", providerLabel: "Codex", state: "idle", createdMs: 1 },-]);--beforeAll(async () => { await loadLocaleChunk("society"); });-beforeEach(() => {- localStorage.clear();- useOfficeStore.setState({ selection: null, hover: null, walkTo: null });- useOfficeSettings.setState({ ...DEFAULT_OFFICE_SETTINGS });-});-afterEach(cleanup);--function tools(overrides: Partial<Parameters<typeof OfficeTools>[0]> = {}) {- const props = {- layout, follow: false, onFollow: vi.fn(), onOverview: vi.fn(), helpOpen: false, onHelp: vi.fn(),- list: { label: "Agents list", ide: false, onOpen: vi.fn() }, ...overrides,- };- render(<OfficeTools {...props} />);- return props;-}--describe("office toolbar", () => {- test("is a handful of named icon buttons, each doing its one thing", () => {- const props = tools();- const bar = screen.getByRole("toolbar", { name: "Map tools" });- expect(within(bar).getAllByRole("button").map((b) => b.getAttribute("aria-label"))).toEqual([- "Follow me", "Overview", "Places", "Agents list", "Help & settings",- ]);- fireEvent.click(screen.getByRole("button", { name: "Follow me" }));- fireEvent.click(screen.getByRole("button", { name: "Overview" }));- fireEvent.click(screen.getByRole("button", { name: "Agents list" }));- fireEvent.click(screen.getByRole("button", { name: "Help & settings" }));- expect(props.onFollow).toHaveBeenCalledOnce();- expect(props.onOverview).toHaveBeenCalledOnce();- expect(props.list?.onOpen).toHaveBeenCalledOnce();- expect(props.onHelp).toHaveBeenCalledOnce();- // The help key is announced, and shown in the button's label on hover.- const help = screen.getByRole("button", { name: "Help & settings" });- expect(help.getAttribute("aria-keyshortcuts")).toBe("H");- expect(help.dataset.tip).toBe("Help & settings (H)");- });-- test("shows what is on: following, the open directory; and no list on a floor without one", () => {- tools({ follow: true, helpOpen: true, list: null });- expect(screen.getByRole("button", { name: "Follow me" }).getAttribute("aria-pressed")).toBe("true");- expect(screen.getByRole("button", { name: "Help & settings" }).getAttribute("aria-pressed")).toBe("true");- expect(screen.queryByRole("button", { name: "Agents list" })).toBeNull();- });-- test("the places menu reaches every station by keyboard: open one, or walk there", () => {- tools();- const trigger = screen.getByRole("button", { name: "Places" });- expect(trigger.getAttribute("aria-expanded")).toBe("false");- fireEvent.click(trigger);- expect(trigger.getAttribute("aria-expanded")).toBe("true");- const menu = screen.getByRole("group", { name: "Places" });- // One "open" and one "walk there" button per station of the floor, the reception among them.- expect(within(menu).getAllByRole("button")).toHaveLength(stationsFor(layout).length * 2);- expect(within(menu).getByRole("button", { name: "Reception: Open the directory" })).toBeTruthy();-- // Resting on a place lights its object in the world.- const open = within(menu).getByRole("button", { name: "Team room: Manage teams" });- fireEvent.focus(open);- expect(useOfficeStore.getState().hover).toEqual({ kind: "checkpoint", id: "team" });- fireEvent.click(open);- expect(useOfficeStore.getState().selection).toEqual({ kind: "checkpoint", id: "team" });- expect(useOfficeStore.getState().hover).toBeNull();- expect(screen.queryByRole("group", { name: "Places" })).toBeNull();-- fireEvent.click(screen.getByRole("button", { name: "Places" }));- fireEvent.click(screen.getByRole("button", { name: "Walk to Wardrobe" }));- const wardrobe = stationsFor(layout).find((s) => s.selection.id === "wardrobe")!;- expect(useOfficeStore.getState().walkTo?.point).toEqual(wardrobe.approach);- expect(useOfficeStore.getState().selection).toBeNull();- });-- test("lists the rooms' places and the teams apart, and gives every row a name", () => {- const board = (dept: string) => ({ id: `studio-board:${dept}`, x: 4, z: -6, facing: 0 });- const studios: Studio[] = [- { deptId: "d0", teamId: "g1", name: "Launch crew", members: ["a1"], leadId: null, board: board("d0"), huddleSpotIds: [], centre: { x: 4, z: -3 } },- { deptId: "pool", teamId: null, name: "", members: [], leadId: null, board: board("pool"), huddleSpotIds: [], centre: { x: 9, z: -3 } },- ];- const campus: OfficeLayout = { ...layout, studios };- tools({ layout: campus });- fireEvent.click(screen.getByRole("button", { name: "Places" }));- const menu = screen.getByRole("group", { name: "Places" });- const teams = within(menu).getByRole("region", { name: "Teams" });- expect(within(teams).getByRole("button", { name: "Launch crew: Open the team" })).toBeTruthy();- // The studio of agents without a team is never a bare "Team board".- expect(within(teams).getByRole("button", { name: "Without a team: Open the team" })).toBeTruthy();- expect(within(menu).queryByRole("button", { name: /^Team board/ })).toBeNull();- const places = within(menu).getByRole("region", { name: "Places" });- expect(within(places).getByRole("button", { name: "Team room: Manage teams" })).toBeTruthy();- expect(within(places).queryByRole("button", { name: /Launch crew/ })).toBeNull();- for (const station of stationsFor(campus)) expect(stationLabel(station, (key) => key)).not.toBe("");- });-- test("the free plot's stand is listed with the teams, as the place to start one", () => {- const stand = { id: "team-stand", kind: "lobbyLamp" as const, x: 6, z: 4, rotationY: 0, room: "floor" as const };- tools({ layout: { ...layout, furniture: [...layout.furniture.filter((item) => item.id !== stand.id), stand] } });- fireEvent.click(screen.getByRole("button", { name: "Places" }));- const teams = within(screen.getByRole("group", { name: "Places" })).getByRole("region", { name: "Teams" });- fireEvent.click(within(teams).getByRole("button", { name: "Free plot: Start a team here" }));- expect(useOfficeStore.getState().selection).toEqual({ kind: "team", id: "team-stand" });- });-- test("the arrow keys move through the rows, and sideways to a row's walk button", () => {- tools();- fireEvent.click(screen.getByRole("button", { name: "Places" }));- const menu = screen.getByRole("group", { name: "Places" });- const rows = [...menu.querySelectorAll<HTMLElement>("[data-place-open]")];- expect(rows.length).toBeGreaterThan(3);- const press = (key: string) => {- const event = new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true });- const reachedWindow = vi.fn();- window.addEventListener("keydown", reachedWindow);- (document.activeElement ?? menu).dispatchEvent(event);- window.removeEventListener("keydown", reachedWindow);- // The list keeps its arrows to itself: the character must not walk on them.- expect(reachedWindow, key).not.toHaveBeenCalled();- expect(event.defaultPrevented, key).toBe(true);- };- rows[0]!.focus();- press("ArrowDown");- expect(document.activeElement).toBe(rows[1]);- press("ArrowDown");- expect(document.activeElement).toBe(rows[2]);- press("ArrowUp");- expect(document.activeElement).toBe(rows[1]);- press("ArrowRight");- expect((document.activeElement as HTMLElement).dataset.placeWalk).toBeDefined();- expect(rows[1]!.closest("[data-place-row]")!.contains(document.activeElement)).toBe(true);- press("ArrowLeft");- expect(document.activeElement).toBe(rows[1]);- press("End");- expect(document.activeElement).toBe(rows[rows.length - 1]);- press("ArrowDown");- expect(document.activeElement).toBe(rows[rows.length - 1]);- press("Home");- expect(document.activeElement).toBe(rows[0]);- press("ArrowUp");- expect(document.activeElement).toBe(rows[0]);- // The row in focus is lit in the world.- expect(useOfficeStore.getState().hover).toEqual(stationsFor(layout)[0]!.selection);- });-- test("opened from the keyboard it lands on the first place", () => {- tools();- const trigger = screen.getByRole("button", { name: "Places" });- trigger.focus();- fireEvent.keyDown(trigger, { key: "ArrowDown" });- const menu = screen.getByRole("group", { name: "Places" });- expect(document.activeElement).toBe(menu.querySelector("[data-place-open]"));- });-- test("Escape closes the places menu and hands focus back to its button", () => {- tools();- const trigger = screen.getByRole("button", { name: "Places" });- fireEvent.click(trigger);- fireEvent.focus(screen.getByRole("button", { name: "Team room: Manage teams" }));- fireEvent.keyDown(screen.getByRole("group", { name: "Places" }), { key: "Escape" });- expect(screen.queryByRole("group", { name: "Places" })).toBeNull();- expect(document.activeElement).toBe(trigger);- // Nothing stays lit in the world behind a closed menu.- expect(useOfficeStore.getState().hover).toBeNull();- });-});--describe("station prompt", () => {- test("is one button: the key, the action, the object's name", () => {- const onUse = vi.fn();- render(<StationPrompt line={{ how: "key", action: "Create an agent", object: "Spawn point" }} onUse={onUse} />);- const prompt = screen.getByRole("button");- expect(prompt.textContent).toBe("ECreate an agentSpawn point");- fireEvent.click(prompt);- expect(onUse).toHaveBeenCalledOnce();- });-- test("in a narrow host it shows the key and the whole action, and keeps the object's name for screen readers", () => {- render(<StationPrompt compact line={{ how: "key", action: "Call the elevator", object: "Elevator" }} onUse={vi.fn()} />);- const prompt = screen.getByRole("button");- expect(prompt.dataset.compact).toBe("true");- expect(prompt.querySelector("kbd")!.textContent).toBe("E");- expect(prompt.querySelector("b")!.textContent).toBe("Call the elevator");- // The name is still part of the button's text, but not drawn.- const object = screen.getByText("Elevator");- expect(object.className).toBe("sr-only");- cleanup();- render(<StationPrompt line={{ how: "key", action: "Call the elevator", object: "Elevator" }} onUse={vi.fn()} />);- expect(screen.getByText("Elevator").className).toBe("");- expect(screen.getByRole("button").dataset.compact).toBeUndefined();- });-- test("names the click instead of the key for something pointed at from afar", () => {- render(<StationPrompt line={{ how: "click", action: "Talk to Ada" }} onUse={vi.fn()} />);- expect(screen.getByRole("button").textContent).toBe("ClickTalk to Ada");- });-- test("every station of every floor has its action in words", () => {- const t = (key: string) => key;- const floors = [layout, buildOfficeLayout([], { variant: "coding" })];- const ids = new Set(floors.flatMap((floor) => stationsFor(floor).map((s) => s.id)));- render(<ul>{[...ids].map((id) => <li key={id}><StationWords id={id} /></li>)}</ul>);- for (const id of ids) {- const words = screen.getByTestId(`words-${id}`).textContent ?? "";- expect(words, id).not.toContain("society.");- expect(words.length, id).toBeGreaterThan(3);- }- // The coffee bar's action flips while a break is on.- expect(stationAction({ id: "break" }, t)).toBe("society.office.use_break");- expect(stationAction({ id: "break" }, t, true)).toBe("society.office.use_break_end");- expect(stationAction({ id: "team" }, t, true)).toBe("society.office.use_team");- });-});--function StationWords({ id }: { id: string }) {- // The real translator, so a missing key shows up as the key itself.- const t = useT();- return <span data-testid={`words-${id}`}>{stationAction({ id }, t)} · {t(`society.office.cp_${id}`)}</span>;-}--describe("control hints", () => {- test("show the essentials once and are dismissed for good", () => {- const onDismiss = vi.fn();- render(<ControlHints onDismiss={onDismiss} />);- const hints = screen.getByRole("region", { name: "Controls" });- expect(within(hints).getAllByRole("listitem").map((li) => li.textContent)).toEqual([- "WASDWalk", "DragLook around", "EUse what is near", "HAll controls",- ]);- fireEvent.click(screen.getByRole("button", { name: "Got it" }));- expect(onDismiss).toHaveBeenCalledOnce();- });-- test("are remembered per browser profile", () => {- expect(loadOfficeSettings().hintsSeen).toBe(false);- useOfficeSettings.getState().set({ hintsSeen: true });- expect(loadOfficeSettings().hintsSeen).toBe(true);- useOfficeSettings.getState().reset();- expect(loadOfficeSettings().hintsSeen).toBe(false);- });-- test("stay away for someone who had switched the old permanent hint bar off", () => {- localStorage.setItem("jarvis.office.settings.v1", JSON.stringify({ alwaysRun: true, showHintBar: false }));- expect(loadOfficeSettings()).toEqual({ alwaysRun: true, hintsSeen: true });- localStorage.setItem("jarvis.office.settings.v1", JSON.stringify({ alwaysRun: false, showHintBar: true }));- expect(loadOfficeSettings().hintsSeen).toBe(false);- });-- test("fall back to the defaults when storage is unreadable", () => {- const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);- localStorage.setItem("jarvis.office.settings.v1", "{not json");- expect(loadOfficeSettings()).toEqual(DEFAULT_OFFICE_SETTINGS);- expect(warn).toHaveBeenCalled();- warn.mockRestore();- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeHud.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeHud.tsxdeleted file mode 100644index 5fb8404d59..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeHud.tsx+++ /dev/null@@ -1,169 +0,0 @@-/**- * The quiet parts of the office HUD: a small icon toolbar (follow, overview,- * places, list, help), the one prompt for whatever the person can use right- * now, and the control hints a first-time visitor sees once. Theme tokens- * only; nothing here polls or animates on its own.- */-import { useEffect, useId, useRef, useState, type ReactNode } from "react";-import { CircleHelp, List, LocateFixed, MapPin, Maximize, SquareTerminal } from "lucide-react";-import { useT } from "@/i18n";-import type { OfficeLayout } from "./officeLayout";-import { OFFICE_CONTROLS } from "./officeControls";-import { useOfficeStore } from "./officeStore";-import { KeyCaps, PlacesList } from "./ReceptionPanel";--export { stationAction, stationLabel } from "./stationText";--function Tool({ label, shortcut, children, ...rest }: {- label: string; shortcut?: string; children: ReactNode;-} & Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, "children" | "aria-label">) {- return (- <button type="button" className="office-tool" aria-label={label} aria-keyshortcuts={shortcut}- data-tip={shortcut ? `${label} (${shortcut})` : label} {...rest}>- {children}- </button>- );-}--/**- * The places of this floor, opened from the toolbar: every station as a real- * button, for pointer and keyboard alike. An opaque card that never grows- * past the stage; when there is more below, its lower edge fades to say so.- */-function PlacesCard({ id, layout, focusFirst, onPicked }: { id: string; layout: OfficeLayout; focusFirst: boolean; onPicked: () => void }) {- const t = useT();- const scroller = useRef<HTMLDivElement>(null);- const [more, setMore] = useState(false);- useEffect(() => {- const el = scroller.current;- if (!el) return;- const check = () => setMore(el.scrollHeight - el.scrollTop - el.clientHeight > 4);- check();- el.addEventListener("scroll", check, { passive: true });- window.addEventListener("resize", check);- return () => {- el.removeEventListener("scroll", check);- window.removeEventListener("resize", check);- };- }, [layout]);- // Opened from the keyboard: land on the first place, so the arrows work at once.- useEffect(() => {- if (focusFirst) scroller.current?.querySelector<HTMLElement>("[data-place-open]")?.focus({ preventScroll: true });- }, [focusFirst]);- return (- <div id={id} className="office-places-card" role="group" aria-label={t("society.office.hud_places")} data-more={more || undefined}>- <div ref={scroller} className="office-places-scroll">- <PlacesList layout={layout} withReception onPicked={onPicked} />- </div>- </div>- );-}--export function OfficeTools({ layout, follow, onFollow, onOverview, helpOpen, onHelp, list }: {- layout: OfficeLayout;- follow: boolean; onFollow: () => void; onOverview: () => void;- helpOpen: boolean; onHelp: () => void;- /** The roster this floor belongs to: the agents view, the IDE, or the IDE tab's sessions list; null on a floor without one. */- list: { label: string; ide: boolean; onOpen: () => void } | null;-}) {- const t = useT();- const [places, setPlaces] = useState<{ open: boolean; byKeyboard: boolean }>({ open: false, byKeyboard: false });- const dock = useRef<HTMLDivElement>(null);- const trigger = useRef<HTMLButtonElement>(null);- const placesId = useId();- const close = () => {- setPlaces({ open: false, byKeyboard: false });- // A row that was pointed at is gone with the card; nothing may stay lit in the world.- useOfficeStore.getState().setHover(null);- };- useEffect(() => {- if (!places.open) return;- const outside = (event: PointerEvent) => {- if (event.target instanceof Node && !dock.current?.contains(event.target)) close();- };- document.addEventListener("pointerdown", outside, true);- return () => document.removeEventListener("pointerdown", outside, true);- }, [places.open]);- return (- <div ref={dock} className="office-hud office-tools-dock" data-office-ui- onKeyDown={(event) => {- if (event.key !== "Escape" || !places.open) return;- event.preventDefault();- event.stopPropagation();- close();- trigger.current?.focus();- }}>- <div className="office-tools" role="toolbar" aria-label={t("society.office.hud_tools")}>- <Tool label={t("society.office.me")} aria-pressed={follow} onClick={onFollow}><LocateFixed aria-hidden /></Tool>- <Tool label={t("society.office.overview")} onClick={onOverview}><Maximize aria-hidden /></Tool>- <button ref={trigger} type="button" className="office-tool" aria-label={t("society.office.hud_places")}- data-tip={places.open ? undefined : t("society.office.hud_places")} aria-expanded={places.open} aria-controls={placesId}- // A click without a pointer (Enter, Space) came from the keyboard.- onClick={(event) => (places.open ? close() : setPlaces({ open: true, byKeyboard: event.detail === 0 }))}- onKeyDown={(event) => {- if (event.key !== "ArrowDown") return;- // Arrow down opens the card on its first place, or steps into a card that is already open.- event.preventDefault();- event.stopPropagation();- if (places.open) dock.current?.querySelector<HTMLElement>("[data-place-open]")?.focus();- else setPlaces({ open: true, byKeyboard: true });- }}>- <MapPin aria-hidden />- </button>- {list && <Tool label={list.label} onClick={list.onOpen}>{list.ide ? <SquareTerminal aria-hidden /> : <List aria-hidden />}</Tool>}- <Tool label={t("society.office.guide.hud_button")} shortcut="H" aria-pressed={helpOpen} onClick={onHelp}><CircleHelp aria-hidden /></Tool>- </div>- {places.open && <PlacesCard id={placesId} layout={layout} focusFirst={places.byKeyboard} onPicked={close} />}- </div>- );-}--/** What the prompt says: how it is triggered, the action, and (for a station) the object it belongs to. */-export interface PromptLine {- /** `key`: the person stands at it and E uses it. `click`: the pointer rests on it from afar. */- how: "key" | "click";- action: string;- object?: string;-}--/**- * The one prompt on screen: a key cap, the action, the object's name. A real button, so a click or a tap works too.- * In a narrow host (`compact`, the IDE side panel) there is no room for both texts: the action is shown whole,- * wrapping if it must, and the object's name is kept for screen readers only.- */-export function StationPrompt({ line, onUse, compact = false }: { line: PromptLine; onUse: () => void; compact?: boolean }) {- const t = useT();- return (- <button type="button" className="office-prompt" data-office-ui data-compact={compact || undefined} onClick={onUse}>- {line.how === "key"- ? <kbd className="office-key">E</kbd>- : <kbd className="office-key" data-mouse>{t("society.office.guide.mouse_click")}</kbd>}- <b>{line.action}</b>- {line.object && <span className={compact ? "sr-only" : undefined}>{line.object}</span>}- </button>- );-}--const HINT_IDS = ["walk", "rotate", "interact", "guide"] as const;--/**- * The controls, once: shown to someone who has not dismissed them yet,- * remembered per browser profile (officeSettings). Reception's settings bring- * them back.- */-export function ControlHints({ onDismiss }: { onDismiss: () => void }) {- const t = useT();- return (- <section className="office-card office-hints" data-office-ui aria-label={t("society.office.hints_label")}>- <ul>- {HINT_IDS.map((id) => {- const control = OFFICE_CONTROLS.find((c) => c.id === id);- if (!control) return null;- // One way to do it is enough for a first hint; the guide lists every alternative.- return <li key={id}><KeyCaps control={{ keys: control.keys.slice(0, 1) }} />{t(`society.office.hint_${id}`)}</li>;- })}- </ul>- <button type="button" className="office-hints-dismiss" onClick={onDismiss}>{t("society.office.hints_dismiss")}</button>- </section>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeMinimap.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeMinimap.tsxdeleted file mode 100644index cc636f6aeb..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeMinimap.tsx+++ /dev/null@@ -1,327 +0,0 @@-/**- * The office minimap, game style: a square card in the top-right corner that- * follows the person's character (player-centred, north-up, zoomable), with- * the camera's view as a soft cone, agents as portrait tokens with a status- * ring, off-screen agents as arrows on the card edge, and gold checkpoint icons.- *- * The painted floor (with a margin of sky around it) is drawn once into an- * offscreen canvas and only redrawn when the layout, the zoom, the pixel ratio- * or the theme changes. Every frame (≤ 20 Hz, paused while the document is- * hidden) just blits that layer at the player's offset and paints the moving- * markers from the per-frame module state (`player`, `agentPositions`,- * `cameraView`), never from React state.- *- * Click focuses the camera on a spot (or selects the agent under the pointer),- * double-click walks the character there, the wheel zooms.- */-import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent as ReactMouseEvent, type PointerEvent as ReactPointerEvent } from "react";-import { Map as MapIcon, Minus, Plus } from "lucide-react";-import { useReducedMotion } from "framer-motion";-import { useT } from "@/i18n";-import type { CampusZoneKind, CheckpointKind, OfficeLayout, Point, Rect, RoomKind } from "./officeLayout";-import { cameraView, player, useOfficeStore } from "./officeStore";-import { agentPositions } from "./walkerRegistry";-import {- MAP_PAINT, ZOOM_DEFAULT_M, ZOOM_MAX_M, ZOOM_MIN_M, centredTransform, clampToEdge, clampToRect, clampZoom, drawAgentToken, drawCheckpoints, minimapCentre,- drawEdgeArrow, drawFloorArt, drawPlayerArrow, drawViewCone, mapToWorld, pickNearest, placeAt, worldToMap, zoomStep,- type AgentToken, type MapPoint, type MapTransform,-} from "./minimap";-import {- agentColour, context2d, offscreenLayer, usePixelRatio, useThemeVersion, useThrottledFrames, type OfficeMapAgent,-} from "./mapHooks";--export type OfficeMinimapAgent = OfficeMapAgent;--export interface OfficeMinimapProps {- layout: OfficeLayout;- agents: ReadonlyMap<string, OfficeMapAgent>;- selectedId: string | null;- /** Opens the full map (the "Map (M)" button). */- onOpenMap: () => void;-}--/** Card edge in CSS px (square). */-export const MINIMAP_SIZE = 200;-const FRAME_MS = 50;-const HIT_PX = 10;-const EDGE_INSET = 12;-const TOKEN_R = 6.5;-const CHECKPOINT_PX = 14;-const STORAGE_KEY = "jarvis.office.minimap.zoom";--function readZoom(): number {- try {- const raw = window.localStorage.getItem(STORAGE_KEY);- return raw ? clampZoom(Number(raw)) : ZOOM_DEFAULT_M;- } catch {- // Storage blocked (private mode, sandboxed WebView): start at the default zoom.- return ZOOM_DEFAULT_M;- }-}--function writeZoom(metres: number): void {- try {- window.localStorage.setItem(STORAGE_KEY, String(metres));- } catch {- // Storage blocked: the zoom lasts for this visit only, which is harmless.- }-}--interface Layer { canvas: HTMLCanvasElement; area: Rect; scale: number; cssW: number; cssH: number }--interface Hit extends MapPoint { id: string; world: Point }--interface Tooltip { x: number; y: number; text: string }--export function OfficeMinimap({ layout, agents, selectedId, onOpenMap }: OfficeMinimapProps) {- const t = useT();- const reduced = useReducedMotion() ?? false;- const [zoom, setZoom] = useState(readZoom);- const [tooltip, setTooltip] = useState<Tooltip | null>(null);- const mapRef = useRef<HTMLDivElement>(null);- const canvasRef = useRef<HTMLCanvasElement>(null);- const layerRef = useRef<Layer | null>(null);- const hitsRef = useRef<Hit[]>([]);- const transformRef = useRef<MapTransform>(centredTransform(player, zoom, MINIMAP_SIZE, MINIMAP_SIZE));- const themeVersion = useThemeVersion();- const dpr = usePixelRatio();-- // The render loop reads these through a ref, so a roster refetch never restarts it.- const live = useRef({ agents, selectedId, zoom, reduced, bounds: layout.bounds });- live.current = { agents, selectedId, zoom, reduced, bounds: layout.bounds };- /** Where the person's arrow is on the card: the middle, except near the floor's edge. */- const meRef = useRef({ x: MINIMAP_SIZE / 2, y: MINIMAP_SIZE / 2 });-- const draw = useCallback((now: number) => {- const canvas = canvasRef.current;- const ctx = context2d(canvas);- if (!canvas || !ctx) return;- const { agents: roster, selectedId: sel, zoom: metres, reduced: still, bounds } = live.current;- const size = MINIMAP_SIZE;- // The card follows the person but stays on the floor.- const tr = centredTransform(minimapCentre(player, bounds, metres), metres, size, size);- transformRef.current = tr;- const ratio = canvas.width / size;- ctx.setTransform(ratio, 0, 0, ratio, 0, 0);- ctx.globalAlpha = 1;- ctx.fillStyle = MAP_PAINT.space;- ctx.fillRect(0, 0, size, size);- const layer = layerRef.current;- if (layer) {- const origin = worldToMap(tr, { x: layer.area.minX, z: layer.area.minZ });- ctx.drawImage(layer.canvas, origin.x, origin.y, layer.cssW, layer.cssH);- }- const centre = worldToMap(tr, player);- meRef.current = centre;- if (cameraView.ready) drawViewCone(ctx, centre, cameraView.yaw, cameraView.halfWidth, size * 0.5);-- const hits: Hit[] = [];- const pulse = still ? null : (now % 1400) / 1400;- let selected: { token: AgentToken; edge: ReturnType<typeof clampToEdge> } | null = null;- for (const agent of roster.values()) {- const pos = agentPositions.get(agent.agentId);- if (!pos) continue;- const token: AgentToken = {- id: agent.agentId, name: agent.name, state: agent.state, colour: agentColour(agent), selected: agent.agentId === sel,- ...worldToMap(tr, pos),- };- const edge = clampToEdge(token, size, size, EDGE_INSET);- hits.push({ id: token.id, x: edge.x, y: edge.y, world: { x: pos.x, z: pos.z } });- if (token.selected) { selected = { token, edge }; continue; }- if (edge.clamped) drawEdgeArrow(ctx, edge.x, edge.y, edge.angle, token);- else drawAgentToken(ctx, token, TOKEN_R, null);- }- // The selected agent last, so it sits on top of its neighbours.- if (selected) {- if (selected.edge.clamped) drawEdgeArrow(ctx, selected.edge.x, selected.edge.y, selected.edge.angle, selected.token);- else drawAgentToken(ctx, selected.token, TOKEN_R, pulse);- }- hitsRef.current = hits;- drawPlayerArrow(ctx, centre.x, centre.y, player.heading, 9);- }, []);-- // Static layer: layout, zoom, pixel ratio or theme changed.- useEffect(() => {- const canvas = canvasRef.current;- if (!canvas) return;- canvas.width = Math.round(MINIMAP_SIZE * dpr);- canvas.height = Math.round(MINIMAP_SIZE * dpr);- const scale = MINIMAP_SIZE / zoom;- // Enough sky around the floor that the card is never empty at the railing.- const margin = zoom / 2 + 2;- const b = layout.bounds;- const area: Rect = { minX: b.minX - margin, maxX: b.maxX + margin, minZ: b.minZ - margin, maxZ: b.maxZ + margin };- const cssW = (area.maxX - area.minX) * scale;- const cssH = (area.maxZ - area.minZ) * scale;- const off = offscreenLayer(cssW, cssH, dpr);- if (!off) {- layerRef.current = null;- return;- }- const lt: MapTransform = { scale, offsetX: -area.minX * scale, offsetY: -area.minZ * scale, width: cssW, height: cssH };- drawFloorArt(off.ctx, layout, lt, area);- drawCheckpoints(off.ctx, layout, lt, CHECKPOINT_PX);- layerRef.current = { canvas: off.canvas, area, scale, cssW, cssH };- draw(performance.now());- }, [layout, zoom, dpr, themeVersion, draw]);-- useThrottledFrames(draw, FRAME_MS, true);-- const changeZoom = useCallback((direction: number) => {- setZoom((prev) => {- const next = zoomStep(prev, direction);- if (next !== prev) writeZoom(next);- return next;- });- }, []);-- // The wheel zooms the map instead of scrolling or zooming anything behind it.- useEffect(() => {- const el = mapRef.current;- if (!el) return;- const onWheel = (event: WheelEvent) => {- event.preventDefault();- if (event.deltaY !== 0) changeZoom(event.deltaY < 0 ? 1 : -1);- };- el.addEventListener("wheel", onWheel, { passive: false });- return () => el.removeEventListener("wheel", onWheel);- }, [changeZoom]);-- const mapPoint = (event: { clientX: number; clientY: number }): MapPoint | null => {- const canvas = canvasRef.current;- if (!canvas) return null;- const rect = canvas.getBoundingClientRect();- if (rect.width <= 0 || rect.height <= 0) return null;- return { x: ((event.clientX - rect.left) / rect.width) * MINIMAP_SIZE, y: ((event.clientY - rect.top) / rect.height) * MINIMAP_SIZE };- };-- const onClick = (event: ReactMouseEvent<HTMLCanvasElement>) => {- const at = mapPoint(event);- if (!at) return;- const store = useOfficeStore.getState();- const hit = pickNearest(hitsRef.current, at, HIT_PX);- if (hit) {- store.select({ kind: "agent", id: hit.id });- store.focusOn(hit.world);- return;- }- store.focusOn(clampToRect(mapToWorld(transformRef.current, at), layout.floor));- };-- const onDoubleClick = (event: ReactMouseEvent<HTMLCanvasElement>) => {- const at = mapPoint(event);- if (!at) return;- useOfficeStore.getState().requestWalk(clampToRect(mapToWorld(transformRef.current, at), layout.floor));- };-- const checkpointLabels: Record<CheckpointKind, string> = {- spawn: t("society.office.cp_spawn"),- launch: t("society.office.cp_launch"),- create: t("society.office.cp_create"),- manage: t("society.office.cp_manage"),- team: t("society.office.cp_team"),- wardrobe: t("society.office.cp_wardrobe"),- lead: t("society.office.cp_lead"),- break: t("society.office.cp_break"),- elevator: t("society.office.cp_elevator"),- mission: t("society.office.cp_mission"),- studio: t("society.office.cp_studio"),- levels: t("society.office.cp_levels"),- ship: t("society.office.cp_ship"),- };- const roomLabels: Record<RoomKind, string> = {- lead: t("society.office.room_lead"),- team: t("society.office.room_team"),- wardrobe: t("society.office.room_wardrobe"),- reception: t("society.office.room_reception"),- break: t("society.office.room_break"),- command: t("society.office.room_command"),- server: t("society.office.room_server"),- arcade: t("society.office.room_arcade"),- classics: t("society.office.room_classics"),- puzzle: t("society.office.room_puzzle"),- action: t("society.office.room_action"),- foyer: t("society.office.room_foyer"),- prizes: t("society.office.room_prizes"),- snack: t("society.office.room_snack"),- levels: t("society.office.room_levels"),- };- const youLabel = t("society.office.minimap_you");- // Agents floor: the campus between the studios. The pool studio has no team name; the map gives it one.- const zoneLabels: Record<CampusZoneKind, string> = {- boulevard: t("society.office.zone_boulevard"),- plaza: t("society.office.zone_boulevard"),- atrium: t("society.office.zone_atrium"),- plot: t("society.office.zone_plot"),- garden: t("society.office.zone_garden"),- booths: t("society.office.zone_booths"),- library: t("society.office.zone_library"),- cafe: t("society.office.zone_cafe"),- };- const openSpace = t(layout.variant === "agents" ? "society.office.studio_pool" : "society.office.open_space");-- const onPointerMove = (event: ReactPointerEvent<HTMLCanvasElement>) => {- const at = mapPoint(event);- if (!at) return;- let text: string | null = null;- const hit = pickNearest(hitsRef.current, at, HIT_PX);- if (hit) {- text = agents.get(hit.id)?.name ?? null;- } else if ((at.x - meRef.current.x) ** 2 + (at.y - meRef.current.y) ** 2 <= HIT_PX * HIT_PX) {- text = youLabel;- } else {- const place = placeAt(layout, mapToWorld(transformRef.current, at));- if (place?.kind === "checkpoint") text = checkpointLabels[place.id];- else if (place?.kind === "room") text = roomLabels[place.id];- else if (place?.kind === "department") text = place.label || openSpace;- else if (place?.kind === "zone") text = zoneLabels[place.id];- }- setTooltip((prev) => {- if (!text) return null;- const next = { x: Math.round(at.x), y: Math.round(at.y), text };- return prev && prev.text === next.text && prev.x === next.x && prev.y === next.y ? prev : next;- });- };-- const working = useMemo(() => {- let n = 0;- for (const agent of agents.values()) if (agent.state === "working") n += 1;- return n;- }, [agents]);- const summary = t("society.office.minimap_aria").replace("{0}", String(agents.size)).replace("{1}", String(working));- const zoomLabel = t("society.office.minimap_zoom").replace("{0}", String(Math.round(zoom)));-- return (- <div className="office-hud office-minimap" data-office-ui role="group" aria-label={t("society.office.minimap_title")}>- <div ref={mapRef} className="office-minimap-map" style={{ width: MINIMAP_SIZE, height: MINIMAP_SIZE }}>- <canvas ref={canvasRef} className="office-minimap-canvas" role="img" aria-label={summary}- style={{ width: MINIMAP_SIZE, height: MINIMAP_SIZE }}- onClick={onClick} onDoubleClick={onDoubleClick} onPointerMove={onPointerMove} onPointerLeave={() => setTooltip(null)} />- <span className="office-minimap-north" aria-hidden>{t("society.office.compass_n")}</span>- {tooltip && (- // Flip to the pointer's left on the right half so the label never runs off the card.- <span className="office-minimap-tooltip" role="presentation" data-side={tooltip.x > MINIMAP_SIZE / 2 ? "left" : "right"}- style={{ left: tooltip.x > MINIMAP_SIZE / 2 ? tooltip.x - 10 : tooltip.x + 10, top: Math.max(tooltip.y - 8, 22) }}>- {tooltip.text}- </span>- )}- </div>- <div className="office-minimap-bar">- <button type="button" className="office-minimap-btn" onClick={() => changeZoom(-1)} disabled={zoom >= ZOOM_MAX_M}- aria-label={t("society.office.minimap_zoom_out")} title={t("society.office.minimap_zoom_out")}>- <Minus aria-hidden size={13} />- </button>- <span className="office-minimap-zoom" aria-live="polite">{zoomLabel}</span>- <button type="button" className="office-minimap-btn" onClick={() => changeZoom(1)} disabled={zoom <= ZOOM_MIN_M}- aria-label={t("society.office.minimap_zoom_in")} title={t("society.office.minimap_zoom_in")}>- <Plus aria-hidden size={13} />- </button>- <button type="button" className="office-minimap-btn office-minimap-open" onClick={onOpenMap}- aria-keyshortcuts="M" title={t("society.office.minimap_open_map_label")}>- <MapIcon aria-hidden size={13} />- <span>{t("society.office.minimap_open_map")}</span>- </button>- </div>- </div>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficePanels.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficePanels.tsxdeleted file mode 100644index 880f657815..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficePanels.tsx+++ /dev/null@@ -1,118 +0,0 @@-/**- * What the person's selection opens in the office: an agent's walkie-talkie- * (an IDE session on the coding floor has its own PaneCommandPanel), or the- * surface of a station. Every action here uses an existing app path — the- * create dialog, agent card and chat, chat groups — the office adds no new- * backend contract.- *- * Not every station has a surface here: the spawn terminal opens the app's- * create dialog, the lead's desk selects the lead, the coffee bar calls a- * break, the elevator and the Level Hall open their own screens. OfficeStage- * turns those selections into their action.- */-import { useT } from "@/i18n";-import type { SocietyAgent } from "../data";-import type { OfficeLayout } from "./officeLayout";-import type { NavGrid } from "./officeNav";-import { type OfficeFloor, type Selection } from "./officeStore";-import { AgentTalkPanel } from "./AgentTalkPanel";-import type { PlayerProfile } from "./playerProfile";-import { WardrobePanel } from "./WardrobePanel";-import { ReceptionPanel } from "./ReceptionPanel";-import { TeamRoomPanel } from "./TeamRoomPanel";-import { MissionControlPanel } from "./MissionControlPanel";-import { LaunchPanel } from "./SpawnPanel";-import { StationSheet, StationSidePanel } from "./StationSheet";-import { isReception, isTeamStand } from "./stations";--export interface OfficeActions {- onOpenAgent: (id: string) => void;- onOpenLedger: () => void;- onCreateAgent?: () => void;- onOpenGroup?: (groupId: string) => void;-}--/** How a station's surface is shown: a dialog over the map, or a panel docked beside it. */-export type StationSurfaceKind = "sheet" | "side";--/** The stations that open a surface of their own, and how. Everything else is an action (see OfficeStage). */-export function stationSurface(selection: Selection | null): StationSurfaceKind | null {- if (!selection) return null;- if (selection.kind === "team") return "sheet";- if (selection.kind !== "checkpoint") return null;- if (selection.id === "wardrobe") return "side";- if (isReception(selection) || selection.id === "team" || selection.id === "launch" || selection.id === "mission") return "sheet";- return null;-}--/** The agent panel is a walkie-talkie to that agent (AgentTalkPanel). */-export function AgentPanel({ agent, actions, onClose }: { agent: SocietyAgent; actions: OfficeActions; onClose: () => void }) {- return <AgentTalkPanel agent={agent} actions={actions} onClose={onClose} />;-}--export function StationSurface({ selection, floor = "agents", agents, layout, grid, sample, profile, onProfile, actions, onClose, returnFocus }: {- selection: Selection; floor?: OfficeFloor; agents: SocietyAgent[]; layout: OfficeLayout; sample: boolean;- /** The floor's nav grid: a team opened from its studio board meets at that board, on places the grid allows. */- grid?: NavGrid;- profile: PlayerProfile; onProfile: (next: PlayerProfile) => void; actions: OfficeActions; onClose: () => void;- /** Hands focus back to the map once a dialog has closed. */- returnFocus?: () => void;-}) {- const t = useT();- if (selection.kind === "team") {- const studio = (layout.studios ?? []).find((s) => s.board?.id === selection.id);- if (!studio) {- // The free plot's stand: no team stands here yet, so the sheet opens on the form that starts one.- if (!isTeamStand(layout, selection)) return null;- return (- <StationSheet title={t("society.office.cp_found")} description={t("society.office.plot_free")} onClose={onClose} returnFocus={returnFocus}>- <TeamRoomPanel agents={agents} layout={layout} sample={sample} actions={actions} onMeet={onClose} compose />- </StationSheet>- );- }- return (- <StationSheet title={studio.teamId ? studio.name : t("society.office.team_pool")} description={t("society.office.cp_board_hint")} onClose={onClose} returnFocus={returnFocus}>- <TeamRoomPanel agents={agents} layout={layout} sample={sample} actions={actions} onMeet={onClose}- focus={{ teamId: studio.teamId, members: studio.members, studio, grid }} />- </StationSheet>- );- }- if (selection.kind !== "checkpoint") return null;- const id = selection.id;- if (id === "wardrobe") {- return (- <StationSidePanel title={t("society.office.cp_wardrobe")} description={t("society.office.wardrobe_body")} onClose={onClose}>- <WardrobePanel profile={profile} onProfile={onProfile} agents={agents} sample={sample} />- </StationSidePanel>- );- }- if (isReception(selection)) {- return (- <StationSheet title={t("society.office.cp_manage")} description={t("society.office.cp_manage_hint")} onClose={onClose} returnFocus={returnFocus}>- <ReceptionPanel floor={floor} layout={layout} agents={agents} actions={actions} />- </StationSheet>- );- }- if (id === "team") {- return (- <StationSheet title={t("society.office.cp_team")} description={t("society.office.cp_team_hint")} onClose={onClose} returnFocus={returnFocus}>- <TeamRoomPanel agents={agents} layout={layout} sample={sample} actions={actions} onMeet={onClose} />- </StationSheet>- );- }- if (id === "launch") {- return (- <StationSheet size="md" title={t("society.office.cp_launch")} description={t("society.office.launch_body")} onClose={onClose} returnFocus={returnFocus}>- <LaunchPanel />- </StationSheet>- );- }- if (id === "mission") {- return (- <StationSheet size="md" title={t("society.office.cp_mission")} description={t("society.office.cp_mission_hint")} onClose={onClose} returnFocus={returnFocus}>- <MissionControlPanel />- </StationSheet>- );- }- return null;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficePlayer.keys.test.ts b/dodaios/ui/web/frontend/src/components/society/office/OfficePlayer.keys.test.tsdeleted file mode 100644index ed365308a6..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficePlayer.keys.test.ts+++ /dev/null@@ -1,39 +0,0 @@-import { afterEach, describe, expect, it } from "vitest";-import { forgetHeldKeysUnderDialog, ownsKeyboard } from "./OfficePlayer";--afterEach(() => { document.body.innerHTML = ""; });--describe("ownsKeyboard", () => {- it("leaves plain page focus to the character", () => {- expect(ownsKeyboard(document.body)).toBe(false);- });- it("gives text fields their keys", () => {- const input = document.createElement("input");- document.body.append(input);- expect(ownsKeyboard(input)).toBe(true);- });- it("gives an open dialog every key, even with focus outside it", () => {- const dialog = document.createElement("div");- dialog.setAttribute("role", "dialog");- dialog.setAttribute("data-state", "open");- document.body.append(dialog);- expect(ownsKeyboard(document.body)).toBe(true);- });-});--describe("forgetHeldKeysUnderDialog", () => {- it("keeps held walking keys while nothing else owns the keyboard", () => {- const pressed = new Set(["KeyD"]);- expect(forgetHeldKeysUnderDialog(pressed)).toBe(false);- expect([...pressed]).toEqual(["KeyD"]);- });- it("drops a key still held when an arcade game opened, so the character stops behind it", () => {- const pressed = new Set(["ArrowUp", "KeyD"]);- const dialog = document.createElement("div");- dialog.setAttribute("role", "dialog");- dialog.setAttribute("data-state", "open");- document.body.append(dialog);- expect(forgetHeldKeysUnderDialog(pressed)).toBe(true);- expect(pressed.size).toBe(0);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficePlayer.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficePlayer.tsxdeleted file mode 100644index 36ec458c6b..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficePlayer.tsx+++ /dev/null@@ -1,387 +0,0 @@-/**- * The person's own character: walks with WASD/arrows (camera-relative, Shift- * runs, Space jumps — a sprint jump is faster than a sprint) or by clicking- * the floor, and interacts with whatever is nearby (E).- * Zooming out never requires walking — everything stays clickable from afar.- *- * A click draws the route on the floor (dots to a ring at the destination).- * The character walks round people and furniture, never through them, and- * never comes to rest inside anything solid or beyond the floor's edge.- */-import { useEffect, useMemo, useRef } from "react";-import { Html } from "@react-three/drei";-import { useFrame, useThree } from "@react-three/fiber";-import { DoubleSide, Object3D, Vector3, type Group, type InstancedMesh, type Mesh, type MeshBasicMaterial } from "three";-import type { FigureDrive } from "../figures/FigureRig";-import { ToyFigure } from "./ToyFigure";-import type { ToyLook } from "./toyFigureModel";-import { isWalkable, nearestWalkable, type NavGrid } from "./officeNav";-import { clickPaceFor, stepClearOfBodies, turnToward } from "./officeMotion";-import { advanceWalk, beginWalk, routeMarks, type Walk } from "./officeWalk";-import { standingPlaceFor } from "./officeTeams";-import { officeSession, player, sameSelection, useOfficeStore, type Selection } from "./officeStore";-import { agentPositions, bodiesExcept, bodiesNear, companions } from "./walkerRegistry";-import { OFFICE_FIGURE_HEIGHT_M } from "./OfficeAgents";-import { seatOf, type OfficeLayout } from "./officeLayout";-import { chairInReach, seatDesks, useLeadSeat } from "./leadSeat";-import { useOfficeDog } from "./dogLife";-import { TreatBone } from "./dogProps";-import { isRunning, useOfficeSettings } from "./officeSettings";-import { nearestInteractable } from "./stations";-import { jumpSquash, newJump, pressJump, stepJump } from "./officeJump";-import { useProgression } from "../progression/progressionStore";-import { PERSON_SUBJECT } from "../progression/progressionApi";-import { LevelChip } from "../progression/LevelHud";-import { useDressedFigure } from "../progression/regalia/dress";-import { useCourier } from "./courierStore";--/** The person's pace: a brisk walk, and a sprint on Shift (m/s). */-export const PLAYER_WALK_SPEED = 2.0;-export const PLAYER_SPRINT_SPEED = 4.4;--/** Bodies further than this from the character play no part in a click-to-move walk. */-const BODY_RANGE_M = 7;-/** How far the character may be from free ground before it is put back at the floor's entrance instead. */-const RESCUE_RANGE_M = 8;-/** The route marker: dots on the floor and a ring at the destination, in the character's own gold. */-const MARKER = { dots: 40, colour: "#f5b83d", y: 0.035 } as const;--/** Talk range to an agent, in metres. */-export const AGENT_TALK_RANGE = 1.8;--/** Play range around the spot in front of an arcade screen, in metres. */-export const ARCADE_PLAY_RANGE = 0.9;--const MOVE_KEYS: Record<string, [number, number]> = {- KeyW: [0, 1], ArrowUp: [0, 1], KeyS: [0, -1], ArrowDown: [0, -1],- KeyA: [-1, 0], ArrowLeft: [-1, 0], KeyD: [1, 0], ArrowRight: [1, 0],-};--/** Keys typed into a field, a dialog or any other DOM control never walk the character. */-export function ownsKeyboard(target: EventTarget | null): boolean {- // An open modal owns every key, wherever focus happens to sit.- if (typeof document !== "undefined" && document.querySelector("[role='dialog'][data-state='open'], [role='alertdialog'][data-state='open']")) return true;- if (!(target instanceof HTMLElement)) return false;- if (target.isContentEditable) return true;- const tag = target.tagName;- return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || !!target.closest("[role='dialog']");-}--/**- * Held movement keys stop counting the moment a modal (an arcade game, the- * elevator panel) takes the keyboard: the dialog swallows the keys pressed- * inside it, and the character must not keep walking behind it on a key that- * was still held when it opened. Returns true when it forgot something.- */-export function forgetHeldKeysUnderDialog(pressed: Set<string>): boolean {- if (pressed.size === 0 || !ownsKeyboard(null)) return false;- pressed.clear();- return true;-}--/** Space on a focused button, tab or switch activates that control, never a jump. */-function activatesControl(target: EventTarget | null): boolean {- return target instanceof HTMLElement && !!target.closest("button, a[href], [role='button'], [role='tab'], [role='switch'], [role='checkbox']");-}--/** Pressed movement keys (and Space for jumping), tracked on the window while the office is awake. */-function useMoveKeys(enabled: boolean, onInteract: () => void, onJump: () => void) {- const pressed = useRef(new Set<string>());- const run = useRef(false);- const jumpHeld = useRef(false);- useEffect(() => {- if (!enabled) { pressed.current.clear(); return; }- const down = (event: KeyboardEvent) => {- if (ownsKeyboard(event.target) || event.ctrlKey || event.metaKey || event.altKey) return;- run.current = event.shiftKey;- if (event.code in MOVE_KEYS) { pressed.current.add(event.code); event.preventDefault(); }- else if (event.code === "KeyE" && !event.repeat) { onInteract(); event.preventDefault(); }- else if (event.code === "Space" && !activatesControl(event.target)) {- event.preventDefault();- if (!event.repeat) onJump();- jumpHeld.current = true;- }- };- const up = (event: KeyboardEvent) => {- pressed.current.delete(event.code);- if (event.code === "Space") jumpHeld.current = false;- run.current = event.shiftKey;- };- // A key held while the window loses focus never sees its keyup; forget- // everything then, or the character walks on by itself. (Not on- // visibilitychange: the desktop WebView reports visible windows as hidden.)- const release = () => { pressed.current.clear(); jumpHeld.current = false; };- window.addEventListener("keydown", down);- // Releases are heard in the capture phase, before any overlay that handles its own keys can swallow them.- window.addEventListener("keyup", up, true);- window.addEventListener("blur", release);- return () => {- release();- window.removeEventListener("keydown", down);- window.removeEventListener("keyup", up, true);- window.removeEventListener("blur", release);- };- }, [enabled, onInteract, onJump]);- return { pressed, run, jumpHeld };-}--/** What E reaches from where the character stands: a station, an agent or a game cabinet (stations.ts). */-const REACH = { agent: AGENT_TALK_RANGE, arcade: ARCADE_PLAY_RANGE } as const;--export function OfficePlayer({ layout, grid, look, name, awake, reduced }: {- layout: OfficeLayout; grid: NavGrid; look: ToyLook; name: string; awake: boolean; reduced: boolean;-}) {- const group = useRef<Group>(null);- const body = useRef<Group>(null);- const ring = useRef<Mesh>(null);- const jump = useMemo(newJump, []);- const drive = useRef<FigureDrive>({ mode: "idle", speed: 0 });- const camera = useThree((s) => s.camera);- const forward = useMemo(() => new Vector3(), []);- const lastWalk = useRef(0);- // The click-to-move walk in progress: its route, stuck watch and time budget.- const walk = useRef<Walk | null>(null);- const others = useRef<{ x: number; z: number }[]>([]);- const nearbyRef = useRef<Selection | null>(null);- const interact = useMemo(() => () => {- // E on the lead's chair sits down (or stands up again); otherwise it opens what is nearby.- const seat = useLeadSeat.getState();- if (seat.seated) { seat.set({ seated: null, standUp: true }); return; }- if (seat.near) { seat.set({ seated: seat.near, pending: null }); return; }- // The dog: pet it, or hand over the bone; the treat jar hands one out.- if (useOfficeDog.getState().interact()) return;- const nearby = nearbyRef.current;- if (nearby) useOfficeStore.getState().select(nearby);- }, []);- const onJump = useMemo(() => () => pressJump(jump), [jump]);- const hasBone = useOfficeDog((s) => s.hasBone);- // Seated at Mission Control the camera is the character's eyes: its own figure would block the view.- const firstPerson = useLeadSeat((s) => !!layout.command && s.seated === layout.command.id);- // In the courier the keys fly the ship and the character rides inside it, out of sight.- const flying = useCourier((s) => s.flying);- const { pressed, run, jumpHeld } = useMoveKeys(awake && !flying, interact, onJump);- // A level-up of the person's own: the character hops for joy and waves while it stands.- useEffect(() => useProgression.subscribe((state, prev) => {- if (state.cheerUntil > prev.cheerUntil && !reduced) pressJump(jump);- }), [jump, reduced]);- const level = useProgression((s) => (s.snapshot ? s.subjects[PERSON_SUBJECT]?.level ?? 1 : null));- const dressed = useDressedFigure("person", PERSON_SUBJECT, look);-- // Arrive by the elevator once per app run; coming back to the map keeps the- // character where it was, unless a changed floor plan put that spot in a wall.- useEffect(() => {- if (!awake) return;- player.path = []; player.moving = false;- if (officeSession.playerPlaced && isWalkable(grid, player)) return;- const start = (officeSession.playerPlaced ? nearestWalkable(grid, player) : null)- ?? nearestWalkable(grid, layout.spawn) ?? layout.spawn;- player.x = start.x; player.z = start.z;- if (!officeSession.playerPlaced) player.heading = Math.PI;- officeSession.playerPlaced = true;- }, [grid, layout.spawn, awake]);-- useFrame((_, rawDt) => {- // Aboard the courier the character goes nowhere: it steps out again beside the hatch (SkyCourier).- if (flying) { if (nearbyRef.current) { nearbyRef.current = null; useOfficeStore.getState().setNearby(null); } return; }- const dt = Math.min(rawDt, 0.1);- const store = useOfficeStore.getState();- // Sitting on the lead's chair: hold the seat until the person moves, walks- // somewhere else or presses E; then step out to the nearest free spot.- const seatState = useLeadSeat.getState();- const seatDesk = seatState.seated ? seatDesks(layout).find((d) => d.id === seatState.seated) : undefined;- const walkRequested = !!store.walkTo && store.walkTo.seq !== lastWalk.current;- if (seatState.seated && (!seatDesk || pressed.current.size > 0 || walkRequested)) seatState.set({ seated: null, standUp: true });- if (useLeadSeat.getState().standUp) {- const out = nearestWalkable(grid, player);- if (out) { player.x = out.x; player.z = out.z; }- player.path = [];- useLeadSeat.getState().set({ standUp: false });- }- if (useLeadSeat.getState().seated && seatDesk) {- const seat = seatOf(seatDesk);- player.x = seat.x; player.z = seat.z; player.heading = seat.facing; player.path = []; player.moving = false;- drive.current.mode = "sit";- drive.current.speed = 0;- Object.assign(jump, newJump());- body.current?.position.setY(0);- body.current?.scale.set(1, 1, 1);- group.current?.position.set(player.x, 0, player.z);- if (group.current) group.current.rotation.y = player.heading;- if (nearbyRef.current) { nearbyRef.current = null; store.setNearby(null); }- return;- }- // Clicked the chair from afar: sit as soon as the walk there ends beside it.- if (seatState.pending) {- const target = seatDesks(layout).find((d) => d.id === seatState.pending);- if (!target || pressed.current.size > 0) seatState.set({ pending: null });- else if (player.path.length === 0 && chairInReach([target], player)) seatState.set({ seated: target.id, pending: null });- }- // Click-to-move / "walk there" requests.- if (store.walkTo && store.walkTo.seq !== lastWalk.current) {- lastWalk.current = store.walkTo.seq;- // A target inside something solid or on somebody (a desk, a chair, a seated agent, the middle of the holo- // deck) is reached at a free standing place beside it: the character never comes to rest inside furniture- // or a figure, and never on a chair that is not its own to sit on.- const goal = store.walkTo.point;- const free = standingPlaceFor(layout, grid, goal, bodiesNear(null, goal, 4, null, []));- walk.current = free ? beginWalk(grid, player, free, bodiesNear(null, player, BODY_RANGE_M, null, others.current)) : null;- if (!walk.current) player.path = [];- }- // Keyboard movement, relative to where the camera looks; nothing while a dialog owns the keys.- if (forgetHeldKeysUnderDialog(pressed.current)) jumpHeld.current = false;- let ix = 0, iz = 0;- for (const code of pressed.current) { ix += MOVE_KEYS[code][0]; iz += MOVE_KEYS[code][1]; }- const sprinting = isRunning(run.current, useOfficeSettings.getState().alwaysRun);- const steering = ix !== 0 || iz !== 0 || player.path.length > 0;- stepJump(jump, dt, jumpHeld.current, sprinting && steering);- // A sprint jump carries its boost while airborne (eased in and out by stepJump).- const speed = (sprinting ? PLAYER_SPRINT_SPEED : PLAYER_WALK_SPEED) * jump.speedMul;- let moved = 0;- if (ix !== 0 || iz !== 0) {- // Standing inside something solid (a snapped walk ended in it): step out first, or no move is ever free.- if (!isWalkable(grid, player)) {- const out = nearestWalkable(grid, player);- if (out) { player.x = out.x; player.z = out.z; }- }- player.path = [];- camera.getWorldDirection(forward);- forward.y = 0;- if (forward.lengthSq() < 1e-6) forward.set(0, 0, -1);- forward.normalize();- // Right = forward × up.- const rx = -forward.z, rz = forward.x;- let dx = forward.x * iz + rx * ix, dz = forward.z * iz + rz * ix;- const len = Math.hypot(dx, dz);- dx /= len; dz /= len;- const step = speed * dt;- const nx = player.x + dx * step, nz = player.z + dz * step;- // Slide along walls and around people: full move, else each axis alone.- // Moving away from someone you already touch is always allowed, so nobody gets stuck.- const free = (p: { x: number; z: number }) => isWalkable(grid, p) && stepClearOfBodies(p, player, bodiesExcept(null, null));- if (free({ x: nx, z: nz })) { player.x = nx; player.z = nz; moved = step; }- else if (free({ x: nx, z: player.z })) { player.x = nx; moved = Math.abs(dx * step); }- else if (free({ x: player.x, z: nz })) { player.z = nz; moved = Math.abs(dz * step); }- player.heading = turnToward(player.heading, Math.atan2(dx, dz), 12 * dt);- if (!store.follow) store.setFollow(true);- } else if (player.path.length > 0 && walk.current) {- // Round people and furniture, never through them; a walk that cannot go on stops where it is. A long- // route is jogged and ends in a walk; Shift (or "always run") sprints all the way.- const pace = sprinting ? speed : clickPaceFor(walk.current.remaining, PLAYER_WALK_SPEED, PLAYER_SPRINT_SPEED) * jump.speedMul;- const step = advanceWalk(walk.current, player, grid, dt, bodiesNear(null, player, BODY_RANGE_M, null, others.current), { speed: pace, place: false });- moved = step.moved;- if (step.arrived || step.event === "lost" || step.event === "blocked") { player.path = []; walk.current = null; }- } else if (player.path.length > 0) {- player.path = [];- }- // Never inside furniture or beyond the floor: whatever left the standing character in a solid cell (a floor- // plan rebuilt under it, a seat it was lifted out of) puts it on the nearest free ground.- if (player.path.length === 0 && !isWalkable(grid, player)) {- const out = nearestWalkable(grid, player, RESCUE_RANGE_M) ?? nearestWalkable(grid, layout.spawn) ?? layout.spawn;- player.x = out.x; player.z = out.z;- }- player.moving = moved > 0;- drive.current.mode = moved > 0 ? "walk" : performance.now() < useProgression.getState().cheerUntil ? "wave" : "idle";- drive.current.speed = moved / Math.max(dt, 1e-3);- if (group.current) {- group.current.position.set(player.x, 0, player.z);- group.current.rotation.y = player.heading;- }- // The body rides the hop; the gold ring stays on the floor as its shadow.- if (body.current) {- body.current.position.y = jump.y;- const [sw, sh] = reduced ? [1, 1] : jumpSquash(jump);- body.current.scale.set(sw, sh, sw);- }- if (ring.current) ring.current.scale.setScalar(1 - Math.min(0.35, jump.y * 0.6));- if (ring.current) (ring.current.material as MeshBasicMaterial).opacity = reduced ? 0.8 : 0.6 + Math.sin(performance.now() / 400) * 0.2;- // What can the character reach right now? The lead's chair has its own prompt beside it.- const chair = chairInReach(seatDesks(layout), player);- if (useLeadSeat.getState().near !== (chair?.id ?? null)) useLeadSeat.getState().set({ near: chair?.id ?? null });- const nearby = chair ? null : nearestInteractable(layout, player, agentPositions, companions, REACH);- // Compared with the store too: a floor switch clears the store's reading while the character still stands at the elevator.- if (!sameSelection(nearby, nearbyRef.current) || !sameSelection(nearby, store.nearby)) { nearbyRef.current = nearby; store.setNearby(nearby); }- });-- return (- <>- <RouteMarker animate={awake && !reduced} />- <group ref={group} visible={!firstPerson && !flying}>- <mesh ref={ring} rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.02, 0]}>- <ringGeometry args={[0.42, 0.52, 40]} />- <meshBasicMaterial color="#f5b83d" transparent opacity={0.8} side={DoubleSide} depthWrite={false} />- </mesh>- <group ref={body}>- <ToyFigure look={dressed.look} drive={drive} paused={!awake} heightM={OFFICE_FIGURE_HEIGHT_M} holding={hasBone ? <TreatBone scale={1.15} /> : undefined}- regalia={dressed.regalia} />- {!firstPerson && (- <Html center position={[0, OFFICE_FIGURE_HEIGHT_M + 0.35, 0]} zIndexRange={[25, 0]}>- <span className="office-plate office-plate-player" data-office-ui>- <span className="office-plate-badge" style={{ background: "#f5b83d" }} aria-hidden>★</span>- <span className="office-plate-name">{name}</span>- {level !== null && <LevelChip kind="person" level={level} />}- </span>- </Html>- )}- </group>- </group>- </>- );-}--/**- * Where a click sends the character: dots along the route and a ring at its- * end, shown while a click-to-move walk is under way. It reads the route the- * character is following, so it shortens as the walk goes on and vanishes on- * arrival or when the keyboard takes over. Takes no pointer events.- */-function RouteMarker({ animate }: { animate: boolean }) {- const dots = useRef<InstancedMesh>(null);- const goal = useRef<Group>(null);- const pulse = useRef<Mesh>(null);- const dummy = useMemo(() => new Object3D(), []);- useFrame(({ clock }) => {- const path = player.path;- const showing = path.length > 0;- if (goal.current) goal.current.visible = showing;- if (dots.current) dots.current.visible = showing;- if (!showing || !goal.current || !dots.current) return;- const end = path[path.length - 1];- goal.current.position.set(end.x, MARKER.y, end.z);- if (pulse.current) {- const beat = animate ? (clock.elapsedTime * 1.4) % 1 : 0.35;- pulse.current.scale.setScalar(0.7 + beat * 0.9);- (pulse.current.material as MeshBasicMaterial).opacity = animate ? 0.6 * (1 - beat) : 0.4;- }- const marks = routeMarks(player, path, 0.9, MARKER.dots);- marks.forEach((mark, i) => {- dummy.position.set(mark.x, MARKER.y, mark.z);- dummy.rotation.set(-Math.PI / 2, 0, 0);- dummy.updateMatrix();- dots.current!.setMatrixAt(i, dummy.matrix);- });- dots.current.count = marks.length;- dots.current.instanceMatrix.needsUpdate = true;- });- return (- <>- <instancedMesh ref={dots} args={[undefined, undefined, MARKER.dots]} visible={false} frustumCulled={false} raycast={() => null}>- <circleGeometry args={[0.07, 12]} />- <meshBasicMaterial color={MARKER.colour} transparent opacity={0.7} side={DoubleSide} depthWrite={false} />- </instancedMesh>- <group ref={goal} visible={false}>- <mesh rotation={[-Math.PI / 2, 0, 0]} raycast={() => null}>- <ringGeometry args={[0.2, 0.27, 32]} />- <meshBasicMaterial color={MARKER.colour} transparent opacity={0.9} side={DoubleSide} depthWrite={false} />- </mesh>- <mesh rotation={[-Math.PI / 2, 0, 0]} raycast={() => null}>- <circleGeometry args={[0.07, 16]} />- <meshBasicMaterial color={MARKER.colour} transparent opacity={0.9} side={DoubleSide} depthWrite={false} />- </mesh>- <mesh ref={pulse} rotation={[-Math.PI / 2, 0, 0]} raycast={() => null}>- <ringGeometry args={[0.3, 0.34, 32]} />- <meshBasicMaterial color={MARKER.colour} transparent opacity={0.4} side={DoubleSide} depthWrite={false} />- </mesh>- </group>- </>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeProps.test.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeProps.test.tsxdeleted file mode 100644index 355a3e610c..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeProps.test.tsx+++ /dev/null@@ -1,88 +0,0 @@-import { afterEach, describe, expect, it } from "vitest";-import { act, createRoot, extend, type ReconcilerRoot } from "@react-three/fiber";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import * as THREE from "three";-import { Box3, type Object3D } from "three";-import { FURNITURE_SIZE, type Furniture, type FurnitureKind } from "./officeLayout";-import { FurniturePiece, MeetingChairs, PROP_RENDERERS } from "./OfficeProps";--/** Just enough of a WebGLRenderer for R3F to mount a scene graph without a GPU. */-function fakeRenderer(canvas: HTMLCanvasElement) {- const noop = () => undefined;- return {- domElement: canvas,- render: noop, setSize: noop, setPixelRatio: noop, setAnimationLoop: noop, dispose: noop,- getPixelRatio: () => 1,- shadowMap: { enabled: false, type: 0, needsUpdate: false },- xr: { enabled: false, isPresenting: false, addEventListener: noop, removeEventListener: noop, setAnimationLoop: noop },- outputColorSpace: "srgb", toneMapping: 0, toneMappingExposure: 1,- info: { render: {}, memory: {} },- };-}--// <Canvas> registers the three namespace; a bare root must do it itself.-extend(THREE);--let root: ReconcilerRoot<HTMLCanvasElement> | null = null;--async function mount(element: JSX.Element): Promise<Object3D> {- const canvas = document.createElement("canvas");- const current = createRoot(canvas);- root = current;- current.configure({- // Test double: R3F only needs the renderer's shape here, nothing is drawn.- gl: fakeRenderer(canvas) as unknown as NonNullable<Parameters<typeof current.configure>[0]>["gl"],- frameloop: "never",- size: { width: 100, height: 100, top: 0, left: 0 },- });- let captured: Object3D | null = null;- await act(async () => {- // Some props read app data (the server room's wall reads Spend): give them a client that never retries.- current.render(- <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>- <group ref={(g) => { captured = g; }}>{element}</group>- </QueryClientProvider>,- );- });- if (!captured) throw new Error("the element did not mount");- return captured;-}--afterEach(() => {- root?.unmount();- root = null;-});--const KINDS = Object.keys(FURNITURE_SIZE) as FurnitureKind[];--// Every case mounts a scene graph; on a loaded runner the first mounts share the suite's start-up cost.-describe("office props", { timeout: 20_000 }, () => {- it("has a renderer for every furniture kind", () => {- expect(Object.keys(PROP_RENDERERS).sort()).toEqual([...KINDS].sort());- });-- it.each(KINDS)("%s stays inside its footprint", async (kind) => {- const size = kind === "rug" ? { w: 3, d: 2 } : undefined;- const item: Furniture = { id: `test-${kind}`, kind, x: 0, z: 0, rotationY: 0, room: "floor", size };- const group = await mount(<FurniturePiece item={item} />);- group.updateMatrixWorld(true);- const box = new Box3().setFromObject(group);- const { w, d, h } = { ...FURNITURE_SIZE[kind], ...(size ?? {}) };- const eps = 0.02;- expect(box.min.x).toBeGreaterThanOrEqual(-w / 2 - eps);- expect(box.max.x).toBeLessThanOrEqual(w / 2 + eps);- expect(box.min.z).toBeGreaterThanOrEqual(-d / 2 - eps);- expect(box.max.z).toBeLessThanOrEqual(d / 2 + eps);- expect(box.min.y).toBeGreaterThanOrEqual(-eps);- expect(box.max.y).toBeLessThanOrEqual(Math.max(h, 0.03) + 0.05);- });-- it("puts the meeting chairs on both long sides, outside the table", async () => {- const table: Furniture = { id: "t", kind: "meetingTable", x: 0, z: 0, rotationY: 0, room: "team" };- const group = await mount(<MeetingChairs table={table} />);- group.updateMatrixWorld(true);- const box = new Box3().setFromObject(group);- expect(box.min.z).toBeLessThan(-FURNITURE_SIZE.meetingTable.d / 2);- expect(box.max.z).toBeGreaterThan(FURNITURE_SIZE.meetingTable.d / 2);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeProps.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeProps.tsxdeleted file mode 100644index 2a9f0d389d..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeProps.tsx+++ /dev/null@@ -1,590 +0,0 @@-/**- * Room props for the walkable office: every `FurnitureKind` in the toy-office- * style (docs/agent-society/office-map.md §2) — rounded primitives, matte- * colours, and a few simple canvas-drawn faces (screens, board, mirror).- *- * Every piece is built in local space centred on the origin, front facing +z,- * and stays inside its `FURNITURE_SIZE` box (w along x, d along z, height h):- * navigation walks around exactly that footprint. Geometries, materials and- * canvas textures are module-level singletons shared by every copy.- */-import { memo } from "react";-import { useT } from "@/i18n";-import { CylinderGeometry, MeshStandardMaterial, SphereGeometry } from "three";-import { canvasMaterial } from "./canvasMaterials";-import { LEAD_RENDERERS } from "./LeadSuite";-import { COMMAND_RENDERERS } from "./CommandOffice";-import { SERVER_RENDERERS } from "./ServerRoom";-import { TEAM_RENDERERS } from "./TeamRoomDecor";-import { BREAK_RENDERERS } from "./BreakLounge";-import { WARDROBE_RENDERERS } from "./WardrobeRoom";-import { LOBBY_RENDERERS } from "./LobbyDecor";-import { SPAWN_RENDERERS } from "./SpawnPoint";-import { LEVEL_HALL_RENDERERS } from "./LevelHall";-import { STUDIO_RENDERERS } from "./StudioBoard";-import { StaticBatch } from "./StaticBatch";-import { ARCADE_RENDERERS } from "../arcade/ArcadeHallProps";-import { MeetingChair } from "./OfficeChairs";-import { Bookshelf, Box, Couch, GEO, MAT, matte, Plant, Rounded, Rug } from "./OfficeFurniture";-import { FURNITURE_SIZE, type Furniture, type FurnitureKind } from "./officeLayout";-import { PROP_COLOURS as P } from "./officePalette";--type Vec3 = [number, number, number];--function roundRect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number): void {- ctx.beginPath();- ctx.moveTo(x + r, y);- ctx.arcTo(x + w, y, x + w, y + h, r);- ctx.arcTo(x + w, y + h, x, y + h, r);- ctx.arcTo(x, y + h, x, y, r);- ctx.arcTo(x, y, x + w, y, r);- ctx.closePath();-}--/**- * Reception's help display: the map's main keys as key caps, each over a gold- * pictogram of what it does (walk, run, use, map, help). Shapes only, no words,- * so it reads the same in every language.- */-function drawReceptionHelp(ctx: CanvasRenderingContext2D, w: number, h: number): void {- const bg = ctx.createLinearGradient(0, 0, 0, h);- bg.addColorStop(0, "#1a2742");- bg.addColorStop(1, "#0f1628");- ctx.fillStyle = bg;- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "#f5b83d";- ctx.fillRect(0, 0, w, 7);- const cap = (x: number, y: number, cw: number, label: string) => {- ctx.fillStyle = "#0a0f1c";- roundRect(ctx, x, y + 5, cw, 46, 9);- ctx.fill();- ctx.fillStyle = "#eef2f8";- roundRect(ctx, x, y, cw, 44, 9);- ctx.fill();- ctx.fillStyle = "#1a2742";- ctx.font = "700 24px system-ui, sans-serif";- ctx.textAlign = "center";- ctx.textBaseline = "middle";- ctx.fillText(label, x + cw / 2, y + 23);- };- const gold = () => { ctx.strokeStyle = "#f5b83d"; ctx.fillStyle = "#f5b83d"; ctx.lineWidth = 5; ctx.lineCap = "round"; ctx.lineJoin = "round"; };- const iy = 150;- // WASD cluster over a four-way arrow.- const kx = 26, ky = 30, kw = 44;- cap(kx + kw + 6, ky, kw, "W");- cap(kx, ky + 52, kw, "A"); cap(kx + kw + 6, ky + 52, kw, "S"); cap(kx + 2 * (kw + 6), ky + 52, kw, "D");- gold();- const cx = kx + 1.5 * kw + 6;- ctx.beginPath();- ctx.moveTo(cx - 22, iy); ctx.lineTo(cx + 22, iy); ctx.moveTo(cx, iy - 16); ctx.lineTo(cx, iy + 16);- ctx.moveTo(cx - 14, iy - 7); ctx.lineTo(cx - 22, iy); ctx.lineTo(cx - 14, iy + 7);- ctx.moveTo(cx + 14, iy - 7); ctx.lineTo(cx + 22, iy); ctx.lineTo(cx + 14, iy + 7);- ctx.stroke();- // Shift: a double chevron (run).- const col = (x: number, cw: number, label: string, icon: (x: number) => void) => { cap(x, 56, cw, label); gold(); icon(x + cw / 2); };- col(186, 92, "Shift", (x) => {- ctx.beginPath();- for (const dx of [-12, 6]) { ctx.moveTo(x + dx, iy - 12); ctx.lineTo(x + dx + 12, iy); ctx.lineTo(x + dx, iy + 12); }- ctx.stroke();- });- // E: a filled ring (use what is nearby).- col(298, 52, "E", (x) => {- ctx.beginPath(); ctx.arc(x, iy, 14, 0, Math.PI * 2); ctx.stroke();- ctx.beginPath(); ctx.arc(x, iy, 5, 0, Math.PI * 2); ctx.fill();- });- // M: a folded map.- col(370, 52, "M", (x) => {- ctx.beginPath();- ctx.moveTo(x - 18, iy - 10); ctx.lineTo(x - 6, iy - 15); ctx.lineTo(x + 6, iy - 10); ctx.lineTo(x + 18, iy - 15);- ctx.lineTo(x + 18, iy + 10); ctx.lineTo(x + 6, iy + 15); ctx.lineTo(x - 6, iy + 10); ctx.lineTo(x - 18, iy + 15); ctx.closePath();- ctx.moveTo(x - 6, iy - 15); ctx.lineTo(x - 6, iy + 10); ctx.moveTo(x + 6, iy - 10); ctx.lineTo(x + 6, iy + 15);- ctx.stroke();- });- // H: a question mark in a ring (help), the key the whole guide hangs on.- col(442, 52, "H", (x) => {- ctx.beginPath(); ctx.arc(x, iy, 17, 0, Math.PI * 2); ctx.stroke();- ctx.beginPath(); ctx.arc(x, iy - 4, 6, Math.PI * 1.05, Math.PI * 2.3); ctx.lineTo(x, iy + 5); ctx.stroke();- ctx.beginPath(); ctx.arc(x, iy + 11, 2.6, 0, Math.PI * 2); ctx.fill();- });-}--/** The gold info sign on the reception counter's front (drawn on a disc, so the square corners never show). */-function drawInfoSign(ctx: CanvasRenderingContext2D, w: number, h: number): void {- ctx.clearRect(0, 0, w, h);- const r = w / 2 - 4;- const disc = ctx.createRadialGradient(w * 0.42, h * 0.38, r * 0.1, w / 2, h / 2, r);- disc.addColorStop(0, "#ffe19a");- disc.addColorStop(1, "#f0a92b");- ctx.fillStyle = disc;- ctx.beginPath(); ctx.arc(w / 2, h / 2, r, 0, Math.PI * 2); ctx.fill();- ctx.strokeStyle = "rgba(255,255,255,0.55)";- ctx.lineWidth = w * 0.025;- ctx.beginPath(); ctx.arc(w / 2, h / 2, r * 0.86, 0, Math.PI * 2); ctx.stroke();- // The "i": a dot over a rounded stem.- ctx.fillStyle = "#2a1a04";- ctx.beginPath(); ctx.arc(w / 2, h * 0.3, w * 0.075, 0, Math.PI * 2); ctx.fill();- roundRect(ctx, w / 2 - w * 0.065, h * 0.43, w * 0.13, h * 0.34, w * 0.05);- ctx.fill();-}--/** Arcade screen: the Asteroid Run attract screen, a rocket among faceted rocks. */-function drawArcade(ctx: CanvasRenderingContext2D, w: number, h: number): void {- const sky = ctx.createLinearGradient(0, 0, 0, h);- sky.addColorStop(0, "#07060f");- sky.addColorStop(1, "#171133");- ctx.fillStyle = sky;- ctx.fillRect(0, 0, w, h);- // Warp streaks running out from the vanishing point.- const vx = w * 0.52, vy = h * 0.42;- ctx.lineCap = "round";- for (let i = 0; i < 46; i += 1) {- const a = (i * 2.399) % (Math.PI * 2), r0 = 14 + ((i * 37) % 60), len = 8 + ((i * 13) % 22);- ctx.strokeStyle = `rgba(201, 212, 255, ${0.25 + ((i * 7) % 10) / 20})`;- ctx.lineWidth = 1 + (i % 3) * 0.5;- ctx.beginPath();- ctx.moveTo(vx + Math.cos(a) * r0, vy + Math.sin(a) * r0);- ctx.lineTo(vx + Math.cos(a) * (r0 + len), vy + Math.sin(a) * (r0 + len));- ctx.stroke();- }- // Low-poly rocks: a fan of facets, each triangle shaded by its facing.- const rock = (cx: number, cy: number, r: number, seed: number) => {- const n = 7;- const pts = Array.from({ length: n }, (_, i) => {- const a = (i / n) * Math.PI * 2 + seed, k = 0.75 + (((seed * 31 + i * 17) % 10) / 10) * 0.4;- return [cx + Math.cos(a) * r * k, cy + Math.sin(a) * r * k] as const;- });- const hub = [cx - r * 0.15, cy - r * 0.2] as const;- pts.forEach((p, i) => {- const q = pts[(i + 1) % n];- const light = 0.45 + 0.4 * Math.max(0, Math.cos((i / n) * Math.PI * 2 + seed - 2.3));- ctx.fillStyle = `rgb(${Math.round(120 * light + 60)}, ${Math.round(128 * light + 62)}, ${Math.round(165 * light + 70)})`;- ctx.beginPath(); ctx.moveTo(hub[0], hub[1]); ctx.lineTo(p[0], p[1]); ctx.lineTo(q[0], q[1]); ctx.closePath(); ctx.fill();- });- };- rock(w * 0.84, h * 0.2, 24, 1);- rock(w * 0.16, h * 0.3, 15, 2);- rock(w * 0.62, h * 0.24, 9, 3);- rock(w * 0.3, h * 0.62, 7, 4);- rock(w * 0.82, h * 0.7, 17, 5);- // The rocket, flying into the screen: exhaust, fins, body, nose, window.- const rx = w * 0.46, ry = h * 0.7;- ctx.save();- ctx.translate(rx, ry);- ctx.rotate(-0.5);- ctx.fillStyle = "#ffcc33";- ctx.beginPath(); ctx.moveTo(-7, 14); ctx.lineTo(0, 44); ctx.lineTo(7, 14); ctx.closePath(); ctx.fill();- ctx.fillStyle = "#e0443e";- ctx.beginPath(); ctx.moveTo(-9, 2); ctx.lineTo(-20, 18); ctx.lineTo(-8, 14); ctx.closePath(); ctx.fill();- ctx.beginPath(); ctx.moveTo(9, 2); ctx.lineTo(20, 18); ctx.lineTo(8, 14); ctx.closePath(); ctx.fill();- ctx.fillStyle = "#eef2f8";- ctx.fillRect(-9, -16, 18, 30);- ctx.fillStyle = "#3b82f6";- ctx.fillRect(-9, -6, 18, 5);- ctx.beginPath(); ctx.moveTo(-9, -16); ctx.lineTo(0, -32); ctx.lineTo(9, -16); ctx.closePath(); ctx.fill();- ctx.restore();- // A laser bolt and the score line.- ctx.strokeStyle = "#ffe066";- ctx.lineWidth = 2.5;- ctx.beginPath(); ctx.moveTo(w * 0.55, h * 0.48); ctx.lineTo(w * 0.6, h * 0.36); ctx.stroke();- ctx.fillStyle = "#e6ebff";- for (let i = 0; i < 4; i += 1) ctx.fillRect(12 + i * 10, 10, 7, 7);- ctx.fillStyle = "#facc15";- ctx.fillRect(12, 22, 54, 3);-}--/** Elevator floor indicator: an amber "up" arrow and a dim "down" arrow. */-function drawIndicator(ctx: CanvasRenderingContext2D, w: number, h: number): void {- ctx.fillStyle = "#111318";- ctx.fillRect(0, 0, w, h);- const arrow = (cx: number, up: boolean, colour: string) => {- ctx.fillStyle = colour;- ctx.beginPath();- const s = up ? -1 : 1;- ctx.moveTo(cx, h / 2 + s * 14);- ctx.lineTo(cx - 14, h / 2 - s * 10);- ctx.lineTo(cx + 14, h / 2 - s * 10);- ctx.closePath();- ctx.fill();- };- arrow(w * 0.3, true, P.indicator);- arrow(w * 0.7, false, "#4b5160");-}--/** Mirror glass: a cool gradient with two soft diagonal highlights. */-function drawMirror(ctx: CanvasRenderingContext2D, w: number, h: number): void {- const grad = ctx.createLinearGradient(0, 0, w, h);- grad.addColorStop(0, "#f1f9fe");- grad.addColorStop(1, "#b9d7ea");- ctx.fillStyle = grad;- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "rgba(255,255,255,0.55)";- for (const [x, width] of [[0.15, 0.18], [0.5, 0.08]] as const) {- ctx.beginPath();- ctx.moveTo(w * x, h);- ctx.lineTo(w * (x + width), h);- ctx.lineTo(w * (x + width + 0.6), 0);- ctx.lineTo(w * (x + 0.6), 0);- ctx.closePath();- ctx.fill();- }-}--/** Coffee menu chalkboard. */-function drawMenu(ctx: CanvasRenderingContext2D, w: number, h: number, title: string): void {- ctx.fillStyle = P.chalkboard;- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "#f8fafc";- ctx.font = "700 36px system-ui, -apple-system, 'Segoe UI', sans-serif";- ctx.textAlign = "center";- ctx.textBaseline = "middle";- ctx.fillText(title, w / 2, 34, w - 24);- for (let i = 0; i < 4; i += 1) {- const y = 78 + i * 28;- ctx.fillStyle = "rgba(248,250,252,0.8)";- ctx.fillRect(24, y, 90 + ((i * 29) % 50), 7);- ctx.fillStyle = "#fde68a";- ctx.fillRect(w - 58, y, 34, 7);- }-}--// ----------------------------------------------------------------------------// Shared materials and geometries-// -----------------------------------------------------------------------------const PM = {- steel: matte(P.steel, { roughness: 0.35, metalness: 0.25 }),- steelDark: matte(P.steelDark, { roughness: 0.45, metalness: 0.2 }),- shaft: matte(P.elevatorShaft),- lockers: P.lockers.map((c) => matte(c)),- lockerVent: matte(P.lockerVent),- mug: matte(P.mug),- coffee: matte(P.coffee),- espresso: matte(P.espresso, { roughness: 0.35, metalness: 0.25 }),- arcadeBody: matte(P.arcadeBody),- arcadeTrim: matte(P.arcadeTrim),- marquee: matte(P.arcadeMarquee, { emissive: P.arcadeMarquee, emissiveIntensity: 0.8 }),- joystick: matte(P.joystick, { roughness: 0.4 }),- arcadeButtons: P.arcadeButtons.map((c) => matte(c, { emissive: c, emissiveIntensity: 0.35 })),- bell: matte(P.bell, { roughness: 0.35, metalness: 0.3 }),- boardFrame: matte(P.boardFrame),- displayFrame: matte(P.displayFrame, { roughness: 0.5 }),- paper: matte(P.paper),- rugInner: matte(P.rugInner),- gold: matte("#f5b83d", { emissive: "#f5b83d", emissiveIntensity: 0.6 }),- brochures: P.lockers.map((c) => matte(c, { roughness: 0.8 })),- indicatorLight: matte(P.indicator, { emissive: P.indicator, emissiveIntensity: 0.9 }),-};--const lazy = {- receptionHelp: () => canvasMaterial("prop:receptionHelp", 512, 192, drawReceptionHelp, { glow: 0.85, fallback: "#1a2742", roughness: 0.4 }),- infoSign: () => canvasMaterial("prop:infoSign", 256, 256, drawInfoSign, { glow: 0.7, fallback: "#f5b83d", roughness: 0.4 }),- arcade: () => canvasMaterial("prop:arcade", 256, 200, drawArcade, { glow: 1, fallback: "#07060f", roughness: 0.4 }),- indicator: () => canvasMaterial("prop:indicator", 128, 48, drawIndicator, { glow: 0.9, fallback: "#111318", roughness: 0.4 }),- mirror: () => canvasMaterial("prop:mirror", 128, 256, drawMirror, { glow: 0.25, fallback: P.mirror, roughness: 0.1 }),- menu: (title: string) => canvasMaterial(`prop:menu:${title}`, 256, 192, (ctx, w, h) => drawMenu(ctx, w, h, title), { glow: 0.15, fallback: P.chalkboard, roughness: 0.9 }),-};--const PGEO = {- cyl: new CylinderGeometry(1, 1, 1, 20),- sphere: new SphereGeometry(1, 20, 14),- dome: new SphereGeometry(1, 16, 8, 0, Math.PI * 2, 0, Math.PI / 2),-};--function Cyl({ radius, height, position, material, cast = true }: {- radius: number; height: number; position: Vec3; material: MeshStandardMaterial; cast?: boolean;-}) {- return <mesh geometry={PGEO.cyl} material={material} position={position} scale={[radius, height, radius]} castShadow={cast} receiveShadow />;-}--function Panel({ size, position, material, rotation }: {- size: [number, number]; position: Vec3; material: MeshStandardMaterial; rotation?: Vec3;-}) {- return (- <mesh position={position} rotation={rotation} material={material}>- <planeGeometry args={size} />- </mesh>- );-}--// ----------------------------------------------------------------------------// Props (local space: centred on the origin, front faces +z)-// -----------------------------------------------------------------------------/**- * Six chairs around a meeting table: three per long side at local x = -1.1, 0,- * +1.1 and z = ∓1.25, each facing the table. They sit outside the table's- * footprint and are not navigation obstacles (they match the `meeting-*` spots).- */-export function MeetingChairs({ table }: { table: Furniture }) {- return (- <group position={[table.x, 0, table.z]} rotation={[0, table.rotationY, 0]}>- {[-1.1, 0, 1.1].map((x) => (- <group key={x}>- <group position={[x, 0, -1.25]}><MeetingChair /></group>- <group position={[x, 0, 1.25]} rotation={[0, Math.PI, 0]}><MeetingChair /></group>- </group>- ))}- </group>- );-}--/**- * Reception counter: the visitor side (+z) is a high white counter with a- * wood top and a service bell; the receptionist side (-z) is a lower work- * surface whose monitor faces -z.- */-/** Vertical slat positions across the reception back wall. */-const RECEPTION_SLATS = Array.from({ length: 15 }, (_, i) => -1.26 + i * 0.18);--/**- * Reception counter, the office's help desk. Visitor side (+z): a white- * counter on a dark plinth with wood end caps, a wood feature panel carrying- * a glowing gold info sign, gold light lines under the lip and along the- * floor, and on the wood top a service bell, a brochure stand and a small- * plant. Behind it a slatted wood wall holds the help display with the map's- * main keys, so the desk reads as "ask here" from across the floor.- */-function ReceptionDesk() {- return (- <group>- {/* Back wall: dark panel, light slats, a gold light line on top. */}- <Box size={[2.8, 2.1, 0.05]} position={[0, 1.05, -0.42]} material={MAT.woodDark} />- {RECEPTION_SLATS.map((x) => <Box key={x} size={[0.07, 2.02, 0.03]} position={[x, 1.05, -0.38]} material={MAT.wood} />)}- <Box size={[2.8, 0.05, 0.1]} position={[0, 2.125, -0.405]} material={MAT.woodDark} />- <Box size={[2.7, 0.018, 0.02]} position={[0, 2.09, -0.345]} material={PM.gold} cast={false} />- {/* Help display on the wall, facing the visitors. */}- <Rounded size={[1.56, 0.64, 0.05]} radius={0.03} position={[0, 1.62, -0.34]} material={PM.displayFrame} />- <Panel size={[1.46, 0.548]} position={[0, 1.62, -0.3135]} material={lazy.receptionHelp()} />- <Box size={[0.6, 0.02, 0.012]} position={[0, 1.95, -0.32]} material={PM.gold} cast={false} />-- {/* Receptionist side: a low work surface on two pedestals and a keyboard. */}- <Rounded size={[2.5, 0.04, 0.3]} radius={0.015} position={[0, 0.74, -0.17]} material={MAT.deskTop} />- <Box size={[0.36, 0.72, 0.26]} position={[-1.05, 0.36, -0.17]} material={MAT.deskBody} />- <Box size={[0.36, 0.72, 0.26]} position={[1.05, 0.36, -0.17]} material={MAT.deskBody} />- <Box size={[0.4, 0.02, 0.12]} position={[0.2, 0.77, -0.2]} material={MAT.keyboard} />-- {/* Visitor counter: plinth, body and wood end caps (body stops short of the caps: no coplanar faces). */}- <Box size={[2.64, 0.08, 0.34]} position={[0, 0.04, 0.22]} material={MAT.woodDark} />- <Box size={[2.5, 0.012, 0.012]} position={[0, 0.07, 0.395]} material={PM.gold} cast={false} />- <Rounded size={[2.6, 0.9, 0.38]} radius={0.12} position={[0, 0.53, 0.24]} material={MAT.deskBody} />- <Rounded size={[0.1, 0.96, 0.42]} radius={0.03} position={[-1.35, 0.5, 0.23]} material={MAT.wood} />- <Rounded size={[0.1, 0.96, 0.42]} radius={0.03} position={[1.35, 0.5, 0.23]} material={MAT.wood} />- <Rounded size={[2.8, 0.05, 0.46]} radius={0.02} position={[0, 1.005, 0.22]} material={MAT.wood} />- <Box size={[2.5, 0.016, 0.012]} position={[0, 0.965, 0.432]} material={PM.gold} cast={false} />- {/* Front feature panel with the info sign. */}- <Rounded size={[0.92, 0.62, 0.03]} radius={0.02} position={[0, 0.52, 0.43]} material={MAT.wood} />- <mesh position={[0, 0.54, 0.448]} material={lazy.infoSign()}>- <circleGeometry args={[0.2, 40]} />- </mesh>-- {/* On the counter: service bell, brochure stand, a small plant. */}- <Cyl radius={0.07} height={0.012} position={[0.95, 1.036, 0.26]} material={MAT.monitor} />- <mesh geometry={PGEO.dome} material={PM.bell} position={[0.95, 1.042, 0.26]} scale={0.055} castShadow />- <mesh geometry={PGEO.sphere} material={PM.bell} position={[0.95, 1.1, 0.26]} scale={0.012} />- <Box size={[0.34, 0.02, 0.12]} position={[-0.9, 1.04, 0.24]} material={PM.displayFrame} />- {P.lockers.slice(0, 3).map((colour, i) => (- <group key={colour} position={[-1.01 + i * 0.11, 1.11, 0.24]} rotation={[-0.2, 0, 0]}>- <Box size={[0.085, 0.13, 0.01]} position={[0, 0, 0]} material={PM.brochures[i]!} />- </group>- ))}- <Cyl radius={0.05} height={0.07} position={[-0.35, 1.065, 0.3]} material={MAT.pot} />- <mesh geometry={GEO.blob} material={MAT.leaf} position={[-0.35, 1.13, 0.3]} scale={[0.07, 0.06, 0.07]} castShadow />- <mesh geometry={GEO.blob} material={MAT.leafDark} position={[-0.32, 1.17, 0.29]} scale={0.035} castShadow />- </group>- );-}--/** A row of four coloured lockers, doors facing +z. */-function Lockers() {- return (- <group>- <Box size={[2.4, 0.05, 0.46]} position={[0, 0.025, 0]} material={MAT.deskLeg} />- {PM.lockers.map((material, i) => {- const x = -0.9 + i * 0.6;- return (- <group key={i}>- <Rounded size={[0.57, 1.8, 0.46]} radius={0.03} position={[x, 0.95, 0]} material={material} />- {[1.6, 1.66, 1.72].map((y) => <Box key={y} size={[0.3, 0.025, 0.01]} position={[x, y, 0.232]} material={PM.lockerVent} cast={false} />)}- <Box size={[0.03, 0.14, 0.03]} position={[x + 0.2, 1.0, 0.235]} material={PM.steelDark} cast={false} />- </group>- );- })}- <Box size={[2.4, 0.04, 0.48]} position={[0, 1.87, 0]} material={MAT.deskBody} />- </group>- );-}--/** Tall standing mirror in a wood frame; the glass faces +z. */-function Mirror() {- return (- <group>- <Box size={[0.14, 0.05, 0.12]} position={[-0.33, 0.025, 0]} material={MAT.woodDark} />- <Box size={[0.14, 0.05, 0.12]} position={[0.33, 0.025, 0]} material={MAT.woodDark} />- <Rounded size={[0.9, 1.84, 0.07]} radius={0.03} position={[0, 0.97, -0.02]} material={MAT.wood} />- <Panel size={[0.74, 1.66]} position={[0, 0.97, 0.0155]} material={lazy.mirror()} />- </group>- );-}--/** Coffee counter with an espresso machine, cups and a small menu board; service side faces +z. */-function CoffeeBar() {- const t = useT();- return (- <group>- <Rounded size={[2.4, 0.68, 0.62]} radius={0.04} position={[0, 0.34, 0.03]} material={MAT.deskBody} />- {[-0.78, 0, 0.78].map((x) => <Box key={x} size={[0.7, 0.5, 0.012]} position={[x, 0.33, 0.342]} material={MAT.wood} cast={false} />)}- <Rounded size={[2.4, 0.04, 0.68]} radius={0.015} position={[0, 0.7, 0.01]} material={MAT.woodDark} />- {/* Espresso machine. */}- <Rounded size={[0.5, 0.3, 0.34]} radius={0.04} position={[-0.65, 0.87, -0.1]} material={PM.espresso} />- <Box size={[0.4, 0.08, 0.01]} position={[-0.65, 0.95, 0.072]} material={MAT.monitor} cast={false} />- <Box size={[0.08, 0.05, 0.08]} position={[-0.72, 0.82, 0.1]} material={PM.steelDark} />- <Box size={[0.08, 0.05, 0.08]} position={[-0.58, 0.82, 0.1]} material={PM.steelDark} />- <Box size={[0.32, 0.015, 0.12]} position={[-0.65, 0.728, 0.12]} material={PM.steelDark} cast={false} />- <Cyl radius={0.035} height={0.06} position={[-0.72, 0.765, 0.12]} material={PM.mug} />- {/* Cups. */}- {[0.05, 0.17, 0.29, 0.41].map((x, i) => (- <group key={x}>- <Cyl radius={0.04} height={0.08} position={[x, 0.76, 0.14]} material={PM.mug} />- {i === 1 && <Cyl radius={0.034} height={0.004} position={[x, 0.8, 0.14]} material={PM.coffee} cast={false} />}- </group>- ))}- {/* Menu board leaning back on the counter. */}- <group position={[0.92, 0.72, -0.18]} rotation={[-0.18, 0, 0]}>- <Box size={[0.44, 0.33, 0.02]} position={[0, 0.165, -0.005]} material={MAT.wood} />- <Panel size={[0.38, 0.28]} position={[0, 0.165, 0.0055]} material={lazy.menu(t("society.office.coffee_menu"))} />- </group>- </group>- );-}--/** Round low wood table with a mug and a magazine. */-function CoffeeTable() {- return (- <group>- <Cyl radius={0.28} height={0.03} position={[0, 0.015, 0]} material={MAT.woodDark} />- <Cyl radius={0.06} height={0.24} position={[0, 0.135, 0]} material={MAT.woodDark} />- <Cyl radius={0.55} height={0.05} position={[0, 0.275, 0]} material={MAT.wood} />- <Box size={[0.22, 0.01, 0.3]} position={[-0.15, 0.305, -0.05]} material={MAT.books[2]} cast={false} />- <Cyl radius={0.045} height={0.085} position={[0.18, 0.3425, 0.1]} material={PM.mug} />- <Cyl radius={0.038} height={0.004} position={[0.18, 0.386, 0.1]} material={PM.coffee} cast={false} />- <Box size={[0.015, 0.045, 0.012]} position={[0.232, 0.345, 0.1]} material={PM.mug} cast={false} />- </group>- );-}--/** Retro arcade cabinet; screen, controls and marquee face +z. */-function Arcade() {- return (- <group>- <Rounded size={[0.7, 0.95, 0.62]} radius={0.03} position={[0, 0.475, -0.04]} material={PM.arcadeBody} />- <Box size={[0.6, 0.12, 0.01]} position={[0, 0.12, 0.272]} material={PM.arcadeTrim} cast={false} />- <Box size={[0.2, 0.22, 0.01]} position={[0, 0.6, 0.272]} material={PM.arcadeTrim} cast={false} />- <group position={[0, 1.0, 0.2]} rotation={[0.25, 0, 0]}>- <Rounded size={[0.7, 0.08, 0.3]} radius={0.02} position={[0, 0, 0]} material={PM.arcadeTrim} />- <Cyl radius={0.012} height={0.08} position={[-0.15, 0.08, 0]} material={MAT.monitor} cast={false} />- <mesh geometry={PGEO.sphere} material={PM.joystick} position={[-0.15, 0.13, 0]} scale={0.035} castShadow />- {PM.arcadeButtons.map((material, i) => (- <Cyl key={i} radius={0.025} height={0.02} position={[0.05 + i * 0.08, 0.045, 0]} material={material} cast={false} />- ))}- </group>- <Rounded size={[0.7, 0.72, 0.42]} radius={0.03} position={[0, 1.4, -0.15]} material={PM.arcadeBody} />- <Box size={[0.62, 0.5, 0.01]} position={[0, 1.36, 0.062]} material={PM.arcadeTrim} cast={false} />- <Panel size={[0.56, 0.44]} position={[0, 1.36, 0.068]} material={lazy.arcade()} />- <Box size={[0.7, 0.14, 0.14]} position={[0, 1.72, 0]} material={PM.marquee} />- <Box size={[0.012, 1.6, 0.5]} position={[-0.356, 0.9, -0.05]} material={PM.arcadeTrim} cast={false} />- <Box size={[0.012, 1.6, 0.5]} position={[0.356, 0.9, -0.05]} material={PM.arcadeTrim} cast={false} />- </group>- );-}--/** Stable small hash of an id (colour picks, variations). */-export function idHash(id: string): number {- let hash = 0;- for (const ch of id) hash = (hash * 31 + ch.charCodeAt(0)) >>> 0;- return hash;-}--/** A flat rug with an inner field, sized per instance. */-function RugPiece({ w, d }: { w: number; d: number }) {- const inset = Math.min(0.3, Math.min(w, d) * 0.15);- return (- <group>- <Rug position={[0, 0.01, 0]} size={[w, d]} />- <Box size={[w - inset, 0.022, d - inset]} position={[0, 0.011, 0]} material={PM.rugInner} cast={false} />- </group>- );-}--/** Steel elevator doors in a free-standing shaft block; doors face +z, wood slats on the back. */-function Elevator() {- return (- <group>- {/* The back stops 3 cm short of the slats' outer face: coplanar faces z-fight into stripes. */}- <Rounded size={[2.2, 2.4, 0.27]} radius={0.04} position={[0, 1.2, -0.035]} material={PM.shaft} />- <Box size={[0.1, 2.08, 0.06]} position={[-0.66, 1.04, 0.12]} material={PM.steelDark} />- <Box size={[0.1, 2.08, 0.06]} position={[0.66, 1.04, 0.12]} material={PM.steelDark} />- <Box size={[1.42, 0.1, 0.06]} position={[0, 2.13, 0.12]} material={PM.steelDark} />- <Box size={[0.6, 2.0, 0.03]} position={[-0.305, 1.0, 0.11]} material={PM.steel} />- <Box size={[0.6, 2.0, 0.03]} position={[0.305, 1.0, 0.11]} material={PM.steel} />- <Box size={[0.012, 2.0, 0.035]} position={[0, 1.0, 0.112]} material={PM.steelDark} cast={false} />- <Box size={[1.3, 0.02, 0.08]} position={[0, 0.01, 0.15]} material={PM.steelDark} cast={false} />- <Box size={[0.34, 0.14, 0.02]} position={[0, 2.28, 0.11]} material={MAT.monitor} cast={false} />- <Panel size={[0.3, 0.1]} position={[0, 2.28, 0.1205]} material={lazy.indicator()} />- <Box size={[0.1, 0.22, 0.02]} position={[0.9, 1.1, 0.11]} material={PM.steel} cast={false} />- <Box size={[0.035, 0.035, 0.01]} position={[0.9, 1.15, 0.122]} material={PM.indicatorLight} cast={false} />- <Box size={[0.035, 0.035, 0.01]} position={[0.9, 1.05, 0.122]} material={PM.steelDark} cast={false} />- {[-0.9, -0.54, -0.18, 0.18, 0.54, 0.9].map((x) => (- <Box key={x} size={[0.1, 2.1, 0.03]} position={[x, 1.1, -0.185]} material={MAT.woodDark} cast={false} />- ))}- </group>- );-}--/** Plant scale that keeps the canopy inside the 0.6 m plant footprint. */-export const PROP_PLANT_SIZE = 0.82;--const COUCH_FIT_X = FURNITURE_SIZE.couch.w / 2.36;--/** Every furniture kind maps to exactly one renderer (the Record type keeps this exhaustive). */-export const PROP_RENDERERS: Record<FurnitureKind, (props: { item: Furniture }) => JSX.Element> = {- receptionDesk: () => <ReceptionDesk />,- lockers: () => <Lockers />,- mirror: () => <Mirror />,- coffeeBar: () => <CoffeeBar />,- // The shared couch's armrests reach 2.36 m; squeeze it into the 2.2 m footprint.- couch: () => <group scale={[COUCH_FIT_X, 1, 1]}><Couch position={[0, 0, 0]} /></group>,- coffeeTable: () => <CoffeeTable />,- arcade: () => <Arcade />,- bookshelf: () => <Bookshelf position={[0, 0, 0]} />,- plant: () => <Plant position={[0, 0, 0]} size={PROP_PLANT_SIZE} />,- rug: ({ item }) => {- const size = item.size ?? FURNITURE_SIZE.rug;- return <RugPiece w={size.w} d={size.d} />;- },- elevator: () => <Elevator />,- ...LEAD_RENDERERS,- ...COMMAND_RENDERERS,- ...SERVER_RENDERERS,- ...TEAM_RENDERERS,- ...BREAK_RENDERERS,- ...WARDROBE_RENDERERS,- ...LOBBY_RENDERERS,- ...SPAWN_RENDERERS,- ...LEVEL_HALL_RENDERERS,- ...STUDIO_RENDERERS,- ...ARCADE_RENDERERS,-};--/**- * One furniture item, placed at (x, 0, z) and turned by `rotationY` (0 = front faces +z). `merged` draws the- * piece as a few merged meshes that stay inside its own named group: for a piece that must remain an object of- * its own (a station lights up through the meshes under its group) but is as static as any other.- */-export const FurniturePiece = memo(function FurniturePiece({ item, merged = false }: { item: Furniture; merged?: boolean }) {- const Render = PROP_RENDERERS[item.kind];- return (- <group position={[item.x, 0, item.z]} rotation={[0, item.rotationY, 0]} name={`prop:${item.id}`}>- {merged ? <StaticBatch signature={item.id} keepFlat><Render item={item} /></StaticBatch> : <Render item={item} />}- </group>- );-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeRooms.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeRooms.tsxdeleted file mode 100644index b50bdf11d4..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeRooms.tsx+++ /dev/null@@ -1,376 +0,0 @@-/**- * Rooms of the walkable office: a floor overlay per room, glass walls along- * the layout's wall segments, and a name sign above each room's door.- * Pattern textures and sign textures are drawn once and cached.- */-import { useEffect, useMemo } from "react";-import { BoxGeometry, DoubleSide, MeshStandardMaterial, RepeatWrapping, type BufferGeometry, type Texture } from "three";-import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";-import { Box, MAT, Rounded } from "./OfficeFurniture";-import { cachedCanvasTexture } from "./canvasMaterials";-import { ARCH, archPosts, type Door, type Room, type RoomKind, type WallSegment } from "./officeLayout";-import { CAMPUS_ROOM_FLOORS, OFFICE, ROOM_FLOOR_COLOURS } from "./officePalette";--// ----------------------------------------------------------------------------// Floors-// -----------------------------------------------------------------------------/** Deterministic pseudo-random numbers, so the patterns never shimmer between loads. */-function lcg(seed: number): () => number {- let state = seed >>> 0;- return () => {- state = (state * 1664525 + 1013904223) >>> 0;- return state / 0x1_0000_0000;- };-}--/** Metres covered by one repeat of each floor pattern. */-const PATTERN_METRES: Record<RoomKind, number> = { lead: 2.6, team: 2, wardrobe: 2, reception: 3.2, break: 2.4, command: 3.2, server: 2,- arcade: 2.4, classics: 2, puzzle: 2, action: 2, foyer: 2.4, prizes: 2, snack: 1.6, levels: 3.2 };--interface FloorTones { base: string; accents: readonly string[] }-const CAMPUS_FLOORS: Partial<Record<RoomKind, FloorTones>> = CAMPUS_ROOM_FLOORS;-/** A room kind's floor tones: the agents floor's rooms wear the campus's finishes, every other floor its own. */-function floorTones(kind: RoomKind, campus: boolean): FloorTones {- return (campus ? CAMPUS_FLOORS[kind] : undefined) ?? ROOM_FLOOR_COLOURS[kind];-}--function drawFloor(kind: RoomKind, { base, accents }: FloorTones, ctx: CanvasRenderingContext2D, w: number, h: number): void {- const rand = lcg(kind.length * 7919 + kind.charCodeAt(0));- ctx.fillStyle = base;- ctx.fillRect(0, 0, w, h);- if (kind === "lead") {- // A chevron of planks: columns of slanted planks that alternate direction, so- // the tile wraps seamlessly on both axes (64-px columns, 16-px planks).- const col = 64, plank = 16, image = ctx.createImageData(w, h);- const tones = accents.map((hex) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)));- for (let y = 0; y < h; y += 1) {- for (let x = 0; x < w; x += 1) {- const c = Math.floor(x / col), xm = x % col;- const yy = (y + (c % 2 === 0 ? xm : col - xm)) % h;- const index = Math.floor(yy / plank);- const [r, g, b] = tones[(index * 7 + c * 3) % tones.length];- // Seams between planks and along the chevron's spine, plus a faint grain.- const seam = yy % plank < 1.2 || xm < 1 ? 0.62 : 1;- const grain = 0.93 + 0.07 * Math.sin((yy * 0.9 + xm * 0.35 + index * 11) * 0.8);- const o = (y * w + x) * 4;- image.data[o] = r * seam * grain;- image.data[o + 1] = g * seam * grain;- image.data[o + 2] = b * seam * grain;- image.data[o + 3] = 255;- }- }- ctx.putImageData(image, 0, 0);- } else if (kind === "break") {- // Light-oak planks, staggered; segments run past both edges so the tile wraps.- for (let row = 0; row < 8; row += 1) {- const offset = ((row % 2) * 64 + ((row * 53) % 64)) - 128;- for (let seg = 0; seg < 4; seg += 1) {- ctx.fillStyle = accents[(row + seg * 3) % accents.length];- ctx.fillRect(offset + seg * 128, row * 32, 128, 32);- ctx.fillStyle = "rgba(110,84,56,0.22)";- ctx.fillRect(offset + seg * 128, row * 32, 1.5, 32);- }- ctx.fillStyle = "rgba(110,84,56,0.18)";- ctx.fillRect(0, row * 32, w, 1.5);- }- } else if (kind === "wardrobe") {- // Terrazzo: a pale ground with small stone chips in the accent tones.- for (let i = 0; i < 900; i += 1) {- ctx.fillStyle = accents[Math.floor(rand() * accents.length)];- const s = 2 + rand() * 4;- ctx.fillRect(Math.floor(rand() * w), Math.floor(rand() * h), s, s * (0.6 + rand() * 0.6));- }- } else if (kind === "levels") {- // Level Hall: a ceremonial floor of cream and charcoal marble squares, each with soft veins, laid with fine joints.- const [cream, charcoal, creamVein, brass] = [0, 1, 2, 3].map((i) => accents[i] ?? base);- const tiles = 4, size = w / tiles;- for (let ty = 0; ty < tiles; ty += 1) {- for (let tx = 0; tx < tiles; tx += 1) {- const dark = (tx + ty) % 2 === 1;- const x0 = tx * size, y0 = ty * size;- ctx.fillStyle = dark ? charcoal : cream;- ctx.fillRect(x0, y0, size, size);- // Veins: a few long, gently wandering strokes per tile, clipped to it.- ctx.save();- ctx.beginPath();- ctx.rect(x0, y0, size, size);- ctx.clip();- for (let v = 0; v < 3; v += 1) {- ctx.globalAlpha = dark ? 0.16 + rand() * 0.1 : 0.22 + rand() * 0.14;- ctx.strokeStyle = dark ? "#5b5e68" : creamVein;- ctx.lineWidth = 0.6 + rand() * 1.1;- ctx.beginPath();- let vx = x0 - 4, vy = y0 + rand() * size;- ctx.moveTo(vx, vy);- while (vx < x0 + size + 4) {- vx += 6 + rand() * 12;- vy += (rand() - 0.45) * 10;- ctx.lineTo(vx, vy);- }- ctx.stroke();- }- ctx.restore();- ctx.globalAlpha = 1;- }- }- // Fine joints, a hint of brass where the squares meet.- ctx.fillStyle = brass;- ctx.globalAlpha = 0.35;- for (let i = 0; i < tiles; i += 1) {- ctx.fillRect(i * size, 0, 1, h);- ctx.fillRect(0, i * size, w, 1);- }- ctx.globalAlpha = 1;- } else if (kind === "team") {- // Carpet grain: fine speckles in the accent tones, plus a faint weave.- for (let i = 0; i < 2600; i += 1) {- ctx.fillStyle = accents[Math.floor(rand() * accents.length)];- ctx.fillRect(Math.floor(rand() * w), Math.floor(rand() * h), 2, 2);- }- ctx.fillStyle = "rgba(0,0,0,0.035)";- for (let y = 0; y < h; y += 8) ctx.fillRect(0, y, w, 1);- } else if (kind === "command") {- // Mission Control: dark graphite microcement, soft clouds of lighter and- // darker trowel marks and a faint sheen, no joints.- for (let i = 0; i < 520; i += 1) {- ctx.globalAlpha = 0.18 + rand() * 0.2;- ctx.fillStyle = accents[Math.floor(rand() * accents.length)];- const r = 6 + rand() * 22;- ctx.beginPath();- ctx.ellipse(rand() * w, rand() * h, r * (1 + rand()), r, rand() * Math.PI, 0, Math.PI * 2);- ctx.fill();- }- ctx.globalAlpha = 1;- } else {- // Tiles: the server room's raised-floor grid, reception's large pale stone slabs.- const tiles = kind === "server" ? 4 : 2;- const size = w / tiles;- for (let ty = 0; ty < tiles; ty += 1) {- for (let tx = 0; tx < tiles; tx += 1) {- ctx.fillStyle = accents[Math.floor(rand() * accents.length)];- ctx.fillRect(tx * size, ty * size, size, size);- if (kind === "reception") {- for (let i = 0; i < 90; i += 1) {- ctx.fillStyle = rand() > 0.5 ? "rgba(255,255,255,0.18)" : "rgba(120,110,95,0.12)";- ctx.fillRect(tx * size + rand() * size, ty * size + rand() * size, 3, 3);- }- }- }- }- ctx.fillStyle = kind === "server" ? "rgba(110,118,130,0.45)" : "rgba(150,142,130,0.28)";- for (let i = 0; i < tiles; i += 1) {- ctx.fillRect(i * size, 0, 3, h);- ctx.fillRect(0, i * size, w, 3);- }- }-}--function floorTexture(kind: RoomKind, campus: boolean): Texture | null {- const tones = floorTones(kind, campus);- const texture = cachedCanvasTexture(`floor:${kind}:${tones.base}`, 256, 256, (ctx, w, h) => drawFloor(kind, tones, ctx, w, h));- if (texture) {- texture.wrapS = texture.wrapT = RepeatWrapping;- texture.anisotropy = 8;- }- return texture;-}--function RoomFloor({ room, campus }: { room: Room; campus: boolean }) {- const w = room.maxX - room.minX;- const d = room.maxZ - room.minZ;- const material = useMemo(() => {- const base = floorTexture(room.kind, campus);- let map: Texture | null = null;- if (base) {- map = base.clone();- map.repeat.set(w / PATTERN_METRES[room.kind], d / PATTERN_METRES[room.kind]);- map.needsUpdate = true;- }- return new MeshStandardMaterial({ color: map ? "#ffffff" : floorTones(room.kind, campus).base, map, roughness: 0.85 });- }, [room.kind, campus, w, d]);- // The clone and its material belong to this room; the cached base texture stays.- useEffect(() => () => { material.map?.dispose(); material.dispose(); }, [material]);- return (- <mesh position={[(room.minX + room.maxX) / 2, 0.004, (room.minZ + room.maxZ) / 2]} rotation={[-Math.PI / 2, 0, 0]}- material={material} receiveShadow>- <planeGeometry args={[w, d]} />- </mesh>- );-}--/**- * A floor overlay per room: a plank chevron (lead), slate felt (team), terrazzo (wardrobe), pale stone (reception),- * light oak (break). `campus`: the agents floor, whose rooms take the campus's own oak, limestone and felt.- */-export function RoomFloors({ rooms, campus = false }: { rooms: Room[]; campus?: boolean }) {- return <group>{rooms.map((room) => <RoomFloor key={room.id} room={room} campus={campus} />)}</group>;-}--// ----------------------------------------------------------------------------// Walls-// -----------------------------------------------------------------------------export const WALL_HEIGHT = 2.1;-const BASE_HEIGHT = 0.12;-const POST_SPACING = 1.8;--/** Frosted manifestation on the glass at eye level: a broad band and a pinstripe above it. */-const FROST = { y: 1.05, h: 0.18, stripeY: 1.22, stripeH: 0.025 } as const;-const frostMaterial = new MeshStandardMaterial({- color: "#f4f1ec", transparent: true, opacity: 0.55, roughness: 0.95, side: DoubleSide, depthWrite: false,-});--/** A box of a wall run, in the run's own frame. */-function boxAt(size: [number, number, number], position: [number, number, number]): BufferGeometry {- return new BoxGeometry(...size).translate(...position);-}--/**- * One glass wall run: slim black steel base, mullions and top rail around a- * clear pane with a frosted band at eye level, so the glass reads as glass.- * Every room on every floor has the same glazing. A run is three meshes- * whatever its length: the whole frame is one merged geometry, the two- * frosted bands another.- */-function GlassWall({ wall }: { wall: WallSegment }) {- const length = Math.hypot(wall.x2 - wall.x1, wall.z2 - wall.z1);- const angle = Math.atan2(wall.z2 - wall.z1, wall.x2 - wall.x1);- const parts = useMemo(() => {- const posts = Math.max(2, Math.ceil(length / POST_SPACING) + 1);- const steel = [- boxAt([length, 0.06, 0.06], [0, 0.03, 0]),- boxAt([length, 0.04, 0.05], [0, WALL_HEIGHT - 0.02, 0]),- ...Array.from({ length: posts }, (_, i) => boxAt([0.03, WALL_HEIGHT, 0.05], [-length / 2 + (length * i) / (posts - 1), WALL_HEIGHT / 2, 0])),- ];- const frame = mergeGeometries(steel);- for (const piece of steel) piece.dispose();- const bands = [boxAt([length, FROST.h, 0.024], [0, FROST.y, 0]), boxAt([length, FROST.stripeH, 0.024], [0, FROST.stripeY, 0])];- const frost = mergeGeometries(bands);- for (const band of bands) band.dispose();- return { frame, frost };- }, [length]);- useEffect(() => () => { parts.frame?.dispose(); parts.frost?.dispose(); }, [parts]);- if (length < 0.05) return null;- return (- // The camera rig finds a wall run by this tag and lowers it while it stands between camera and character.- <group position={[(wall.x1 + wall.x2) / 2, 0, (wall.z1 + wall.z2) / 2]} rotation={[0, -angle, 0]} userData={{ officeWall: wall }}>- {parts.frame && <mesh geometry={parts.frame} material={MAT.railing} castShadow receiveShadow />}- <Box size={[length, WALL_HEIGHT - BASE_HEIGHT - 0.04, 0.02]} position={[0, (WALL_HEIGHT + BASE_HEIGHT - 0.04) / 2, 0]}- material={MAT.glass} cast={false} />- {parts.frost && <mesh geometry={parts.frost} material={frostMaterial} />}- </group>- );-}--/** Glass walls, 2.1 m high, along every wall segment of the layout. */-export function RoomWalls({ walls }: { walls: WallSegment[] }) {- return (- <group>- {walls.map((wall) => <GlassWall key={`${wall.room}:${wall.x1}:${wall.z1}:${wall.x2}:${wall.z2}`} wall={wall} />)}- </group>- );-}--// ----------------------------------------------------------------------------// Signs-// -----------------------------------------------------------------------------const SIGN_W = 1.5;-const SIGN_H = 0.36;-const SIGN_TEXT_W = 1.4;-const SIGN_CANVAS = { w: 512, h: 112 } as const;--const signMaterials = new Map<string, MeshStandardMaterial>();-/** A sign face; the lead office's is bronze lettering between two fine rules, on the same board as every room's. */-function signMaterial(label: string, lead = false): MeshStandardMaterial {- const key = `${lead ? "lead" : "room"}:${label}`;- let material = signMaterials.get(key);- if (!material) {- const map = cachedCanvasTexture(`room-sign:${key}`, SIGN_CANVAS.w, SIGN_CANVAS.h, (ctx, w, h) => {- ctx.fillStyle = OFFICE.signBoard;- ctx.fillRect(0, 0, w, h);- if (lead) {- ctx.fillStyle = "#b08d5c";- ctx.fillRect(14, 10, w - 28, 3);- ctx.fillRect(14, h - 13, w - 28, 3);- }- ctx.fillStyle = lead ? "#e3c594" : OFFICE.signText;- ctx.textAlign = "center";- ctx.textBaseline = "middle";- // Shrink long names (e.g. "Despacho del líder") to fit before cutting them off.- const room = w - 32;- let size = 56;- const font = (px: number) => `600 ${px}px system-ui, -apple-system, 'Segoe UI', sans-serif`;- ctx.font = font(size);- while (size > 34 && ctx.measureText(label).width > room) {- size -= 2;- ctx.font = font(size);- }- let text = label;- while (text.length > 1 && ctx.measureText(text).width > room) text = text.slice(0, -1);- ctx.fillText(text === label ? label : `${text.slice(0, -1).trimEnd()}…`, w / 2, h / 2 + 2);- });- material = new MeshStandardMaterial({- color: map ? "#ffffff" : OFFICE.signBoard, map, roughness: 0.8,- // The lead's bronze lettering glows faintly, like a lit plaque.- ...(lead && map ? { emissive: "#ffffff", emissiveMap: map, emissiveIntensity: 0.35 } : {}),- });- signMaterials.set(key, material);- }- return material;-}--/** Charcoal wayfinding board with the label on both faces, centred on its local origin. */-function SignBoard({ label, lead = false }: { label: string; lead?: boolean }) {- const material = signMaterial(label, lead);- const textH = (SIGN_TEXT_W * SIGN_CANVAS.h) / SIGN_CANVAS.w;- return (- <group>- <Rounded size={[SIGN_W, SIGN_H, 0.06]} radius={0.025} position={[0, 0, 0]} material={MAT.sign} />- <mesh position={[0, 0, 0.0305]} material={material}><planeGeometry args={[SIGN_TEXT_W, textH]} /></mesh>- <mesh position={[0, 0, -0.0305]} rotation={[0, Math.PI, 0]} material={material}><planeGeometry args={[SIGN_TEXT_W, textH]} /></mesh>- </group>- );-}--/** Where a door-top sign sits: the door's centre on its wall line, turned to run along the wall. */-function doorAnchor(room: Room, door: Door): { x: number; z: number; rotationY: number } {- switch (door.side) {- case "south": return { x: door.at, z: room.maxZ, rotationY: 0 };- case "north": return { x: door.at, z: room.minZ, rotationY: 0 };- case "west": return { x: room.minX, z: door.at, rotationY: Math.PI / 2 };- case "east": return { x: room.maxX, z: door.at, rotationY: Math.PI / 2 };- }-}--/**- * A room's name sign. Walled rooms: a board sitting on a header rail across- * their first door, readable from both sides. Open rooms: a free-standing arch- * (two slim posts, board on top) centred on the room's north edge.- */-export function RoomSign({ room, label }: { room: Room; label: string }) {- const door = room.walled ? room.doors[0] : undefined;- if (door) {- const { x, z, rotationY } = doorAnchor(room, door);- return (- <group position={[x, 0, z]} rotation={[0, rotationY, 0]}>- <Box size={[door.width, 0.07, 0.07]} position={[0, WALL_HEIGHT - 0.035, 0]} material={MAT.railing} />- <group position={[0, WALL_HEIGHT + SIGN_H / 2 + 0.02, 0]}><SignBoard label={label} lead={room.kind === "lead"} /></group>- </group>- );- }- const archY = 2.3;- const postH = archY + SIGN_H / 2;- // Post positions come from the layout, which also makes them navigation obstacles.- const [west, east] = archPosts(room);- const cx = (west.x + east.x) / 2;- return (- <group position={[cx, 0, west.z]}>- <Box size={[ARCH.post, postH, ARCH.post]} position={[west.x - cx, postH / 2, 0]} material={MAT.railing} />- <Box size={[ARCH.post, postH, ARCH.post]} position={[east.x - cx, postH / 2, 0]} material={MAT.railing} />- <Box size={[east.x - west.x + ARCH.post, 0.04, ARCH.post]} position={[0, archY - SIGN_H / 2 - 0.02, 0]} material={MAT.railing} />- <group position={[0, archY, 0]}><SignBoard label={label} /></group>- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeScene.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeScene.tsxdeleted file mode 100644index 165c3822cb..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeScene.tsx+++ /dev/null@@ -1,290 +0,0 @@-/**- * 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- * a department per IDE workspace; each dresses its plan in its own look- * (AgentsFloorLook / CodingFloorLook). The Level Hall's floor wears the- * agents floor's materials. The arcade floor has a plan and a look of its own- * (ArcadeHall); the person, the elevator and the camera work the same there.- */-import { useLayoutEffect, useMemo } from "react";-import type { ThreeEvent } from "@react-three/fiber";-import { Color } from "three";-import { useT } from "@/i18n";-import type { SocietyAgent } from "../data";-import type { ToyLook } from "./toyFigureModel";-import { DeskInstances } from "./DeskInstances";-import { DeskDressing } from "./DeskDressing";-import { CodingSlab, CodingStudio } from "./CodingFloorLook";-import { CodingFloorAmbience } from "./CodingFloorAmbience";-import { CodingPlaza } from "./CodingPlaza";-import { DeskBusyLights } from "./DeskBusyLights";-import { AGENTS_SCENE, AgentsDepartment, agentsRug, AgentsSlab } from "./AgentsFloorLook";-import { AgentsFloorAmbience } from "./AgentsFloorAmbience";-import { CampusGround } from "./CampusGround";-import { StaticBatch } from "./StaticBatch";-import { BuildingShell } from "./BuildingShell";-import { CITY_BACKDROP } from "./SingularityCity";-import { SkyCourier } from "./SkyCourier";-import { SkyPadStructure } from "./SkyPadStructure";-import { ExecutiveDesks, LeadOfficeLight } from "./LeadSuite";-import { LiveMonitors } from "./LiveMonitors";-import { TerminalMonitors } from "./TerminalMonitors";-import type { PaneOccupant } from "./codingFloor";-import { GigiFlyer } from "./GigiFlyer";-import { useEventStore } from "@/store/events";-import type { DeskChat } from "./useDeskChats";-import { FurniturePiece, MeetingChairs } from "./OfficeProps";-import { TeamBoardFace } from "./TeamBoardFace";-import { TeamRoomFittings } from "./TeamRoomDecor";-import { BreakLoungeFittings } from "./BreakLounge";-import { WardrobeFittings } from "./WardrobeRoom";-import { LevelHallFittings } from "./LevelHall";-import { LobbyFittings } from "./LobbyDecor";-import { SpawnFittings } from "./SpawnPoint";-import { RoomFloors, RoomSign, RoomWalls } from "./OfficeRooms";-import { StationObjects } from "./StationObjects";-import { ElevatorCallButton } from "./ElevatorCallButton";-import { ArcadeHall } from "../arcade/ArcadeHall";-import { OFFICE_FIGURE_HEIGHT_M, OfficeAgents, type WalkerContext } from "./OfficeAgents";-import { OfficePlayer } from "./OfficePlayer";-import { OfficeDog } from "./OfficeDog";-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 } from "./officePalette";-import { officeSession, player as playerBody, useOfficeStore, type OfficeFloor, type Selection } from "./officeStore";-import { arrivalPose } from "./officeFloors";-import { ProgressionLayer } from "../progression/ProgressionLayer";--/** The person's character as a mover for Gigi to follow (the body object itself, mutated every frame). */-const PLAYER_OWNER = { current: playerBody };--/**- * Places the character on a floor it just arrived at (elevator ride, or a- * mount that asked for another floor). Runs as a layout effect, so it lands- * before the player controller checks its spot; it repeats for every rebuilt- * plan until the floor's roster has loaded, then the arrival is done.- */-function FloorArrival({ floor, layout, grid, ready, awake }: { floor: OfficeFloor; layout: OfficeLayout; grid: NavGrid; ready: boolean; awake: boolean }) {- useLayoutEffect(() => {- if (!awake) return;- const arrival = officeSession.arrival;- if (!arrival || arrival.floor !== floor) return;- const pose = arrivalPose(layout, arrival.at, officeSession.floors[floor]);- const spot = isWalkable(grid, pose) ? pose : nearestWalkable(grid, pose) ?? layout.spawn;- playerBody.x = spot.x; playerBody.z = spot.z; playerBody.heading = pose.heading;- playerBody.path = []; playerBody.moving = false;- officeSession.playerPlaced = true;- if (ready) officeSession.arrival = null;- }, [floor, layout, grid, ready, awake]);- return null;-}--/** On the coding floor Jarvis is nobody's desk mate: the person's pet (Gigi by default) comes along. */-function GigiCompanion({ grid, awake, reduced }: { grid: NavGrid; awake: boolean; reduced: boolean }) {- const speaking = useEventStore((s) => s.voiceState === "speaking");- const clear = useMemo(() => (x: number, z: number) => isWalkable(grid, { x, z }), [grid]);- return <GigiFlyer owner={PLAYER_OWNER} mode="follow" speaking={speaking} paused={!awake} reduced={reduced} clear={clear} />;-}--export interface OfficeSceneProps {- floor: OfficeFloor;- /** The coding floor's figures by agent id (their IDE panes); empty on the agents floor. */- occupants: ReadonlyMap<string, PaneOccupant>;- /** The floor's roster has loaded (ends a pending arrival). */- ready: boolean;- layout: OfficeLayout;- grid: NavGrid;- walkers: WalkerContext;- agents: ReadonlyMap<string, SocietyAgent>;- newcomers: ReadonlySet<string>;- awake: boolean;- reduced: boolean;- overview: number;- player: { look: ToyLook; name: string };- selection: Selection | null;- nearby: Selection | null;- chats: ReadonlyMap<string, DeskChat>;- onOpenScreen: (agentId: string, screen: Point & { y: number }, facing: number) => void;- /** The elevator's call button: lit after a press, the floor picker open (its pill steps aside), and the press itself. */- elevatorCall: { lit: boolean; picking: boolean; onPress: () => void };-}--/** The stations, the elevator's call button and the person: the same on every floor. */-function SharedFloorParts({ floor, layout, grid, ready, awake, reduced, player, selection, nearby, elevatorCall }: Pick<OfficeSceneProps,- "floor" | "layout" | "grid" | "ready" | "awake" | "reduced" | "player" | "selection" | "nearby" | "elevatorCall">) {- const shaft = layout.furniture.find((f) => f.kind === "elevator");- const atLift = nearby?.kind === "checkpoint" && nearby.id === "elevator";- return (- <>- {/* Stations are the objects of the room: a click target and a rim on each, nothing floating over the floor. */}- <StationObjects layout={layout} nearby={nearby} selection={selection} animate={awake && !reduced} />- {shaft && (- <ElevatorCallButton shaft={shaft} floor={floor} lit={elevatorCall.lit} animate={awake && !reduced}- near={atLift} onPress={elevatorCall.onPress} />- )}- <FloorArrival floor={floor} layout={layout} grid={grid} ready={ready} awake={awake} />- <OfficePlayer layout={layout} grid={grid} look={player.look} name={player.name} awake={awake} reduced={reduced} />- <PlayerBubble height={OFFICE_FIGURE_HEIGHT_M + 0.49} />- </>- );-}--export function OfficeScene(props: OfficeSceneProps) {- const { floor, layout, grid, walkers, agents, newcomers, awake, reduced, selection, nearby, chats, overview } = props;- const arcade = floor === "arcade";- const select = useOfficeStore((s) => s.select);- const desks = useMemo(() => allDesks(layout), [layout]);- const dogBeds = useMemo(() => layout.furniture.filter((f) => f.kind === "dogBed"), [layout]);- const treatJar = layout.furniture.find((f) => f.kind === "treatJar") ?? null;- const onFloorClick = (event: ThreeEvent<MouseEvent>) => {- // A drag that ends on the floor rotated the camera; only a real click walks.- if (event.delta > 6) return;- event.stopPropagation();- useOfficeStore.getState().requestWalk({ x: event.point.x, z: event.point.z });- };- // One tree for every floor (the dressing swaps, the person and the camera stay mounted), in the order the frame loop needs:- // the floor, the person, then whoever walks around them, the camera last.- return (- <>- {arcade- // While a cabinet is being played its screen in the hall rests: the live preview would only draw behind the overlay.- ? <ArcadeHall layout={layout} onFloorClick={onFloorClick} awake={awake} reduced={reduced}- nearCabinet={nearby?.kind === "arcade" && selection?.kind !== "arcade" ? nearby.id : null} />- : <OfficeFloorDressing {...props} desks={desks} onFloorClick={onFloorClick} />}- <SharedFloorParts {...props} />- {dogBeds.length > 0 && <OfficeDog beds={dogBeds} rooms={layout.rooms} jar={treatJar} grid={grid} awake={awake} reduced={reduced} />}- {!arcade && (- <OfficeAgents desks={desks} agents={agents} ctx={walkers} newcomers={newcomers} awake={awake} reduced={reduced} chats={chats}- selectedId={selection?.kind === "agent" ? selection.id : null} onSelect={(id) => select({ kind: "agent", id })} />- )}- {/* Upstairs the person's pet comes along: to the coding floor and to play in the arcade. */}- {floor !== "agents" && <GigiCompanion grid={grid} awake={awake} reduced={reduced} />}- {/* Levels: what everyone wears, level-up bursts and "+XP"; after the walkers, so it reads this frame's positions. */}- <ProgressionLayer awake={awake} reduced={reduced} />- <OfficeCameraRig layout={layout} overview={overview} />- </>- );-}--/**- * The props a station lights up when the person is near, and the spawn point's pad: each stays an object of its- * own (the rim is drawn on the meshes under its group) and is merged only within itself. Every other piece of- * the agents floor is drawn merged with all the others (StaticBatch).- */-const STATION_PROP_KINDS: ReadonlySet<FurnitureKind> = new Set<FurnitureKind>([- "spawnTerminal", "spawnPad", "receptionDesk", "agentTotem", "teamBoard", "dressingMirror", "mirror", "coffeeBar", "elevator", "studioBoard", "teamStand",-]);--/** Everything that dresses the agents and coding floors: slab, rooms, departments, desks, monitors, furniture. */-function OfficeFloorDressing({ floor, occupants, layout, agents, newcomers, awake, reduced, chats, onOpenScreen, desks, onFloorClick }: OfficeSceneProps & {- desks: ReturnType<typeof allDesks>;- onFloorClick: (event: ThreeEvent<MouseEvent>) => void;-}) {- const t = useT();- // Lead desks carry their own size and are built as executive desks, not bench instances.- const benchDesks = useMemo(() => desks.filter((d) => !d.size), [desks]);- // Each desk takes its department's zone colour for the felt screen and the seat fabric.- const zones = useMemo(() => new Map(layout.departments.flatMap((dept) => dept.desks.map((desk) => [desk.id, dept.tint] as const))), [layout]);- // A team lead's place is marked in its team's colour: the chair, a mat under it and a name stand on the desk.- const leadSigns = useMemo(() => new Map(leadDesks(layout).map(({ desk, dept }) => [desk.id, agentsRug(dept.tint).border] as const)), [layout]);- const leadRoom = layout.rooms.find((r) => r.kind === "lead");- const teamRoom = layout.rooms.find((r) => r.kind === "team");- const breakRoom = layout.rooms.find((r) => r.kind === "break");- const coding = floor === "coding";- // Every working floor is a floor of the same tower: the city's haze stands behind them all.- const 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);- const shadowMap = span > 50 ? 4096 : 2048;- const table = layout.furniture.find((f) => f.kind === "meetingTable");- const board = layout.furniture.find((f) => f.kind === "teamBoard");- const wardrobeRug = layout.furniture.find((f) => f.kind === "roundRug" && f.room === "wardrobe");- const lobbyLamp = layout.furniture.find((f) => f.kind === "lobbyLamp");- const spawnTerminal = layout.furniture.find((f) => f.kind === "spawnTerminal");- const levelStage = layout.furniture.find((f) => f.kind === "studioStage");- const levelGuide = layout.furniture.find((f) => f.kind === "levelGuide") ?? null;- // The agents floor's furniture, room signs, studio walls and meeting chairs never change once built: they are- // merged by material, a few dozen draw calls instead of well over a thousand (and as many again for shadows).- const batch = floor === "agents";- const roomLabels = layout.rooms.map((room) => t(`society.office.room_${room.kind}`));- const signs = layout.rooms.map((room, i) => <RoomSign key={room.id} room={room} label={roomLabels[i]} />);- const batchKey = useMemo(() => [- layout.furniture.map((f) => `${f.id}@${f.x},${f.z},${f.rotationY}`).join(";"),- layout.departments.map((d) => `${d.id}:${d.label}:${d.tint}@${d.minX},${d.minZ},${d.maxX},${d.maxZ}`).join(";"),- roomLabels.join(";"), t("society.office.studio_pool"), t("society.office.studio_sign_team"), t("society.office.studio_sign_pool"),- // eslint-disable-next-line react-hooks/exhaustive-deps- ].join("|"), [layout, roomLabels.join(";"), t]);- return (- <>- <primitive attach="background" object={background} />- <fog attach="fog" args={[space, span * 2.2, span * 4.5]} />- {/* The city's sky has its own stars, above a horizon the camera never shows; the coding floor's night is all stars. */}- <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. */}- <directionalLight key={shadowMap} position={[maxX + 10, 26, maxZ + 6]} intensity={1.55} color="#fff7ec" castShadow- shadow-mapSize={[shadowMap, shadowMap]} shadow-bias={-0.0004} shadow-normalBias={0.03}- shadow-camera-left={-span * 0.7} shadow-camera-right={span * 0.7}- shadow-camera-top={span * 0.7} shadow-camera-bottom={-span * 0.7} shadow-camera-far={Math.max(120, span * 2 + 40)} />- {coding ? <CodingSlab layout={layout} onFloorClick={onFloorClick} /> : <AgentsSlab layout={layout} onFloorClick={onFloorClick} />}- {coding ? <CodingFloorAmbience layout={layout} /> : <AgentsFloorAmbience layout={layout} />}- {/* Every working floor is a floor of the tower: window walls, the tower below, the city outside. */}- <BuildingShell layout={layout} reduced={reduced} />- {/* The sky pad outside the east windows, and the courier standing on it. */}- {layout.skyPad && <>- <SkyPadStructure pad={layout.skyPad} bounds={layout.bounds} reduced={reduced} onFloorClick={onFloorClick} />- <SkyCourier layout={layout} reduced={reduced} awake={awake} />- </>}- <RoomFloors rooms={layout.rooms} campus={!coding} />- <RoomWalls walls={layout.walls} />- {!batch && signs}- {coding- ? <>- {layout.departments.map((dept) => <CodingStudio key={dept.id} dept={dept} agents={agents} />)}- <DeskDressing desks={benchDesks} departments={layout.departments} />- <DeskBusyLights desks={benchDesks} occupants={occupants} animate={awake && !reduced} />- {spawnTerminal && <CodingPlaza at={spawnTerminal} />}- </>- : <>- {/* The campus ground (boulevards, atrium, free plot, planted courts); the Level Hall's floor has none. */}- <CampusGround layout={layout} />- {benchDesks.length > 0 && <>- <DeskInstances desks={benchDesks} agents={agents} zones={zones} />- <DeskDressing desks={benchDesks} departments={layout.departments} floor="agents" leadSigns={leadSigns} />- </>}- </>}- <ExecutiveDesks desks={desks} agents={agents} onOpenScreen={onOpenScreen} />- {leadRoom && <LeadOfficeLight room={leadRoom} />}- {floor === "coding"- ? <TerminalMonitors desks={desks} occupants={occupants} awake={awake} onOpen={onOpenScreen} />- : <LiveMonitors desks={desks} agents={agents} chats={chats} onOpen={onOpenScreen} />}- {batch- ? <>- <StaticBatch signature={batchKey}>- {signs}- {layout.departments.map((dept) => <AgentsDepartment key={dept.id} dept={dept} />)}- {layout.furniture.filter((item) => !STATION_PROP_KINDS.has(item.kind)).map((item) => <FurniturePiece key={item.id} item={item} />)}- {table && <MeetingChairs table={table} />}- </StaticBatch>- {layout.furniture.filter((item) => STATION_PROP_KINDS.has(item.kind)).map((item) => <FurniturePiece key={item.id} item={item} merged />)}- </>- : <>- {layout.furniture.map((item) => <FurniturePiece key={item.id} item={item} />)}- {table && <MeetingChairs table={table} />}- </>}- {board && <TeamBoardFace board={board} enabled={awake && floor === "agents"} />}- {teamRoom && table && <TeamRoomFittings room={teamRoom} table={table} />}- {breakRoom && <BreakLoungeFittings room={breakRoom} furniture={layout.furniture} />}- {wardrobeRug && <WardrobeFittings rug={wardrobeRug} />}- {levelStage && <LevelHallFittings stage={levelStage} guide={levelGuide} />}- {lobbyLamp && <LobbyFittings lamp={lobbyLamp} />}- {spawnTerminal && <SpawnFittings terminal={spawnTerminal} arrival={layout.arrival} floor={floor} newcomers={newcomers} animate={awake && !reduced} />}- </>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeStage.lifecycle.test.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeStage.lifecycle.test.tsxdeleted file mode 100644index d603e6e3cf..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeStage.lifecycle.test.tsx+++ /dev/null@@ -1,175 +0,0 @@-import { useContext, useEffect, type ReactNode } from "react";-import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";-import { afterEach, expect, it, vi } from "vitest";-import { CanvasActivity } from "@/hooks/useCanvasAwake";-import { useOfficeStore } from "./officeStore";-import { useProgression } from "../progression/progressionStore";-import { OfficeStage } from "./OfficeStage";--const state = vi.hoisted(() => ({- canvasMounts: 0, canvasUnmounts: 0, visits: 0, maps: 0, tools: 0, drawn: [] as [string, string][],- roster: { data: { agents: [], sample: false } },- coding: { occupants: [], byAgentId: new Map(), loaded: true },- rosterEnabled: vi.fn(), codingEnabled: vi.fn(), chatsEnabled: vi.fn(),- client: { invalidateQueries: vi.fn(async () => undefined) },-}));--vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));-vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => state.client }));-vi.mock("framer-motion", () => ({ useReducedMotion: () => false }));-vi.mock("@/hooks/useWebglSurface", () => ({ useWebglSurface: () => ({ generation: 0 }) }));-vi.mock("@/lib/graphDimension", () => ({ useWebglSupported: () => true }));-vi.mock("@/hooks/usePets", () => ({ useActivePet: () => null }));-vi.mock("../companion/companionPetStore", () => ({ useSyncCompanionPet: () => undefined }));-vi.mock("../data", () => ({- useSocietyRoster: (enabled: boolean) => { state.rosterEnabled(enabled); return state.roster; },- useQuickCreateAgent: () => async () => undefined,-}));-vi.mock("./codingFloor", () => ({- useCodingFloorOccupants: (enabled: boolean) => { state.codingEnabled(enabled); return state.coding; },-}));-vi.mock("./useDeskChats", () => ({- useDeskChats: (_sessions: unknown, enabled: boolean) => { state.chatsEnabled(enabled); return new Map(); },-}));-vi.mock("./useDprBudget", () => ({ useDprBudget: () => 1 }));-// The agents floor is built from the teams; the stage waits for the first answer about them.-vi.mock("@/lib/societyChatGroups", async (importOriginal) => ({ ...(await importOriginal<typeof import("@/lib/societyChatGroups")>()), useSocietyChatGroups: () => ({ data: [], isSuccess: true, isError: false, failureCount: 0 }) }));-vi.mock("@react-three/fiber", () => ({- advance: () => undefined,- Canvas: ({ children, frameloop }: { children: ReactNode; frameloop: string }) => {- const active = useContext(CanvasActivity);- useEffect(() => {- state.canvasMounts += 1;- return () => { state.canvasUnmounts += 1; };- }, []);- return <div data-testid="canvas" data-loop={frameloop} data-active={active}>{children}</div>;- },-}));-vi.mock("./OfficeScene", () => ({- OfficeScene: ({ awake, floor }: { awake: boolean; floor: string }) => {- // What the stage draws, and what the shared store says at that very moment of rendering.- state.drawn.push([floor, useOfficeStore.getState().floor]);- return <div data-testid="scene" data-awake={awake} />;- },-}));-vi.mock("./OfficeCameraRig", () => ({ ZOOM_SECONDS: 1 }));-vi.mock("./OfficeFrameDriver", () => ({ OfficeFrameDriver: () => null }));-vi.mock("./OfficePlayer", () => ({ ownsKeyboard: () => false }));-vi.mock("./OfficePanels", () => ({- AgentPanel: () => null,- StationSurface: () => <div data-testid="surface" />,- stationSurface: (selection: { kind: string; id: string } | null) => (selection?.kind === "checkpoint" && selection.id === "manage" ? "sheet" : null),-}));-vi.mock("./TeamRoomPanel", () => ({ MeetingStatus: () => null }));-vi.mock("./OfficeHud", () => ({- OfficeTools: () => { useEffect(() => { state.tools += 1; return () => { state.tools -= 1; }; }, []); return null; },- StationPrompt: () => null, ControlHints: () => <div data-testid="hints" />, stationAction: () => "", stationLabel: () => "",-}));-vi.mock("./PaneCommandPanel", () => ({ PaneCommandPanel: () => null }));-vi.mock("./ArcadeCabinet", () => ({ ArcadeCabinet: () => null }));-vi.mock("./ElevatorPanel", () => ({ ElevatorPanel: () => null }));-vi.mock("./ElevatorDoors", () => ({ ElevatorDoors: () => null }));-vi.mock("./OfficeMinimap", () => ({ OfficeMinimap: () => {- useEffect(() => { state.maps += 1; return () => { state.maps -= 1; }; }, []);- return null;-} }));-vi.mock("../progression/useProgressionSync", () => ({ useProgressionSync: () => {- useEffect(() => { state.visits += 1; return () => { state.visits -= 1; }; }, []);-} }));-vi.mock("../progression/LevelHud", () => ({ LevelHud: () => null, LevelToasts: () => null }));-vi.mock("../progression/LevelUpBanner", () => ({ LevelUpBanner: () => null }));-vi.mock("../progression/hall/LevelHallScreen", () => ({ LevelHallScreen: () => null }));--afterEach(() => {- cleanup();- useOfficeStore.getState().select(null);- useProgression.getState().openPanel(null);- vi.useRealTimers();- vi.clearAllMocks();- state.canvasMounts = 0;- state.canvasUnmounts = 0;-});--it("retains one canvas across chat visits while stopping input, visits, HUD and polling", () => {- vi.useFakeTimers();- const view = render(<OfficeStage />);- const canvas = screen.getByTestId("canvas");- expect(canvas.dataset.loop).toBe("always");- expect(state.canvasMounts).toBe(1);- expect(state.visits).toBe(1);- expect(state.maps).toBe(1);- expect(state.tools).toBe(1);- // H opens the directory at the reception from anywhere, as a dialog over the map; H again closes it.- fireEvent.keyDown(window, { code: "KeyH" });- expect(useOfficeStore.getState().selection).toEqual({ kind: "checkpoint", id: "manage" });- expect(screen.getByTestId("surface")).toBeTruthy();- fireEvent.keyDown(window, { code: "KeyH" });- expect(useOfficeStore.getState().selection).toBeNull();- fireEvent.keyDown(window, { code: "KeyH" });- expect(useOfficeStore.getState().selection).toEqual({ kind: "checkpoint", id: "manage" });-- view.rerender(<OfficeStage active={false} />);- expect(screen.getByTestId("canvas")).toBe(canvas);- expect(canvas.dataset.loop).toBe("never");- expect(canvas.dataset.active).toBe("false");- expect(screen.getByTestId("scene").dataset.awake).toBe("false");- expect(state.visits).toBe(0);- expect(state.maps).toBe(0);- expect(state.tools).toBe(0);- expect(screen.queryByTestId("surface")).toBeNull();- expect(state.rosterEnabled).toHaveBeenLastCalledWith(false);- expect(state.codingEnabled).toHaveBeenLastCalledWith(false);- expect(state.chatsEnabled).toHaveBeenLastCalledWith(false);- expect(useOfficeStore.getState().selection).toBeNull();- for (const code of ["KeyH", "KeyL", "KeyM"]) {- const event = new KeyboardEvent("keydown", { code, bubbles: true, cancelable: true });- window.dispatchEvent(event);- expect(event.defaultPrevented).toBe(false);- }- expect(useOfficeStore.getState().selection).toBeNull();- expect(useProgression.getState().panel).toBeNull();- act(() => vi.advanceTimersByTime(30_000));- expect(state.client.invalidateQueries).not.toHaveBeenCalled();-- view.rerender(<OfficeStage />);- expect(screen.getByTestId("canvas")).toBe(canvas);- expect(canvas.dataset.loop).toBe("always");- expect(state.canvasMounts).toBe(1);- expect(state.canvasUnmounts).toBe(0);- expect(state.visits).toBe(1);- expect(state.maps).toBe(1);- expect(state.rosterEnabled).toHaveBeenLastCalledWith(true);- act(() => vi.advanceTimersByTime(7_000));- expect(state.client.invalidateQueries).toHaveBeenCalledOnce();- view.unmount();- expect(state.canvasUnmounts).toBe(1);- expect(state.visits).toBe(0);- expect(state.maps).toBe(0);-});--it("opens on the floor its host names without writing to the shared store while rendering", () => {- useOfficeStore.setState({ floor: "agents" });- state.drawn.length = 0;- // Another mounted office (the Agents view behind the IDE tab) watches the same store.- const seenByOther: string[] = [];- function OtherHost() { seenByOther.push(useOfficeStore((s) => s.floor)); return null; }- render(<><OtherHost /><OfficeStage initialFloor="coding" /></>);- // The store was untouched while the stage rendered: the switch came after, in an effect…- expect(state.drawn[0]).toEqual(["coding", "agents"]);- // …yet the stage never drew a frame of the other floor,- expect(state.drawn.map(([floor]) => floor)).not.toContain("agents");- // and the store, and with it every other host, ends up on the named floor.- expect(useOfficeStore.getState().floor).toBe("coding");- expect(seenByOther).toEqual(["agents", "coding"]);- expect(document.querySelector(".office-stage")?.getAttribute("data-office-floor")).toBe("coding");- useOfficeStore.setState({ floor: "agents" });-});--it("releases the coding poll while a visited coding floor is hidden", () => {- const view = render(<OfficeStage initialFloor="coding" />);- expect(state.codingEnabled).toHaveBeenLastCalledWith(true);- view.rerender(<OfficeStage initialFloor="coding" active={false} />);- expect(state.codingEnabled).toHaveBeenLastCalledWith(false);- view.rerender(<OfficeStage initialFloor="coding" />);- expect(state.codingEnabled).toHaveBeenLastCalledWith(true);-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/OfficeStage.tsx b/dodaios/ui/web/frontend/src/components/society/office/OfficeStage.tsxdeleted file mode 100644index 67eafa01fc..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/OfficeStage.tsx+++ /dev/null@@ -1,725 +0,0 @@-/**- * Agents > Map: the office. The person walks their own character through the- * floor (or zooms out and clicks), agents live their day according to their- * real run state, and checkpoints turn rooms into actions: create, manage,- * team up, dress up, talk to the lead, call a coffee break. One elevator ride- * up is the coding floor: a figure per IDE coding session, its terminal live- * on the monitor, and Gigi flying along with the person. The top floor is the- * arcade: a hall of retro cabinets, every one of them playable.- */-import { Component, lazy, Suspense, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";-import { useQueryClient } from "@tanstack/react-query";-import { useSyncCompanionPet } from "../companion/companionPetStore";-import { useActivePet } from "@/hooks/usePets";-import { advance, Canvas } from "@react-three/fiber";-import { useReducedMotion } from "framer-motion";-import { CanvasActivity, useCanvasAwake } from "@/hooks/useCanvasAwake";-import { useWebglSurface } from "@/hooks/useWebglSurface";-import { useWebglSupported } from "@/lib/graphDimension";-import { useT } from "@/i18n";-import { useEventStore } from "@/store/events";-import { useQuickCreateAgent, useSocietyRoster, type SocietyAgent } from "../data";-import { isCreateCancelled } from "../create/createAgentStore";-import { OfficeScene } from "./OfficeScene";-import { allDesks, buildOfficeLayout, countStates, seatedCount, type OfficeTeamInput } from "./officeLayout";-import { buildHallLayout } from "./hallFloorLayout";-import { chatGroupsKnown, useSocietyChatGroups } from "@/lib/societyChatGroups";-import { buildNavGrid } from "./officeNav";-import { SpotBook } from "./officeBehavior";-import { CAMERA_FOV } from "./officeCamera";-import { ZOOM_SECONDS } from "./OfficeCameraRig";-import { useDeskChats } from "./useDeskChats";-import type { Point } from "./officeLayout";-import { player, sameSelection, switchFloor, useOfficeStore, type OfficeFloor, type Selection } from "./officeStore";-import { courierSession, useCourier } from "./courierStore";-import { CourierHud } from "./CourierHud";-import { agentPositions, seatedAtDesk } from "./walkerRegistry";-import { useCodingFloorOccupants, type PaneOccupant } from "./codingFloor";-import { openPaneSession } from "./codingNavigate";-import { useDprBudget } from "./useDprBudget";-import { knownOnFloor, noteArrivals } from "./officeFloors";-import { atElevator } from "./elevatorCall";-import { loadProfile, playerLook, saveProfile, type PlayerProfile } from "./playerProfile";-import { AgentPanel, StationSurface, stationSurface, type OfficeActions } from "./OfficePanels";-import { MeetingStatus } from "./TeamRoomPanel";-import { ControlHints, OfficeTools, StationPrompt, stationAction, stationLabel, type PromptLine } from "./OfficeHud";-import { CALL_MS, isReception, loungeCentre, selectionKey, spawnScreenDive, stationOf, stationsFor } from "./stations";-import { PaneCommandPanel } from "./PaneCommandPanel";-import type { WalkerContext } from "./OfficeAgents";-import { ownsKeyboard } from "./OfficePlayer";-import { ArcadeCabinet } from "./ArcadeCabinet";-import { ElevatorPanel } from "./ElevatorPanel";-import { ElevatorDoors, type DoorsPhase } from "./ElevatorDoors";-import { buildArcadeLayout } from "../arcade/arcadeFloorLayout";-import { ARCADE_GAMES, gameForCabinet, type RetroGameId } from "../arcade/arcadeGames";-import { useOfficeSettings, useReceptionTab } from "./officeSettings";-import "./office.css";-import "./officeHud.css";-import "./officeMinimap.css";-import "./officeFloors.css";-import { OfficeMinimap } from "./OfficeMinimap";-import { OfficeFullMap } from "./OfficeFullMap";-import { OfficeFrameDriver } from "./OfficeFrameDriver";-import { useProgressionSync } from "../progression/useProgressionSync";-import { useProgression } from "../progression/progressionStore";-import { LevelHud, LevelToasts } from "../progression/LevelHud";-import { LevelUpBanner } from "../progression/LevelUpBanner";-import { LevelHallScreen } from "../progression/hall/LevelHallScreen";-import "../progression/progression.css";--// Only loaded when a host without its own create dialog (the IDE's side panel) spawns an agent.-// Only loaded when someone plays a retro cabinet on the arcade floor.-const RetroArcadeOverlay = lazy(() => import("../arcade/RetroArcadeOverlay").then((m) => ({ default: m.RetroArcadeOverlay })));--// Dev-only handles for runtime checks of walking and panels.-if (import.meta.env.DEV && typeof window !== "undefined") Object.assign(window, { __officeStore: useOfficeStore, __officePlayer: player, __officeAgents: agentPositions, __officeSeated: seatedAtDesk,- // Steps the scene without requestAnimationFrame (hidden test tabs): __officeStep(frames, dtMs).- __officeStep: (frames = 60, dtMs = 16) => { let t = performance.now(); for (let i = 0; i < frames; i += 1) { t += dtMs; advance(t); } } });--/** Status refresh while the office is on screen; jittered so windows never poll in lockstep (AP-33). */-const REFRESH_MS = 5000;-const REFRESH_JITTER_MS = 1500;--const EMPTY_OCCUPANTS: ReadonlyMap<string, PaneOccupant> = new Map();--/** How long a station's short answer stays on screen. */-const NOTICE_MS = 4200;--/** Is this key press text going into a field? */-function typesText(target: EventTarget | null): boolean {- return target instanceof HTMLElement && (target.isContentEditable || target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.tagName === "SELECT");-}--/** The elevator doors: they slide in DOORS_MS and stay shut between DOORS_HOLD_MIN_MS and DOORS_HOLD_MAX_MS while the floor changes. */-const DOORS_MS = 640;-const DOORS_HOLD_MIN_MS = 450;-const DOORS_HOLD_MAX_MS = 1600;--class RenderBoundary extends Component<{ children: ReactNode; fallbackText: string }, { failed: boolean }> {- state = { failed: false };- static getDerivedStateFromError() { return { failed: true }; }- componentDidCatch(error: Error) { console.warn("Office renderer unavailable", error); }- render() {- return this.state.failed ? <div className="office-fallback" role="status">{this.props.fallbackText}</div> : this.props.children;- }-}--export interface OfficeStageProps {- /** The agents list (the IDE tab passes its own sessions list). */- onOpenLedger?: () => void;- onSelectAgent?: (id: string | null) => void;- onCreateAgent?: () => void;- onOpenGroup?: (groupId: string) => void;- /** The floor to show on mount; without it the office opens on the floor it was left on. */- initialFloor?: OfficeFloor;- /** A narrow host (the IDE side panel): smaller HUD, no minimap or compass. */- compact?: boolean;- /** A visited map keeps its renderer while its host shows chat. */- active?: boolean;-}--/** Visit-only subscriptions and sounds end when the retained world is hidden. */-function OfficeVisit({ floor }: { floor: OfficeFloor }) {- useProgressionSync(true, floor);- return null;-}--function useRosterRefresh(awake: boolean) {- const client = useQueryClient();- useEffect(() => {- if (!awake) return;- let timer: ReturnType<typeof setTimeout>;- const schedule = () => {- timer = setTimeout(() => {- void client.invalidateQueries({ queryKey: ["society", "roster"] });- schedule();- }, REFRESH_MS + Math.random() * REFRESH_JITTER_MS);- };- schedule();- return () => clearTimeout(timer);- }, [awake, client]);-}--/**- * Agents created while the office is open appear on the spawn pad in the- * middle of the floor and walk to their desk; everyone else is simply there.- * Each floor keeps its own memory, so riding up or down never makes a whole- * floor "arrive".- */-function useNewcomers(active: SocietyAgent[], floor: OfficeFloor): ReadonlySet<string> {- const [newcomers, setNewcomers] = useState<{ floor: OfficeFloor; ids: ReadonlySet<string> }>({ floor, ids: new Set() });- useEffect(() => {- const fresh = noteArrivals(knownOnFloor(floor), active.map((a) => a.agentId));- if (fresh.length === 0) return;- setNewcomers((prev) => ({ floor, ids: new Set([...(prev.floor === floor ? prev.ids : []), ...fresh]) }));- }, [active, floor]);- return newcomers.floor === floor ? newcomers.ids : EMPTY_IDS;-}-const EMPTY_IDS: ReadonlySet<string> = new Set();--export function OfficeStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenGroup, initialFloor, compact = false, active: onScreen = true }: OfficeStageProps) {- const t = useT();- const hostRef = useRef<HTMLDivElement>(null);- const visible = useCanvasAwake(hostRef);- const awake = onScreen && visible;- const onScreenRef = useRef(onScreen);- onScreenRef.current = onScreen;- const reduced = useReducedMotion() ?? false;- const { generation } = useWebglSurface(hostRef);- const webgl = useWebglSupported();- // A mount that names a floor opens there (e.g. the IDE tab on the coding floor).- // The switch writes to the store every host shares, so it happens in a layout effect, never while rendering- // (another mounted office subscribed to `floor` would be updated in the middle of this render). Until it has- // run, this stage already renders the floor it was asked for, so not a single frame shows the other one.- const [opening, setOpening] = useState<OfficeFloor | null>(initialFloor ?? null);- useLayoutEffect(() => {- if (!opening) return;- switchFloor(opening, false);- setOpening(null);- // Once per mount: a host that changes `initialFloor` later does not move a person who has ridden elsewhere.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);- const storeFloor = useOfficeStore((s) => s.floor);- const floor = opening ?? storeFloor;- const coding = floor === "coding";- // The arcade floor has no agents: no roster, desks or chats, just the cabinets.- const arcade = floor === "arcade";- // Nobody works in the Level Hall either: it is the levels' own floor.- const hall = floor === "hall";- const roster = useSocietyRoster(awake);- useRosterRefresh(awake && floor === "agents");- // Jarvis keeps the person company as the pet chosen in My Pets.- useSyncCompanionPet();- const petName = useActivePet()?.name || "Gigi";- // Levels: the person, their pet and every agent earn XP for real work; the Verse shows and celebrates it.- const [overview, setOverview] = useState(0);- const [mapOpen, setMapOpen] = useState(false);- const [profile, setProfile] = useState<PlayerProfile>(loadProfile);- const selection = useOfficeStore((s) => s.selection);- const nearby = useOfficeStore((s) => s.nearby);- const follow = useOfficeStore((s) => s.follow);- const select = useOfficeStore((s) => s.select);-- // The call button tells how many are upstairs, so standing at the elevator wakes the coding roster too.- const atLift = nearby?.kind === "checkpoint" && nearby.id === "elevator";- const codingFloor = useCodingFloorOccupants(awake && (coding || atLift));- const jarvisAgents = useMemo(() => (roster.data?.agents ?? []).filter((a) => a.lifecycle !== "archived"), [roster.data]);- const codingAgents = useMemo(() => codingFloor.occupants.map((o) => o.agent), [codingFloor.occupants]);- // The agents floor is built from the teams (society chat groups): every team has its studio. The roster waits- // for the first answer about them, so nobody is seated in the pool and then sent across the floor.- const chatGroups = useSocietyChatGroups(awake && floor === "agents");- const teamsKnown = chatGroupsKnown(chatGroups);- const teams = useMemo<OfficeTeamInput[]>(() => (chatGroups.data ?? []).map((group) => ({- id: group.group_id, name: group.name, members: group.members, createdMs: group.created_ms, leadId: group.lead_agent_id ?? null,- })), [chatGroups.data]);- const active = useMemo(() => (arcade || hall ? [] : coding ? codingAgents : teamsKnown ? jarvisAgents : []),- [arcade, hall, coding, codingAgents, jarvisAgents, teamsKnown]);- const ready = arcade || hall ? true : coding ? codingFloor.loaded : !!roster.data && teamsKnown;- const occupants = useMemo(() => (coding ? codingFloor.byAgentId : EMPTY_OCCUPANTS), [coding, codingFloor.byAgentId]);- const occupantsRef = useRef(occupants);- occupantsRef.current = occupants;- const agents = useMemo(() => new Map<string, SocietyAgent>(active.map((a) => [a.agentId, a])), [active]);- const newcomers = useNewcomers(active, floor);- // The floor plan depends on who works where, never on run state: a status- // refresh changes monitors and behaviour without re-seating anyone.- // The same holds for the teams: their 10 s refetch rebuilds the floor only when a team's name, members or lead changed.- const teamsKey = floor === "agents"- ? teams.map((team) => `${team.id}|${team.name}|${team.createdMs}|${team.leadId ?? ""}|${team.members.join("+")}`).join(",") : "";- const seatingKey = floor + ":" + active.map((a) => `${a.agentId}|${a.tier}|${a.providerLabel}|${a.createdMs}`).join(",") + "#" + teamsKey;- const layout = useMemo(() => (floor === "arcade" ? buildArcadeLayout() : floor === "hall" ? buildHallLayout()- : buildOfficeLayout(active, { variant: floor, teams })),- // eslint-disable-next-line react-hooks/exhaustive-deps- [seatingKey]);- // Truthful overflow: how many of the floor's agents the plan could not seat.- const seated = useMemo(() => seatedCount(layout), [layout]);- const grid = useMemo(() => buildNavGrid(layout), [layout]);- // One reservation book for the whole visit: a rebuilt floor plan (someone- // joined or left) must not forget who already sits on which couch.- const [book] = useState(() => new SpotBook());- useEffect(() => { book.retain(new Set(layout.spots.map((spot) => spot.id))); }, [book, layout]);- const agentsRef = useRef(agents);- agentsRef.current = agents;- const walkers = useMemo<WalkerContext>(() => {- const desks = allDesks(layout);- return {- layout, grid, book, spawn: layout.arrival,- colleagues: () => desks.filter((d) => d.agentId && agentsRef.current.get(d.agentId)?.state === "working")- .map((d) => ({ agentId: d.agentId as string, desk: d })),- };- }, [layout, grid, book]);-- // Coding sessions have no desk chat; their monitors poll the terminal instead.- const sessions = useMemo(() => new Map(active.filter((a) => a.chatSessionId).map((a) => [a.agentId, a.chatSessionId as string])), [active]);- const chats = useDeskChats(sessions, awake && floor === "agents");- // Opening someone: a coding agent opens its IDE pane; a Jarvis agent its chat- // (a host without an agent view, like the IDE tab, goes to the Agents section).- const openAgent = useCallback((agentId: string) => {- const occupant = occupantsRef.current.get(agentId);- if (occupant) { openPaneSession(occupant.pane); return; }- if (onSelectAgent) onSelectAgent(agentId);- else useEventStore.getState().setActiveSection("agents");- }, [onSelectAgent]);- // Clicking a chat monitor dives into it, then opens that agent's chat. A- // coding agent's monitor opens its command panel instead: prompt it right- // here, and "open" from there shows the pane maximized in the grid.- const openTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);- useEffect(() => () => clearTimeout(openTimer.current), []);- const [diving, setDiving] = useState(false);- const openScreen = useCallback((agentId: string, screen: Point & { y: number }, facing: number) => {- select(null);- clearTimeout(openTimer.current);- if (occupantsRef.current.has(agentId)) { select({ kind: "agent", id: agentId }); return; }- if (reduced) { openAgent(agentId); return; }- useOfficeStore.getState().zoomInto([screen.x, screen.y, screen.z], facing);- // The screen fills the view, then the real chat view fades in over it.- setDiving(true);- openTimer.current = setTimeout(() => { openAgent(agentId); setDiving(false); }, ZOOM_SECONDS * 1000 + 260);- }, [openAgent, reduced, select]);- // A Mission Control monitor was clicked: the camera dives into its glass,- // then the section it shows opens. The Agents view hosting this map switches- // to its list; any other host navigates to the Agents section.- const sectionDive = useOfficeStore((s) => s.sectionDive);- const lastSectionDive = useRef(sectionDive?.seq ?? 0);- useEffect(() => {- if (!sectionDive || sectionDive.seq === lastSectionDive.current) return;- lastSectionDive.current = sectionDive.seq;- if (!awake) return;- const { section } = sectionDive;- const go = () => {- if (section === "agents" && !compact && onOpenLedger) onOpenLedger();- else useEventStore.getState().setActiveSection(section);- };- clearTimeout(openTimer.current);- if (reduced) { go(); return; }- setDiving(true);- openTimer.current = setTimeout(() => { go(); setDiving(false); }, ZOOM_SECONDS * 1000 + 260);- }, [sectionDive, compact, onOpenLedger, reduced, awake]);-- // The elevator: pressing its call button, standing at the doors, opens the- // button panel; pressing a floor there closes the elevator doors over the- // stage, the floor switches behind them, and they open once the new floor- // has loaded (capped). A press from afar (a click on the button, the floor- // token or E anywhere) walks the character over instead; it never rides- // from a distance. Reduced motion switches floors at once.- const [picking, setPicking] = useState(false);- const [ride, setRide] = useState<{ from: OfficeFloor; to: OfficeFloor; phase: DoorsPhase; closedMs: number } | null>(null);- const rideTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);- useEffect(() => () => clearTimeout(rideTimer.current), []);- const pressCall = useCallback(() => {- if (ride || picking) return;- const lift = layout.checkpoints.find((cp) => cp.id === "elevator");- if (!atElevator(player, lift)) {- if (lift) useOfficeStore.getState().requestWalk({ x: lift.x, z: lift.z });- return;- }- useOfficeStore.getState().select(null);- setPicking(true);- }, [ride, picking, layout]);- const closePicker = useCallback(() => setPicking(false), []);- const pickFloor = useCallback((to: OfficeFloor) => {- setPicking(false);- const from = useOfficeStore.getState().floor;- if (ride || to === from) return;- if (reduced) { switchFloor(to, true); return; }- setRide({ from, to, phase: "closing", closedMs: 0 });- clearTimeout(rideTimer.current);- rideTimer.current = setTimeout(() => {- switchFloor(to, true);- setRide((r) => (r ? { ...r, phase: "closed", closedMs: performance.now() } : r));- rideTimer.current = setTimeout(() => setRide((r) => (r?.phase === "closed" ? { ...r, phase: "opening" } : r)), DOORS_HOLD_MAX_MS);- }, DOORS_MS);- }, [ride, reduced]);- // E beside the courier on the sky pad, or a click on it, boards it: the flight takes the keys and the camera.- const flying = useCourier((s) => s.flying);- useEffect(() => {- if (!awake || selection?.kind !== "checkpoint" || selection.id !== "ship") return;- select(null);- // Like the elevator, never from a distance: a click from afar walks the person over to the hatch first.- const hatch = layout.checkpoints.find((cp) => cp.id === "ship");- if (hatch && Math.hypot(player.x - hatch.x, player.z - hatch.z) > hatch.radius + 0.6) {- useOfficeStore.getState().requestWalk({ x: hatch.x, z: hatch.z });- return;- }- useCourier.getState().board();- }, [selection, select, awake, layout]);- // E at the elevator, or a click on its floor token, presses the call button instead of opening a panel.- useEffect(() => {- if (!awake || selection?.kind !== "checkpoint" || selection.id !== "elevator") return;- select(null);- pressCall();- }, [selection, select, pressCall, awake]);- useEffect(() => {- if (ride?.phase === "closed" && floor === ride.to && ready) {- // The doors stay shut a short beat at least, so the change reads as a ride and not a cut.- const left = DOORS_HOLD_MIN_MS - (performance.now() - ride.closedMs);- clearTimeout(rideTimer.current);- rideTimer.current = setTimeout(() => setRide((r) => (r ? { ...r, phase: "opening" } : r)), Math.max(0, left));- }- if (ride?.phase === "opening") {- clearTimeout(rideTimer.current);- rideTimer.current = setTimeout(() => setRide(null), DOORS_MS);- }- }, [ride, floor, ready]);-- const counts = countStates(active);- const updateProfile = useCallback((next: PlayerProfile) => { setProfile(next); saveProfile(next); }, []);- // The coding floor's list is the IDE (or, in the IDE tab, its sessions list).- const openList = useCallback(() => {- if (coding && !compact) useEventStore.getState().setActiveSection("agentic-ide");- else onOpenLedger?.();- }, [coding, compact, onOpenLedger]);- // Spawning a Jarvis agent (the spawn point, reception): the host's one-click create, or the office's- // own where the host has none. The panel closes and the camera turns to the pad, where the agent appears.- const quickCreate = useQuickCreateAgent();- const creatingRef = useRef(false);- const createAgent = useCallback((turnToPad = true) => {- const store = useOfficeStore.getState();- store.select(null);- if (turnToPad && Math.hypot(player.x - layout.arrival.x, player.z - layout.arrival.z) > 4) store.focusOn(layout.arrival);- if (onCreateAgent) { onCreateAgent(); return; }- // A double click must not create two agents.- if (creatingRef.current) return;- creatingRef.current = true;- void quickCreate()- .catch((error) => {- if (!isCreateCancelled(error)) console.warn("Agent creation failed", error);- })- .finally(() => { creatingRef.current = false; });- }, [onCreateAgent, layout, quickCreate]);- const actions = useMemo<OfficeActions>(() => ({- onOpenAgent: openAgent,- onOpenLedger: openList, onCreateAgent: () => createAgent(), onOpenGroup,- }), [openAgent, openList, createAgent, onOpenGroup]);-- // A short line the HUD says once (a station answered without opening anything).- const [notice, setNotice] = useState<string | null>(null);- const noticeTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);- useEffect(() => () => clearTimeout(noticeTimer.current), []);- const say = useCallback((text: string) => {- setNotice(text);- clearTimeout(noticeTimer.current);- noticeTimer.current = setTimeout(() => setNotice(null), NOTICE_MS);- }, []);- // The coffee break in progress: who was called, until the call runs out on its own.- const [coffeeBreak, setCoffeeBreak] = useState<{ ids: string[]; untilMs: number } | null>(null);- useEffect(() => {- if (!coffeeBreak) return;- const timer = setTimeout(() => setCoffeeBreak(null), Math.max(0, coffeeBreak.untilMs - Date.now()));- return () => clearTimeout(timer);- }, [coffeeBreak]);- // Stations that act instead of opening a surface: the spawn terminal opens the app's create dialog- // (after a dive into its screen), the lead's desk selects the lead, the coffee bar calls or ends a break.- useEffect(() => {- if (!awake || selection?.kind !== "checkpoint") return;- const store = useOfficeStore.getState();- if (selection.id === "spawn") {- store.select(null);- clearTimeout(openTimer.current);- // The dive leads into the dialog; a host that creates at once (no dialog) keeps the pad in view instead.- const dive = onCreateAgent && !reduced ? spawnScreenDive(layout, player) : null;- if (!dive) { createAgent(); return; }- store.zoomInto(dive.target, dive.facing, dive.size);- openTimer.current = setTimeout(() => createAgent(false), ZOOM_SECONDS * 1000 + 120);- } else if (selection.id === "lead") {- const lead = active.filter((a) => a.tier === "lead").sort((a, b) => a.createdMs - b.createdMs || a.agentId.localeCompare(b.agentId))[0];- if (lead) { store.select({ kind: "agent", id: lead.agentId }); return; }- store.select(null);- say(t("society.office.lead_empty"));- } else if (selection.id === "break") {- store.select(null);- if (coffeeBreak && coffeeBreak.untilMs > Date.now()) {- store.release(coffeeBreak.ids);- setCoffeeBreak(null);- say(t("society.office.break_ended"));- return;- }- const idle = active.filter((a) => a.state === "idle").map((a) => a.agentId);- if (idle.length === 0) { say(t("society.office.break_none")); return; }- store.summon(idle, loungeCentre(layout), CALL_MS);- setCoffeeBreak({ ids: idle, untilMs: Date.now() + CALL_MS });- say(t("society.office.break_called").replace("{0}", String(idle.length)));- }- }, [selection, awake, onCreateAgent, reduced, layout, createAgent, active, coffeeBreak, say, t]);- // Something opened: whatever the pointer rested on in the world is behind it now (a dialog swallows the pointer-out).- useEffect(() => {- if (!selection) return;- useOfficeStore.getState().setHover(null);- document.body.style.cursor = "";- }, [selection]);- // The coding floor's spawn terminal: dive into its screen first, then its launcher opens (reduced motion: at once).- const atLaunch = selection?.kind === "checkpoint" && selection.id === "launch";- const [launcherOpen, setLauncherOpen] = useState(false);- const layoutRef = useRef(layout);- layoutRef.current = layout;- useEffect(() => {- if (!awake || !atLaunch) { setLauncherOpen(false); return; }- const dive = reduced ? null : spawnScreenDive(layoutRef.current, player);- if (!dive) { setLauncherOpen(true); return; }- useOfficeStore.getState().zoomInto(dive.target, dive.facing, dive.size);- const timer = setTimeout(() => setLauncherOpen(true), ZOOM_SECONDS * 1000 + 120);- return () => clearTimeout(timer);- }, [atLaunch, awake, reduced]);- // A team studio that left the floor plan takes its open sheet with it.- useEffect(() => {- if (awake && selection?.kind === "team" && !stationOf(layout, selection)) select(null);- }, [selection, layout, select, awake]);-- // Whatever closes (a dialog, a docked panel) hands the keyboard back to the map's canvas host, so the walking- // keys answer at once and focus never strands on a button that is gone.- const focusMap = useCallback(() => hostRef.current?.focus({ preventScroll: true }), []);- const hadSelection = useRef(false);- useEffect(() => {- const had = hadSelection.current;- hadSelection.current = !!selection;- if (!awake || selection || !had) return;- const focused = document.activeElement;- if (!focused || focused === document.body) focusMap();- }, [selection, awake, focusMap]);- // Escape closes an open panel before it can leave the map.- useEffect(() => {- if (!awake) return;- const onKey = (event: KeyboardEvent) => {- // A field or a dialog (e.g. the create dialog opened from reception) owns its own Escape.- if (event.key !== "Escape" || !useOfficeStore.getState().selection || ownsKeyboard(event.target)) return;- event.preventDefault();- event.stopPropagation();- select(null);- focusMap();- };- document.addEventListener("keydown", onKey, true);- return () => document.removeEventListener("keydown", onKey, true);- }, [select, awake]);-- // H (or the HUD button) opens reception on the controls guide from anywhere, and closes it again.- const toggleGuide = useCallback(() => {- if (isReception(useOfficeStore.getState().selection)) { select(null); return; }- useReceptionTab.getState().setTab("controls");- select({ kind: "checkpoint", id: "manage" });- }, [select]);- useEffect(() => {- if (!awake) return;- const onKey = (event: KeyboardEvent) => {- // In the courier, H is the pilot's own help.- if (event.code !== "KeyH" || event.repeat || event.ctrlKey || event.metaKey || event.altKey || courierSession.flying) return;- const current = useOfficeStore.getState().selection;- // The open directory is a dialog of its own: H closes it again unless the person is typing in it.- if (isReception(current) ? typesText(event.target) : ownsKeyboard(event.target)) return;- if (current?.kind === "arcade") return;- event.preventDefault();- toggleGuide();- };- window.addEventListener("keydown", onKey);- return () => window.removeEventListener("keydown", onKey);- }, [toggleGuide, awake]);-- // The Level Hall's two checkpoints open its screen: the stage on the studio, the guide on the overview.- useEffect(() => {- if (!awake || selection?.kind !== "checkpoint" || (selection.id !== "studio" && selection.id !== "levels")) return;- useProgression.getState().openPanel(selection.id === "studio" ? "studio" : "overview");- select(null);- }, [selection, select, awake]);-- // L (or the level card) opens the Level Hall screen, and closes it again.- useEffect(() => {- if (!awake) return;- const onKey = (event: KeyboardEvent) => {- // In the courier, L is the landing assist.- if (event.code !== "KeyL" || event.repeat || event.ctrlKey || event.metaKey || event.altKey || courierSession.flying) return;- const levels = useProgression.getState();- if (ownsKeyboard(event.target) && !levels.panel) return;- if (useOfficeStore.getState().selection?.kind === "arcade") return;- event.preventDefault();- levels.openPanel(levels.panel ? null : "overview");- };- window.addEventListener("keydown", onKey);- return () => window.removeEventListener("keydown", onKey);- }, [awake]);- // The Level Hall screen closes with the map.- useEffect(() => () => { if (onScreenRef.current) useProgression.getState().openPanel(null); }, []);-- // Leaving the map forgets panels and calls; the office opens fresh next time.- useEffect(() => () => {- if (!onScreenRef.current) return;- const store = useOfficeStore.getState();- store.select(null);- store.setNearby(null);- store.setHover(null);- store.clearSummons();- }, []);-- useEffect(() => {- if (onScreen) return;- // A mode change ends input and pending navigation without discarding GPU resources.- clearTimeout(openTimer.current);- clearTimeout(rideTimer.current);- setDiving(false);- setPicking(false);- setRide(null);- setMapOpen(false);- useProgression.getState().openPanel(null);- clearTimeout(noticeTimer.current);- setNotice(null);- setCoffeeBreak(null);- const store = useOfficeStore.getState();- store.select(null);- store.setNearby(null);- store.setHover(null);- store.clearSummons();- }, [onScreen]);-- // A panel for an agent that left the roster closes itself.- useEffect(() => {- if (awake && selection?.kind === "agent" && ready && !agents.has(selection.id)) select(null);- }, [selection, agents, ready, select, awake]);-- const selectedAgent = selection?.kind === "agent" ? agents.get(selection.id) ?? null : null;- const selectedPane = selectedAgent ? occupants.get(selectedAgent.agentId) ?? null : null;- const nearbyGame = nearby?.kind === "arcade" ? gameForCabinet(nearby.id) : null;- // The one prompt: what the pointer rests on from afar, else what the character stands at.- const hover = useOfficeStore((s) => s.hover);- const promptTarget: Selection | null = hover && !sameSelection(hover, nearby) ? hover : nearby;- const breakOn = !!coffeeBreak;- const promptLine = useMemo<PromptLine | null>(() => {- if (!promptTarget) return null;- const how = promptTarget === nearby ? "key" : "click";- if (promptTarget.kind === "agent") {- const name = agents.get(promptTarget.id)?.name;- return name ? { how, action: t(coding ? "society.office.prompt_pane" : "society.office.prompt_agent").replace("{0}", name) } : null;- }- if (promptTarget.kind === "arcade") {- const game = gameForCabinet(promptTarget.id);- return { how, action: game ? t("society.arcade.play_prompt").replace("{0}", game.title) : t("society.office.arcade_prompt") };- }- const station = stationsFor(layout).find((s) => s.key === selectionKey(promptTarget));- return station ? { how, action: stationAction(station, t, breakOn), object: stationLabel(station, t) } : null;- }, [promptTarget, nearby, agents, coding, layout, breakOn, t]);- // Standing at a retro cabinet fetches its overlay, so pressing E opens it at once instead of after a chunk load.- const nearbyRetro = nearbyGame?.kind === "retro";- useEffect(() => { if (nearbyRetro) void import("../arcade/RetroArcadeOverlay"); }, [nearbyRetro]);- // The cabinet being played: the break room's (and the hall's Asteroid Run) open the 3D game, the others a retro game.- const playing = selection?.kind === "arcade" ? gameForCabinet(selection.id) : null;- const playsAsteroids = selection?.kind === "arcade" && (!playing || playing.kind === "asteroid3d");- const titleKey = arcade ? "society.office.arcade_floor_title" : hall ? "society.office.hall_floor_title"- : coding ? "society.office.coding_title" : "society.office.title";- const playerName = profile.name.trim() || t("society.office.you");- const playerToyLook = useMemo(() => playerLook(profile), [profile]);- const agentNames = useMemo(() => new Map(jarvisAgents.map((a) => [a.agentId, a.name])), [jarvisAgents]);- const hintsSeen = useOfficeSettings((s) => s.hintsSeen);- const receptionOpen = isReception(selection);- // A station's own surface: a dialog over the map, or a panel docked beside it (the wardrobe).- // The coding floor's spawn terminal has a screen: its launcher opens once the camera has dived into it.- const surface = atLaunch && !launcherOpen ? null : stationSurface(selection);- const agentPanel = selection?.kind === "agent" && !!selectedAgent && !selectedPane;-- // A full-view office draws no more pixels than a side-panel one would afford.- const dpr = useDprBudget(hostRef);-- return (- <CanvasActivity.Provider value={awake}>- <section className={compact ? "office-stage office-stage-compact" : "office-stage"} aria-label={t(titleKey)}- data-office-agents={active.length} data-office-floor={floor} data-office-awake={awake}>- <div ref={hostRef} className="office-viewport" tabIndex={0} role="application" aria-label={t("society.office.viewport")}>- {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: 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)}>- <OfficeFrameDriver enabled={awake && compact} />- <OfficeScene floor={floor} occupants={occupants} ready={ready} layout={layout} grid={grid} walkers={walkers} agents={agents} newcomers={newcomers}- awake={awake} reduced={reduced} overview={overview} player={{ look: playerToyLook, name: playerName }}- selection={selection} nearby={nearby} chats={chats} onOpenScreen={openScreen}- elevatorCall={{ lit: picking || !!ride, picking, onPress: pressCall }} />- </Canvas>- </Suspense>- </RenderBoundary>- ) : <div className="office-fallback" role="status">{t("society.office.no_graphics")}</div>}- </div>-- {awake && <>- <OfficeVisit floor={floor} />- <div className="office-hud office-hud-left" data-office-ui>- {/* One card: the floor's name, and under it who is doing what. */}- <div className="office-card office-title">- <strong>{t(titleKey)}</strong>- {arcade- ? <span>{t("society.office.arcade_floor_subtitle").replace("{0}", String(ARCADE_GAMES.length))}</span>- : hall ? <span>{t("society.office.hall_floor_subtitle")}</span> : (- <span className="office-states" role="status" aria-live="polite">- <span data-tone="working"><i aria-hidden />{t("society.office.count_working").replace("{0}", String(counts.working))}</span>- <span data-tone="waiting"><i aria-hidden />{t("society.office.count_waiting").replace("{0}", String(counts.waiting))}</span>- <span data-tone="idle"><i aria-hidden />{t("society.office.count_idle").replace("{0}", String(counts.idle))}</span>- {counts.paused > 0 && <span data-tone="paused"><i aria-hidden />{t("society.office.count_paused").replace("{0}", String(counts.paused))}</span>}- </span>- )}- </div>- <LevelHud playerName={playerName} petName={petName} compact={compact} />- {/* A running team meeting, while its sheet is closed; this card also ends it when its time is up. */}- {surface !== "sheet" && <MeetingStatus agents={active} layout={layout} actions={actions} compact />}- {!coding && roster.data?.sample && <p className="office-card office-note">{t("society.office.sample")}</p>}- {coding && codingFloor.loaded && active.length === 0 && <p className="office-card office-note">{t("society.office.coding_empty")}</p>}- {active.length > seated && <p className="office-card office-note">{t("society.office.overflow").replace("{0}", String(seated))}</p>}- </div>-- {/* The wardrobe and the Level Hall are places (the places menu, their own keys), not permanent buttons. */}- <OfficeTools layout={layout} follow={follow} onFollow={() => useOfficeStore.getState().setFollow(true)}- onOverview={() => setOverview((v) => v + 1)} helpOpen={receptionOpen} onHelp={toggleGuide}- list={!arcade && !hall && (!coding || !compact || onOpenLedger) ? {- label: t(coding ? (compact ? "society.office.ledger_coding" : "society.office.open_ide") : "society.office.ledger"),- ide: coding && !compact, onOpen: openList,- } : null} />-- {playsAsteroids && <ArcadeCabinet onClose={() => select(null)} />}- {playing && playing.kind === "retro" && (- <Suspense fallback={null}>- <RetroArcadeOverlay gameId={playing.id as RetroGameId} onClose={() => select(null)} />- </Suspense>- )}-- {/* A coding session is a window of its own on the stage, not a panel in the corner slot. */}- {selection?.kind === "agent" && selectedPane && (- <PaneCommandPanel occupant={selectedPane} compact={compact} onOpen={() => openPaneSession(selectedPane.pane)} onClose={() => select(null)} />- )}- {/* An agent's walkie-talkie and the wardrobe sit beside the map; every other station's surface is a dialog over it. */}- {(agentPanel || surface === "side") && selection && (- <div className="office-panel-slot" data-tall={surface === "side" || undefined}>- {agentPanel && selectedAgent- ? <AgentPanel agent={selectedAgent} actions={actions} onClose={() => select(null)} />- : <StationSurface selection={selection} floor={floor} agents={active} layout={layout} grid={grid} sample={!coding && (roster.data?.sample ?? false)}- profile={profile} onProfile={updateProfile} actions={actions} onClose={() => select(null)} />}- </div>- )}- {surface === "sheet" && selection && (- <StationSurface selection={selection} floor={floor} agents={active} layout={layout} grid={grid} sample={!coding && (roster.data?.sample ?? false)}- profile={profile} onProfile={updateProfile} actions={actions} onClose={() => select(null)} returnFocus={focusMap} />- )}-- {/* Bottom centre: the one prompt, a station's short answer, and the controls for a first visit. */}- <div className="office-hud office-hud-bottom">- {promptLine && promptTarget && !selection && !picking && !ride && !flying && (- <StationPrompt line={promptLine} compact={compact} onUse={() => select(promptTarget)} />- )}- <div role="status" aria-live="polite">{notice && <p className="office-card office-notice" data-office-ui>{notice}</p>}</div>- {!compact && !hintsSeen && !selection && !picking && !ride && !flying && (- <ControlHints onDismiss={() => useOfficeSettings.getState().set({ hintsSeen: true })} />- )}- </div>- {flying && <CourierHud />}- {diving && <div className="office-dive-fade" aria-hidden />}- {picking && !ride && <ElevatorPanel floor={floor} onPick={pickFloor} onClose={closePicker} />}- {ride && <ElevatorDoors from={ride.from} to={ride.to} phase={ride.phase} />}- {!compact && <OfficeMinimap layout={layout} agents={agents} selectedId={selection?.kind === "agent" ? selection.id : null}- onOpenMap={() => setMapOpen(true)} />}- <OfficeFullMap open={mapOpen} onOpen={() => setMapOpen(true)} onClose={() => setMapOpen(false)}- layout={layout} agents={agents} selectedId={selection?.kind === "agent" ? selection.id : null} />- <LevelToasts names={agentNames} agents={jarvisAgents} />- <LevelHallScreen agents={jarvisAgents} playerName={playerName} petName={petName} playerLook={playerToyLook} />- <LevelUpBanner playerName={playerName} petName={petName} />- </>}- </section>- </CanvasActivity.Provider>- );-}--export default OfficeStage;diff --git a/dodaios/ui/web/frontend/src/components/society/office/PaneCommandPanel.tsx b/dodaios/ui/web/frontend/src/components/society/office/PaneCommandPanel.tsxdeleted file mode 100644index 68420c1aa4..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/PaneCommandPanel.tsx+++ /dev/null@@ -1,348 +0,0 @@-/**- * A coding session on the coding floor, shown as the pane it is — in a window- * over the map: the Agentic IDE's title bar (state dot, agent mark, the pane's- * title, the pane actions as quiet icons) over the IDE's own live terminal.- * Nothing else — no chips, no toolbar, no side notes, no second prompt box.- *- * The window opens bottom-right at about half the stage's width, moves by its- * title bar, resizes by any edge or corner, and remembers where the reader- * left it (./paneWindow). Its size is fixed while nothing is being dragged, so- * the terminal inside never resizes the agent on its own.- *- * The terminal is the IDE pane's `AgenticTerminal` itself, attached as one more- * viewer of the same PTY: the same renderer, font and colours, and typed into- * directly, exactly like the pane in the IDE. It opens as the pane's size lead- * in this window (../../agentic/paneSizeLead), so the same pane in the IDE grid- * behind the office follows this window's size instead of trading it back and- * forth. Colours come from the pane's own appearance tables (./terminalThemes),- * so the window matches the IDE's panes in light and dark, including a light- * pane in a dark app.- */-import {- useEffect, useId, useLayoutEffect, useMemo, useRef, useState,- type CSSProperties, type MouseEvent as ReactMouseEvent, type PointerEvent as ReactPointerEvent, type RefObject,-} from "react";-import { Footprints, Hand, LocateFixed, Maximize2, Square, Trash2, X } from "lucide-react";-import { useT } from "@/i18n";-import { useThemeValue } from "@/hooks/useTheme";-import { closeTerminal, forkTerminal, interruptTerminal } from "@/lib/agenticIdeApi";-import { usePaneTitle } from "@/store/paneRecaps";-import { useWorkspacePanesStore } from "@/store/workspacePanes";-import { AgentMark } from "@/components/agentic/AgentMark";-import { AgenticTerminal } from "@/components/agentic/AgenticTerminal";-import { FONT_DEFAULT } from "@/components/agentic/paneFont";-import { warmTerminalFont } from "@/lib/terminalFont";-import { BranchIcon } from "@/components/agentic/branchIcon";-import { PANE_BRAND, PANE_CHROME, PANE_SOLID, PANE_TILE, storedPaneStyle, storedTerminalAppearance, themeFor } from "@/components/agentic/terminalThemes";-import type { PaneOccupant } from "./codingFloor";-import { player, useOfficeStore } from "./officeStore";-import { agentPositions } from "./walkerRegistry";-import { CALL_MS } from "./AgentTalkPanel";-import {- defaultRect, loadStoredWindow, moveRect, placeStored, resizeRect, saveStoredWindow, toStored,- type ResizeEdge, type StageSize, type WindowRect,-} from "./paneWindow";-import "./paneCommand.css";--// This module loads with the office, well before a session is clicked: fetch-// the terminal's font now, so the first panel opens on a font that is already-// here instead of waiting for it (measured: ~0.4 s of the first open).-warmTerminalFont(FONT_DEFAULT);--/** A second press within this window confirms closing the session. */-const CONFIRM_MS = 4000;-/** How long a success line stays on the window; an error stays until the next action. */-const NOTE_MS = 4000;-const EDGES: readonly ResizeEdge[] = ["n", "s", "e", "w", "ne", "nw", "se", "sw"];--function sinceLabel(at: number | null, t: (key: string) => string): string {- if (!at) return "";- const seconds = Math.max(0, Date.now() / 1000 - at);- if (seconds < 60) return t("society.office.since_now");- if (seconds < 3600) return t("society.office.since_minutes").replace("{0}", String(Math.floor(seconds / 60)));- if (seconds < 86400) return t("society.office.since_hours").replace("{0}", String(Math.floor(seconds / 3600)));- return t("society.office.since_days").replace("{0}", String(Math.floor(seconds / 86400)));-}--type Note = { tone: "ok" | "error"; text: string } | null;-type Gesture = {- kind: "move" | "resize";- edge: ResizeEdge;- pointerId: number;- startX: number;- startY: number;- start: WindowRect;-};--/** The stage the window floats over (its offset parent), measured before paint and on every resize. */-function useStageSize(panel: RefObject<HTMLElement | null>): StageSize | null {- const [stage, setStage] = useState<StageSize | null>(null);- useLayoutEffect(() => {- const host = panel.current?.parentElement;- if (!host) return;- const measure = () => {- const width = host.clientWidth, height = host.clientHeight;- setStage((prev) => (prev && prev.width === width && prev.height === height ? prev : { width, height }));- };- measure();- if (typeof ResizeObserver === "undefined") return;- const observer = new ResizeObserver(measure);- observer.observe(host);- return () => observer.disconnect();- }, [panel]);- return stage;-}--export function PaneCommandPanel({ occupant, compact = false, onOpen, onClose }: {- occupant: PaneOccupant;- /** The office inside the IDE's side panel: the window opens clear of the HUD buttons along the bottom. */- compact?: boolean;- onOpen: () => void;- onClose: () => void;-}) {- const t = useT();- const headingId = useId();- const { agent, pane } = occupant;- const panel = useRef<HTMLElement>(null);- const [note, setNote] = useState<Note>(null);- const [confirmClose, setConfirmClose] = useState(false);- const appTheme = useThemeValue();- // The IDE's pane appearance: the reader's stored choice, else the app's theme.- const appearance = storedTerminalAppearance() ?? appTheme;- // The IDE's pane style (Workspace options): the window wears the same tile- // as the panes in the grid — square, slim title row, blue while in use.- const paneStyle = storedPaneStyle();- const brand = PANE_BRAND[appearance];- const chrome = PANE_CHROME[appearance];- const ansi = themeFor(appearance);- const paneTitle = usePaneTitle(pane.workspace_id, pane.name);- const where = agentPositions.get(agent.agentId);- const live = pane.status === "live";- const working = occupant.dot === "working";- const since = sinceLabel(pane.activity_since || null, t);- const title = paneTitle || pane.recap.trim() || agent.name;-- const stage = useStageSize(panel);- const [stored, setStored] = useState(() => loadStoredWindow(compact));- // The window mid-drag. Held apart from `stored` so a drag costs one small- // render per frame and is written to storage once, when it ends.- const [dragRect, setDragRect] = useState<WindowRect | null>(null);- const gesture = useRef<Gesture | null>(null);- const frame = useRef<number | null>(null);- const [resizing, setResizing] = useState(false);- const rest = stage ? (stored ? placeStored(stored, stage) : defaultRect(stage, compact)) : null;- const rect = dragRect ?? rest;-- useEffect(() => { panel.current?.focus({ preventScroll: true }); setNote(null); setConfirmClose(false); }, [agent.agentId]);- useEffect(() => {- if (!confirmClose) return;- const timer = setTimeout(() => setConfirmClose(false), CONFIRM_MS);- return () => clearTimeout(timer);- }, [confirmClose]);- useEffect(() => {- if (note?.tone !== "ok") return;- const timer = setTimeout(() => setNote(null), NOTE_MS);- return () => clearTimeout(timer);- }, [note]);- useEffect(() => () => { if (frame.current !== null) cancelAnimationFrame(frame.current); }, []);-- const refresh = () => { void useWorkspacePanesStore.getState().load(); };-- /** Run one session action; it answers with the line the window shows once it is done. */- const run = async (action: () => Promise<string>) => {- setNote(null);- try {- setNote({ tone: "ok", text: await action() });- refresh();- } catch (err) {- setNote({ tone: "error", text: err instanceof Error ? err.message : String(err) });- }- };-- const stop = () => void run(async () => {- await interruptTerminal(pane.name, pane.workspace_id);- return t("society.office.cmd_stopped").replace("{0}", agent.name);- });- const fork = () => void run(async () => {- const { terminal } = await forkTerminal(pane.name, { workspaceId: pane.workspace_id, worktree: false });- return t("society.office.cmd_forked").replace("{0}", terminal.name);- });- const close = () => {- if (!confirmClose) { setConfirmClose(true); return; }- setConfirmClose(false);- void run(async () => {- await closeTerminal(pane.name, pane.workspace_id);- return t("society.office.cmd_closed").replace("{0}", agent.name);- });- };-- /* ---- moving and resizing ------------------------------------------------ */-- const begin = (event: ReactPointerEvent<HTMLElement>, kind: Gesture["kind"], edge: ResizeEdge = "se") => {- if (event.button !== 0 || !rest) return;- // The title bar's buttons stay buttons.- if (kind === "move" && (event.target as HTMLElement).closest("button")) return;- event.preventDefault();- event.currentTarget.setPointerCapture?.(event.pointerId);- gesture.current = { kind, edge, pointerId: event.pointerId, startX: event.clientX, startY: event.clientY, start: rest };- setDragRect(rest);- if (kind === "resize") setResizing(true);- };-- const follow = (event: ReactPointerEvent<HTMLElement>) => {- const g = gesture.current;- if (!g || g.pointerId !== event.pointerId || !stage) return;- const dx = event.clientX - g.startX, dy = event.clientY - g.startY;- const next = g.kind === "move" ? moveRect(g.start, dx, dy, stage) : resizeRect(g.start, g.edge, dx, dy, stage);- // At most one render per frame, however fast the pointer reports.- if (frame.current !== null) cancelAnimationFrame(frame.current);- frame.current = requestAnimationFrame(() => { frame.current = null; setDragRect(next); });- };-- const finish = (event: ReactPointerEvent<HTMLElement>) => {- const g = gesture.current;- if (!g || g.pointerId !== event.pointerId) return;- gesture.current = null;- if (frame.current !== null) { cancelAnimationFrame(frame.current); frame.current = null; }- if (stage) {- const dx = event.clientX - g.startX, dy = event.clientY - g.startY;- const end = g.kind === "move" ? moveRect(g.start, dx, dy, stage) : resizeRect(g.start, g.edge, dx, dy, stage);- // A press without a real drag moves nothing and remembers nothing.- if (end.x !== g.start.x || end.y !== g.start.y || end.w !== g.start.w || end.h !== g.start.h) {- const next = toStored(end, stage);- setStored(next);- saveStoredWindow(compact, next);- }- }- setDragRect(null);- setResizing(false);- };-- /**- * The pointer was taken away mid-drag (the OS, a touch turned into a scroll,- * capture lost). Its last coordinates are not a place anyone chose — a- * cancelled pointer often reports (0, 0) — so the window goes back to where- * the drag began and nothing is remembered. After a normal release the- * gesture is already over and this does nothing.- */- const abandon = (event: ReactPointerEvent<HTMLElement>) => {- const g = gesture.current;- if (!g || g.pointerId !== event.pointerId) return;- gesture.current = null;- if (frame.current !== null) { cancelAnimationFrame(frame.current); frame.current = null; }- setDragRect(null);- setResizing(false);- };-- const gestureHandlers = (kind: Gesture["kind"], edge?: ResizeEdge) => ({- onPointerDown: (event: ReactPointerEvent<HTMLElement>) => begin(event, kind, edge),- onPointerMove: follow,- onPointerUp: finish,- onPointerCancel: abandon,- onLostPointerCapture: abandon,- });-- /** Double-click on the title bar: back to where the window first opened. */- const resetPlace = (event: ReactMouseEvent) => {- if ((event.target as HTMLElement).closest("button")) return;- setStored(null);- saveStoredWindow(compact, null);- };-- /* ---- the terminal ------------------------------------------------------- */-- // Built once per pane and size state, so the window re-rendering while it is- // carried around never re-renders the terminal inside it. Mounted only once- // the stage has a size: the first size the agent hears is the window's, and- // a window with no room cannot hold the pane's size lead against the grid.- const ready = stage !== null && stage.width > 0 && stage.height > 0;- const terminal = useMemo(() => ready ? (- // Keyed by the pane, so another session is a fresh socket, never this one's screen under a new name.- <AgenticTerminal key={`${pane.workspace_id}/${pane.name}`} headerMode="none" sizeLead- name={pane.name} workspaceId={pane.workspace_id} agent={pane.agent}- displayName={pane.display_name || pane.agent || agent.name}- appearance={appearance} fontSize={FONT_DEFAULT} layoutBusy={resizing}- onAttachError={(message) => setNote({ tone: "error", text: message })} />- ) : null, [ready, pane.workspace_id, pane.name, pane.agent, pane.display_name, agent.name, appearance, resizing]);-- const dot = occupant.dot === "working" ? ansi.green- : occupant.dot === "waiting" ? ansi.yellow- : occupant.dot === "error" ? ansi.red : brand.inkFaint;- const edge = occupant.dot === "error" ? chrome.edge.error : live ? chrome.edge.live : chrome.edge.exited;- const vars = {- "--pane-ink": brand.ink,- "--pane-ink-muted": brand.inkMuted,- "--pane-ink-faint": brand.inkFaint,- "--pane-chip": brand.chip,- "--pane-rule": chrome.border,- "--pane-edge": edge,- "--pane-ground": PANE_SOLID[appearance],- "--pane-float": chrome.float,- "--pane-ok": ansi.green,- "--pane-fault": ansi.red,- "--pane-focus": PANE_TILE[appearance].focus,- } as CSSProperties;- const style: CSSProperties = rect- ? { ...vars, left: rect.x, top: rect.y, width: rect.w, height: rect.h }- // Not placed until the stage is measured, which happens before the first paint.- : { ...vars, visibility: "hidden" };-- return (- <aside ref={panel} className="office-pane" data-office-ui data-appearance={appearance} data-style={paneStyle}- data-gesture={dragRect ? (resizing ? "resize" : "move") : undefined}- style={style} aria-labelledby={headingId} tabIndex={-1}>- <header className="office-pane-head" title={t("society.office.pane_window_hint")}- {...gestureHandlers("move")} onDoubleClick={resetPlace}>- <span className="office-pane-dot" style={{ background: dot }} role="img"- aria-label={t(`society.office.pane_state_${occupant.stateKey}`)} />- <AgentMark agent={pane.agent} label={pane.display_name || pane.agent} variant="plain" size="sm"- className="!text-[color:var(--pane-ink)] [&>.bg-foreground]:!bg-[color:var(--pane-ink)]" />- <h2 id={headingId} title={`${title} (${pane.name})`} className={paneStyle === "minimal" ? "font-mono" : undefined}>{title}</h2>- <span className="office-pane-meta">- {t(`society.office.pane_state_${occupant.stateKey}`)}{since ? ` · ${since}` : ""}- </span>- <div className="office-pane-actions" role="toolbar" aria-label={t("society.office.talk_tools")}>- {working && live && (- <button type="button" onClick={stop} title={t("society.office.cmd_stop")} aria-label={t("society.office.cmd_stop")}>- <Square aria-hidden />- </button>- )}- <button type="button" disabled={!live} onClick={fork} title={t("society.office.cmd_fork")} aria-label={t("society.office.cmd_fork")}>- <BranchIcon aria-hidden />- </button>- <button type="button" disabled={!where} onClick={() => where && useOfficeStore.getState().requestWalk(where)}- title={t("society.office.action_walk")} aria-label={t("society.office.action_walk")}>- <Footprints aria-hidden />- </button>- <button type="button" onClick={() => useOfficeStore.getState().summon([agent.agentId], { x: player.x, z: player.z }, CALL_MS)}- title={t("society.office.action_call")} aria-label={t("society.office.action_call")}>- <Hand aria-hidden />- </button>- <button type="button" disabled={!where} onClick={() => where && useOfficeStore.getState().focusOn(where)}- title={t("society.office.action_focus")} aria-label={t("society.office.action_focus")}>- <LocateFixed aria-hidden />- </button>- <button type="button" onClick={onOpen} title={t("society.office.pane_open")} aria-label={t("society.office.pane_open")}>- <Maximize2 aria-hidden />- </button>- <button type="button" data-danger aria-pressed={confirmClose} onClick={close}- title={t(confirmClose ? "society.office.cmd_close_confirm" : "society.office.cmd_close")}- aria-label={t(confirmClose ? "society.office.cmd_close_confirm" : "society.office.cmd_close")}>- <Trash2 aria-hidden />- </button>- <span className="office-pane-sep" aria-hidden />- <button type="button" onClick={onClose} title={t("society.office.close")} aria-label={t("society.office.close")}>- <X aria-hidden />- </button>- </div>- </header>-- <div className="office-pane-term">{terminal}</div>- {/* Over the terminal, never below it: a line that took rows away would resize the agent. */}- {note && <p className="office-pane-status" role="status" data-tone={note.tone} onClick={() => setNote(null)}>{note.text}</p>}- {EDGES.map((grip) => (- <div key={grip} className="office-pane-grip" data-edge={grip} aria-hidden {...gestureHandlers("resize", grip)} />- ))}- </aside>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/PaneLiveScreen.tsx b/dodaios/ui/web/frontend/src/components/society/office/PaneLiveScreen.tsxdeleted file mode 100644index d7c1ef502c..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/PaneLiveScreen.tsx+++ /dev/null@@ -1,101 +0,0 @@-/**- * A still of one coding session's terminal, drawn the way the Agentic IDE- * draws a pane: the pane's own font, weight and ink, the bottom of the real- * screen with its cursor, and the font fitted to the pane's column count so a- * narrow TUI fills the window instead of hugging its left edge.- *- * Mission Control's screens feed it from the shared in-memory screen feed. The- * pane panel itself shows the IDE's live terminal instead (./PaneCommandPanel).- */-import { useLayoutEffect, useRef, useState, type RefObject } from "react";-import type { PaneScreen } from "@/lib/paneScreensApi";-import { TERMINAL_FONT_STACK, TERMINAL_FONT_WEIGHT } from "@/lib/terminalFont";-import { visibleRows } from "./terminalScreen";--/** Font bounds in CSS pixels: a wide TUI shrinks the text, a narrow one never blows it up. */-const MIN_FONT = 10, MAX_FONT = 15;-/** Wider terminals than this are cut on the right rather than shrunk further. */-const MAX_FIT_COLS = 120;-/** A monospace glyph is about this wide per pixel of font size. */-const CHAR_RATIO = 0.6;-/** The panes draw at line height 1.0; a touch more keeps the small window airy. */-const LINE_RATIO = 1.15;-/** Horizontal padding of the screen, matching `.office-pane-screen` in the CSS. */-const PAD = 12;--export interface LiveGrid { font: number; lineH: number; cols: number; fit: number }--/** Font and grid for a terminal `cols` wide in a box of `width` x `height`. Pure. */-export function liveGrid(cols: number, width: number, height: number): LiveGrid {- const inner = Math.max(0, width - 2 * PAD);- const want = Math.max(20, Math.min(cols || 80, MAX_FIT_COLS));- const font = Math.max(MIN_FONT, Math.min(MAX_FONT, Math.floor(inner / (want * CHAR_RATIO))));- const lineH = Math.round(font * LINE_RATIO);- return {- font,- lineH,- cols: Math.max(1, Math.floor(inner / (font * CHAR_RATIO))),- fit: Math.max(1, Math.floor(height / lineH)),- };-}--function useBoxSize(ref: RefObject<HTMLElement | null>): { width: number; height: number } {- const [size, setSize] = useState({ width: 0, height: 0 });- useLayoutEffect(() => {- const el = ref.current;- if (!el) return;- const measure = () => {- const width = el.clientWidth, height = el.clientHeight;- setSize((prev) => (prev.width === width && prev.height === height ? prev : { width, height }));- };- measure();- if (typeof ResizeObserver === "undefined") return;- const observer = new ResizeObserver(measure);- observer.observe(el);- return () => observer.disconnect();- }, [ref]);- return size;-}--/** One terminal screen, fitted to its box; `screen` undefined = still loading, null = unknown pane. */-export function PaneScreenView({ screen, label, loadingText, emptyText, onOpen, className = "office-pane-screen" }: {- screen: PaneScreen | null | undefined;- label: string;- loadingText: string;- emptyText: string;- onOpen?: () => void;- className?: string;-}) {- const box = useRef<HTMLDivElement>(null);- const { width, height } = useBoxSize(box);- const grid = liveGrid(screen?.cols ?? 80, width, height);- const view = screen ? visibleRows(screen.lines, grid.fit, screen.cursor) : null;- const cursor = screen?.cursor && view ? [screen.cursor[0] - view.first, screen.cursor[1]] as const : null;- const empty = !view || view.rows.every((row) => !row.trim());-- return (- <div ref={box} className={className} role="img" aria-label={label} onDoubleClick={onOpen}>- {empty ? (- <p className="office-pane-empty">{screen === undefined ? loadingText : emptyText}</p>- ) : (- <pre aria-hidden style={{- fontFamily: TERMINAL_FONT_STACK, fontWeight: TERMINAL_FONT_WEIGHT, fontSize: grid.font, lineHeight: `${grid.lineH}px`,- }}>- {view!.rows.map((row, i) => {- const line = row.length > grid.cols ? `${row.slice(0, grid.cols - 1)}…` : row;- if (!cursor || cursor[0] !== i || cursor[1] >= grid.cols) return <div key={i}>{line || " "}</div>;- const col = cursor[1];- const padded = line.padEnd(col + 1, " ");- return (- <div key={i}>- {padded.slice(0, col)}- <span className="office-pane-cursor">{padded[col]}</span>- {padded.slice(col + 1)}- </div>- );- })}- </pre>- )}- </div>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/RealChatScreen.tsx b/dodaios/ui/web/frontend/src/components/society/office/RealChatScreen.tsxdeleted file mode 100644index 01d87ecbcd..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/RealChatScreen.tsx+++ /dev/null@@ -1,55 +0,0 @@-/**- * The agent's REAL chat on its desk monitor: the same AgentChatPanel the chat- * view shows, live, drawn onto the screen plane. Each monitor owns its own- * chat store (one socket through the shared connect budget), so it never- * touches the chat the rest of the app has open. Display only: clicks go to- * the monitor underneath, which dives into the chat view.- */-import { Suspense, lazy, useContext, useEffect, useMemo } from "react";-import { CanvasActivity } from "@/hooks/useCanvasAwake";-import { Html } from "@react-three/drei";-import { QueryClientProvider, useQueryClient } from "@tanstack/react-query";-import { createAgentChatStore } from "@/store/agentChat";-import type { SocietyAgent } from "../data";-import { useBlendingCanvasLayer } from "./blendingLayer";--const AgentChatPanel = lazy(() => import("../chat/AgentChatPanel").then((m) => ({ default: m.AgentChatPanel })));--/** The chat is laid out at a normal window size, then scaled onto the 0.66 × 0.38 m screen. */-export const REAL_CHAT_PX = { w: 880, h: 507 } as const;-const SCREEN_W_M = 0.66;-/** drei maps one CSS pixel to distanceFactor / 400 metres in transform mode. */-const SCREEN_Z_RANGE: [number, number] = [10, 0];-const DISTANCE_FACTOR = (SCREEN_W_M * 400) / REAL_CHAT_PX.w;--type RealChatScreenProps = {- agent: SocietyAgent; roster: SocietyAgent[]; position: [number, number, number];-};--export function RealChatScreen(props: RealChatScreenProps) {- const active = useContext(CanvasActivity);- return active ? <ActiveRealChatScreen {...props} /> : null;-}--function ActiveRealChatScreen({ agent, roster, position }: RealChatScreenProps) {- // drei renders <Html> content in a separate React root: the app's data client- // must be handed over, or the chat panel's queries throw and the screen stays blank.- const client = useQueryClient();- const store = useMemo(() => createAgentChatStore("society", `office-monitor:${agent.agentId}`), [agent.agentId]);- // Leaving the monitor closes its socket; the chat itself keeps running on the server.- useEffect(() => () => store.getState().disconnect(), [store]);- // Another <Html> mounting later would drop the canvas under this screen (see blendingLayer).- useBlendingCanvasLayer(SCREEN_Z_RANGE);- return (- <Html transform occlude="blending" position={position} distanceFactor={DISTANCE_FACTOR} zIndexRange={SCREEN_Z_RANGE}- style={{ width: REAL_CHAT_PX.w, height: REAL_CHAT_PX.h, pointerEvents: "none" }}>- <div className="office-real-chat" data-office-ui>- <QueryClientProvider client={client}>- <Suspense fallback={null}>- <AgentChatPanel agent={agent} roster={roster} chatStore={store} />- </Suspense>- </QueryClientProvider>- </div>- </Html>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/ReceptionPanel.tsx b/dodaios/ui/web/frontend/src/components/society/office/ReceptionPanel.tsxdeleted file mode 100644index 13235c5891..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/ReceptionPanel.tsx+++ /dev/null@@ -1,292 +0,0 @@-/**- * Reception: the office's directory. Four tabs — everyone on the floor (show- * on the map, open, the agents view), every place of the floor (open it, or- * walk there), the complete controls guide (from officeControls, searchable)- * and the map's settings (officeSettings). H opens it on the controls tab- * from anywhere, so nobody has to find the desk to learn the keys.- *- * Nothing is created here: new agents come from the spawn terminal.- */-import { useState } from "react";-import { ArrowDown, ArrowLeft, ArrowRight, ArrowUp, ChevronRight, Footprints, Search } from "lucide-react";-import { useT } from "@/i18n";-import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import { Switch } from "@/components/ui/switch";-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";-import type { SocietyAgent } from "../data";-import { countStates, type OfficeLayout } from "./officeLayout";-import { useOfficeStore, type OfficeFloor } from "./officeStore";-import { agentPositions } from "./walkerRegistry";-import { isReception, stationsFor, type Station } from "./stations";-import { AgentFace } from "./AgentFace";-import { StationGlyph } from "./stationIcons";-import { stationAction, stationLabel } from "./stationText";-import { arrowCap, CONTROL_GROUPS, controlsFor, mouseGesture, type ArrowKey, type OfficeControl } from "./officeControls";-import { useOfficeSettings, useReceptionTab, type ReceptionTab } from "./officeSettings";-import type { OfficeActions } from "./OfficePanels";-import "./reception.css";--const TABS: readonly ReceptionTab[] = ["agents", "places", "controls", "settings"];--const ARROW_ICON: Record<ArrowKey, typeof ArrowUp> = { up: ArrowUp, down: ArrowDown, left: ArrowLeft, right: ArrowRight };--/** How a key cap reads aloud and in the search ("Space", "Arrow up", "Drag"). */-function useCapLabel() {- const t = useT();- return (cap: string) => {- const gesture = mouseGesture(cap);- if (gesture) return t(`society.office.guide.mouse_${gesture}`);- const arrow = arrowCap(cap);- if (arrow) return t(`society.office.guide.key_${arrow}`);- return cap === "Space" ? t("society.office.guide.key_space") : cap;- };-}--export function KeyCaps({ control }: { control: Pick<OfficeControl, "keys"> }) {- const t = useT();- const label = useCapLabel();- return (- <span className="office-keys">- {control.keys.map((alt, i) => (- <span key={i} className="office-keys-alt">- {i > 0 && <span className="office-keys-or">{t("society.office.guide.or")}</span>}- {alt.map((cap, j) => {- if (cap === "+") return <span key={j} className="office-keys-plus" aria-hidden>+</span>;- if (mouseGesture(cap)) return <kbd key={j} className="office-key" data-mouse>{label(cap)}</kbd>;- const arrow = arrowCap(cap);- if (arrow) {- const Icon = ARROW_ICON[arrow];- return <kbd key={j} className="office-key" aria-label={label(cap)}><Icon size={12} aria-hidden /></kbd>;- }- return <kbd key={j} className="office-key">{label(cap)}</kbd>;- })}- </span>- ))}- </span>- );-}--/**- * Arrow keys inside the places list: up and down move through the rows, right- * goes to a row's "walk there" and left back to the row, Home and End jump.- * Returns the button to focus, or null when the key is not one of them.- */-export function placesKeyTarget(list: HTMLElement, from: Element | null, key: string): HTMLElement | null {- const rows = [...list.querySelectorAll<HTMLElement>("[data-place-open]")];- if (rows.length === 0) return null;- const row = from instanceof HTMLElement ? from.closest<HTMLElement>("[data-place-row]") : null;- const index = row ? rows.findIndex((button) => row.contains(button)) : -1;- if (key === "Home") return rows[0]!;- if (key === "End") return rows[rows.length - 1]!;- if (key === "ArrowDown") return rows[index < 0 ? 0 : Math.min(rows.length - 1, index + 1)]!;- if (key === "ArrowUp") return rows[index < 0 ? rows.length - 1 : Math.max(0, index - 1)]!;- if (!row) return null;- if (key === "ArrowRight") return row.querySelector<HTMLElement>("[data-place-walk]");- if (key === "ArrowLeft") return row.querySelector<HTMLElement>("[data-place-open]");- return null;-}--/**- * Every place of the floor as a real button: open it from here, or walk- * there. Also the keyboard path to every station. The rooms' stations come- * first, then the team studios' boards under their team's name.- */-export function PlacesList({ layout, onPicked, withReception = false }: {- layout: OfficeLayout; onPicked?: () => void;- /** The reception itself is a place too, except in its own directory. */- withReception?: boolean;-}) {- const t = useT();- const store = useOfficeStore;- const stations = stationsFor(layout).filter((station) => withReception || !isReception(station.selection));- const groups = [- { id: "places", label: t("society.office.hud_places"), rows: stations.filter((station) => station.selection.kind !== "team") },- { id: "teams", label: t("society.office.places_teams"), rows: stations.filter((station) => station.selection.kind === "team") },- ].filter((group) => group.rows.length > 0);- const point = (station: Station | null) => store.getState().setHover(station ? station.selection : null);- // Whatever closes the list must not leave a place lit in the world.- const done = () => { point(null); onPicked?.(); };- return (- <div className="grid gap-2" data-places- onKeyDown={(event) => {- const target = placesKeyTarget(event.currentTarget, document.activeElement, event.key);- if (!target) return;- // The arrows belong to the list while focus is in it; they must not walk the character too.- event.preventDefault();- event.stopPropagation();- target.focus();- target.scrollIntoView?.({ block: "nearest" });- }}>- {groups.map((group) => (- <section key={group.id} className="grid gap-0.5" aria-label={group.label}>- {groups.length > 1 && <h3 className="px-2 pt-1 text-xs font-semibold text-muted-foreground">{group.label}</h3>}- <ul className="grid list-none gap-0.5 p-0">- {group.rows.map((station) => {- const name = stationLabel(station, t);- const action = stationAction(station, t);- return (- <li key={station.key} data-place-row className="flex items-center gap-1 rounded-md hover:bg-secondary focus-within:bg-secondary"- onPointerEnter={() => point(station)} onPointerLeave={() => point(null)}>- <button type="button" data-place-open className="flex min-w-0 flex-1 items-center gap-3 rounded-md px-2 py-1.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- aria-label={`${name}: ${action}`}- onFocus={() => point(station)} onBlur={() => point(null)}- onClick={() => { done(); store.getState().select(station.selection); }}>- <span aria-hidden className="grid size-7 shrink-0 place-items-center rounded-md border border-border bg-background text-muted-foreground"><StationGlyph icon={station.icon} size={15} /></span>- <span className="grid min-w-0 gap-0.5">- <span className="truncate text-sm font-medium text-foreground">{name}</span>- <span className="truncate text-xs text-muted-foreground">{action}</span>- </span>- <ChevronRight size={14} aria-hidden className="ml-auto shrink-0 text-muted-foreground" />- </button>- <button type="button" data-place-walk className="mr-1 inline-flex size-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-background hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- aria-label={t("society.office.guide.place_walk_label").replace("{0}", name)} title={t("society.office.guide.place_walk")}- onClick={() => { done(); store.getState().select(null); store.getState().requestWalk(station.approach); }}>- <Footprints size={15} aria-hidden />- </button>- </li>- );- })}- </ul>- </section>- ))}- </div>- );-}--function AgentsTab({ agents, actions }: { agents: readonly SocietyAgent[]; actions: OfficeActions }) {- const t = useT();- const counts = countStates(agents);- const show = (agent: SocietyAgent) => {- const store = useOfficeStore.getState();- const where = agentPositions.get(agent.agentId);- if (where) store.focusOn(where);- store.select({ kind: "agent", id: agent.agentId });- };- return (- <div className="grid gap-3">- <div className="flex flex-wrap items-center justify-between gap-2">- <p className="text-sm text-muted-foreground">- {[t("society.office.count_working").replace("{0}", String(counts.working)), t("society.office.count_waiting").replace("{0}", String(counts.waiting)),- t("society.office.count_idle").replace("{0}", String(counts.idle))].join(" · ")}- </p>- <Button type="button" size="sm" variant="outline" onClick={actions.onOpenLedger}>{t("society.office.manage_action")}</Button>- </div>- {agents.length === 0 ? <p className="rounded-lg border border-dashed border-border p-5 text-sm text-muted-foreground">{t("society.office.manage_empty")}</p> : (- <ul className="grid max-h-[22rem] list-none gap-0.5 overflow-y-auto p-0">- {agents.map((agent) => (- <li key={agent.agentId} className="flex items-center gap-3 rounded-md px-2 py-1.5 hover:bg-secondary/60">- <AgentFace agent={agent} />- <span className="grid min-w-0 flex-1">- <span className="truncate text-sm font-medium" title={agent.name}>{agent.name}</span>- {(agent.title || agent.providerLabel) && <span className="truncate text-xs text-muted-foreground">{agent.title || agent.providerLabel}</span>}- </span>- <span className="flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground">- <i className="office-dot" data-state={agent.state} aria-hidden />{t(`society.office.state_${agent.state}`)}- </span>- <Button type="button" size="sm" variant="ghost" aria-label={t("society.office.show_agent").replace("{0}", agent.name)}- onClick={() => show(agent)}>{t("society.office.action_show")}</Button>- <Button type="button" size="sm" variant="ghost" aria-label={t("society.office.open_agent").replace("{0}", agent.name)}- onClick={() => actions.onOpenAgent(agent.agentId)}>{t("society.office.action_open")}</Button>- </li>- ))}- </ul>- )}- </div>- );-}--function ControlsTab({ floor }: { floor: OfficeFloor }) {- const t = useT();- const label = useCapLabel();- const [query, setQuery] = useState("");- const needle = query.trim().toLocaleLowerCase();- // A search matches the action's words, or names one of its keys exactly ("e", "shift").- const matches = (control: OfficeControl) => !needle- || t(`society.office.guide.ctl_${control.id}`).toLocaleLowerCase().includes(needle)- || control.keys.flat().some((cap) => cap !== "+" && label(cap).toLocaleLowerCase() === needle);- const groups = CONTROL_GROUPS- .map((group) => ({ group, controls: controlsFor(group, floor).filter(matches) }))- .filter((g) => g.controls.length > 0);- return (- <div className="grid gap-3">- <div className="relative">- <Search size={15} aria-hidden className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />- <Input type="search" className="pl-9" value={query} onChange={(e) => setQuery(e.target.value)} placeholder={t("society.office.guide.search")}- aria-label={t("society.office.guide.search")}- onKeyDown={(e) => { if (e.key === "Escape" && query) { e.preventDefault(); e.stopPropagation(); setQuery(""); } }} />- </div>- {groups.length === 0 ? <p className="py-4 text-center text-sm text-muted-foreground" role="status">{t("society.office.guide.search_empty")}</p> : (- <div className="grid gap-4">- {groups.map(({ group, controls }) => (- <section key={group} className="grid gap-1" aria-label={t(`society.office.guide.group_${group}`)}>- <h3 className="text-xs font-semibold text-muted-foreground">{t(`society.office.guide.group_${group}`)}</h3>- <ul className="grid list-none p-0">- {controls.map((control) => (- <li key={control.id} className="flex items-center justify-between gap-3 border-t border-border/60 py-1.5 text-sm first:border-t-0">- <span className="min-w-0">{t(`society.office.guide.ctl_${control.id}`)}</span>- <KeyCaps control={control} />- </li>- ))}- </ul>- </section>- ))}- </div>- )}- <p className="flex items-center gap-2 text-xs text-muted-foreground"><kbd className="office-key">H</kbd>{t("society.office.guide.tip_guide")}</p>- </div>- );-}--function SettingRow({ title, hint, children }: { title: string; hint: string; children: React.ReactNode }) {- return (- <div className="flex items-center justify-between gap-4 p-3">- <span className="grid min-w-0 gap-0.5">- <span className="text-sm font-medium">{title}</span>- <span className="text-xs text-muted-foreground">{hint}</span>- </span>- {children}- </div>- );-}--function SettingsTab() {- const t = useT();- const settings = useOfficeSettings();- return (- <div className="grid gap-3">- <p className="text-sm text-muted-foreground">{t("society.office.guide.settings_intro")}</p>- <div className="divide-y divide-border rounded-lg border border-border">- <SettingRow title={t("society.office.guide.set_always_run")} hint={t("society.office.guide.set_always_run_hint")}>- <Switch checked={settings.alwaysRun} aria-label={t("society.office.guide.set_always_run")}- onCheckedChange={(alwaysRun) => settings.set({ alwaysRun })} />- </SettingRow>- <SettingRow title={t("society.office.guide.set_hints")} hint={t("society.office.guide.set_hints_hint")}>- <Button type="button" size="sm" variant="outline" disabled={!settings.hintsSeen} onClick={() => settings.set({ hintsSeen: false })}>- {t("society.office.guide.set_hints_action")}- </Button>- </SettingRow>- </div>- <div><Button type="button" size="sm" variant="ghost" onClick={settings.reset}>{t("society.office.guide.set_reset")}</Button></div>- </div>- );-}--export function ReceptionPanel({ floor, layout, agents, actions }: {- floor: OfficeFloor; layout: OfficeLayout; agents: readonly SocietyAgent[]; actions: OfficeActions;-}) {- const t = useT();- const tab = useReceptionTab((s) => s.tab);- const setTab = useReceptionTab((s) => s.setTab);- return (- <Tabs value={tab} onValueChange={(value) => setTab(value as ReceptionTab)}>- <TabsList aria-label={t("society.office.guide.tablist")}>- {TABS.map((id) => <TabsTrigger key={id} value={id}>{t(`society.office.guide.tab_${id}`)}</TabsTrigger>)}- </TabsList>- <TabsContent value="agents"><AgentsTab agents={agents} actions={actions} /></TabsContent>- <TabsContent value="places"><PlacesList layout={layout} /></TabsContent>- <TabsContent value="controls"><ControlsTab floor={floor} /></TabsContent>- <TabsContent value="settings"><SettingsTab /></TabsContent>- </Tabs>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/ServerRoom.tsx b/dodaios/ui/web/frontend/src/components/society/office/ServerRoom.tsxdeleted file mode 100644index c636a04a74..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/ServerRoom.tsx+++ /dev/null@@ -1,1152 +0,0 @@-/**- * The coding floor's server room: two rows of 42U racks facing each other- * across a cold aisle, a NOC console in front of a status wall, a UPS with- * its battery cabinet and a fire-suppression bank beside the door.- *- * Racks are drawn, not modelled: every row's server faces are one canvas- * texture built from a deterministic rack plan, and the same plan places the- * status LEDs (one instanced mesh per row) and the patch cables (another).- * The LEDs twinkle from a single throttled useFrame per row that rewrites the- * instance colours in place — no per-frame allocation. The screens redraw on- * a slow timer and read the floor's live panes, so the cluster load follows- * the coding agents at work. The status wall is the exception: it shows what- * the Agentic IDE's agents really spent (the Spend section's read model), and- * a click on it dives in and opens Spend.- *- * Pieces are built in local space centred on the origin, front facing +z, and- * stay inside their FURNITURE_SIZE box.- */-import { useContext, useEffect, useMemo, useRef, useState } from "react";-import { CanvasActivity } from "@/hooks/useCanvasAwake";-import { useCanvasInterval } from "@/hooks/useCanvasInterval";-import { useFrame } from "@react-three/fiber";-import { fill, useT } from "@/i18n";-import { useRunLocale } from "@/components/runs/format";-import {- CanvasTexture, Color, CylinderGeometry, InstancedMesh, MeshBasicMaterial, MeshStandardMaterial, Object3D,- RepeatWrapping, SphereGeometry, SRGBColorSpace, TorusGeometry, type Texture,-} from "three";-import { useWorkspacePanesStore } from "@/store/workspacePanes";-import { EMPTY_FILTERS, useCostSummary, type CostFilters, type CostSummary } from "@/hooks/useCosts";-import { cachedCanvasTexture, canvasMaterial } from "./canvasMaterials";-import { paneOccupants } from "./codingFloor";-import { useMonitorDive } from "./CommandOffice";-import { Box, GEO, MAT, matte, Rounded } from "./OfficeFurniture";-import { FURNITURE_SIZE, type Furniture, type FurnitureKind } from "./officeLayout";--type Ctx = CanvasRenderingContext2D;--// ----------------------------------------------------------------------------// Materials-// -----------------------------------------------------------------------------const SRV = {- cabinet: matte("#1a1d22", { roughness: 0.5, metalness: 0.3 }),- cabinetEdge: matte("#2b3038", { roughness: 0.4, metalness: 0.4 }),- plinth: matte("#0e1013", { roughness: 0.7 }),- handle: matte("#b9c0c9", { roughness: 0.25, metalness: 0.8 }),- trayRail: matte("#17191c", { roughness: 0.5, metalness: 0.4 }),- fibre: matte("#f5c518", { roughness: 0.55 }),- cableBlue: matte("#2f6fd6", { roughness: 0.8 }),- cableGrey: matte("#8d96a1", { roughness: 0.8 }),- cableRed: matte("#d9453b", { roughness: 0.8 }),- // Accent light strips: lit from within, so they read as light in any scene lighting.- ice: new MeshStandardMaterial({ color: "#7fe9ff", emissive: "#5fdcff", emissiveIntensity: 1.4, toneMapped: false }),- panel: new MeshStandardMaterial({ color: "#e8f6ff", emissive: "#cdeeff", emissiveIntensity: 1.2, toneMapped: false }),- glass: new MeshStandardMaterial({- color: "#a9dcff", transparent: true, opacity: 0.13, roughness: 0.05, metalness: 0.2, depthWrite: false,- }),- red: matte("#c8262b", { roughness: 0.35, metalness: 0.1 }),- valve: matte("#aab2bc", { roughness: 0.3, metalness: 0.7 }),- cream: matte("#ece8df", { roughness: 0.6 }),- backplate: matte("#cfd4da", { roughness: 0.7 }),- ledGreen: new MeshStandardMaterial({ color: "#46f08c", emissive: "#46f08c", emissiveIntensity: 1.2, toneMapped: false }),- stoolSeat: matte("#2a3a44", { roughness: 0.8 }),-};--const SGEO = {- cyl: new CylinderGeometry(1, 1, 1, 20),- dome: new SphereGeometry(1, 20, 10, 0, Math.PI * 2, 0, Math.PI / 2),- // A half ring: a patch cable hanging in a loop below its port.- loop: new TorusGeometry(1, 0.13, 5, 14, Math.PI),-};--/** A cached texture cloned once per repeat, so every rack door shares one drawing. */-const repeatedMaterials = new Map<string, MeshStandardMaterial>();-function repeatedMaterial(- key: string, width: number, height: number, draw: (ctx: Ctx, w: number, h: number) => void,- repeat: [number, number], fallback: string, roughness = 0.6,-): MeshStandardMaterial {- const id = `${key}:${repeat.join("x")}`;- let material = repeatedMaterials.get(id);- if (!material) {- const base = cachedCanvasTexture(key, width, height, draw);- let map: Texture | null = null;- if (base) {- map = base.clone();- map.wrapS = map.wrapT = RepeatWrapping;- map.repeat.set(repeat[0], repeat[1]);- map.needsUpdate = true;- }- material = new MeshStandardMaterial({ color: map ? "#ffffff" : fallback, map, roughness, metalness: 0.2 });- repeatedMaterials.set(id, material);- }- return material;-}--function Panel({ size, position, material, rotationY = 0 }: {- size: [number, number]; position: [number, number, number]; material: MeshStandardMaterial | MeshBasicMaterial; rotationY?: number;-}) {- return (- <mesh position={position} rotation={[0, rotationY, 0]} material={material}>- <planeGeometry args={size} />- </mesh>- );-}--function Cyl({ radius, height, position, material, cast = true }: {- radius: number; height: number; position: [number, number, number]; material: MeshStandardMaterial; cast?: boolean;-}) {- return <mesh geometry={SGEO.cyl} material={material} position={position} scale={[radius, height, radius]} castShadow={cast} receiveShadow />;-}--/** Deterministic hash in [0, 1): the same seed always gives the same rack plan and twinkle. */-function hash01(n: number): number {- const s = Math.sin(n * 12.9898 + 78.233) * 43758.5453;- return s - Math.floor(s);-}--function seedOf(id: string): number {- let h = 7;- for (let i = 0; i < id.length; i += 1) h = (h * 31 + id.charCodeAt(i)) >>> 0;- return h;-}--// ----------------------------------------------------------------------------// Rack plan: what sits in each U, where its LEDs and cables go-// -----------------------------------------------------------------------------type UnitType = "patch" | "manager" | "switch" | "server1" | "server2" | "gpu" | "storage" | "blank" | "ups";-type RackRole = "network" | "compute" | "gpu" | "storage";--const UNIT_U: Record<UnitType, number> = { patch: 1, manager: 1, switch: 1, server1: 1, server2: 2, gpu: 4, storage: 4, blank: 1, ups: 2 };-const n = (type: UnitType, count: number): UnitType[] => Array.from({ length: count }, () => type);--/** Each role's units from the top down; a 2U UPS always sits at the bottom, the rest stays empty rails. */-const ROLE_UNITS: Record<RackRole, UnitType[]> = {- network: ["patch", "manager", "patch", "manager", ...n("switch", 4), "blank", "patch", "manager", ...n("switch", 4), "blank", "blank", ...n("server2", 3), "blank", ...n("server1", 4)],- compute: ["patch", "manager", "switch", "switch", "blank", ...n("server1", 10), "blank", ...n("server2", 5), "blank", ...n("server1", 6)],- gpu: ["patch", "manager", "switch", "blank", ...n("gpu", 7), "blank", ...n("server1", 2)],- storage: ["patch", "manager", "switch", ...n("server2", 2), ...n("storage", 6), "blank", ...n("server1", 2)],-};-const ROLE_ORDER: RackRole[] = ["network", "compute", "gpu", "gpu", "storage"];--export const RACKS_PER_ROW = 5;-const RACK_W = FURNITURE_SIZE.serverRack.w / RACKS_PER_ROW;-const ROW_W = FURNITURE_SIZE.serverRack.w;-const ROW_D = FURNITURE_SIZE.serverRack.d;-/** The 42U mounting area on the front, in metres above the floor. */-const FACE = { y0: 0.13, h: 1.9 };-const FACE_Z = ROW_D * 0.45 + 0.003;-const CANVAS = { rackPx: 192, h: 1024 };-const PX_U = CANVAS.h / 42;--type LedMode = 0 | 1 | 2; // steady, activity flicker, slow heartbeat-interface Led { px: number; py: number; colour: string; mode: LedMode; size: number }-interface CableLoop { px: number; py: number; radius: number; colour: string }-interface PlacedUnit { type: UnitType; rack: number; py: number; ph: number }-export interface RackPlan { units: PlacedUnit[]; leds: Led[]; loops: CableLoop[] }--const LED = { green: "#3dff8a", amber: "#ffb020", blue: "#38bdf8", cyan: "#5eead4", red: "#ff5a4f" };-const CABLES = ["#3b82f6", "#facc15", "#ef4444", "#22c55e", "#e5e7eb", "#f97316", "#a855f7"];--/** Device extent inside a rack column (19" between the rails). */-const DEV = { x: 24, w: 144 };--/** Lays out a row of racks for a seed: pure, so the canvas and the meshes always agree. */-export function rackPlan(seed: number): RackPlan {- const units: PlacedUnit[] = [];- const leds: Led[] = [];- const loops: CableLoop[] = [];- const shift = seed % ROLE_ORDER.length;- let k = 0;- const rnd = () => hash01(seed * 0.001 + (k += 1) * 1.618);- for (let rack = 0; rack < RACKS_PER_ROW; rack += 1) {- const role = ROLE_ORDER[(rack + shift) % ROLE_ORDER.length];- const x0 = rack * CANVAS.rackPx + DEV.x;- let top = 42;- const place = (type: UnitType, u: number) => {- const h = UNIT_U[type];- const py = (42 - u) * PX_U;- const ph = h * PX_U;- units.push({ type, rack, py, ph });- const cy = py + ph / 2;- const right = x0 + DEV.w;- switch (type) {- case "server1":- leds.push({ px: right - 20, py: cy, colour: LED.blue, mode: 0, size: 0.011 });- leds.push({ px: right - 11, py: cy, colour: LED.green, mode: 1, size: 0.011 });- break;- case "server2":- leds.push({ px: right - 12, py: py + 9, colour: LED.green, mode: 0, size: 0.012 });- for (let i = 0; i < 4; i += 1) leds.push({ px: x0 + 18 + i * 20, py: py + ph - 8, colour: LED.green, mode: 1, size: 0.008 });- if (rnd() < 0.12) leds.push({ px: right - 12, py: py + ph - 9, colour: LED.amber, mode: 2, size: 0.011 });- break;- case "gpu":- leds.push({ px: right - 14, py: py + ph - 14, colour: LED.cyan, mode: 0, size: 0.013 });- leds.push({ px: right - 14, py: py + 14, colour: LED.cyan, mode: 2, size: 0.012 });- leds.push({ px: right - 14, py: cy, colour: LED.green, mode: 1, size: 0.011 });- break;- case "storage":- for (let r = 0; r < 4; r += 1) for (let c = 0; c < 6; c += 2) {- const bad = rnd() < 0.03;- leds.push({ px: x0 + 12 + c * 19 + 14, py: py + 6 + r * 23 + 18, colour: bad ? LED.red : LED.green, mode: bad ? 2 : 1, size: 0.007 });- }- break;- case "switch":- for (let i = 0; i < 8; i += 1) leds.push({ px: x0 + 14 + i * 12, py: py + 5, colour: rnd() < 0.2 ? LED.amber : LED.green, mode: 1, size: 0.006 });- leds.push({ px: right - 8, py: cy, colour: LED.green, mode: 0, size: 0.009 });- break;- case "patch":- // Short patch cables drop from the panel into the cable manager below.- for (let i = 0; i < 5; i += 1) {- loops.push({ px: x0 + 16 + i * 26 + rnd() * 10, py: cy + 2, radius: 0.028 + rnd() * 0.03, colour: CABLES[Math.floor(rnd() * CABLES.length)] });- }- break;- case "ups":- leds.push({ px: right - 12, py: cy, colour: LED.green, mode: 0, size: 0.012 });- break;- default:- break;- }- };- for (const type of ROLE_UNITS[role]) {- const h = UNIT_U[type];- if (top - h + 1 <= 2) break;- place(type, top);- top -= h;- }- place("ups", 2);- }- return { units, leds, loops };-}--/** Canvas px → local metres on the row's front face. */-const toX = (px: number) => -ROW_W / 2 + (px / (CANVAS.rackPx * RACKS_PER_ROW)) * ROW_W;-const toY = (py: number) => FACE.y0 + (1 - py / CANVAS.h) * FACE.h;--function drawUnit(ctx: Ctx, unit: PlacedUnit, rand: () => number): void {- const x = unit.rack * CANVAS.rackPx + DEV.x;- const y = unit.py + 1;- const w = DEV.w;- const h = unit.ph - 2;- const bezel = (fill: string) => {- ctx.fillStyle = fill;- ctx.fillRect(x, y, w, h);- ctx.fillStyle = "rgba(255,255,255,0.07)";- ctx.fillRect(x, y, w, 1.5);- ctx.fillStyle = "rgba(0,0,0,0.35)";- ctx.fillRect(x, y + h - 1.5, w, 1.5);- };- const ears = () => {- ctx.fillStyle = "#4a525d";- ctx.fillRect(x, y, 5, h);- ctx.fillRect(x + w - 5, y, 5, h);- };- switch (unit.type) {- case "server1": {- bezel("#2a2f37");- ears();- for (let i = 0; i < 8; i += 1) {- ctx.fillStyle = "#15181d";- ctx.fillRect(x + 9 + i * 12, y + 3, 10, h - 6);- ctx.fillStyle = "#4b5461";- ctx.fillRect(x + 9 + i * 12, y + 3, 10, 1.5);- }- ctx.fillStyle = "#1a1d22";- for (let i = 0; i < 4; i += 1) ctx.fillRect(x + 108 + i * 5, y + 4, 2, h - 8);- break;- }- case "server2": {- bezel("#262b33");- ears();- for (let r = 0; r < 2; r += 1) for (let c = 0; c < 6; c += 1) {- ctx.fillStyle = "#3a414b";- ctx.fillRect(x + 9 + c * 19, y + 4 + r * 21, 17, 18);- ctx.fillStyle = "#14171b";- ctx.fillRect(x + 11 + c * 19, y + 7 + r * 21, 13, 10);- }- ctx.fillStyle = "#d8dde3";- ctx.fillRect(x + 126, y + 18, 10, 6);- break;- }- case "gpu": {- bezel("#1b1f25");- ears();- // Honeycomb intake over most of the face, an accent stripe and a badge.- ctx.fillStyle = "#0b0d10";- for (let r = 0; r < 12; r += 1) for (let c = 0; c < 15; c += 1) {- ctx.beginPath();- ctx.arc(x + 12 + c * 7.4 + (r % 2) * 3.7, y + 8 + r * 7, 2.3, 0, Math.PI * 2);- ctx.fill();- }- ctx.fillStyle = "#2dd4bf";- ctx.fillRect(x + w - 26, y + 6, 3, h - 12);- ctx.fillStyle = "#c9d1da";- ctx.fillRect(x + w - 19, y + h / 2 + 8, 11, 5);- break;- }- case "storage": {- bezel("#22262d");- ears();- for (let r = 0; r < 4; r += 1) for (let c = 0; c < 6; c += 1) {- ctx.fillStyle = rand() < 0.5 ? "#434b56" : "#3b424c";- ctx.fillRect(x + 12 + c * 19, y + 5 + r * 23, 17, 21);- ctx.fillStyle = "#15181c";- ctx.fillRect(x + 14 + c * 19, y + 8 + r * 23, 13, 9);- }- break;- }- case "switch": {- bezel("#1f2329");- for (let r = 0; r < 2; r += 1) for (let c = 0; c < 12; c += 1) {- ctx.fillStyle = "#6b7480";- ctx.fillRect(x + 12 + c * 8, y + 8 + r * 7, 7, 6);- ctx.fillStyle = "#07080a";- ctx.fillRect(x + 13 + c * 8, y + 9 + r * 7, 5, 4);- }- ctx.fillStyle = "#aab2bc";- for (let i = 0; i < 4; i += 1) ctx.fillRect(x + 112 + i * 7, y + 8, 6, 12);- break;- }- case "patch": {- bezel("#15181c");- for (let r = 0; r < 2; r += 1) for (let c = 0; c < 12; c += 1) {- ctx.fillStyle = "#050608";- ctx.fillRect(x + 12 + c * 10.5, y + 5 + r * 8, 7, 6);- if (rand() < 0.7) {- ctx.fillStyle = CABLES[Math.floor(rand() * CABLES.length)];- ctx.fillRect(x + 13 + c * 10.5, y + 6 + r * 8, 5, 4);- }- }- break;- }- case "manager": {- bezel("#0f1114");- ctx.fillStyle = "#050607";- ctx.fillRect(x + 8, y + h / 2 - 3, w - 16, 6);- ctx.fillStyle = "#23272d";- for (let i = 0; i < 8; i += 1) ctx.fillRect(x + 10 + i * 17, y + 3, 6, h - 6);- break;- }- case "ups": {- bezel("#1e2228");- ears();- ctx.fillStyle = "#6ee7b7";- ctx.fillRect(x + 16, y + 14, 36, 16);- ctx.fillStyle = "#0f3d2e";- ctx.fillRect(x + 19, y + 18, 20, 3);- ctx.fillStyle = "#171a1f";- for (let i = 0; i < 10; i += 1) ctx.fillRect(x + 64 + i * 6, y + 8, 3, h - 16);- break;- }- case "blank": {- bezel("#121418");- ctx.fillStyle = "#2a2f36";- ctx.fillRect(x + 7, y + h / 2 - 1.5, 3, 3);- ctx.fillRect(x + w - 10, y + h / 2 - 1.5, 3, 3);- break;- }- }-}--function drawRackFaces(plan: RackPlan, seed: number, ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#07080a";- ctx.fillRect(0, 0, w, h);- for (let rack = 0; rack < RACKS_PER_ROW; rack += 1) {- const x0 = rack * CANVAS.rackPx;- // Empty rails: square cage-nut holes up the mounting posts.- ctx.fillStyle = "#0c0e11";- ctx.fillRect(x0 + DEV.x, 0, DEV.w, h);- for (const rx of [x0 + DEV.x - 12, x0 + DEV.x + DEV.w + 2]) {- ctx.fillStyle = "#3a4049";- ctx.fillRect(rx, 0, 10, h);- ctx.fillStyle = "#101216";- for (let u = 0; u < 42; u += 1) for (let j = 0; j < 3; j += 1) ctx.fillRect(rx + 3, u * PX_U + 3 + j * 7, 4, 4);- }- }- let k = 0;- const rand = () => hash01(seed * 0.0007 + (k += 1) * 2.414);- for (const unit of plan.units) drawUnit(ctx, unit, rand);-}--/** The rear door: perforated steel with a latch, one drawing repeated per rack. */-function drawPerforated(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#23272e";- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "#0a0b0d";- for (let y = 18; y < h - 14; y += 7) for (let x = 12 + ((y / 7) % 2) * 3.5; x < w - 16; x += 7) {- ctx.beginPath();- ctx.arc(x, y, 2.2, 0, Math.PI * 2);- ctx.fill();- }- ctx.fillStyle = "#15181c";- ctx.fillRect(0, 0, 5, h);- ctx.fillRect(w - 5, 0, 5, h);- ctx.fillStyle = "#9aa3ad";- ctx.fillRect(w - 13, h * 0.45, 4, h * 0.1);-}--/** Row plate on the aisle end of each row: the row letter and its rack range. */-function drawRowPlate(letter: string, ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#1c2026";- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "#5eead4";- ctx.fillRect(0, h - 10, w, 10);- ctx.fillStyle = "#ffffff";- ctx.textAlign = "center";- ctx.textBaseline = "middle";- ctx.font = "700 120px system-ui, -apple-system, 'Segoe UI', sans-serif";- ctx.fillText(letter, w / 2, h * 0.42);- ctx.fillStyle = "#9fb0c2";- ctx.font = "600 34px system-ui, -apple-system, 'Segoe UI', sans-serif";- ctx.fillText(`${letter}01–${letter}05`, w / 2, h * 0.78);-}--// ----------------------------------------------------------------------------// Instanced LEDs and patch cables-// -----------------------------------------------------------------------------const LED_GEO = GEO.box;-const TMP = new Object3D();-const TMP_COLOUR = new Color();-/** Twinkle rate: the LEDs re-roll their state this many times a second. */-const TWINKLE_HZ = 9;--function RackLeds({ plan }: { plan: RackPlan }) {- const { mesh, base, modes } = useMemo(() => {- const material = new MeshBasicMaterial({ color: "#ffffff", toneMapped: false });- const made = new InstancedMesh(LED_GEO, material, plan.leds.length);- const colours = new Float32Array(plan.leds.length * 3);- const ledModes = new Uint8Array(plan.leds.length);- plan.leds.forEach((led, i) => {- TMP.position.set(toX(led.px), toY(led.py), FACE_Z + 0.004);- TMP.scale.set(led.size, led.size, 0.006);- TMP.updateMatrix();- made.setMatrixAt(i, TMP.matrix);- TMP_COLOUR.set(led.colour);- made.setColorAt(i, TMP_COLOUR);- TMP_COLOUR.toArray(colours, i * 3);- ledModes[i] = led.mode;- });- made.instanceMatrix.needsUpdate = true;- made.computeBoundingBox();- made.computeBoundingSphere();- return { mesh: made, base: colours, modes: ledModes };- }, [plan]);- useEffect(() => () => { mesh.dispose(); (mesh.material as MeshBasicMaterial).dispose(); }, [mesh]);- const lastTick = useRef(-1);- useFrame(({ clock }) => {- const t = clock.elapsedTime;- const tick = Math.floor(t * TWINKLE_HZ);- if (tick === lastTick.current || !mesh.instanceColor) return;- lastTick.current = tick;- const out = mesh.instanceColor.array as Float32Array;- for (let i = 0; i < modes.length; i += 1) {- const mode = modes[i];- const level = mode === 0 ? 1- : mode === 1 ? (hash01(i * 7.13 + tick * 0.37) > 0.42 ? 1 : 0.12)- : 0.3 + 0.7 * (0.5 + 0.5 * Math.sin(t * 2.2 + i * 0.9));- out[i * 3] = base[i * 3] * level;- out[i * 3 + 1] = base[i * 3 + 1] * level;- out[i * 3 + 2] = base[i * 3 + 2] * level;- }- mesh.instanceColor.needsUpdate = true;- });- return <primitive object={mesh} />;-}--function PatchCables({ plan }: { plan: RackPlan }) {- const mesh = useMemo(() => {- const made = new InstancedMesh(SGEO.loop, matte("#ffffff", { roughness: 0.7 }), plan.loops.length);- plan.loops.forEach((loop, i) => {- // The half ring opens upwards: both ends plug into the panel, the loop sags below it.- TMP.position.set(toX(loop.px), toY(loop.py), FACE_Z + 0.012);- TMP.rotation.set(0, 0, Math.PI);- TMP.scale.set(loop.radius, loop.radius, loop.radius);- TMP.updateMatrix();- made.setMatrixAt(i, TMP.matrix);- made.setColorAt(i, TMP_COLOUR.set(loop.colour));- });- TMP.rotation.set(0, 0, 0);- made.instanceMatrix.needsUpdate = true;- made.computeBoundingBox();- made.computeBoundingSphere();- return made;- }, [plan]);- useEffect(() => () => { mesh.dispose(); (mesh.material as MeshStandardMaterial).dispose(); }, [mesh]);- return <primitive object={mesh} />;-}--// ----------------------------------------------------------------------------// A row of five 42U racks-// -----------------------------------------------------------------------------const RACK_XS = Array.from({ length: RACKS_PER_ROW }, (_, i) => -ROW_W / 2 + RACK_W * (i + 0.5));-const POST_XS = Array.from({ length: RACKS_PER_ROW + 1 }, (_, i) => Math.max(-ROW_W / 2 + 0.015, Math.min(ROW_W / 2 - 0.015, -ROW_W / 2 + RACK_W * i)));-const RUNG_XS = Array.from({ length: 12 }, (_, i) => -ROW_W / 2 + 0.125 + i * 0.25);-const TRAY_Y = 2.21;--export function ServerRack({ item }: { item: Furniture }) {- const seed = seedOf(item.id);- const plan = useMemo(() => rackPlan(seed), [seed]);- const face = canvasMaterial(`server:faces:${seed}`, CANVAS.rackPx * RACKS_PER_ROW, CANVAS.h,- (ctx, w, h) => drawRackFaces(plan, seed, ctx, w, h), { glow: 0.22, fallback: "#15181d", roughness: 0.45 });- const rear = repeatedMaterial("server:rear", 128, 512, drawPerforated, [RACKS_PER_ROW, 1], "#23272e", 0.55);- const letter = item.id.endsWith("-e") ? "B" : "A";- const plate = canvasMaterial(`server:plate:${letter}`, 256, 320, (ctx, w, h) => drawRowPlate(letter, ctx, w, h),- { glow: 0.3, fallback: "#1c2026", roughness: 0.5 });- const bodyH = FACE.h + 0.1;- const halfD = ROW_D / 2;- return (- <group>- {/* Plinth with a cool toe-kick glow on the aisle side, the cabinet body and its lid. */}- <Box size={[ROW_W - 0.02, 0.1, ROW_D - 0.06]} position={[0, 0.05, 0]} material={SRV.plinth} />- <Box size={[ROW_W - 0.04, 0.014, 0.01]} position={[0, 0.05, halfD - 0.03]} material={SRV.ice} cast={false} />- <Box size={[ROW_W, bodyH, ROW_D * 0.9]} position={[0, 0.1 + bodyH / 2, 0]} material={SRV.cabinet} />- <Box size={[ROW_W, 0.05, ROW_D]} position={[0, 0.1 + bodyH + 0.025, 0]} material={SRV.cabinetEdge} />- <Box size={[ROW_W - 0.06, 0.016, 0.01]} position={[0, 0.1 + bodyH + 0.01, halfD - 0.004]} material={SRV.ice} cast={false} />- {/* The server faces, their LEDs and patch cables, behind a smoked glass door per rack. */}- <Panel size={[ROW_W, FACE.h]} position={[0, FACE.y0 + FACE.h / 2, FACE_Z]} material={face} />- <RackLeds plan={plan} />- <PatchCables plan={plan} />- <Panel size={[ROW_W - 0.02, bodyH]} position={[0, 0.1 + bodyH / 2, halfD - 0.02]} material={SRV.glass} />- {POST_XS.map((x) => <Box key={x} size={[0.03, bodyH, 0.07]} position={[x, 0.1 + bodyH / 2, halfD - 0.04]} material={SRV.cabinetEdge} />)}- {RACK_XS.map((x) => <Box key={x} size={[0.016, 0.22, 0.02]} position={[x + RACK_W / 2 - 0.06, 1.12, halfD - 0.012]} material={SRV.handle} cast={false} />)}- {/* Perforated rear doors facing the wall, and a row plate on the aisle end (local -x). */}- <Panel size={[ROW_W, bodyH - 0.04]} position={[0, 0.1 + bodyH / 2, -ROW_D * 0.45 - 0.003]} material={rear} rotationY={Math.PI} />- <Panel size={[0.5, 0.62]} position={[-ROW_W / 2 - 0.003, 1.62, 0.05]} material={plate} rotationY={-Math.PI / 2} />- {/* The overhead ladder tray on short brackets: black rails, rungs, and blue, grey and yellow runs. */}- {[-1.2, 0, 1.2].map((x) => <Box key={x} size={[0.03, TRAY_Y - 2.13, 0.03]} position={[x, (TRAY_Y + 2.13) / 2 - 0.02, 0]} material={SRV.trayRail} cast={false} />)}- {[-0.19, 0.19].map((z) => <Box key={z} size={[ROW_W, 0.06, 0.015]} position={[0, TRAY_Y + 0.03, z]} material={SRV.trayRail} />)}- {RUNG_XS.map((x) => <Box key={x} size={[0.025, 0.012, 0.37]} position={[x, TRAY_Y + 0.006, 0]} material={SRV.trayRail} cast={false} />)}- <Box size={[ROW_W - 0.04, 0.04, 0.12]} position={[0, TRAY_Y + 0.032, -0.09]} material={SRV.cableBlue} />- <Box size={[ROW_W - 0.04, 0.03, 0.06]} position={[0, TRAY_Y + 0.027, 0.03]} material={SRV.cableGrey} />- <Box size={[ROW_W - 0.04, 0.03, 0.05]} position={[0, TRAY_Y + 0.027, 0.11]} material={SRV.cableRed} />- {/* The yellow fibre raceway along the front, dropping a spout into every rack. */}- <Box size={[ROW_W, 0.07, 0.1]} position={[0, 2.215, halfD - 0.06]} material={SRV.fibre} />- {RACK_XS.map((x) => <Box key={x} size={[0.06, 0.05, 0.06]} position={[x, 2.16, halfD - 0.08]} material={SRV.fibre} cast={false} />)}- {RACK_XS.map((x) => <Box key={x} size={[0.05, TRAY_Y - 2.13, 0.05]} position={[x - 0.1, (TRAY_Y + 2.13) / 2, -0.1]} material={SRV.cableBlue} cast={false} />)}- </group>- );-}--// ----------------------------------------------------------------------------// The cold aisle: perforated floor tiles, overhead trays, a linear light-// -----------------------------------------------------------------------------const AISLE = FURNITURE_SIZE.coldAisle;--function drawAisleFloor(ctx: Ctx, w: number, h: number): void {- const cols = 4, rows = 5;- const tw = w / cols, th = h / rows;- for (let r = 0; r < rows; r += 1) for (let c = 0; c < cols; c += 1) {- const perforated = c === 0 || c === cols - 1;- const x = c * tw, y = r * th;- ctx.fillStyle = perforated ? "#a9b0b9" : (r + c) % 2 === 0 ? "#c9ced5" : "#c3c8cf";- ctx.fillRect(x, y, tw, th);- if (perforated) {- ctx.fillStyle = "#58606b";- for (let py = y + 10; py < y + th - 6; py += 8) for (let px = x + 10; px < x + tw - 6; px += 8) {- ctx.beginPath();- ctx.arc(px, py, 2.3, 0, Math.PI * 2);- ctx.fill();- }- }- ctx.fillStyle = "rgba(90,98,110,0.6)";- ctx.fillRect(x, y, tw, 2);- ctx.fillRect(x, y, 2, th);- }-}--const CROSS_ZS = [-AISLE.d / 2 + 0.35, AISLE.d / 2 - 0.35];--export function ColdAisle() {- const floor = canvasMaterial("server:aisle", 256, 320, drawAisleFloor, { fallback: "#c3c8cf", roughness: 0.75 });- const w = AISLE.w;- return (- <group>- <mesh position={[0, 0.009, 0]} rotation={[-Math.PI / 2, 0, 0]} material={floor} receiveShadow>- <planeGeometry args={[w, AISLE.d]} />- </mesh>- {/* Two ladder trays bridge the aisle between the rows. */}- {CROSS_ZS.map((z) => (- <group key={z} position={[0, 2.25, z]}>- {[-0.12, 0.12].map((dz) => <Box key={dz} size={[w, 0.05, 0.012]} position={[0, 0, dz]} material={SRV.trayRail} cast={false} />)}- {[-0.9, -0.45, 0, 0.45, 0.9].map((x) => <Box key={x} size={[0.02, 0.01, 0.24]} position={[x, -0.02, 0]} material={SRV.trayRail} cast={false} />)}- <Box size={[w - 0.04, 0.03, 0.1]} position={[0, -0.005, -0.03]} material={SRV.cableBlue} cast={false} />- <Box size={[w - 0.04, 0.025, 0.05]} position={[0, -0.007, 0.06]} material={SRV.fibre} cast={false} />- </group>- ))}- {/* A slim linear luminaire hung between the trays, and the aisle's one cool light. */}- <Box size={[0.07, 0.035, AISLE.d - 0.9]} position={[0, 2.21, 0]} material={SRV.trayRail} cast={false} />- <Box size={[0.05, 0.006, AISLE.d - 0.95]} position={[0, 2.19, 0]} material={SRV.panel} cast={false} />- <pointLight position={[0, 1.95, 0]} color="#8fe3ff" intensity={4} distance={5.5} decay={2} />- </group>- );-}--// ----------------------------------------------------------------------------// Live screens: the NOC console and the status wall-// -----------------------------------------------------------------------------interface ClusterData { load: number; working: number; total: number }--/** Cluster load follows the coding agents at work: an idle floor hums along, a busy one runs hot. */-function useClusterData(): ClusterData {- const panes = useWorkspacePanesStore((s) => s.panes);- return useMemo(() => {- let working = 0, total = 0;- for (const { agent } of paneOccupants(panes)) {- total += 1;- if (agent.state === "working") working += 1;- }- return { load: 0.28 + 0.62 * (total ? working / total : 0), working, total };- }, [panes]);-}--/** A counter that ticks on a slow timer; the screens redraw on it, never per frame. */-function useTicker(ms: number): number {- const [tick, setTick] = useState(0);- useCanvasInterval(() => setTick((t) => t + 1), ms);- return tick;-}--function useCanvasScreen(width: number, height: number, key: string, draw: (ctx: Ctx, w: number, h: number) => void): MeshBasicMaterial {- const canvas = useMemo(() => (typeof document !== "undefined" ? document.createElement("canvas") : null), []);- const material = useMemo(() => {- if (!canvas) return new MeshBasicMaterial({ color: "#0b0d10" });- canvas.width = width;- canvas.height = height;- const texture = new CanvasTexture(canvas);- texture.colorSpace = SRGBColorSpace;- texture.anisotropy = 8;- return new MeshBasicMaterial({ map: texture, toneMapped: false });- }, [canvas, width, height]);- const drawRef = useRef(draw);- drawRef.current = draw;- useEffect(() => {- let ctx: Ctx | null = null;- try { ctx = canvas?.getContext("2d") ?? null; } catch {- // jsdom without the canvas package: the plain dark screen is the right fallback.- ctx = null;- }- if (!ctx || !material.map) return;- drawRef.current(ctx, width, height);- material.map.needsUpdate = true;- }, [key, canvas, material, width, height]);- useEffect(() => () => { material.map?.dispose(); material.dispose(); }, [material]);- return material;-}--const SCREEN_BG = "#070b12";-const FONT = (px: number, weight = 600) => `${weight} ${px}px ui-monospace, 'Cascadia Mono', 'SF Mono', Menlo, monospace`;--/** A smooth pseudo-random series for charts: deterministic in (seed, i). */-function series(seed: number, i: number, base: number, swing: number): number {- return base + swing * (0.55 * Math.sin(i * 0.35 + seed) + 0.3 * Math.sin(i * 0.9 + seed * 2.1) + 0.15 * (hash01(i + seed * 13) - 0.5) * 2);-}--function drawChart(ctx: Ctx, x: number, y: number, w: number, h: number, tick: number, seed: number, level: number, colour: string, fill: string): void {- ctx.strokeStyle = "rgba(120,160,200,0.14)";- ctx.lineWidth = 1;- for (let i = 1; i < 4; i += 1) {- ctx.beginPath();- ctx.moveTo(x, y + (h * i) / 4);- ctx.lineTo(x + w, y + (h * i) / 4);- ctx.stroke();- }- const points = 40;- const value = (i: number) => Math.max(0.04, Math.min(0.97, series(seed, i + tick, level, 0.16)));- ctx.beginPath();- ctx.moveTo(x, y + h);- for (let i = 0; i < points; i += 1) ctx.lineTo(x + (w * i) / (points - 1), y + h - value(i) * h);- ctx.lineTo(x + w, y + h);- ctx.closePath();- ctx.fillStyle = fill;- ctx.fill();- ctx.beginPath();- for (let i = 0; i < points; i += 1) {- const px = x + (w * i) / (points - 1), py = y + h - value(i) * h;- if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py);- }- ctx.strokeStyle = colour;- ctx.lineWidth = 3;- ctx.stroke();-}--function tempColour(t: number): string {- if (t < 0.45) return "#1f9d8b";- if (t < 0.65) return "#3fc58a";- if (t < 0.8) return "#e8b23a";- return "#e5553f";-}--/** What the status wall shows: the Agentic IDE's spend over the Spend section's default window. */-export interface IdeSpend {- days: number;- cost: number;- billed: number;- tokens: number;- sessions: number;- /** Cost per bucket (a day), oldest first. */- series: { key: string; cost: number }[];- /** The costliest models, most expensive first. */- models: { name: string; cost: number }[];-}--/** The wall's numbers from a cost summary. Pure. */-export function ideSpendFrom(summary: CostSummary | undefined, days: number): IdeSpend | null {- if (!summary) return null;- const { totals } = summary;- return {- days,- cost: totals.cost_usd,- billed: Math.max(0, totals.cost_usd - totals.subscription_usd),- tokens: totals.tokens_total,- sessions: summary.refs_total,- series: summary.series.map((b) => ({ key: b.key, cost: b.cost_usd })),- models: [...summary.by_model].sort((a, b) => b.cost_usd - a.cost_usd).slice(0, 5).map((b) => ({ name: b.key, cost: b.cost_usd })),- };-}--/** $1,234 · $12.30 · $0.042: whole dollars once it is large, cents below, grouped for `locale`. Pure. */-export function formatUsd(v: number, locale = "en-US"): string {- if (v >= 1000) return `$${Math.round(v).toLocaleString(locale)}`;- if (v >= 1) return `$${v.toFixed(2)}`;- if (v > 0) return `$${v.toFixed(3)}`;- return "$0";-}--/** 1.2B · 34.5M · 812K · 950. Pure. */-export function formatCount(v: number): string {- if (v >= 1e9) return `${(v / 1e9).toFixed(1)}B`;- if (v >= 1e6) return `${(v / 1e6).toFixed(1)}M`;- if (v >= 1e3) return `${Math.round(v / 1e3)}K`;- return String(Math.round(v));-}--/** The status wall's words and its locale, resolved by the component that draws it. */-interface StatusWallLabels {- locale: string; spend: string; days: string; na: string; cost: string; billed: string; tokens: string; sessions: string;- peak: string; empty: string; unavailable: string; loading: string; topModels: string;-}--function drawStatusWall(ctx: Ctx, w: number, h: number, spend: IdeSpend | null, failed: boolean, l: StatusWallLabels): void {- const usd = (v: number) => formatUsd(v, l.locale);- ctx.fillStyle = SCREEN_BG;- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "#5eead4";- ctx.fillRect(0, 0, w, 6);- ctx.textBaseline = "middle";- ctx.textAlign = "left";- ctx.fillStyle = "#e6f1ff";- ctx.font = FONT(44, 700);- ctx.fillText("AGENTIC IDE", 36, 50);- const titleW = ctx.measureText("AGENTIC IDE").width;- ctx.fillStyle = "#8fa3ba";- ctx.font = FONT(30);- ctx.fillText(`${l.spend} · ${spend ? fill(l.days, { days: spend.days }) : "…"}`, 36 + titleW + 24, 52);- ctx.textAlign = "right";- ctx.font = FONT(34);- ctx.fillText(new Date().toLocaleTimeString(l.locale, { hour: "2-digit", minute: "2-digit" }), w - 36, 50);- // KPI tiles: what the IDE's agents cost, what of it an API key paid, tokens, sessions.- const dash = failed ? l.na : "…";- const tiles: [string, string, string][] = [- [l.cost, spend ? usd(spend.cost) : dash, "#5eead4"],- [l.billed, spend ? usd(spend.billed) : dash, "#e8b23a"],- [l.tokens, spend ? formatCount(spend.tokens) : dash, "#7dd3fc"],- [l.sessions, spend ? spend.sessions.toLocaleString(l.locale) : dash, "#c4b5fd"],- ];- const tw = (w - 72 - 3 * 20) / 4;- tiles.forEach(([label, value, colour], i) => {- const x = 36 + i * (tw + 20);- ctx.fillStyle = "#0e1522";- ctx.fillRect(x, 96, tw, 128);- ctx.fillStyle = colour;- ctx.fillRect(x, 96, 5, 128);- ctx.textAlign = "left";- ctx.fillStyle = "#8fa3ba";- ctx.font = FONT(24);- ctx.fillText(label, x + 22, 126, tw - 30);- ctx.fillStyle = colour;- ctx.font = FONT(value.length > 8 ? 46 : 58, 700);- ctx.fillText(value, x + 22, 184);- });- // Cost per day as bars, and the costliest models beside it.- const cx = 36, cy = 262, cw = w * 0.6, ch = h - cy - 44;- ctx.strokeStyle = "rgba(120,160,200,0.14)";- ctx.lineWidth = 1;- for (let i = 0; i <= 4; i += 1) {- ctx.beginPath(); ctx.moveTo(cx, cy + (ch * i) / 4); ctx.lineTo(cx + cw, cy + (ch * i) / 4); ctx.stroke();- }- const bars = spend?.series ?? [];- const peak = Math.max(0, ...bars.map((b) => b.cost));- if (peak > 0) {- const bw = cw / bars.length;- bars.forEach((b, i) => {- const bh = (b.cost / peak) * ch;- ctx.fillStyle = i === bars.length - 1 ? "#5eead4" : "rgba(94,234,212,0.55)";- ctx.fillRect(cx + i * bw + bw * 0.15, cy + ch - bh, Math.max(2, bw * 0.7), bh);- });- ctx.textAlign = "left";- ctx.fillStyle = "#8fa3ba";- ctx.font = FONT(20);- ctx.fillText(fill(l.peak, { amount: usd(peak) }), cx, cy + ch + 24);- } else {- ctx.textAlign = "center";- ctx.fillStyle = "#4b5d72";- ctx.font = FONT(26);- ctx.fillText(spend ? l.empty : failed ? l.unavailable : l.loading, cx + cw / 2, cy + ch / 2);- }- const mx = cx + cw + 40, mw = w - mx - 36;- ctx.textAlign = "left";- ctx.fillStyle = "#8fa3ba";- ctx.font = FONT(22);- ctx.fillText(l.topModels, mx, cy + 8);- const models = spend?.models ?? [];- const top = models[0]?.cost || 1;- models.forEach((m, i) => {- const y = cy + 48 + i * ((ch - 30) / 5);- ctx.textAlign = "left";- ctx.fillStyle = "#e6f1ff";- ctx.font = FONT(22, 600);- const cost = usd(m.cost);- const room = mw - ctx.measureText(cost).width - 20;- let name = m.name;- while (name.length > 3 && ctx.measureText(`${name}…`).width > room) name = name.slice(0, -1);- ctx.fillText(name === m.name ? name : `${name}…`, mx, y);- ctx.textAlign = "right";- ctx.fillStyle = "#5eead4";- ctx.fillText(cost, mx + mw, y);- ctx.fillStyle = "#101a28";- ctx.fillRect(mx, y + 18, mw, 6);- ctx.fillStyle = "#1f9d8b";- ctx.fillRect(mx, y + 18, Math.max(4, (mw * m.cost) / top), 6);- });-}--function drawThroughput(ctx: Ctx, w: number, h: number, data: ClusterData, tick: number, net: string, locale: string): void {- ctx.fillStyle = SCREEN_BG;- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "#7dd3fc";- ctx.font = FONT(26, 700);- ctx.textAlign = "left";- ctx.textBaseline = "middle";- ctx.fillText(`${net} Gb/s`, 22, 28);- ctx.textAlign = "right";- ctx.fillStyle = "#e6f1ff";- ctx.fillText((40 + data.load * 60 + 3 * Math.sin(tick)).toLocaleString(locale, { minimumFractionDigits: 1, maximumFractionDigits: 1 }), w - 22, 28);- drawChart(ctx, 18, 58, w - 36, h - 76, tick, 4.2, 0.3 + data.load * 0.5, "#7dd3fc", "rgba(125,211,252,0.14)");- drawChart(ctx, 18, 58, w - 36, h - 76, tick, 9.1, 0.2 + data.load * 0.3, "#c4b5fd", "rgba(196,181,253,0.08)");-}--function drawThermal(ctx: Ctx, w: number, h: number, data: ClusterData, tick: number): void {- ctx.fillStyle = SCREEN_BG;- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "#5eead4";- ctx.font = FONT(26, 700);- ctx.textAlign = "left";- ctx.textBaseline = "middle";- ctx.fillText("GPU", 22, 28);- // Utilisation bars, one per GPU node.- const bars = 14;- const bw = (w - 44) / bars;- for (let i = 0; i < bars; i += 1) {- const v = Math.max(0.06, Math.min(1, data.load + 0.25 * (hash01(i * 5.7 + tick * 0.5) - 0.5)));- const bh = (h - 90) * v;- ctx.fillStyle = "#101a28";- ctx.fillRect(22 + i * bw + 3, 58, bw - 6, h - 90);- ctx.fillStyle = tempColour(v);- ctx.fillRect(22 + i * bw + 3, 58 + (h - 90) - bh, bw - 6, bh);- }- ctx.fillStyle = "#8fa3ba";- ctx.font = FONT(20);- ctx.textAlign = "left";- ctx.fillText(`${Math.round(data.load * 100)}%`, 22, h - 16);-}--function drawLog(ctx: Ctx, w: number, h: number, _data: ClusterData, tick: number): void {- ctx.fillStyle = SCREEN_BG;- ctx.fillRect(0, 0, w, h);- ctx.textBaseline = "middle";- ctx.textAlign = "left";- const rows = 9;- for (let i = 0; i < rows; i += 1) {- const entry = tick + rows - i;- const y = 26 + i * ((h - 36) / rows);- const warn = hash01(entry * 1.3) < 0.12;- ctx.fillStyle = warn ? "#e8b23a" : "#3dff8a";- ctx.beginPath();- ctx.arc(26, y, 6, 0, Math.PI * 2);- ctx.fill();- ctx.fillStyle = "#4b5d72";- ctx.font = FONT(20);- ctx.fillText(`${String(10 + (entry % 50)).padStart(2, "0")}:${String((entry * 7) % 60).padStart(2, "0")}`, 44, y);- ctx.fillStyle = warn ? "#f4d27a" : "#b7c7d9";- ctx.fillRect(122, y - 4, 90 + hash01(entry * 2.7) * (w - 260), 8);- }-}--function Screen({ w, h, material }: { w: number; h: number; material: MeshBasicMaterial }) {- return (- <group>- <Rounded size={[w + 0.04, h + 0.04, 0.03]} radius={0.01} position={[0, 0, 0]} material={MAT.monitor} />- <mesh position={[0, 0, 0.0155]} material={material}>- <planeGeometry args={[w, h]} />- </mesh>- </group>- );-}--const WALL = { w: 2.3, h: 0.94, y: 1.6 };--/** The Spend section's default window, narrowed to what the Agentic IDE's agents spent. */-const IDE_SPEND_FILTERS: CostFilters = { ...EMPTY_FILTERS, surfaces: ["agentic-ide"] };--/** A floor-standing status display: the Agentic IDE's spend for the whole room. A click dives into it and opens Spend. */-export function StatusWall() {- const active = useContext(CanvasActivity);- const summary = useCostSummary(IDE_SPEND_FILTERS, active);- const spend = ideSpendFrom(summary.data, IDE_SPEND_FILTERS.days);- // The clock in the corner moves once a minute; the numbers when the summary answers.- const tick = useTicker(30_000);- const t = useT();- const locale = useRunLocale();- const labels: StatusWallLabels = {- locale,- spend: t("society.office.status_spend"),- days: t("society.office.status_days"),- na: t("society.office.status_na"),- cost: t("society.office.status_cost"),- billed: t("society.office.status_billed"),- tokens: t("society.office.status_tokens"),- sessions: t("society.office.status_sessions"),- peak: t("society.office.status_peak"),- empty: t("society.office.status_empty"),- unavailable: t("society.office.status_unavailable"),- loading: t("society.office.status_loading"),- topModels: t("society.office.status_top_models"),- };- const screen = useCanvasScreen(1280, Math.round((1280 * WALL.h) / WALL.w), `${tick}:${summary.dataUpdatedAt}:${summary.isError}:${JSON.stringify(labels)}`,- (ctx, w, h) => drawStatusWall(ctx, w, h, spend, summary.isError && !spend, labels));- const dive = useMonitorDive("costs", [WALL.w, WALL.h], 0.0155);- return (- <group>- <Box size={[1.3, 0.03, 0.28]} position={[0, 0.015, 0]} material={SRV.cabinet} />- {[-0.5, 0.5].map((x) => <Box key={x} size={[0.07, WALL.y - 0.1, 0.06]} position={[x, (WALL.y - 0.1) / 2, -0.06]} material={SRV.cabinetEdge} />)}- <group position={[0, WALL.y, -0.02]} {...dive}>- <Screen w={WALL.w} h={WALL.h} material={screen} />- </group>- <Box size={[WALL.w - 0.1, 0.012, 0.012]} position={[0, WALL.y - WALL.h / 2 - 0.05, -0.02]} material={SRV.ice} cast={false} />- </group>- );-}--const MON = { w: 0.6, h: 0.34, y: 1.07 };-const MON_CANVAS = { w: 640, h: Math.round((640 * 0.34) / 0.6) };-const NOC_D = FURNITURE_SIZE.nocConsole.d;-const DESK = { d: 0.72, z: -NOC_D / 2 + 0.36, top: 0.74 };-const STOOL_Z = NOC_D / 2 - 0.26;-const MUG = new CylinderGeometry(0.04, 0.036, 0.1, 16);--/** The NOC console: a graphite desk with three monitors (network, GPUs, the event log) and a stool. */-export function NocConsole() {- const data = useClusterData();- const tick = useTicker(2000);- const t = useT();- const locale = useRunLocale();- const netLabel = t("society.office.status_net");- const key = `${tick}:${data.load}:${netLabel}:${locale}`;- const net = useCanvasScreen(MON_CANVAS.w, MON_CANVAS.h, key, (ctx, w, h) => drawThroughput(ctx, w, h, data, tick, netLabel, locale));- const gpu = useCanvasScreen(MON_CANVAS.w, MON_CANVAS.h, key, (ctx, w, h) => drawThermal(ctx, w, h, data, tick));- const log = useCanvasScreen(MON_CANVAS.w, MON_CANVAS.h, key, (ctx, w, h) => drawLog(ctx, w, h, data, tick));- const monZ = DESK.z - DESK.d / 2 + 0.16;- return (- <group>- {/* Desk: a dark top on two panel legs, a modesty panel and a cool strip under the lip. */}- <Rounded size={[1.96, 0.04, DESK.d]} radius={0.012} position={[0, DESK.top, DESK.z]} material={SRV.cabinetEdge} />- {[-0.93, 0.93].map((x) => <Box key={x} size={[0.04, DESK.top - 0.02, DESK.d - 0.08]} position={[x, (DESK.top - 0.02) / 2, DESK.z]} material={SRV.cabinet} />)}- <Box size={[1.82, 0.42, 0.02]} position={[0, 0.48, DESK.z - DESK.d / 2 + 0.06]} material={SRV.cabinet} />- <Box size={[1.9, 0.01, 0.01]} position={[0, DESK.top - 0.03, DESK.z + DESK.d / 2 - 0.02]} material={SRV.ice} cast={false} />- {/* Three monitors on one bar: the side screens turned in towards the operator. */}- <Box size={[1.5, 0.03, 0.03]} position={[0, MON.y - 0.08, monZ - 0.04]} material={MAT.monitorArm} cast={false} />- <Box size={[0.05, MON.y - DESK.top - 0.08, 0.05]} position={[0, (MON.y + DESK.top - 0.08) / 2, monZ - 0.05]} material={MAT.monitorArm} />- <Box size={[0.26, 0.012, 0.18]} position={[0, DESK.top + 0.026, monZ - 0.02]} material={MAT.monitorArm} cast={false} />- <group position={[0, MON.y, monZ]}><Screen w={MON.w} h={MON.h} material={net} /></group>- <group position={[-0.63, MON.y, monZ + 0.1]} rotation={[0, 0.38, 0]}><Screen w={MON.w} h={MON.h} material={gpu} /></group>- <group position={[0.63, MON.y, monZ + 0.1]} rotation={[0, -0.38, 0]}><Screen w={MON.w} h={MON.h} material={log} /></group>- {/* Keyboard, mouse, a mug and a headset on its stand. */}- <Rounded size={[0.44, 0.02, 0.14]} radius={0.006} position={[0, DESK.top + 0.03, DESK.z + 0.15]} material={MAT.keyboard} cast={false} />- <Rounded size={[0.06, 0.02, 0.1]} radius={0.01} position={[0.32, DESK.top + 0.03, DESK.z + 0.16]} material={MAT.keyboard} cast={false} />- <mesh geometry={MUG} material={MAT.mug} position={[-0.52, DESK.top + 0.07, DESK.z + 0.12]} castShadow />- <Cyl radius={0.05} height={0.012} position={[0.72, DESK.top + 0.026, DESK.z + 0.08]} material={SRV.cabinet} cast={false} />- <Cyl radius={0.008} height={0.2} position={[0.72, DESK.top + 0.13, DESK.z + 0.08]} material={MAT.monitorArm} cast={false} />- <mesh geometry={SGEO.loop} material={SRV.cabinet} position={[0.72, DESK.top + 0.2, DESK.z + 0.08]} rotation={[0, Math.PI / 2, 0]} scale={0.075} />- {/* A drafting stool: five-star base, gas lift, round seat and foot ring. */}- <group position={[0, 0, STOOL_Z]}>- {[0, 1, 2, 3, 4].map((i) => (- <group key={i} rotation={[0, (i * Math.PI * 2) / 5, 0]}>- <Box size={[0.04, 0.03, 0.2]} position={[0, 0.05, 0.1]} material={MAT.chair} />- </group>- ))}- <Cyl radius={0.025} height={0.56} position={[0, 0.34, 0]} material={MAT.monitorArm} />- <mesh geometry={SGEO.loop} material={MAT.monitorArm} position={[0, 0.3, 0]} rotation={[Math.PI / 2, 0, 0]} scale={[0.17, 0.17, 0.17]} />- <mesh geometry={SGEO.loop} material={MAT.monitorArm} position={[0, 0.3, 0]} rotation={[-Math.PI / 2, 0, 0]} scale={[0.17, 0.17, 0.17]} />- <Cyl radius={0.2} height={0.07} position={[0, 0.66, 0]} material={SRV.stoolSeat} />- </group>- </group>- );-}--// ----------------------------------------------------------------------------// UPS and fire suppression-// -----------------------------------------------------------------------------function drawUpsDisplay(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#0b1a14";- ctx.fillRect(0, 0, w, h);- // Battery glyph, full, and three load bars.- ctx.strokeStyle = "#6ee7b7";- ctx.lineWidth = 5;- ctx.strokeRect(18, 22, 70, 36);- ctx.fillStyle = "#6ee7b7";- ctx.fillRect(88, 32, 8, 16);- ctx.fillRect(25, 29, 56, 22);- ctx.font = "700 34px ui-monospace, Menlo, monospace";- ctx.textBaseline = "middle";- ctx.fillText("100%", 112, 40);- for (let i = 0; i < 3; i += 1) {- ctx.fillStyle = "#123427";- ctx.fillRect(18, 80 + i * 18, w - 36, 10);- ctx.fillStyle = "#6ee7b7";- ctx.fillRect(18, 80 + i * 18, (w - 36) * [0.46, 0.52, 0.41][i], 10);- }-}--function drawVents(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#23272e";- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "#0c0d10";- for (let y = 10; y < h - 6; y += 12) ctx.fillRect(10, y, w - 20, 5);-}--function drawHazardStripes(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#f5c518";- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "#15171a";- for (let x = -h; x < w + h; x += 40) {- ctx.beginPath();- ctx.moveTo(x, h);- ctx.lineTo(x + 20, h);- ctx.lineTo(x + 20 + h, 0);- ctx.lineTo(x + h, 0);- ctx.closePath();- ctx.fill();- }-}--/** A white-on-red pictogram sign: a flame over a gas bottle. */-function drawSuppressionSign(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#c8262b";- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "#ffffff";- ctx.beginPath();- ctx.moveTo(w * 0.5, h * 0.12);- ctx.bezierCurveTo(w * 0.78, h * 0.35, w * 0.7, h * 0.6, w * 0.5, h * 0.62);- ctx.bezierCurveTo(w * 0.3, h * 0.6, w * 0.24, h * 0.38, w * 0.42, h * 0.28);- ctx.bezierCurveTo(w * 0.42, h * 0.4, w * 0.5, h * 0.42, w * 0.5, h * 0.12);- ctx.fill();- ctx.fillRect(w * 0.38, h * 0.7, w * 0.24, h * 0.2);- ctx.fillRect(w * 0.46, h * 0.65, w * 0.08, h * 0.06);-}--const UPS_H = 1.86;--/** A UPS and its battery cabinet side by side, fronts facing +z. */-export function UpsCabinet() {- const display = canvasMaterial("server:ups-display", 256, 150, drawUpsDisplay, { glow: 0.9, fallback: "#0b1a14", roughness: 0.3 });- const vents = canvasMaterial("server:ups-vents", 128, 256, drawVents, { fallback: "#23272e", roughness: 0.6 });- const perforated = repeatedMaterial("server:rear", 128, 512, drawPerforated, [1, 1], "#23272e", 0.55);- const d = FURNITURE_SIZE.ups.d;- const front = d / 2 - 0.02;- return (- <group>- {[-0.3, 0.3].map((x) => (- <group key={x} position={[x, 0, 0]}>- <Box size={[0.58, 0.08, d - 0.06]} position={[0, 0.04, 0]} material={SRV.plinth} />- <Box size={[0.58, UPS_H - 0.08, d - 0.04]} position={[0, 0.08 + (UPS_H - 0.08) / 2, 0]} material={SRV.cabinet} />- <Box size={[0.58, 0.012, 0.01]} position={[0, UPS_H - 0.03, front + 0.006]} material={SRV.ledGreen} cast={false} />- </group>- ))}- {/* UPS: a status display and LEDs over a vented door. */}- <Box size={[0.3, 0.2, 0.012]} position={[-0.3, 1.45, front]} material={MAT.monitor} cast={false} />- <Panel size={[0.26, 0.152]} position={[-0.3, 1.45, front + 0.0065]} material={display} />- {[0, 1, 2].map((i) => <Box key={i} size={[0.018, 0.018, 0.008]} position={[-0.38 + i * 0.04, 1.28, front + 0.004]} material={SRV.ledGreen} cast={false} />)}- <Panel size={[0.46, 0.9]} position={[-0.3, 0.66, front + 0.001]} material={vents} />- {/* Battery cabinet: a perforated door, a latch and a hazard label. */}- <Panel size={[0.5, UPS_H - 0.2]} position={[0.3, 0.08 + (UPS_H - 0.08) / 2, front + 0.001]} material={perforated} />- <Box size={[0.016, 0.2, 0.02]} position={[0.07, 1.05, front + 0.01]} material={SRV.handle} cast={false} />- <Box size={[0.12, 0.1, 0.004]} position={[0.3, 1.55, front + 0.004]} material={SRV.fibre} cast={false} />- {/* The emergency power-off button on the UPS side. */}- <Box size={[0.1, 0.12, 0.05]} position={[-0.3, 1.72, front - 0.02]} material={SRV.fibre} />- <Cyl radius={0.03} height={0.03} position={[-0.3, 1.72, front + 0.01]} material={SRV.red} cast={false} />- </group>- );-}--/** Two clean-agent gas cylinders on a wall frame, their manifold and a control panel, over a hazard plate. */-export function FireSuppression() {- const stripes = repeatedMaterial("server:hazard", 256, 64, drawHazardStripes, [2, 1], "#f5c518", 0.7);- const sign = canvasMaterial("server:suppression-sign", 128, 128, drawSuppressionSign, { glow: 0.2, fallback: "#c8262b", roughness: 0.5 });- const { w, d } = FURNITURE_SIZE.fireSuppression;- const back = -d / 2 + 0.02;- const bottles = [-0.26, 0.04];- return (- <group>- <mesh position={[0, 0.008, 0]} rotation={[-Math.PI / 2, 0, 0]} material={stripes} receiveShadow>- <planeGeometry args={[w - 0.02, d - 0.02]} />- </mesh>- <Box size={[w - 0.02, 1.84, 0.03]} position={[0, 0.94, back]} material={SRV.backplate} />- {bottles.map((x) => (- <group key={x} position={[x, 0, back + 0.17]}>- <Cyl radius={0.13} height={1.2} position={[0, 0.62, 0]} material={SRV.red} />- <mesh geometry={SGEO.dome} material={SRV.red} position={[0, 1.22, 0]} scale={[0.13, 0.1, 0.13]} castShadow />- <Cyl radius={0.035} height={0.1} position={[0, 1.36, 0]} material={SRV.valve} />- {[0.35, 0.95].map((y) => <Box key={y} size={[0.3, 0.04, 0.02]} position={[0, y, -0.13]} material={SRV.trayRail} cast={false} />)}- </group>- ))}- {/* Manifold: a header pipe across both valves, rising to the ceiling line. */}- <Cyl radius={0.022} height={0.1} position={[bottles[0], 1.44, back + 0.17]} material={SRV.valve} cast={false} />- <Cyl radius={0.022} height={0.1} position={[bottles[1], 1.44, back + 0.17]} material={SRV.valve} cast={false} />- <Box size={[0.4, 0.045, 0.045]} position={[(bottles[0] + bottles[1]) / 2 + 0.03, 1.5, back + 0.17]} material={SRV.red} cast={false} />- <Box size={[0.045, 0.4, 0.045]} position={[bottles[1] + 0.1, 1.7, back + 0.17]} material={SRV.red} cast={false} />- {/* Control panel with its status LEDs, and the pictogram sign above it. */}- <Box size={[0.2, 0.3, 0.07]} position={[0.32, 1.25, back + 0.05]} material={SRV.cream} />- <Box size={[0.2, 0.05, 0.072]} position={[0.32, 1.375, back + 0.05]} material={SRV.red} cast={false} />- <Box size={[0.02, 0.02, 0.01]} position={[0.28, 1.28, back + 0.088]} material={SRV.ledGreen} cast={false} />- <Box size={[0.02, 0.02, 0.01]} position={[0.32, 1.28, back + 0.088]} material={SRV.plinth} cast={false} />- <Box size={[0.08, 0.05, 0.01]} position={[0.32, 1.18, back + 0.088]} material={SRV.plinth} cast={false} />- <Panel size={[0.2, 0.2]} position={[0.32, 1.62, back + 0.017]} material={sign} />- </group>- );-}--export const SERVER_RENDERERS = {- serverRack: ({ item }) => <ServerRack item={item} />,- coldAisle: () => <ColdAisle />,- nocConsole: () => <NocConsole />,- statusWall: () => <StatusWall />,- ups: () => <UpsCabinet />,- fireSuppression: () => <FireSuppression />,-} satisfies Partial<Record<FurnitureKind, (props: { item: Furniture }) => JSX.Element>>;diff --git a/dodaios/ui/web/frontend/src/components/society/office/SingularityCity.tsx b/dodaios/ui/web/frontend/src/components/society/office/SingularityCity.tsxdeleted file mode 100644index 799e24ee5a..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/SingularityCity.tsx+++ /dev/null@@ -1,316 +0,0 @@-/**- * 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/dodaios/ui/web/frontend/src/components/society/office/SkyCourier.tsx b/dodaios/ui/web/frontend/src/components/society/office/SkyCourier.tsxdeleted file mode 100644index 48272ffb64..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/SkyCourier.tsx+++ /dev/null@@ -1,732 +0,0 @@-/**- * The courier: the chrome starship on the sky pad, and the person's flight in- * it. Parked, it stands on its gear beside the bridge; the ship station- * (stations.ts) boards it. Flying, this component owns the camera (chase or- * cockpit), reads the keys and a gamepad, steps the flight (courierFlight.ts)- * against the city (courierWorld.ts), and drives the ship's looks: gear,- * engine glow and flames, the engine light, contrails at speed, the shield's- * flash on impact, dust on the deck when it lands or lifts, and the engine- * sound (courierAudio.ts). With reduced motion the flames and dust stay calm- * and the camera does not shake.- *- * The model comes in three levels of detail from the art study- * (art/studies/sky-pad-courier-study); its chrome and gold reflect a small- * environment of the city's night built once per renderer.- */-import { Component, Suspense, useEffect, useMemo, useRef, useState, type ReactNode } from "react";-import { useGLTF } from "@react-three/drei";-import { useFrame, useThree } from "@react-three/fiber";-import {- AdditiveBlending, BackSide, BufferAttribute, BufferGeometry, Color, ConeGeometry, DoubleSide, Float32BufferAttribute, Group, LOD, Mesh,- MeshBasicMaterial, MeshStandardMaterial, Object3D, PerspectiveCamera, PMREMGenerator, PointLight, RepeatWrapping, Scene, ShaderMaterial,- SphereGeometry, Vector3, type Material, type Texture, type WebGLRenderer, type WebGLRenderTarget,-} from "three";-import courierNear from "@/assets/society/courier/courier-lod0.glb";-import courierMid from "@/assets/society/courier/courier-lod1.glb";-import courierFar from "@/assets/society/courier/courier-lod2.glb";-import { planCity } from "./cityPlan";-import { cachedCanvasTexture } from "./canvasMaterials";-import { CourierEngineSound } from "./courierAudio";-import { aimDirection, aimFromForward, cursorTurn, FLIGHT_ACTIONS, flightInput, moveAim, PAD_PRESSES, steerTowards, type MouseAim, PRESS_ACTIONS, type FlightAction, type PadState } from "./courierControls";-import { engageAutopilot, FLIGHT, forwardOf, heightOverDeck, NO_INPUT, parkedState, stepFlight, type FlightState } from "./courierFlight";-import { courierSession, useCourier } from "./courierStore";-import { buildCourierWorld, rayDistance } from "./courierWorld";-import { CAMERA_FOV } from "./officeCamera";-import type { OfficeLayout } from "./officeLayout";-import { ownsKeyboard } from "./OfficePlayer";-import { player as playerBody, useOfficeStore } from "./officeStore";-import { COURIER, type SkyPad } from "./skyPad";-import { COURIER_GROUP } from "./stations";--/** Authored geometry the runtime drives (model units = authored metres): where the gear retracts to, the exhausts, the pod tails. */-const MODEL = {- gearTravel: 1.9,- exhausts: [[-5.9, -0.15, 13.8], [5.9, -0.15, 13.8]] as const,- tails: [[-5.9, -0.15, 20.8], [5.9, -0.15, 20.8]] as const,- shield: [9.2, 4, 21] as const,-} as const;--/** Chase camera: behind and above the ship (world metres), and where it looks. Cockpit: the pilot's eyes. */-const CHASE = { back: 22, up: 6, lookAhead: 24, stiffness: 5 } as const;-const COCKPIT = { up: 1.25, forward: -3.6 } as const;-const FLIGHT_FOV = { cruise: 60, boost: 72 } as const;--// ----------------------------------------------------------------------------// Materials-// -----------------------------------------------------------------------------/** The city's night as a small environment for the chrome: violet sky, a gold glow on one side, dark streets with lights. */-function cityEnvironment(gl: WebGLRenderer): WebGLRenderTarget {- const scene = new Scene();- const geometry = new SphereGeometry(50, 48, 24);- const colours: number[] = [];- const pos = geometry.getAttribute("position");- // Brighter than the real night, so the chrome reads as silver at every angle: a steel-blue dome, a pale horizon.- const top = new Color("#4f5d7c"), horizon = new Color("#c3c8d6"), below = new Color("#2b2840"), glow = new Color("#ffc27a"), c = new Color();- for (let i = 0; i < pos.count; i += 1) {- const y = pos.getY(i) / 50, x = pos.getX(i) / 50, z = pos.getZ(i) / 50;- if (y > 0) c.copy(horizon).lerp(top, Math.min(1, y * 1.3)); else c.copy(horizon).lerp(below, Math.min(1, -y * 2.5));- // The singularity's glow, low in the north.- const toGlow = Math.max(0, -z * 0.95 - x * 0.3) * Math.exp(-Math.abs(y) * 4);- c.lerp(glow, Math.min(0.8, toGlow ** 3));- colours.push(c.r, c.g, c.b);- }- geometry.setAttribute("color", new Float32BufferAttribute(colours, 3));- scene.add(new Mesh(geometry, new MeshBasicMaterial({ vertexColors: true, side: BackSide })));- // A few bright panels for the city's lights to glint in the hull.- const lamp = new MeshBasicMaterial({ color: "#ffe6c4" });- for (let i = 0; i < 14; i += 1) {- const a = (i / 14) * Math.PI * 2, panel = new Mesh(new SphereGeometry(1.6, 8, 6), lamp);- panel.position.set(Math.cos(a) * 40, -6 - (i % 3) * 5, Math.sin(a) * 40);- scene.add(panel);- }- const pmrem = new PMREMGenerator(gl);- const target = pmrem.fromScene(scene, 0.02);- pmrem.dispose();- scene.traverse((o) => { if (o instanceof Mesh) { o.geometry.dispose(); (o.material as Material).dispose(); } });- return target;-}--/** Hull panels: thin seams the chrome's bump map carries, so the surface reads as built and not cast. */-function panelTexture(): Texture | null {- const tex = cachedCanvasTexture("courier:panels", 512, 512, (ctx, w, h) => {- ctx.fillStyle = "#ffffff";- ctx.fillRect(0, 0, w, h);- ctx.strokeStyle = "#9a9a9a";- ctx.lineWidth = 2;- let seed = 0x5eed;- const rand = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);- for (let y = 0; y < h; y += 64) {- ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(w, y); ctx.stroke();- for (let x = rand() * 90; x < w; x += 70 + rand() * 90) { ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x, y + 64); ctx.stroke(); }- }- // Rivet rows and a few hatches.- ctx.fillStyle = "#8a8a8a";- for (let y = 8; y < h; y += 64) for (let x = 6; x < w; x += 12) ctx.fillRect(x, y, 2, 2);- });- // The hull's UVs run across (u) and along (v) it: plates about a metre wide and a metre and a quarter long.- if (tex) { tex.wrapS = tex.wrapT = RepeatWrapping; tex.repeat.set(1.5, 3); }- return tex;-}--interface CourierMaterials {- byName: Record<string, Material>;- glow: MeshBasicMaterial;- /** The white tail and mast lights: a short flash every second and a half. */- strobe: MeshBasicMaterial;- all: Material[];-}--function courierMaterials(env: Texture): CourierMaterials {- const panels = panelTexture();- const chrome = new MeshStandardMaterial({ color: "#dfe3ea", metalness: 1, roughness: 0.16, envMap: env, envMapIntensity: 1.1, bumpMap: panels, bumpScale: 0.12 });- const gold = new MeshStandardMaterial({ color: "#d6a64e", metalness: 1, roughness: 0.24, envMap: env, envMapIntensity: 1.2 });- const graphite = new MeshStandardMaterial({ color: "#16181e", metalness: 0.6, roughness: 0.42, envMap: env });- const glass = new MeshStandardMaterial({ color: "#0b1526", metalness: 0.9, roughness: 0.04, envMap: env, envMapIntensity: 1.6 });- const glow = new MeshBasicMaterial({ color: "#6fd8ff", toneMapped: false });- const strip = new MeshBasicMaterial({ color: "#8be9ff", toneMapped: false });- const belly = new MeshStandardMaterial({ color: "#2b2e35", metalness: 0.85, roughness: 0.3, envMap: env, envMapIntensity: 0.9, bumpMap: panels, bumpScale: 0.1 });- const vent = new MeshStandardMaterial({ color: "#0b0c10", metalness: 0.5, roughness: 0.6 });- const navRed = new MeshBasicMaterial({ color: "#ff2a2a", toneMapped: false });- const navGreen = new MeshBasicMaterial({ color: "#2aff6a", toneMapped: false });- const navWhite = new MeshBasicMaterial({ color: "#ffffff", toneMapped: false });- return {- byName: {- Chrome: chrome, Gold: gold, Graphite: graphite, CanopyGlass: glass, EngineGlow: glow, LightStrip: strip,- Belly: belly, Vent: vent, NavRed: navRed, NavGreen: navGreen, NavWhite: navWhite,- },- glow,- strobe: navWhite,- all: [chrome, gold, graphite, glass, glow, strip, belly, vent, navRed, navGreen, navWhite],- };-}--const GEAR_NAME = /^Gear_(Nose|Left|Right)\.?\d*$/;--/** A level of detail, cloned, re-dressed in the shared materials; returns its gear nodes with their rest heights. */-function dress(source: Object3D, materials: CourierMaterials): { root: Object3D; gear: { node: Object3D; y: number }[] } {- const root = source.clone(true);- const gear: { node: Object3D; y: number }[] = [];- root.traverse((o) => {- if (GEAR_NAME.test(o.name)) gear.push({ node: o, y: o.position.y });- if (o instanceof Mesh) {- const name = (o.material as Material).name.replace(/\.\d+$/, "");- o.material = materials.byName[name] ?? materials.byName.Chrome;- o.castShadow = true;- o.receiveShadow = true;- }- });- return { root, gear };-}--// ----------------------------------------------------------------------------// Effects-// -----------------------------------------------------------------------------const FLAME_VERTEX = /* glsl */ `- varying vec2 vUv;- void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }-`;-const FLAME_FRAGMENT = /* glsl */ `- uniform float uTime, uPower;- varying vec2 vUv;- void main() {- // The cone's base sits at the nozzle, its point trails behind; uv.y is 0 at the base and 1 at the point.- float along = 1.0 - vUv.y;- float flicker = 0.85 + 0.15 * sin(uTime * 43.0 + vUv.x * 30.0) * sin(uTime * 17.0);- vec3 hot = vec3(0.85, 0.97, 1.0) * 3.0, cool = vec3(0.25, 0.55, 1.0) * 1.4;- vec3 col = mix(cool, hot, pow(along, 2.0)) * pow(along, 1.4) * uPower * flicker;- gl_FragColor = vec4(col, 1.0);- #include <tonemapping_fragment>- #include <colorspace_fragment>- }-`;--const SHIELD_VERTEX = /* glsl */ `- varying vec3 vNormalW; varying vec3 vWorld; varying vec3 vLocal;- void main() {- vLocal = position;- vec4 w = modelMatrix * vec4(position, 1.0); vWorld = w.xyz;- vNormalW = normalize(mat3(modelMatrix) * normal);- gl_Position = projectionMatrix * viewMatrix * w;- }-`;-const SHIELD_FRAGMENT = /* glsl */ `- uniform float uTime, uStrength;- varying vec3 vNormalW; varying vec3 vWorld; varying vec3 vLocal;- void main() {- vec3 V = normalize(cameraPosition - vWorld);- float fres = pow(1.0 - abs(dot(normalize(vNormalW), V)), 2.6);- float bands = 0.6 + 0.4 * sin(vLocal.z * 2.4 - uTime * 6.0);- vec3 col = vec3(0.35, 0.85, 1.0) * fres * bands * uStrength * 2.2;- gl_FragColor = vec4(col, 1.0);- #include <tonemapping_fragment>- #include <colorspace_fragment>- }-`;--const TRAIL_POINTS = 26;--/** A contrail behind one pod tail: a camera-facing ribbon through the tail's recent positions. */-class Trail {- readonly geometry = new BufferGeometry();- /** A ring of pooled points, newest at `head`; `count` of them are in use. */- private readonly points = Array.from({ length: TRAIL_POINTS }, () => new Vector3());- private readonly ages = new Float32Array(TRAIL_POINTS);- private head = 0;- private count = 0;- private readonly pos = new Float32Array(TRAIL_POINTS * 2 * 3);- private readonly fade = new Float32Array(TRAIL_POINTS * 2);- constructor() {- this.geometry.setAttribute("position", new BufferAttribute(this.pos, 3));- this.geometry.setAttribute("aFade", new BufferAttribute(this.fade, 1));- const index: number[] = [];- for (let i = 0; i < TRAIL_POINTS - 1; i += 1) { const a = i * 2; index.push(a, a + 1, a + 2, a + 1, a + 3, a + 2); }- this.geometry.setIndex(index);- }- private at(i: number): Vector3 { return this.points[(this.head - i + TRAIL_POINTS) % TRAIL_POINTS]; }- update(tip: Vector3, strength: number, dt: number, camera: Vector3, v: { side: Vector3; dir: Vector3; cam: Vector3 }) {- for (let i = 0; i < TRAIL_POINTS; i += 1) this.ages[i] += dt;- if (this.count === 0 || this.at(0).distanceTo(tip) > 1.4) {- this.head = (this.head + 1) % TRAIL_POINTS;- this.points[this.head].copy(tip);- this.ages[this.head] = 0;- this.count = Math.min(TRAIL_POINTS, this.count + 1);- } else {- this.at(0).copy(tip);- }- for (let i = 0; i < TRAIL_POINTS; i += 1) {- const used = i < this.count;- const p = used ? this.at(i) : this.at(0);- const q = i + 1 < this.count ? this.at(i + 1) : p;- v.dir.subVectors(p, q);- if (v.dir.lengthSq() < 1e-6) v.dir.set(0, 0, 1);- v.cam.subVectors(camera, p).normalize();- v.side.crossVectors(v.dir.normalize(), v.cam).normalize().multiplyScalar(0.12 + i * 0.006);- const o = i * 6;- this.pos[o] = p.x + v.side.x; this.pos[o + 1] = p.y + v.side.y; this.pos[o + 2] = p.z + v.side.z;- this.pos[o + 3] = p.x - v.side.x; this.pos[o + 4] = p.y - v.side.y; this.pos[o + 5] = p.z - v.side.z;- // Fading with age and along the trail, and gone where it would pass right by the camera.- const near = Math.min(1, Math.max(0, (camera.distanceTo(p) - 8) / 20));- const age = this.ages[(this.head - i + TRAIL_POINTS) % TRAIL_POINTS];- const alpha = used ? strength * Math.max(0, 1 - age / 1.2) * (1 - i / TRAIL_POINTS) * near : 0;- this.fade[i * 2] = alpha; this.fade[i * 2 + 1] = alpha;- }- (this.geometry.getAttribute("position") as BufferAttribute).needsUpdate = true;- (this.geometry.getAttribute("aFade") as BufferAttribute).needsUpdate = true;- }- clear() { this.count = 0; this.fade.fill(0); (this.geometry.getAttribute("aFade") as BufferAttribute).needsUpdate = true; }-}--const TRAIL_MATERIAL_SOURCE = {- vertexShader: /* glsl */ `attribute float aFade; varying float vFade; void main() { vFade = aFade; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`,- fragmentShader: /* glsl */ `varying float vFade; void main() { gl_FragColor = vec4(vec3(0.75, 0.85, 1.0) * vFade * 0.4, 1.0); }`,-};--const DUST_COUNT = 220;--// ----------------------------------------------------------------------------// The component-// -----------------------------------------------------------------------------export function SkyCourier({ layout, reduced, awake }: { layout: OfficeLayout; reduced: boolean; awake: boolean }) {- // A model that fails to load leaves the pad empty instead of taking the floor down with it.- return (- <CourierBoundary>- <Suspense fallback={null}>- {layout.skyPad && <Courier layout={layout} pad={layout.skyPad} reduced={reduced} awake={awake} />}- </Suspense>- </CourierBoundary>- );-}--class CourierBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {- state = { failed: false };- static getDerivedStateFromError() { return { failed: true }; }- componentDidCatch(error: unknown) { console.warn("the courier could not be shown", error); }- render() { return this.state.failed ? null : this.props.children; }-}--function Courier({ layout, pad, reduced, awake }: { layout: OfficeLayout; pad: SkyPad; reduced: boolean; awake: boolean }) {- const gl = useThree((s) => s.gl);- const camera = useThree((s) => s.camera) as PerspectiveCamera;- const gltfs = useGLTF([courierNear, courierMid, courierFar]);- // The environment is a render target of its own: built in an effect, so its disposal pairs with its creation.- const [env, setEnv] = useState<WebGLRenderTarget | null>(null);- useEffect(() => {- const target = cityEnvironment(gl);- setEnv(target);- return () => target.dispose();- }, [gl]);- const materials = useMemo(() => (env ? courierMaterials(env.texture) : null), [env]);- useEffect(() => () => { for (const m of materials?.all ?? []) m.dispose(); }, [materials]);- const levels = useMemo(() => {- if (!materials) return null;- const dressed = gltfs.map((g) => dress(g.scene, materials));- const l = new LOD();- l.addLevel(dressed[0].root, 0);- l.addLevel(dressed[1].root, 70);- l.addLevel(dressed[2].root, 170);- return { lod: l, gear: dressed.flatMap((lvl) => lvl.gear) };- }, [gltfs, materials]);-- // Keyed on the pad's numbers, not its object: every rebuilt floor plan (a new agent, a team change) passes a new- // one, and that must neither rebuild the city's colliders nor end a flight.- const padRef = useRef(pad);- padRef.current = pad;- const { minX, maxX, minZ, maxZ } = layout.bounds;- const hx = pad.ship.x, hz = pad.ship.z, hh = pad.ship.heading, padR = pad.pad.r;- const home = useMemo(() => ({ x: hx, z: hz, heading: hh }), [hx, hz, hh]);- const world = useMemo(() => {- const bounds = { minX, maxX, minZ, maxZ };- return buildCourierWorld(planCity(bounds), bounds, padRef.current);- }, [minX, maxX, minZ, maxZ, hx, hz, padR]);- const state = useRef<FlightState>(parkedState(home));- const ship = useRef<Group>(null);-- // Effects.- const flameGeometry = useMemo(() => new ConeGeometry(0.75, 1, 18, 1, true).rotateX(Math.PI / 2).translate(0, 0, 0.5), []);- const flameMaterial = useMemo(() => new ShaderMaterial({- uniforms: { uTime: { value: 0 }, uPower: { value: 0 } }, vertexShader: FLAME_VERTEX, fragmentShader: FLAME_FRAGMENT,- transparent: true, depthWrite: false, blending: AdditiveBlending, side: DoubleSide,- }), []);- const shieldGeometry = useMemo(() => new SphereGeometry(1, 40, 20), []);- const shieldMaterial = useMemo(() => new ShaderMaterial({- uniforms: { uTime: { value: 0 }, uStrength: { value: 0 } }, vertexShader: SHIELD_VERTEX, fragmentShader: SHIELD_FRAGMENT,- transparent: true, depthWrite: false, blending: AdditiveBlending,- }), []);- const trails = useMemo(() => [new Trail(), new Trail()], []);- const trailMaterial = useMemo(() => new ShaderMaterial({ ...TRAIL_MATERIAL_SOURCE, transparent: true, depthWrite: false, blending: AdditiveBlending, side: DoubleSide }), []);- const dust = useMemo(() => {- const geometry = new BufferGeometry();- geometry.setAttribute("position", new BufferAttribute(new Float32Array(DUST_COUNT * 3), 3));- const material = new ShaderMaterial({- uniforms: { uSize: { value: 220 } },- vertexShader: /* glsl */ `attribute float aLife; uniform float uSize; varying float vLife; void main() { vLife = aLife; vec4 mv = modelViewMatrix * vec4(position, 1.0); gl_PointSize = uSize * (0.4 + aLife) / -mv.z; gl_Position = projectionMatrix * mv; }`,- fragmentShader: /* glsl */ `varying float vLife; void main() { vec2 q = gl_PointCoord * 2.0 - 1.0; float a = exp(-dot(q, q) * 3.0) * vLife * 0.35; gl_FragColor = vec4(vec3(0.62, 0.6, 0.66) * a, 1.0); }`,- transparent: true, depthWrite: false, blending: AdditiveBlending,- });- geometry.setAttribute("aLife", new BufferAttribute(new Float32Array(DUST_COUNT), 1));- return { geometry, material, velocity: new Float32Array(DUST_COUNT * 3), life: new Float32Array(DUST_COUNT), next: 0, alive: 0 };- }, []);- useEffect(() => () => {- flameGeometry.dispose(); flameMaterial.dispose(); shieldGeometry.dispose(); shieldMaterial.dispose(); trailMaterial.dispose();- for (const t of trails) t.geometry.dispose();- dust.geometry.dispose(); dust.material.dispose();- }, [flameGeometry, flameMaterial, shieldGeometry, shieldMaterial, trails, trailMaterial, dust]);- const flames = useRef<(Mesh | null)[]>([]);- const shield = useRef<Mesh>(null);- const light = useRef<PointLight>(null);-- // Flight session: held keys, gamepad presses, the sound, the camera's own smoothing.- const flying = useCourier((s) => s.flying);- // The keys and the sound belong to a flight on screen: another section or a hidden window gets its keys back.- const live = flying && awake;- const held = useRef(new Set<string>());- /** Where the pilot aims while the mouse is captured; the ship turns towards it by itself. */- const aim = useRef<MouseAim>({ yaw: 0, pitch: 0 });- const aimDir = useMemo(() => new Vector3(), []);- /** The cursor's place in the view (-1..1, +y up) while cursor steering is on and it is over the view. */- const cursor = useRef<{ x: number; y: number } | null>(null);- const padPressed = useRef(new Set<number>());- const sound = useRef<CourierEngineSound | null>(null);- const camPos = useRef(new Vector3());- const camVel = useRef(new Vector3());- const camPrev = useRef(new Vector3());- const telemetryClock = useRef(0);- const lastImpact = useRef(0);- const landRequest = useCourier((s) => s.landRequest);- const exitRequest = useCourier((s) => s.exitRequest);-- // The model is on the pad: from now on the person can board.- useEffect(() => {- if (!levels) return;- useCourier.getState().setReady(true);- return () => useCourier.getState().setReady(false);- }, [levels]);-- /** The office camera's lens again, after the flight's wider one. */- const restoreCamera = () => {- camera.fov = CAMERA_FOV; camera.near = 0.2; camera.updateProjectionMatrix();- for (const t of trails) t.clear();- };- const leaveShip = () => {- // Step out beside the hatch, facing the ship; the office camera takes over again.- const { board } = padRef.current;- playerBody.x = board.x; playerBody.z = board.z; playerBody.heading = board.facing;- playerBody.path = []; playerBody.moving = false;- restoreCamera();- useCourier.getState().disembark();- useOfficeStore.getState().setFollow(true);- };- const leaveRef = useRef(leaveShip);- leaveRef.current = leaveShip;-- useEffect(() => {- if (landRequest > 0) engageAutopilot(state.current);- }, [landRequest]);- useEffect(() => {- if (exitRequest > 0 && state.current.landed && courierSession.flying) leaveRef.current();- }, [exitRequest]);-- useEffect(() => {- if (!live) return;- camPos.current.copy(camera.position);- camPrev.current.copy(camera.position);- let engine: CourierEngineSound | null = null;- try {- engine = new CourierEngineSound();- engine.resume();- } catch (error) {- // No Web Audio (an old engine, a locked-down WebView): the flight goes on in silence.- console.warn("courier sound unavailable", error);- }- sound.current = engine;- const press = (action: FlightAction) => {- const store = useCourier.getState();- const s = state.current;- if (action === "assist") store.setPrefs({ assist: store.assist === "arcade" ? "simulation" : "arcade" });- else if (action === "camera") store.setPrefs({ view: store.view === "chase" ? "cockpit" : "chase" });- else if (action === "land") engageAutopilot(s);- else if (action === "help") store.set({ helpOpen: !store.helpOpen });- else if (action === "exit" && s.landed) leaveRef.current();- };- const down = (event: KeyboardEvent) => {- const store = useCourier.getState();- // Escape opens and closes the flight settings, wherever focus sits in them.- if (event.key === "Escape") {- store.set({ settingsOpen: !store.settingsOpen });- event.preventDefault();- event.stopPropagation();- return;- }- if (ownsKeyboard(event.target) || store.settingsOpen) return;- // A modifier is a binding of its own (Ctrl sinks by default); held with another key it is a shortcut.- const isModifier = /^(Control|Alt|Meta|OS)/.test(event.code);- if (!isModifier && (event.ctrlKey || event.metaKey || event.altKey)) return;- const action = FLIGHT_ACTIONS.find((a) => store.bindings[a].includes(event.code));- // E is "use" everywhere in the office: standing on the pad, it also steps out.- if (event.code === "KeyE" && state.current.landed && !event.repeat) { leaveRef.current(); event.preventDefault(); event.stopPropagation(); return; }- if (!action) return;- event.preventDefault();- event.stopPropagation();- if (PRESS_ACTIONS.has(action)) { if (!event.repeat) press(action); return; }- held.current.add(event.code);- };- const up = (event: KeyboardEvent) => { held.current.delete(event.code); };- const blur = () => held.current.clear();- // A click into the view captures the mouse for steering; Escape (the browser's own) lets it go again.- const canvas = gl.domElement;- // Some hosts refuse to capture the mouse (an unfocused window, an embedded view): then the cursor steers.- const refused = (error: unknown) => {- console.warn("mouse capture refused, steering with the cursor", error);- if (!useCourier.getState().cursorAim) Object.assign(aim.current, aimFromForward(forwardOf(state.current.q)));- useCourier.getState().set({ cursorAim: true });- };- const capture = () => {- if (document.pointerLockElement === canvas || useCourier.getState().settingsOpen) return;- if (!canvas.requestPointerLock) { refused(new Error("pointer lock unsupported")); return; }- try {- const pending = canvas.requestPointerLock() as unknown as Promise<void> | undefined;- pending?.catch?.(refused);- } catch (error) {- refused(error);- }- };- const point = (event: PointerEvent) => {- const r = canvas.getBoundingClientRect();- if (r.width <= 0 || r.height <= 0) return;- cursor.current = { x: ((event.clientX - r.left) / r.width) * 2 - 1, y: 1 - ((event.clientY - r.top) / r.height) * 2 };- };- const leave = () => { cursor.current = null; };- const move = (event: MouseEvent) => {- if (document.pointerLockElement !== canvas) return;- const s = state.current;- // Moving the mouse during the landing assist takes the ship back, aiming from where it points now.- if (s.autopilot) { s.autopilot = null; Object.assign(aim.current, aimFromForward(forwardOf(s.q))); }- moveAim(aim.current, event.movementX, event.movementY, useCourier.getState().invertPitch);- };- const lockChange = () => {- const locked = document.pointerLockElement === canvas;- // The aim starts where the nose points.- if (locked) Object.assign(aim.current, aimFromForward(forwardOf(state.current.q)));- useCourier.getState().set(locked ? { mouseLocked: true, cursorAim: false } : { mouseLocked: false });- };- canvas.addEventListener("click", capture);- canvas.addEventListener("pointermove", point);- canvas.addEventListener("pointerleave", leave);- window.addEventListener("mousemove", move);- document.addEventListener("pointerlockchange", lockChange);- window.addEventListener("keydown", down, true);- window.addEventListener("keyup", up, true);- window.addEventListener("blur", blur);- pressHandler.current = press;- return () => {- canvas.removeEventListener("click", capture);- canvas.removeEventListener("pointermove", point);- canvas.removeEventListener("pointerleave", leave);- window.removeEventListener("mousemove", move);- document.removeEventListener("pointerlockchange", lockChange);- if (document.pointerLockElement === canvas) document.exitPointerLock();- cursor.current = null;- useCourier.getState().set({ mouseLocked: false, cursorAim: false });- window.removeEventListener("keydown", down, true);- window.removeEventListener("keyup", up, true);- window.removeEventListener("blur", blur);- held.current.clear();- engine?.close();- sound.current = null;- pressHandler.current = null;- };- }, [live, camera, gl]);- const pressHandler = useRef<((action: FlightAction) => void) | null>(null);-- // Leaving the floor or the map mid-flight: the ship is parked again, the person stands beside it, the lens is- // the office's again.- useEffect(() => () => {- if (courierSession.flying) leaveRef.current();- }, []);-- useEffect(() => {- if (!import.meta.env.DEV || typeof window === "undefined") return;- // Dev-only: the live flight state, for runtime checks of the effects and the camera.- Object.assign(window, { __courier: { state: () => state.current, store: useCourier } });- }, []);-- const _v = useMemo(() => ({ a: new Vector3(), b: new Vector3(), c: new Vector3(), f: new Vector3(), u: new Vector3(), side: new Vector3(), dir: new Vector3(), cam: new Vector3() }), []);-- useFrame(({ clock }, rawDt) => {- const g = ship.current;- if (!g || !awake) return;- const dt = Math.min(rawDt, 0.1);- const s = state.current;- const store = useCourier.getState();- if (flying) {- // Gamepad: the first connected pad, its press buttons on their rising edge.- let gamepad: PadState | null = null;- try {- const pads = typeof navigator !== "undefined" && navigator.getGamepads ? navigator.getGamepads() : [];- for (const p of pads) if (p && p.connected) { gamepad = p; break; }- } catch (error) {- // A permissions policy may forbid gamepads; the keyboard still flies. Said once, not every frame.- if (!gamepadWarned.current) { console.warn("gamepads unavailable", error); gamepadWarned.current = true; }- }- if (gamepad) {- for (const [button, action] of PAD_PRESSES) {- const isDown = gamepad.buttons[button]?.pressed ?? false;- if (isDown && !padPressed.current.has(button)) pressHandler.current?.(action);- if (isDown) padPressed.current.add(button); else padPressed.current.delete(button);- }- }- const input = store.settingsOpen ? { ...NO_INPUT } : flightInput(held.current, store.bindings, gamepad, store.invertPitch);- if (store.mouseLocked || store.cursorAim) {- // Mouse aim: the turn and pitch keys move the aim too, and the ship flies to wherever it points.- const a = aim.current;- if (s.landed || s.autopilot) Object.assign(a, aimFromForward(forwardOf(s.q)));- else {- if (!store.mouseLocked && cursor.current && !store.settingsOpen) cursorTurn(a, cursor.current.x, cursor.current.y, dt);- moveAim(a, input.yaw * 600 * dt, -input.pitch * 450 * dt, false);- input.yaw = 0; input.pitch = 0;- steerTowards(input, s.q, aimDirection(a, aimDir));- }- }- stepFlight(s, input, dt, store.assist, world, home);- if (s.impact > lastImpact.current + 6 && sound.current) sound.current.impact(s.impact);- lastImpact.current = s.impact;- flyCamera(dt, input.boost && s.charge > 0.02);- sound.current?.update({- throttle: s.throttle, boost: input.boost && s.charge > 0.02,- ship: s.p, shipVelocity: s.v, listener: camera.position, listenerVelocity: camVel.current,- forward: _v.f.set(0, 0, -1).applyQuaternion(camera.quaternion), up: _v.u.set(0, 1, 0).applyQuaternion(camera.quaternion),- inside: store.view === "cockpit", volume: store.volume,- });- telemetryClock.current += dt;- if (telemetryClock.current > 0.12) {- telemetryClock.current = 0;- const overDeck = heightOverDeck(s, home);- store.set({- telemetry: {- speed: s.v.length(), throttle: s.throttle, charge: s.charge,- altitude: Number.isFinite(overDeck) ? Math.max(0, overDeck) : s.p.y - world.ground,- overPad: Number.isFinite(overDeck), landed: s.landed, autopilot: s.autopilot,- canLand: !s.landed && !s.autopilot,- },- });- }- } else if (!s.landed || s.p.distanceToSquared(_v.a.set(home.x, COURIER.standHeight, home.z)) > 1e-4) {- // Not flown (stepped out, or left mid-air by a floor change): back on the pad.- state.current = parkedState(home);- }-- // Place the ship and dress it for its state.- const st = state.current;- g.position.copy(st.p);- g.quaternion.copy(st.q);- if (levels) for (const { node, y } of levels.gear) node.position.y = y + (1 - st.gear) * MODEL.gearTravel;- const power = st.landed ? 0.12 : 0.25 + st.throttle * 0.75;- materials?.glow.color.setRGB(0.25 + power * 0.6, 0.55 + power * 0.45, 1).multiplyScalar(0.6 + power * 1.8);- materials?.strobe.color.setScalar(reduced || (clock.elapsedTime % 1.5) < 0.09 ? 1.6 : 0.12);- flameMaterial.uniforms.uTime.value = reduced ? 0 : clock.elapsedTime;- flameMaterial.uniforms.uPower.value = st.landed ? 0 : 0.35 + st.throttle * 0.9;- for (const f of flames.current) if (f) f.scale.set(1, 1, st.landed ? 0.01 : 2 + st.throttle * 7);- if (light.current) light.current.intensity = st.landed ? 0 : 10 + st.throttle * 50;- shieldMaterial.uniforms.uTime.value = clock.elapsedTime;- shieldMaterial.uniforms.uStrength.value = st.shield;- if (shield.current) shield.current.visible = st.shield > 0.01;- if (flying) updateTrails(dt);- if (flying || dust.alive > 0) updateDust(dt);- });- const gamepadWarned = useRef(false);-- function flyCamera(dt: number, boosting: boolean) {- const s = state.current, store = useCourier.getState();- const f = forwardOf(s.q, _v.f), u = _v.u.set(0, 1, 0).applyQuaternion(s.q);- if (store.view === "cockpit") {- camera.position.copy(s.p).addScaledVector(u, COCKPIT.up).addScaledVector(f, -COCKPIT.forward);- camera.quaternion.copy(s.q);- // The chase camera starts from here when the pilot switches back.- camPos.current.copy(camera.position);- } else {- // Behind the tail and above it, looking past the nose; with mouse aim, looking where the pilot aims.- const look = (store.mouseLocked || store.cursorAim) && !s.landed && !s.autopilot ? aimDirection(aim.current, aimDir) : f;- const want = _v.a.copy(s.p).addScaledVector(look, -CHASE.back).add(_v.b.set(0, CHASE.up, 0));- // Never through a tower: pull in to just short of whatever stands between the ship and the camera.- const from = _v.b.copy(s.p).add(_v.c.set(0, 2, 0));- const dir = _v.c.copy(want).sub(from);- const reach = dir.length();- dir.normalize();- const free = rayDistance(world, from, dir, reach);- if (free < reach) want.copy(from).addScaledVector(dir, Math.max(2, free - 1.5));- camPos.current.lerp(want, 1 - Math.exp(-CHASE.stiffness * dt));- camera.position.copy(camPos.current);- camera.up.set(0, 1, 0);- camera.lookAt(_v.b.copy(s.p).addScaledVector(look, CHASE.lookAhead).addScaledVector(u, 1.5));- }- placeMarkers();- // The listener's own speed, for the Doppler shift: measured before any shake.- camVel.current.copy(camera.position).sub(camPrev.current).divideScalar(Math.max(dt, 1e-3));- camPrev.current.copy(camera.position);- if (store.view === "chase" && !reduced && s.impact > 4) {- camera.position.add(_v.b.set(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5).multiplyScalar(s.impact * 0.02));- }- const fov = boosting ? FLIGHT_FOV.boost : FLIGHT_FOV.cruise;- camera.fov += (fov - camera.fov) * Math.min(1, dt * 3);- camera.near = 0.3;- camera.far = 1400;- camera.updateProjectionMatrix();- }-- /** The aim reticle and the nose marker on the HUD: where the pilot aims, and where the nose points now. */- function placeMarkers() {- const s = state.current, store = useCourier.getState();- const show = (store.mouseLocked || store.cursorAim) && !s.landed && !s.autopilot;- camera.updateMatrixWorld();- for (const [id, dir] of [["courier-aim", show ? aimDirection(aim.current, aimDir) : null], ["courier-nose", show ? forwardOf(s.q, _v.c) : null]] as const) {- const el = document.getElementById(id);- if (!el) continue;- if (!dir) { el.style.opacity = "0"; continue; }- const ndc = _v.a.copy(s.p).addScaledVector(dir, 220).project(camera);- el.style.opacity = ndc.z < 1 ? "1" : "0";- el.style.left = `${((ndc.x + 1) / 2) * 100}%`;- el.style.top = `${((1 - ndc.y) / 2) * 100}%`;- }- }-- function updateTrails(dt: number) {- const s = state.current;- const strength = Math.max(0, Math.min(1, (s.v.length() - FLIGHT.cruise * 0.6) / (FLIGHT.cruise * 0.6)));- for (let i = 0; i < MODEL.tails.length; i += 1) {- const tail = MODEL.tails[i];- const tip = _v.a.set(tail[0], tail[1], tail[2]).multiplyScalar(COURIER.scale).applyQuaternion(s.q).add(s.p);- trails[i].update(tip, strength, dt, camera.position, _v);- }- }-- function updateDust(dt: number) {- const s = state.current;- const pos = dust.geometry.getAttribute("position") as BufferAttribute;- const life = dust.geometry.getAttribute("aLife") as BufferAttribute;- const above = heightOverDeck(s, home);- // Thrust washing over the deck while the ship is low and not standing still on it.- const wash = flying && !s.landed && above < 16 ? (1 - above / 16) : 0;- const spawn = reduced ? 0 : Math.floor(wash * 90 * dt * 10);- for (let k = 0; k < spawn; k += 1) {- const i = dust.next; dust.next = (dust.next + 1) % DUST_COUNT;- const a = Math.random() * Math.PI * 2, r = 2 + Math.random() * 3;- pos.setXYZ(i, s.p.x + Math.cos(a) * r, 0.2, s.p.z + Math.sin(a) * r);- const speed = 6 + Math.random() * 8;- dust.velocity[i * 3] = Math.cos(a) * speed; dust.velocity[i * 3 + 1] = 0.6 + Math.random() * 1.4; dust.velocity[i * 3 + 2] = Math.sin(a) * speed;- dust.life[i] = 1;- }- let alive = 0;- for (let i = 0; i < DUST_COUNT; i += 1) {- if (dust.life[i] <= 0) { life.setX(i, 0); continue; }- alive += 1;- dust.life[i] = Math.max(0, dust.life[i] - dt * 0.8);- pos.setXYZ(i, pos.getX(i) + dust.velocity[i * 3] * dt, pos.getY(i) + dust.velocity[i * 3 + 1] * dt, pos.getZ(i) + dust.velocity[i * 3 + 2] * dt);- dust.velocity[i * 3] *= 1 - dt * 0.9; dust.velocity[i * 3 + 2] *= 1 - dt * 0.9;- life.setX(i, dust.life[i]);- }- dust.alive = alive;- pos.needsUpdate = true;- life.needsUpdate = true;- }-- if (!levels) return null;- return (- <>- <group ref={ship} name={COURIER_GROUP} visible>- <group scale={COURIER.scale}>- <primitive object={levels.lod} />- {MODEL.exhausts.map((p, i) => (- <mesh key={i} ref={(m) => { flames.current[i] = m; }} geometry={flameGeometry} material={flameMaterial} position={p} renderOrder={6} frustumCulled={false} />- ))}- <pointLight ref={light} position={[0, 0, 14]} color="#7fd8ff" distance={40} decay={2} intensity={0} />- <mesh ref={shield} geometry={shieldGeometry} material={shieldMaterial} scale={MODEL.shield as unknown as [number, number, number]} visible={false} renderOrder={7} />- </group>- </group>- {trails.map((t, i) => <mesh key={i} geometry={t.geometry} material={trailMaterial} frustumCulled={false} renderOrder={5} />)}- <points geometry={dust.geometry} material={dust.material} frustumCulled={false} renderOrder={5} />- </>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/SkyPadStructure.tsx b/dodaios/ui/web/frontend/src/components/society/office/SkyPadStructure.tsxdeleted file mode 100644index f893ac1c5d..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/SkyPadStructure.tsx+++ /dev/null@@ -1,156 +0,0 @@-/**- * The sky pad's structure (skyPad.ts has its plan): the bridge that carries- * the boulevard out through the east windows, the round landing deck with its- * markings, a ring of light round its rim, four light masts, glass rails, and- * the steel that holds it all out from the tower. The deck and the bridge take- * clicks like the floor, so the person can walk out by pointing.- */-import { useEffect, useMemo, useRef } from "react";-import { useFrame, type ThreeEvent } from "@react-three/fiber";-import { CylinderGeometry, MeshBasicMaterial, MeshStandardMaterial, RingGeometry, type Mesh } from "three";-import { cachedCanvasTexture } from "./canvasMaterials";-import { Box, GEO, matte, Railing } from "./OfficeFurniture";-import type { Rect } from "./officeLayout";-import { SKY_PAD, type SkyPad } from "./skyPad";--const PAD_PAINT = {- deck: "#1d2129",- seam: "#2b313b",- ring: "#d4a94e",- mark: "#e8ecf2",- glow: "#5fe3ff",-} as const;--let deckTop: MeshStandardMaterial | null = null;-/** The deck's face: graphite plates, the gold landing circle, the chevrons that lead in and the touchdown cross. */-function deckMaterial(): MeshStandardMaterial {- if (deckTop) return deckTop;- const map = cachedCanvasTexture("skypad:deck", 1024, 1024, (ctx, w, h) => {- const c = w / 2;- ctx.fillStyle = PAD_PAINT.deck;- ctx.fillRect(0, 0, w, h);- // Plates: a radial and ring pattern of thin seams.- ctx.strokeStyle = PAD_PAINT.seam;- ctx.lineWidth = 3;- for (let r = 90; r < c; r += 90) { ctx.beginPath(); ctx.arc(c, c, r, 0, Math.PI * 2); ctx.stroke(); }- for (let i = 0; i < 24; i += 1) {- const a = (i / 24) * Math.PI * 2;- ctx.beginPath(); ctx.moveTo(c + Math.cos(a) * 90, c + Math.sin(a) * 90); ctx.lineTo(c + Math.cos(a) * c, c + Math.sin(a) * c); ctx.stroke();- }- // The landing circle and an inner ring, in gold.- ctx.strokeStyle = PAD_PAINT.ring;- ctx.lineWidth = 16;- ctx.beginPath(); ctx.arc(c, c, c * 0.78, 0, Math.PI * 2); ctx.stroke();- ctx.lineWidth = 6;- ctx.beginPath(); ctx.arc(c, c, c * 0.7, 0, Math.PI * 2); ctx.stroke();- // Chevrons on four sides, pointing in.- ctx.fillStyle = PAD_PAINT.mark;- for (let i = 0; i < 4; i += 1) {- ctx.save();- ctx.translate(c, c);- ctx.rotate((i * Math.PI) / 2);- for (let k = 0; k < 3; k += 1) {- const y = c * 0.86 + k * 26;- ctx.beginPath(); ctx.moveTo(-34, y + 14); ctx.lineTo(0, y - 6); ctx.lineTo(34, y + 14); ctx.lineTo(34, y + 24); ctx.lineTo(0, y + 4); ctx.lineTo(-34, y + 24); ctx.closePath(); ctx.fill();- }- ctx.restore();- }- // The touchdown mark: a thin cross with a ring.- ctx.strokeStyle = PAD_PAINT.mark;- ctx.lineWidth = 8;- ctx.beginPath(); ctx.moveTo(c - 70, c); ctx.lineTo(c + 70, c); ctx.moveTo(c, c - 70); ctx.lineTo(c, c + 70); ctx.stroke();- ctx.lineWidth = 5;- ctx.beginPath(); ctx.arc(c, c, 46, 0, Math.PI * 2); ctx.stroke();- });- deckTop = new MeshStandardMaterial({ color: map ? "#ffffff" : PAD_PAINT.deck, map, roughness: 0.55, metalness: 0.35 });- return deckTop;-}--const STEEL = matte("#2a2e35", { roughness: 0.4, metalness: 0.6 });-const GOLD = matte("#c39a4a", { roughness: 0.3, metalness: 0.85 });-const BRIDGE_DECK = matte("#262b33", { roughness: 0.6, metalness: 0.3 });-const GLOW = new MeshBasicMaterial({ color: PAD_PAINT.glow, toneMapped: false });-const LAMP = new MeshBasicMaterial({ color: "#fff3d6", toneMapped: false });--const SEGMENTS = 64;--/** The rim's glass rail as straight runs round the disc, open where the bridge arrives. */-function rimRuns(pad: SkyPad): [[number, number], [number, number]][] {- const { x, z, r } = pad.pad;- const rr = r - 0.25, half = SKY_PAD.bridgeWidth / 2 + 0.3;- const runs: [[number, number], [number, number]][] = [];- const count = 28;- for (let i = 0; i < count; i += 1) {- const a0 = (i / count) * Math.PI * 2, a1 = ((i + 1) / count) * Math.PI * 2;- const p0: [number, number] = [x + Math.cos(a0) * rr, z + Math.sin(a0) * rr], p1: [number, number] = [x + Math.cos(a1) * rr, z + Math.sin(a1) * rr];- // The bridge comes in from the west (the building's side).- const westOfRim = (p: [number, number]) => p[0] < x && Math.abs(p[1] - z) < half + 0.6;- if (westOfRim(p0) || westOfRim(p1)) continue;- runs.push([p0, p1]);- }- return runs;-}--export function SkyPadStructure({ pad, bounds, reduced, onFloorClick }: {- pad: SkyPad; bounds: Rect; reduced: boolean; onFloorClick: (event: ThreeEvent<MouseEvent>) => void;-}) {- const { x, z, r } = pad.pad;- const deckGeometry = useMemo(() => new CylinderGeometry(r, r * 0.94, SKY_PAD.thickness, SEGMENTS), [r]);- const glowGeometry = useMemo(() => new RingGeometry(r - 0.12, r + 0.05, SEGMENTS * 2).rotateX(-Math.PI / 2), [r]);- const runs = useMemo(() => rimRuns(pad), [pad]);- const glow = useRef<Mesh>(null);- useFrame(({ clock }) => {- // The rim's light breathes slowly; with reduced motion it simply stays on.- if (glow.current && !reduced) (glow.current.material as MeshBasicMaterial).opacity = 0.75 + 0.25 * Math.sin(clock.elapsedTime * 1.4);- });- const glowMaterial = useMemo(() => {- const m = GLOW.clone();- m.transparent = true;- return m;- }, []);- useEffect(() => () => { deckGeometry.dispose(); glowGeometry.dispose(); glowMaterial.dispose(); }, [deckGeometry, glowGeometry, glowMaterial]);- const bridgeX0 = bounds.maxX, bridgeX1 = x - r + 0.6;- const bridgeLength = bridgeX1 - bridgeX0, bridgeMid = (bridgeX0 + bridgeX1) / 2;- const masts = [Math.PI / 4, (3 * Math.PI) / 4, (5 * Math.PI) / 4, (7 * Math.PI) / 4].map((a) => [x + Math.cos(a) * (r - 0.9), z + Math.sin(a) * (r - 0.9)] as const);- return (- <group>- {/* The bridge: deck, gold kerbs, glass rails and the girder under it. */}- <mesh geometry={GEO.box} material={BRIDGE_DECK} position={[bridgeMid, -0.25, z]} scale={[bridgeLength, 0.5, SKY_PAD.bridgeWidth]} receiveShadow onClick={onFloorClick} />- {[-1, 1].map((side) => (- <group key={side}>- <Box size={[bridgeLength, 0.08, 0.16]} position={[bridgeMid, 0.04, z + side * (SKY_PAD.bridgeWidth / 2 - 0.08)]} material={GOLD} cast={false} />- <Railing from={[bridgeX0 + 0.1, z + side * (SKY_PAD.bridgeWidth / 2 - 0.2)]} to={[bridgeX1, z + side * (SKY_PAD.bridgeWidth / 2 - 0.2)]} />- </group>- ))}- <Box size={[bridgeLength, 1.4, 1.2]} position={[bridgeMid, -1.2, z]} material={STEEL} cast={false} />-- {/* The deck: its painted face on top, steel round its edge, a gold band at its lip. */}- <mesh geometry={deckGeometry} material={STEEL} position={[x, -SKY_PAD.thickness / 2, z]} receiveShadow />- <mesh position={[x, 0.004, z]} rotation={[-Math.PI / 2, 0, 0]} receiveShadow onClick={onFloorClick} material={deckMaterial()}>- <circleGeometry args={[r - 0.05, SEGMENTS]} />- </mesh>- <mesh ref={glow} geometry={glowGeometry} material={glowMaterial} position={[x, 0.012, z]} />- {runs.map(([from, to], i) => <Railing key={i} from={from} to={to} height={0.9} />)}-- {/* Four light masts round the rim: glowing lamps, no light sources (a light per mast would cost every lit- material of the floor a recompile on arrival and a share of every pixel). */}- {masts.map(([mx, mz], i) => (- <group key={i} position={[mx, 0, mz]}>- <mesh geometry={GEO.cyl} material={STEEL} position={[0, 1.6, 0]} scale={[0.09, 3.2, 0.09]} />- <mesh geometry={GEO.box} material={LAMP} position={[0, 3.25, 0]} scale={[0.36, 0.14, 0.36]} />- </group>- ))}-- {/* The cantilever: two raking struts from under the deck back into the tower, and a ring beam under the rim. */}- {[-1, 1].map((side) => {- const fromX = x - r * 0.3, fromZ = z + side * r * 0.45, toX = bounds.maxX - 0.15, toZ = z + side * 5, drop = 22;- const dx = toX - fromX, dz = toZ - fromZ, length = Math.hypot(dx, drop, dz);- return (- <mesh key={side} geometry={GEO.box} material={STEEL} position={[(fromX + toX) / 2, -SKY_PAD.thickness - drop / 2, (fromZ + toZ) / 2]}- rotation={[0, -Math.atan2(dz, dx), Math.atan2(-drop, Math.hypot(dx, dz))]} scale={[length, 0.9, 0.9]} />- );- })}- <mesh geometry={GEO.cyl} material={STEEL} position={[x, -SKY_PAD.thickness - 1.2, z]} scale={[r * 0.55, 2.4, r * 0.55]} />- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/SpawnPanel.tsx b/dodaios/ui/web/frontend/src/components/society/office/SpawnPanel.tsxdeleted file mode 100644index b7f5f1001f..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/SpawnPanel.tsx+++ /dev/null@@ -1,13 +0,0 @@-/**- * The coding floor's spawn terminal: Mission Control's launcher (CLI,- * workspace, how many, an optional first task). Whoever it starts appears on- * the spawn pad and walks to a free desk.- *- * The agents floor's terminal has no panel of its own: it opens the app's- * create dialog (see OfficeStage).- */-import { StartAgent } from "./MissionControlPanel";--export function LaunchPanel() {- return <div className="office-mc"><StartAgent /></div>;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/SpawnPoint.tsx b/dodaios/ui/web/frontend/src/components/society/office/SpawnPoint.tsxdeleted file mode 100644index 2cd2324139..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/SpawnPoint.tsx+++ /dev/null@@ -1,647 +0,0 @@-/**- * The spawn point in the middle of both office floors: a round pad set into- * the aisle crossing and, on it, a portal-shaped terminal — two pillars, a- * lintel with the floor's crest, a screen on each side, a console with a- * glowing button each side and an energy core under it. It spawns Jarvis- * agents on the agents floor and coding agents on the coding floor; everyone- * new to a floor appears on the pad in a column of light.- *- * Each floor dresses it in its own materials: pale oak, bronze and a mint- * glow with the brass ghost downstairs; walnut, brass and amber with a brass- * prompt glyph upstairs. Same rules as OfficeProps: every piece is built in- * local space centred on the origin, front facing +z, inside its- * `FURNITURE_SIZE` box; materials and canvas faces are made once per floor- * and shared. The moving parts (the rings round the floor token, the glow- * pulse and the arrival beam) live in `SpawnFittings`.- */-import { useEffect, useRef } from "react";-import { useFrame } from "@react-three/fiber";-import { useT } from "@/i18n";-import {- AdditiveBlending, CylinderGeometry, DoubleSide, MeshBasicMaterial, MeshStandardMaterial, RingGeometry, TorusGeometry,- type BufferGeometry, type Group, type Mesh,-} from "three";-import { cachedCanvasTexture, canvasMaterial } from "./canvasMaterials";-import { Box, GEO, matte, Rounded } from "./OfficeFurniture";-import { drawGhost, GHOST_GEOMETRY } from "./LobbyDecor";-import { FURNITURE_SIZE, SPAWN, type Furniture, type FurnitureKind, type Point } from "./officeLayout";-import { useOfficeStore, type OfficeFloor } from "./officeStore";--type Vec3 = [number, number, number];-type Ctx = CanvasRenderingContext2D;--// ----------------------------------------------------------------------------// The two looks-// -----------------------------------------------------------------------------interface SpawnLook {- /** Pillars, lintel and console; the plinth; the metal trims. */- body: string; plinth: string; metal: string;- /** The screen bezel, and the light every strip, button, core and ring glows in. */- bezel: string; glow: string;- /** Screen: background top and bottom, the text, the accent and its deep tone. */- screenTop: string; screenBottom: string; text: string; accent: string; accentDeep: string;- /** Pad: stone, its speckles, the outer metal band and the accent band. */- pad: string; speck: readonly string[]; padEdge: string; padBand: string;-}--/**- * Downstairs the agents' Scandinavian oak, sage and bronze; upstairs the coding floor's walnut, plum and amber.- * The arcade floor has no spawn point; its entry only keeps the table complete (neon violet and cyan).- */-export const SPAWN_LOOKS: Record<OfficeFloor, SpawnLook> = {- agents: {- body: "#dcc49c", plinth: "#a88660", metal: "#c7a15e", bezel: "#23262b", glow: "#b8f0cf",- screenTop: "#22302a", screenBottom: "#111816", text: "#f1ebe1", accent: "#9fbf9a", accentDeep: "#16201b",- pad: "#e9e3d8", speck: ["#ddd5c7", "#f3efe7", "#cfc6b6"], padEdge: "#a8865a", padBand: "#9fae93",- },- coding: {- body: "#5d3d28", plinth: "#2e1d13", metal: "#d8ae52", bezel: "#1d1b1a", glow: "#ffc27a",- screenTop: "#271b40", screenBottom: "#0f0a1d", text: "#fff1de", accent: "#f3b16b", accentDeep: "#241a3b",- pad: "#2e2638", speck: ["#3b3246", "#251f2e", "#c9a24a"], padEdge: "#c9a24a", padBand: "#f3b16b",- },- arcade: {- body: "#2a2348", plinth: "#15112a", metal: "#9b8cff", bezel: "#0e0c1f", glow: "#7df9ff",- screenTop: "#1c1540", screenBottom: "#0b0918", text: "#f4f1ff", accent: "#ff5fa2", accentDeep: "#1a1236",- pad: "#1a1430", speck: ["#2a1f4a", "#151027", "#7df9ff"], padEdge: "#9b8cff", padBand: "#ff5fa2",- },- // The Level Hall has no spawn point; the entry keeps the table complete in the hall's cream, charcoal and brass.- hall: {- body: "#e7e0d0", plinth: "#2b2d33", metal: "#b8964f", bezel: "#23262b", glow: "#ffe2bd",- screenTop: "#2b2d33", screenBottom: "#16171b", text: "#f6efe1", accent: "#b8964f", accentDeep: "#1c1d21",- pad: "#e7e0d0", speck: ["#ddd5c7", "#f3efe7", "#bdb3a0"], padEdge: "#b8964f", padBand: "#2b2d33",- },-};--interface SpawnMaterials {- body: MeshStandardMaterial; plinth: MeshStandardMaterial; metal: MeshStandardMaterial; bezel: MeshStandardMaterial;- /** Self-lit, so it reads as light in any scene lighting; SpawnFittings pulses it. */- glow: MeshStandardMaterial;- glass: MeshStandardMaterial;-}--const materialCache = new Map<OfficeFloor, SpawnMaterials>();--export function spawnMaterials(floor: OfficeFloor): SpawnMaterials {- let set = materialCache.get(floor);- if (!set) {- const look = SPAWN_LOOKS[floor];- set = {- body: matte(look.body, { roughness: floor === "coding" ? 0.5 : 0.6 }),- plinth: matte(look.plinth, { roughness: 0.55 }),- metal: matte(look.metal, { roughness: 0.3, metalness: 0.7 }),- bezel: matte(look.bezel, { roughness: 0.35, metalness: 0.15 }),- glow: new MeshStandardMaterial({ color: look.glow, emissive: look.glow, emissiveIntensity: 1.25, toneMapped: false }),- glass: new MeshStandardMaterial({ color: "#eef6f8", transparent: true, opacity: 0.22, roughness: 0.05, depthWrite: false }),- };- materialCache.set(floor, set);- }- return set;-}--// ----------------------------------------------------------------------------// Canvas faces-// -----------------------------------------------------------------------------function roundRect(ctx: Ctx, x: number, y: number, w: number, h: number, r: number): void {- ctx.beginPath();- ctx.moveTo(x + r, y);- ctx.arcTo(x + w, y, x + w, y + h, r);- ctx.arcTo(x + w, y + h, x, y + h, r);- ctx.arcTo(x, y + h, x, y, r);- ctx.arcTo(x, y, x + w, y, r);- ctx.closePath();-}--/** Letter spacing where the canvas supports it (Chromium does; older engines just ignore it). */-function spaced(ctx: Ctx, px: number): void {- (ctx as Ctx & { letterSpacing?: string }).letterSpacing = `${px}px`;-}--/** A thick rounded plus, `size` px across, centred on (cx, cy). */-function plus(ctx: Ctx, cx: number, cy: number, size: number, colour: string): void {- const bar = size * 0.24;- ctx.fillStyle = colour;- roundRect(ctx, cx - size / 2, cy - bar / 2, size, bar, bar / 2);- ctx.fill();- roundRect(ctx, cx - bar / 2, cy - size / 2, bar, size, bar / 2);- ctx.fill();-}--const FONT = "Inter, 'Segoe UI', system-ui, sans-serif";-const MONO = "'JetBrains Mono', 'Cascadia Code', Consolas, monospace";--/** The screen's header: the floor's mark, SPAWN and a "ready" light on the right. */-/** The screen's words, translated by the terminal that shows them. */-interface ScreenLabels { title: string; ready: string; caption: string }--function screenHeader(ctx: Ctx, w: number, look: SpawnLook, labels: ScreenLabels, mark: (x: number, y: number) => void): void {- ctx.fillStyle = "rgba(255,255,255,0.05)";- ctx.fillRect(0, 0, w, 96);- ctx.fillStyle = look.accent;- ctx.fillRect(0, 96, w, 4);- mark(44, 48);- ctx.textBaseline = "middle";- ctx.textAlign = "left";- ctx.fillStyle = look.text;- spaced(ctx, 12);- ctx.font = `800 44px ${FONT}`;- ctx.fillText(labels.title, 112, 50, w - 112 - 200);- spaced(ctx, 3);- ctx.font = `700 22px ${FONT}`;- ctx.textAlign = "right";- ctx.fillStyle = "rgba(255,255,255,0.72)";- ctx.fillText(labels.ready, w - 44, 50, 80);- ctx.fillStyle = "#4ade80";- ctx.beginPath(); ctx.arc(w - 146, 49, 9, 0, Math.PI * 2); ctx.fill();- ctx.fillStyle = "rgba(74,222,128,0.25)";- ctx.beginPath(); ctx.arc(w - 146, 49, 16, 0, Math.PI * 2); ctx.fill();- spaced(ctx, 0);- ctx.textAlign = "left";-}--/** The big "spawn" button on the left half: an accent tile with a plus and its caption. */-function spawnButton(ctx: Ctx, look: SpawnLook, caption: string, round: boolean): void {- const cx = 250, cy = 318;- // A soft halo, then the tile.- const halo = ctx.createRadialGradient(cx, cy, 60, cx, cy, 230);- halo.addColorStop(0, `${look.accent}66`);- halo.addColorStop(1, `${look.accent}00`);- ctx.fillStyle = halo;- ctx.fillRect(cx - 240, cy - 240, 480, 480);- const tile = ctx.createLinearGradient(cx, cy - 150, cx, cy + 150);- tile.addColorStop(0, "#ffffff");- tile.addColorStop(0.12, look.accent);- tile.addColorStop(1, look.accent);- ctx.fillStyle = tile;- if (round) { ctx.beginPath(); ctx.arc(cx, cy, 142, 0, Math.PI * 2); } else roundRect(ctx, cx - 158, cy - 142, 316, 284, 44);- ctx.fill();- ctx.strokeStyle = "rgba(255,255,255,0.55)";- ctx.lineWidth = 5;- ctx.stroke();- plus(ctx, cx, cy, 150, look.accentDeep);- ctx.fillStyle = look.text;- ctx.textAlign = "center";- spaced(ctx, 5);- ctx.font = `800 30px ${FONT}`;- ctx.fillText(caption, cx, 520, 470);- spaced(ctx, 0);- ctx.textAlign = "left";-}--/** The coding floor's screen: SPAWN, a new-agent button, the terminal windows of the running agents and a prompt. */-function drawLaunchScreen(ctx: Ctx, w: number, h: number, labels: ScreenLabels): void {- const look = SPAWN_LOOKS.coding;- const bg = ctx.createLinearGradient(0, 0, 0, h);- bg.addColorStop(0, look.screenTop);- bg.addColorStop(1, look.screenBottom);- ctx.fillStyle = bg;- ctx.fillRect(0, 0, w, h);- // A faint blueprint grid.- ctx.strokeStyle = "rgba(243,177,107,0.07)";- ctx.lineWidth = 1;- ctx.beginPath();- for (let x = 0; x <= w; x += 32) { ctx.moveTo(x + 0.5, 100); ctx.lineTo(x + 0.5, h); }- for (let y = 100; y <= h; y += 32) { ctx.moveTo(0, y + 0.5); ctx.lineTo(w, y + 0.5); }- ctx.stroke();- screenHeader(ctx, w, look, labels, (x, y) => {- ctx.fillStyle = look.accent;- ctx.font = `800 46px ${MONO}`;- ctx.textBaseline = "middle";- ctx.textAlign = "center";- ctx.fillText(">_", x + 10, y + 2);- });- spawnButton(ctx, look, labels.caption, false);- // Three terminal windows fanning down the right: two running agents and the one about to spawn.- const states = ["#4ade80", "#fbbf24", null] as const;- states.forEach((dot, i) => {- const x = 520 + i * 16, y = 138 + i * 132, ww = 460, wh = 116;- if (dot) {- ctx.fillStyle = "rgba(10,7,20,0.82)";- roundRect(ctx, x, y, ww, wh, 14);- ctx.fill();- ctx.strokeStyle = "rgba(243,177,107,0.35)";- ctx.lineWidth = 2;- ctx.stroke();- ctx.fillStyle = "rgba(255,255,255,0.07)";- ctx.fillRect(x + 2, y + 2, ww - 4, 28);- ["#f3b16b", "#8b7fb0", "#6c6384"].forEach((c, k) => {- ctx.fillStyle = c;- ctx.beginPath(); ctx.arc(x + 20 + k * 20, y + 16, 6, 0, Math.PI * 2); ctx.fill();- });- ctx.fillStyle = dot;- ctx.beginPath(); ctx.arc(x + ww - 22, y + 16, 7, 0, Math.PI * 2); ctx.fill();- for (let line = 0; line < 3; line += 1) {- ctx.fillStyle = line === 0 ? look.accent : "rgba(255,241,222,0.55)";- ctx.fillRect(x + 20, y + 46 + line * 22, line === 0 ? 18 : 12, 10);- ctx.fillStyle = "rgba(255,241,222,0.42)";- ctx.fillRect(x + 48, y + 46 + line * 22, 120 + ((i * 97 + line * 61) % 230), 10);- }- } else {- ctx.setLineDash([14, 10]);- ctx.strokeStyle = look.accent;- ctx.lineWidth = 3;- roundRect(ctx, x, y, ww, wh, 14);- ctx.stroke();- ctx.setLineDash([]);- plus(ctx, x + ww / 2, y + wh / 2, 46, look.accent);- }- });- // The prompt line with its cursor.- ctx.fillStyle = "rgba(0,0,0,0.25)";- ctx.fillRect(0, h - 92, w, 92);- ctx.textBaseline = "middle";- ctx.font = `700 32px ${MONO}`;- ctx.fillStyle = look.accent;- ctx.fillText("$", 44, h - 46);- ctx.fillStyle = look.text;- ctx.fillText("spawn --agent", 84, h - 46);- const end = 84 + ctx.measureText("spawn --agent").width + 12;- ctx.fillStyle = look.accent;- ctx.fillRect(end, h - 64, 20, 36);-}--/** The agents floor's screen: the ghost and SPAWN, a new-agent button, the team with a place for the next one. */-function drawSpawnScreen(ctx: Ctx, w: number, h: number, labels: ScreenLabels): void {- const look = SPAWN_LOOKS.agents;- const bg = ctx.createLinearGradient(0, 0, 0, h);- bg.addColorStop(0, look.screenTop);- bg.addColorStop(1, look.screenBottom);- ctx.fillStyle = bg;- ctx.fillRect(0, 0, w, h);- screenHeader(ctx, w, look, labels, (x, y) => drawGhost(ctx, x + 12, y - 30, 60, look.text, look.screenTop));- spawnButton(ctx, look, labels.caption, true);- // The team: two toy figures and, dashed, the one about to spawn.- const figures = [{ x: 620, colour: "#c4775a", shirt: "#e9dcc4" }, { x: 780, colour: "#7c8fa8", shirt: "#d9a441" }, { x: 940, colour: null, shirt: null }];- const floorY = 480;- ctx.fillStyle = "rgba(159,191,154,0.14)";- roundRect(ctx, 530, floorY - 6, 480, 16, 8);- ctx.fill();- for (const f of figures) {- if (f.colour && f.shirt) {- ctx.fillStyle = f.shirt;- roundRect(ctx, f.x - 42, floorY - 130, 84, 124, 30);- ctx.fill();- ctx.fillStyle = "#f1dcc3";- ctx.beginPath(); ctx.arc(f.x, floorY - 186, 50, 0, Math.PI * 2); ctx.fill();- ctx.fillStyle = f.colour;- ctx.beginPath(); ctx.arc(f.x, floorY - 200, 50, Math.PI, Math.PI * 2); ctx.fill();- ctx.fillStyle = "#2b2926";- for (const dx of [-16, 16]) { ctx.beginPath(); ctx.arc(f.x + dx, floorY - 180, 6, 0, Math.PI * 2); ctx.fill(); }- } else {- ctx.setLineDash([12, 9]);- ctx.strokeStyle = look.accent;- ctx.lineWidth = 4;- roundRect(ctx, f.x - 42, floorY - 130, 84, 124, 30);- ctx.stroke();- ctx.beginPath(); ctx.arc(f.x, floorY - 186, 50, 0, Math.PI * 2); ctx.stroke();- ctx.setLineDash([]);- plus(ctx, f.x, floorY - 186, 40, look.accent);- // Sparkles round the newcomer.- ctx.fillStyle = look.accent;- for (const [sx, sy, r] of [[f.x + 64, floorY - 250, 7], [f.x - 66, floorY - 226, 5], [f.x + 58, floorY - 120, 5]] as const) {- ctx.beginPath();- ctx.moveTo(sx, sy - r * 2); ctx.lineTo(sx + r * 0.6, sy - r * 0.6); ctx.lineTo(sx + r * 2, sy); ctx.lineTo(sx + r * 0.6, sy + r * 0.6);- ctx.lineTo(sx, sy + r * 2); ctx.lineTo(sx - r * 0.6, sy + r * 0.6); ctx.lineTo(sx - r * 2, sy); ctx.lineTo(sx - r * 0.6, sy - r * 0.6);- ctx.closePath(); ctx.fill();- }- }- }- // Name bars under the two who are here.- for (const f of figures.slice(0, 2)) {- ctx.fillStyle = "rgba(241,235,225,0.75)";- roundRect(ctx, f.x - 50, floorY + 30, 100, 14, 7);- ctx.fill();- }- // A strip of the team's colours along the bottom.- ctx.fillStyle = "rgba(0,0,0,0.22)";- ctx.fillRect(0, h - 92, w, 92);- ["#c4775a", "#7c8fa8", "#d9a441", "#74866c", "#b56a4c", "#9fae93"].forEach((c, i) => {- ctx.fillStyle = c;- ctx.beginPath(); ctx.arc(64 + i * 52, h - 46, 17, 0, Math.PI * 2); ctx.fill();- });- ctx.setLineDash([8, 6]);- ctx.strokeStyle = look.accent;- ctx.lineWidth = 3;- ctx.beginPath(); ctx.arc(64 + 6 * 52, h - 46, 17, 0, Math.PI * 2); ctx.stroke();- ctx.setLineDash([]);-}--/**- * The pad's face, drawn for a circle of the canvas' full width: speckled- * stone, an outer metal band, a ring of tick marks, four chevrons pointing in- * at the terminal and a fine inner circle. The glowing ring is its own mesh.- */-function drawPad(floor: OfficeFloor) {- return (ctx: Ctx, w: number, h: number): void => {- const look = SPAWN_LOOKS[floor];- const cx = w / 2, cy = h / 2, R = w / 2;- ctx.clearRect(0, 0, w, h);- ctx.save();- ctx.beginPath(); ctx.arc(cx, cy, R, 0, Math.PI * 2); ctx.clip();- ctx.fillStyle = look.pad;- ctx.fillRect(0, 0, w, h);- // Terrazzo / limestone speckles, deterministic.- let seed = floor === "coding" ? 7331 : 1337;- const rand = () => { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 0x1_0000_0000; };- for (let i = 0; i < 2600; i += 1) {- const a = rand() * Math.PI * 2, r = Math.sqrt(rand()) * R;- ctx.fillStyle = look.speck[i % look.speck.length];- const s = 2 + rand() * (i % 9 === 0 ? 6 : 3);- ctx.fillRect(cx + Math.cos(a) * r, cy + Math.sin(a) * r, s, s);- }- // The outer metal band and a thin line inside it.- ctx.lineWidth = R * 0.05;- ctx.strokeStyle = look.padEdge;- ctx.beginPath(); ctx.arc(cx, cy, R * 0.975, 0, Math.PI * 2); ctx.stroke();- ctx.lineWidth = R * 0.008;- ctx.beginPath(); ctx.arc(cx, cy, R * 0.915, 0, Math.PI * 2); ctx.stroke();- // Tick marks, longer every 45°.- ctx.strokeStyle = look.padBand;- ctx.lineCap = "round";- for (let i = 0; i < 48; i += 1) {- const a = (i / 48) * Math.PI * 2, major = i % 6 === 0;- const r0 = R * (major ? 0.66 : 0.7), r1 = R * 0.76;- ctx.lineWidth = major ? R * 0.018 : R * 0.008;- ctx.beginPath();- ctx.moveTo(cx + Math.cos(a) * r0, cy + Math.sin(a) * r0);- ctx.lineTo(cx + Math.cos(a) * r1, cy + Math.sin(a) * r1);- ctx.stroke();- }- // Four chevrons pointing in at the terminal.- ctx.fillStyle = look.padBand;- for (let i = 0; i < 4; i += 1) {- const a = (i / 4) * Math.PI * 2 + Math.PI / 4;- ctx.save();- ctx.translate(cx + Math.cos(a) * R * 0.56, cy + Math.sin(a) * R * 0.56);- ctx.rotate(a);- ctx.beginPath();- ctx.moveTo(R * 0.05, -R * 0.07); ctx.lineTo(-R * 0.02, 0); ctx.lineTo(R * 0.05, R * 0.07);- ctx.lineTo(R * 0.02, R * 0.07); ctx.lineTo(-R * 0.05, 0); ctx.lineTo(R * 0.02, -R * 0.07);- ctx.closePath();- ctx.fill();- ctx.restore();- }- ctx.lineWidth = R * 0.01;- ctx.strokeStyle = look.padBand;- ctx.globalAlpha = 0.6;- ctx.beginPath(); ctx.arc(cx, cy, R * 0.46, 0, Math.PI * 2); ctx.stroke();- ctx.globalAlpha = 1;- ctx.restore();- };-}--const padCache = new Map<string, MeshStandardMaterial>();--const faces = {- screen: (floor: OfficeFloor, labels: ScreenLabels) => canvasMaterial(`spawn:screen:${floor}:${labels.title}|${labels.ready}|${labels.caption}`, 1024, 690,- (ctx, w, h) => (floor === "coding" ? drawLaunchScreen : drawSpawnScreen)(ctx, w, h, labels),- { glow: 0.9, fallback: SPAWN_LOOKS[floor].screenTop, roughness: 0.3 }),- pad: (floor: OfficeFloor) => {- const key = `spawn:pad:${floor}`;- let material = padCache.get(key);- if (!material) {- const map = cachedCanvasTexture(key, 1024, 1024, drawPad(floor));- material = new MeshStandardMaterial({ color: map ? "#ffffff" : SPAWN_LOOKS[floor].pad, map, roughness: floor === "coding" ? 0.35 : 0.6 });- padCache.set(key, material);- }- return material;- },-};--// ----------------------------------------------------------------------------// Geometry-// -----------------------------------------------------------------------------const PAD_R = FURNITURE_SIZE.spawnPad.w / 2;-/** The glowing ring set into the pad, inside the checkpoint's gold ring. */-const GLOW_RING: [number, number] = [PAD_R * 0.845, PAD_R * 0.885];--const SGEO = {- pad: new CylinderGeometry(PAD_R, PAD_R, 0.012, 72),- glowRing: new RingGeometry(GLOW_RING[0], GLOW_RING[1], 72),- core: new CylinderGeometry(0.045, 0.045, 1, 16),- tube: new CylinderGeometry(0.1, 0.1, 1, 24, 1, true),- collar: new TorusGeometry(0.105, 0.014, 8, 28),- button: new CylinderGeometry(0.052, 0.052, 0.012, 24),- buttonRing: new TorusGeometry(0.066, 0.008, 6, 24),-};-SGEO.glowRing.rotateX(-Math.PI / 2);-SGEO.collar.rotateX(Math.PI / 2);-SGEO.buttonRing.rotateX(Math.PI / 2);--function Mesh3({ geometry, material, position, rotation, scale, cast = true }: {- geometry: BufferGeometry; material: MeshStandardMaterial; position: Vec3; rotation?: Vec3; scale?: Vec3 | number; cast?: boolean;-}) {- return <mesh geometry={geometry} material={material} position={position} rotation={rotation} scale={scale} castShadow={cast} receiveShadow />;-}--/** A bar of the prompt glyph: a unit box scaled to `size`, turned about z. */-function Bar({ size, position, angle, material }: { size: Vec3; position: Vec3; angle: number; material: MeshStandardMaterial }) {- return <Mesh3 geometry={GEO.box} material={material} position={position} rotation={[0, 0, angle]} scale={size} />;-}--// ----------------------------------------------------------------------------// Props (local space: centred on the origin, front faces +z)-// -----------------------------------------------------------------------------/** Pillar centres and the console height, shared with the fittings. */-const PILLAR_X = 0.54;-const CONSOLE_Y = 0.95;-const SCREEN_Y = 1.42;-const LINTEL_Y = 1.99;--/** The floor's crest on the lintel: the brass ghost downstairs, a brass prompt glyph (>_) upstairs. */-function Crest({ floor, metal }: { floor: OfficeFloor; metal: MeshStandardMaterial }) {- if (floor === "agents") {- // The ghost is 1 unit tall with its back on z = 0 and ~0.08 deep: centre it on the lintel, both faces show.- return <mesh geometry={GHOST_GEOMETRY} material={metal} position={[0, LINTEL_Y + 0.05, -0.02]} scale={[0.15, 0.15, 0.5]} castShadow />;- }- return (- <group position={[-0.03, LINTEL_Y + 0.105, 0]}>- <Bar size={[0.075, 0.022, 0.03]} position={[0, 0.022, 0]} angle={-0.6} material={metal} />- <Bar size={[0.075, 0.022, 0.03]} position={[0, -0.022, 0]} angle={0.6} material={metal} />- <Box size={[0.07, 0.022, 0.03]} position={[0.075, -0.042, 0]} material={metal} />- </group>- );-}--/**- * The spawn terminal: a plinth with a light line, two pillars with light- * strips, a lintel with the floor's crest, the double-sided screen hanging- * between the pillars, and a console slab across them with a glowing spawn- * button each side over a glass tube with the energy core.- */-export function SpawnTerminal() {- const floor = useOfficeStore((s) => s.floor);- const m = spawnMaterials(floor);- const t = useT();- const screen = faces.screen(floor, {- title: t("society.office.spawn_screen_title"),- ready: t("society.office.spawn_screen_ready"),- caption: floor === "coding" ? t("society.office.spawn_screen_new_coding") : t("society.office.spawn_screen_new"),- });- return (- <group>- {/* Plinth with a light line along both long faces. */}- <Rounded size={[1.12, 0.08, 0.62]} radius={0.03} position={[0, 0.04, 0]} material={m.plinth} />- {[-1, 1].map((side) => <Box key={side} size={[1.0, 0.012, 0.01]} position={[0, 0.05, side * 0.312]} material={m.glow} cast={false} />)}-- {/* Pillars: metal feet, wood shafts, a light strip down each face. */}- {[-PILLAR_X, PILLAR_X].map((x) => (- <group key={x}>- <Box size={[0.12, 0.04, 0.22]} position={[x, 0.1, 0]} material={m.metal} />- <Rounded size={[0.12, 1.86, 0.2]} radius={0.04} position={[x, 1.01, 0]} material={m.body} />- {[-1, 1].map((side) => <Box key={side} size={[0.014, 1.6, 0.012]} position={[x, 1.04, side * 0.101]} material={m.glow} cast={false} />)}- </group>- ))}-- {/* Lintel with metal trim lines and the crest. */}- <Rounded size={[1.2, 0.1, 0.22]} radius={0.035} position={[0, LINTEL_Y, 0]} material={m.body} />- {[-1, 1].map((side) => <Box key={side} size={[1.1, 0.012, 0.01]} position={[0, LINTEL_Y, side * 0.111]} material={m.metal} cast={false} />)}- <Crest floor={floor} metal={m.metal} />-- {/* The screen: a bezel between the pillars with a face on each side and metal brackets. */}- <group position={[0, SCREEN_Y, 0]}>- <Rounded size={[0.94, 0.66, 0.07]} radius={0.03} position={[0, 0, 0]} material={m.bezel} />- <Box size={[0.9, 0.012, 0.074]} position={[0, 0.324, 0]} material={m.metal} cast={false} />- <mesh position={[0, 0, 0.0355]} material={screen}><planeGeometry args={[0.86, 0.58]} /></mesh>- <mesh position={[0, 0, -0.0355]} rotation={[0, Math.PI, 0]} material={screen}><planeGeometry args={[0.86, 0.58]} /></mesh>- {[-0.475, 0.475].map((x) => <Box key={x} size={[0.02, 0.1, 0.05]} position={[x, 0, 0]} material={m.metal} />)}- </group>-- {/* The console across the pillars, a spawn button each side. */}- <Rounded size={[0.96, 0.035, 0.46]} radius={0.012} position={[0, CONSOLE_Y, 0]} material={m.body} />- {[-1, 1].map((side) => (- <group key={side} position={[0, CONSOLE_Y + 0.018, side * 0.14]}>- <Mesh3 geometry={SGEO.button} material={m.glow} position={[0, 0.004, 0]} cast={false} />- <Mesh3 geometry={SGEO.buttonRing} material={m.metal} position={[0, 0.004, 0]} cast={false} />- </group>- ))}-- {/* Under it the glass tube with the energy core and a metal collar at each end. */}- <Mesh3 geometry={SGEO.core} material={m.glow} position={[0, 0.515, 0]} scale={[1, 0.83, 1]} cast={false} />- <Mesh3 geometry={SGEO.tube} material={m.glass} position={[0, 0.515, 0]} scale={[1, 0.83, 1]} cast={false} />- <Mesh3 geometry={SGEO.collar} material={m.metal} position={[0, 0.105, 0]} />- <Mesh3 geometry={SGEO.collar} material={m.metal} position={[0, 0.925, 0]} />- </group>- );-}--/** The spawn pad: a thin stone disc with its drawn face and the glowing ring set into it. */-export function SpawnPad() {- const floor = useOfficeStore((s) => s.floor);- const m = spawnMaterials(floor);- return (- <group>- <Mesh3 geometry={SGEO.pad} material={faces.pad(floor)} position={[0, 0.006, 0]} cast={false} />- <Mesh3 geometry={SGEO.glowRing} material={m.glow} position={[0, 0.0135, 0]} cast={false} />- </group>- );-}--export const SPAWN_RENDERERS: Record<Extract<FurnitureKind, "spawnPad" | "spawnTerminal">, (props: { item: Furniture }) => JSX.Element> = {- spawnPad: () => <SpawnPad />,- spawnTerminal: () => <SpawnTerminal />,-};--// ----------------------------------------------------------------------------// Fittings: the moving parts-// -----------------------------------------------------------------------------/** How long a newcomer's column of light lasts. */-const BEAM_S = 1.8;-const BEAM_H = 2.8;--const beamGeometry = new CylinderGeometry(0.42, 0.42, BEAM_H, 32, 1, true);-const burstGeometry = new RingGeometry(0.3, 0.42, 48);-burstGeometry.rotateX(-Math.PI / 2);-const gyroGeometry = [new TorusGeometry(0.52, 0.011, 6, 64), new TorusGeometry(0.6, 0.009, 6, 64)];--const beamMaterials = new Map<OfficeFloor, { beam: MeshBasicMaterial; burst: MeshBasicMaterial }>();-function beamMaterialsFor(floor: OfficeFloor) {- let set = beamMaterials.get(floor);- if (!set) {- // Bright at the floor, gone at the top.- const fade = cachedCanvasTexture("spawn:beam", 4, 128, (ctx, w, h) => {- const g = ctx.createLinearGradient(0, 0, 0, h);- g.addColorStop(0, "rgba(0,0,0,1)");- g.addColorStop(1, "rgba(255,255,255,1)");- ctx.fillStyle = g;- ctx.fillRect(0, 0, w, h);- });- const colour = SPAWN_LOOKS[floor].glow;- set = {- beam: new MeshBasicMaterial({ color: colour, map: fade, transparent: true, opacity: 0, blending: AdditiveBlending, depthWrite: false, side: DoubleSide, toneMapped: false }),- burst: new MeshBasicMaterial({ color: colour, transparent: true, opacity: 0, blending: AdditiveBlending, depthWrite: false, side: DoubleSide, toneMapped: false }),- };- beamMaterials.set(floor, set);- }- return set;-}--/**- * The spawn point's life: a beacon of two gyroscope rings turning above the terminal,- * the glow breathing, and a column of light on the pad whenever someone new- * arrives on the floor (a newcomer walks off the pad to its desk). Reduced- * motion keeps the rings still and skips the beam.- */-export function SpawnFittings({ terminal, arrival, floor, newcomers, animate }: {- terminal: Point; arrival: Point; floor: OfficeFloor; newcomers: ReadonlySet<string>; animate: boolean;-}) {- const m = spawnMaterials(floor);- const beams = beamMaterialsFor(floor);- const gyroA = useRef<Group>(null);- const gyroB = useRef<Group>(null);- const beam = useRef<Mesh>(null);- const burst = useRef<Mesh>(null);- // -1 = start on the next frame; null = no beam running.- const beamStart = useRef<number | null>(null);- const seen = useRef<ReadonlySet<string>>(newcomers);- useEffect(() => {- const fresh = [...newcomers].some((id) => !seen.current.has(id));- seen.current = newcomers;- if (fresh && animate) beamStart.current = -1;- }, [newcomers, animate]);- // The glow is shared: leave it at rest when the fittings go.- useEffect(() => () => { m.glow.emissiveIntensity = 1.25; }, [m]);-- useFrame(({ clock }) => {- const t = clock.elapsedTime;- if (gyroA.current && gyroB.current) {- gyroA.current.rotation.set(animate ? t * 0.9 : 1.1, animate ? t * 0.35 : 0.3, 0);- gyroB.current.rotation.set(animate ? -t * 0.55 : 0.4, 0, animate ? t * 0.7 : 1.2);- }- m.glow.emissiveIntensity = animate ? 1.2 + Math.sin(t * 2.1) * 0.25 : 1.25;- if (beamStart.current === -1) beamStart.current = t;- const start = beamStart.current;- const p = start === null ? 1 : (t - start) / BEAM_S;- const running = p >= 0 && p < 1;- if (!running) beamStart.current = null;- if (beam.current && burst.current) {- beam.current.visible = running;- burst.current.visible = running;- if (running) {- const rise = Math.min(1, p / 0.15);- beams.beam.opacity = 0.75 * rise * (1 - Math.max(0, (p - 0.15) / 0.85));- beam.current.scale.set(1.15 - 0.5 * p, 0.4 + 0.6 * rise, 1.15 - 0.5 * p);- beam.current.position.y = (BEAM_H * beam.current.scale.y) / 2;- burst.current.scale.setScalar(1 + p * 2.2);- beams.burst.opacity = 0.8 * (1 - p);- }- }- });-- return (- <>- <group position={[terminal.x, SPAWN.beaconY, terminal.z]}>- <group ref={gyroA}><mesh geometry={gyroGeometry[0]} material={m.glow} /></group>- <group ref={gyroB}><mesh geometry={gyroGeometry[1]} material={m.glow} /></group>- </group>- <group position={[arrival.x, 0, arrival.z]}>- <mesh ref={beam} geometry={beamGeometry} material={beams.beam} visible={false} renderOrder={2} />- <mesh ref={burst} geometry={burstGeometry} material={beams.burst} position={[0, 0.03, 0]} visible={false} renderOrder={2} />- </group>- </>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/StationObjects.tsx b/dodaios/ui/web/frontend/src/components/society/office/StationObjects.tsxdeleted file mode 100644index e397e9b11d..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/StationObjects.tsx+++ /dev/null@@ -1,119 +0,0 @@-/**- * The stations in the world. Nothing floats over the floor: the object in the- * room is the station. Each one gets an invisible click target the size of- * its object (so it stays usable from the overview, walking is optional) and- * a thin rim on the object itself while the person stands at it, points at- * it or has it open. The one prompt that names it lives in the HUD.- */-import { useEffect, useMemo, useRef } from "react";-import { useFrame, useThree, type ThreeEvent } from "@react-three/fiber";-import type { Mesh, Object3D } from "three";-import type { OfficeLayout } from "./officeLayout";-import { sameSelection, useOfficeStore, type Selection } from "./officeStore";-import { stationsFor, type Station } from "./stations";-import { attachRim, attachedTo, createRimMaterial, detachRim, rimTargets } from "./stationRim";--/** The rim at full strength, and how fast it fades in and out (per second, exponential). */-const RIM_OPACITY = 0.92;-const RIM_FADE = 12;-/** While lit, look this often (frames) whether the object was rebuilt under the rim. */-const RIM_CHECK_FRAMES = 30;--function StationRim({ objects, lit, animate }: { objects: readonly string[]; lit: boolean; animate: boolean }) {- const scene = useThree((s) => s.scene);- const invalidate = useThree((s) => s.invalidate);- const material = useMemo(createRimMaterial, []);- const worn = useRef<{ roots: Object3D[]; shells: Mesh[] }>({ roots: [], shells: [] });- const frames = useRef(0);- const names = objects.join("|");-- const takeOff = () => {- detachRim(worn.current.shells);- worn.current = { roots: [], shells: [] };- };- useEffect(() => () => { takeOff(); material.dispose(); }, [material]);- // Another object under the same station (a rebuilt floor plan): start clean.- useEffect(() => takeOff, [names]);- // A paused or on-demand canvas still has to draw the change.- useEffect(() => { invalidate(); }, [lit, invalidate]);-- useFrame((_, delta) => {- const uniform = material.uniforms.rimOpacity;- const goal = lit ? RIM_OPACITY : 0;- if (uniform.value !== goal) {- uniform.value = animate ? uniform.value + (goal - uniform.value) * (1 - Math.exp(-RIM_FADE * Math.min(delta, 0.1))) : goal;- if (Math.abs(uniform.value - goal) < 0.01) uniform.value = goal;- invalidate();- }- const state = worn.current;- if (!lit) {- if (uniform.value === 0 && state.shells.length > 0) takeOff();- frames.current = 0;- return;- }- // Dress the object on the first lit frame, then look now and then whether it was rebuilt under the rim.- const first = frames.current === 0;- frames.current += 1;- if (!first && frames.current % RIM_CHECK_FRAMES !== 0) return;- const intact = state.roots.length > 0 && state.roots.every((root) => attachedTo(root, scene))- && state.roots.reduce((sum, root) => sum + rimTargets(root).length, 0) === state.shells.length;- if (intact) return;- takeOff();- const roots = objects.map((name) => scene.getObjectByName(name)).filter((root): root is Object3D => !!root);- worn.current = { roots, shells: roots.flatMap((root) => attachRim(root, material)) };- });- return null;-}--function StationObject({ station, lit, animate }: { station: Station; lit: boolean; animate: boolean }) {- const hovered = useRef(false);- const leave = () => {- if (!hovered.current) return;- hovered.current = false;- document.body.style.cursor = "";- const store = useOfficeStore.getState();- if (sameSelection(store.hover, station.selection)) store.setHover(null);- };- // Never leave a pointer cursor or a stale hover behind when the station goes away under the mouse.- useEffect(() => leave, []); // eslint-disable-line react-hooks/exhaustive-deps-- const onClick = (event: ThreeEvent<MouseEvent>) => {- // A drag that ends on the object turned the camera; only a real click uses it.- if (event.delta > 6) return;- event.stopPropagation();- useOfficeStore.getState().select(station.selection);- };- const onPointerOver = (event: ThreeEvent<PointerEvent>) => {- event.stopPropagation();- hovered.current = true;- document.body.style.cursor = "pointer";- useOfficeStore.getState().setHover(station.selection);- };-- return (- <group name={`station:${station.key}`}>- {station.hits.map((box, i) => (- <mesh key={i} position={[box.x, box.y, box.z]} rotation={[0, box.rotationY, 0]} visible={false}- onClick={onClick} onPointerOver={onPointerOver} onPointerOut={leave}>- <boxGeometry args={[box.w, box.h, box.d]} />- </mesh>- ))}- {station.objects.length > 0 && <StationRim objects={station.objects} lit={lit} animate={animate} />}- </group>- );-}--export function StationObjects({ layout, nearby, selection, animate }: {- layout: OfficeLayout; nearby: Selection | null; selection: Selection | null; animate: boolean;-}) {- const stations = useMemo(() => stationsFor(layout), [layout]);- const hover = useOfficeStore((s) => s.hover);- return (- <>- {stations.map((station) => (- <StationObject key={station.key} station={station} animate={animate}- lit={sameSelection(nearby, station.selection) || sameSelection(hover, station.selection) || sameSelection(selection, station.selection)} />- ))}- </>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/StationSheet.test.tsx b/dodaios/ui/web/frontend/src/components/society/office/StationSheet.test.tsxdeleted file mode 100644index e099aa6c2a..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/StationSheet.test.tsx+++ /dev/null@@ -1,72 +0,0 @@-import { useState } from "react";-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";-import { afterEach, beforeAll, describe, expect, test, vi } from "vitest";-import { loadLocaleChunk } from "@/i18n";-import { ownsKeyboard } from "./OfficePlayer";-import { StationSheet, StationSidePanel } from "./StationSheet";--beforeAll(async () => { await loadLocaleChunk("society"); });-afterEach(cleanup);--/** A map host with a button that opens a station's dialog, the way the stage mounts one. */-function Stage({ onReturn }: { onReturn?: () => void }) {- const [open, setOpen] = useState(false);- return (- <div>- <div data-testid="host" tabIndex={0} />- <button type="button" onClick={() => setOpen(true)}>Open teams</button>- {open && (- <StationSheet title="Team room" description="Your teams and their meetings" onClose={() => setOpen(false)}- returnFocus={() => { onReturn?.(); screen.getByTestId("host").focus(); }}>- <input aria-label="Team name" />- </StationSheet>- )}- </div>- );-}--describe("station dialog", () => {- test("is a labelled modal dialog that owns the keyboard while it is open", () => {- render(<Stage />);- fireEvent.click(screen.getByRole("button", { name: "Open teams" }));- const dialog = screen.getByRole("dialog", { name: "Team room" });- expect(dialog.getAttribute("data-state")).toBe("open");- expect(screen.getByText("Your teams and their meetings")).toBeTruthy();- // The walking keys stand down while a dialog is open, wherever focus sits.- expect(ownsKeyboard(document.body)).toBe(true);- });-- test("Escape closes it and hands focus to the map, so the walking keys answer at once", async () => {- const onReturn = vi.fn();- render(<Stage onReturn={onReturn} />);- fireEvent.click(screen.getByRole("button", { name: "Open teams" }));- const dialog = screen.getByRole("dialog");- fireEvent.keyDown(dialog, { key: "Escape" });- await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());- await waitFor(() => expect(onReturn).toHaveBeenCalledOnce());- const host = screen.getByTestId("host");- expect(document.activeElement).toBe(host);- expect(ownsKeyboard(host)).toBe(false);- });-- test("the close button does the same", async () => {- const onReturn = vi.fn();- render(<Stage onReturn={onReturn} />);- fireEvent.click(screen.getByRole("button", { name: "Open teams" }));- fireEvent.click(screen.getByRole("button", { name: "Close" }));- await waitFor(() => expect(onReturn).toHaveBeenCalledOnce());- expect(document.activeElement).toBe(screen.getByTestId("host"));- });-});--describe("station side panel", () => {- test("is a labelled panel that takes focus without taking the walking keys", () => {- const onClose = vi.fn();- render(<StationSidePanel title="Wardrobe" description="Dress yourself or an agent" onClose={onClose}><p>Outfits</p></StationSidePanel>);- const panel = screen.getByRole("complementary", { name: "Wardrobe" });- expect(document.activeElement).toBe(panel);- expect(ownsKeyboard(panel)).toBe(false);- fireEvent.click(screen.getByRole("button", { name: "Close" }));- expect(onClose).toHaveBeenCalledOnce();- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/StationSheet.tsx b/dodaios/ui/web/frontend/src/components/society/office/StationSheet.tsxdeleted file mode 100644index 0103fdd599..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/StationSheet.tsx+++ /dev/null@@ -1,78 +0,0 @@-/**- * What opens from a station. A station that manages something (teams, the- * directory, a launcher) opens a dialog built like every other dialog of the- * app: the same scrim, surface, header and type scale. A station whose effect- * shows in the world (the wardrobe) opens a panel docked at the side instead,- * so the person keeps seeing — and walking — their character.- */-import { useEffect, useId, useRef, type ReactNode } from "react";-import * as Dialog from "@radix-ui/react-dialog";-import { X } from "lucide-react";-import { useT } from "@/i18n";-import { cn } from "@/lib/utils";--const closeButton = "inline-flex size-8 shrink-0 items-center justify-center rounded-md border border-border bg-background text-foreground hover:bg-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";--const WIDTH = {- md: "w-[min(32rem,calc(100vw-2rem))]",- lg: "w-[min(42rem,calc(100vw-2rem))]",-} as const;--export function StationSheet({ title, description, size = "lg", onClose, returnFocus, children }: {- title: string; description?: string; size?: keyof typeof WIDTH; onClose: () => void;- /**- * Where focus goes when the dialog has closed (the map's canvas host, so the walking keys answer at once).- * Without it focus returns to whatever had it before the dialog opened.- */- returnFocus?: () => void;- children: ReactNode;-}) {- const t = useT();- return (- <Dialog.Root open onOpenChange={(open) => { if (!open) onClose(); }}>- <Dialog.Portal>- <Dialog.Overlay className="fixed inset-0 z-[150] bg-scrim/60 backdrop-blur-sm" />- <Dialog.Content data-office-ui {...(description ? {} : { "aria-describedby": undefined })}- onCloseAutoFocus={(event) => {- if (!returnFocus) return;- event.preventDefault();- returnFocus();- }}- className={cn("fixed left-1/2 top-1/2 z-[151] flex max-h-[90dvh] -translate-x-1/2 -translate-y-1/2 flex-col overflow-hidden rounded-xl border border-border bg-background text-foreground shadow-xl", WIDTH[size])}>- <div className="flex items-start justify-between gap-4 border-b border-border p-5">- <div className="grid min-w-0 gap-1.5">- <Dialog.Title className="font-display text-lg font-semibold">{title}</Dialog.Title>- {description && <Dialog.Description className="text-sm text-muted-foreground">{description}</Dialog.Description>}- </div>- <Dialog.Close className={closeButton} aria-label={t("society.office.close")}><X size={16} aria-hidden /></Dialog.Close>- </div>- <div className="grid gap-5 overflow-y-auto p-5">{children}</div>- </Dialog.Content>- </Dialog.Portal>- </Dialog.Root>- );-}--/** The docked variant: a panel in the stage's side slot. Not modal; Escape (handled by the stage) closes it. */-export function StationSidePanel({ title, description, onClose, children }: {- title: string; description?: string; onClose: () => void; children: ReactNode;-}) {- const t = useT();- const headingId = useId();- const panel = useRef<HTMLElement>(null);- // Focus moves into the fresh panel so keyboard and screen-reader users land on it;- // the walking keys keep working because they listen on the window.- useEffect(() => { panel.current?.focus({ preventScroll: true }); }, []);- return (- <aside ref={panel} className="office-card office-panel" data-office-ui aria-labelledby={headingId} tabIndex={-1}>- <header className="flex items-start justify-between gap-3 border-b border-border px-4 py-3">- <div className="grid min-w-0 gap-0.5">- <h2 id={headingId} className="font-display text-base font-semibold">{title}</h2>- {description && <p className="text-xs text-muted-foreground">{description}</p>}- </div>- <button type="button" className={closeButton} onClick={onClose} aria-label={t("society.office.close")}><X size={16} aria-hidden /></button>- </header>- <div className="office-panel-body">{children}</div>- </aside>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/StudioBoard.tsx b/dodaios/ui/web/frontend/src/components/society/office/StudioBoard.tsxdeleted file mode 100644index c712c5de64..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/StudioBoard.tsx+++ /dev/null@@ -1,101 +0,0 @@-/**- * The studio board: every team studio's own wall screen, standing in front of- * its name wall. A slim graphite panel on two steel legs with an oak ledge- * and a warm light bar on top. Its face is a calm paper-white sheet with a- * dot grid; whatever the team is doing is drawn over it by the layer that- * owns the live content, placed with `studioBoardFace` from the layout.- *- * Everything stays inside the `studioBoard` footprint, which navigation walks- * round. All boards share their materials.- *- * The team stand belongs to the same family: the lectern on the free plot- * where a new team is started. A steel post on a foot carries a slanted oak- * panel with a pale sheet, a plus drawn on it and the board's light bar along- * its upper edge. It carries no text; the layer that owns the interaction- * labels it.- */-import { MeshStandardMaterial } from "three";-import { cachedCanvasTexture } from "./canvasMaterials";-import { Box, matte } from "./OfficeFurniture";-import { FURNITURE_SIZE, STUDIO_BOARD_FACE } from "./officeLayout";--const SIZE = FURNITURE_SIZE.studioBoard;-/** The panel behind the face: a bezel round it, and thin enough to leave the face proud of nothing but itself. */-const PANEL = { w: SIZE.w, h: STUDIO_BOARD_FACE.h + 0.18, d: 0.1 } as const;-/** The resting face is the board's face plane; live content is drawn a few millimetres in front of it. */-const REST_FACE_Z = STUDIO_BOARD_FACE.z;--const BOARD_MAT = {- panel: matte("#2a2d33", { roughness: 0.55 }),- leg: matte("#1f2226", { roughness: 0.4, metalness: 0.5 }),- ledge: matte("#d9bf97", { roughness: 0.6 }),- light: new MeshStandardMaterial({ color: "#fff0d8", emissive: "#fff0d8", emissiveIntensity: 1.3, toneMapped: false }),-};--let restFace: MeshStandardMaterial | null = null;-/** Paper-white with a fine dot grid, lit a little from within so it reads as a screen at rest. */-function restFaceMaterial(): MeshStandardMaterial {- if (!restFace) {- const map = cachedCanvasTexture("studio-board:rest", 432, 232, (ctx, w, h) => {- ctx.fillStyle = "#f6f3ec";- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "rgba(60,56,50,0.16)";- for (let y = 12; y < h; y += 20) for (let x = 12; x < w; x += 20) ctx.fillRect(x, y, 2, 2);- });- restFace = new MeshStandardMaterial({- color: map ? "#ffffff" : "#f6f3ec", map, roughness: 0.9,- ...(map ? { emissive: "#ffffff", emissiveMap: map, emissiveIntensity: 0.18 } : {}),- });- }- return restFace;-}--/** One studio board, in its own frame: origin on the floor under its centre, face towards +z. */-function StudioBoard() {- const panelY = STUDIO_BOARD_FACE.y;- const panelBottom = panelY - PANEL.h / 2;- return (- <group>- {[-SIZE.w / 2 + 0.22, SIZE.w / 2 - 0.22].map((x) => (- <Box key={x} size={[0.05, panelBottom, 0.05]} position={[x, panelBottom / 2, -0.02]} material={BOARD_MAT.leg} />- ))}- <Box size={[PANEL.w, PANEL.h, PANEL.d]} position={[0, panelY, 0]} material={BOARD_MAT.panel} />- <mesh position={[0, panelY, REST_FACE_Z]} material={restFaceMaterial()}>- <planeGeometry args={[STUDIO_BOARD_FACE.w, STUDIO_BOARD_FACE.h]} />- </mesh>- {/* The ledge for pens, and the light bar washing the face from above. */}- <Box size={[1.5, 0.03, 0.075]} position={[0, panelBottom - 0.015, 0.035]} material={BOARD_MAT.ledge} cast={false} />- <Box size={[PANEL.w - 0.16, 0.025, 0.05]} position={[0, panelY + PANEL.h / 2 + 0.0125, 0.045]} material={BOARD_MAT.light} cast={false} />- </group>- );-}--/** The slanted panel of the team stand: its size, its slope from the horizontal and its middle's height. */-const STAND = { w: 0.74, d: 0.42, t: 0.03, slope: 0.6, y: 1.04 } as const;-const STAND_MAT = {- sheet: matte("#f6f3ec", { roughness: 0.9 }),- ink: matte("#2b2926", { roughness: 0.8 }),-};--/** The team stand, in its own frame: origin on the floor under its middle, its face towards +z and up. */-function TeamStand() {- return (- <group>- <Box size={[0.46, 0.03, 0.4]} position={[0, 0.015, 0]} material={BOARD_MAT.leg} cast={false} />- <Box size={[0.06, STAND.y - 0.03, 0.06]} position={[0, (STAND.y + 0.03) / 2, -0.03]} material={BOARD_MAT.leg} />- <group position={[0, STAND.y, 0]} rotation={[STAND.slope, 0, 0]}>- <Box size={[STAND.w, STAND.t, STAND.d]} position={[0, 0, 0]} material={BOARD_MAT.ledge} />- <Box size={[STAND.w - 0.1, 0.006, STAND.d - 0.1]} position={[0, STAND.t / 2 + 0.003, 0.01]} material={STAND_MAT.sheet} cast={false} />- {/* The plus: start something here. */}- <Box size={[0.2, 0.006, 0.045]} position={[0, STAND.t / 2 + 0.008, 0.01]} material={STAND_MAT.ink} cast={false} />- <Box size={[0.045, 0.006, 0.2]} position={[0, STAND.t / 2 + 0.008, 0.01]} material={STAND_MAT.ink} cast={false} />- <Box size={[STAND.w - 0.06, 0.018, 0.022]} position={[0, STAND.t / 2 + 0.009, -STAND.d / 2 + 0.02]} material={BOARD_MAT.light} cast={false} />- </group>- </group>- );-}--export const STUDIO_RENDERERS = {- studioBoard: () => <StudioBoard />,- teamStand: () => <TeamStand />,-};diff --git a/dodaios/ui/web/frontend/src/components/society/office/StudioBoards.tsx b/dodaios/ui/web/frontend/src/components/society/office/StudioBoards.tsxdeleted file mode 100644index 89f716ac4f..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/StudioBoards.tsx+++ /dev/null@@ -1,119 +0,0 @@-/**- * The live face of every studio board: team name, members with their real- * run state, the newest lines of the team's chat (studioBoardContent.ts).- *- * A face is a canvas texture, created the first time the camera comes close- * and redrawn only when what it shows changed. Only the few boards nearest- * the camera count as live: they are the ones whose transcript is refreshed- * (useTeamRounds reads `boardWatch`). The faces take no pointer events; the- * board's station does.- */-import { useEffect, useMemo, useRef, useState } from "react";-import { useFrame } from "@react-three/fiber";-import { CanvasTexture, SRGBColorSpace } from "three";-import { useT } from "@/i18n";-import type { SocietyAgent } from "../data";-import { studioBoardFace, type OfficeLayout, type Studio } from "./officeLayout";-import { studiosOf } from "./officeTeams";-import { BOARD_CANVAS, BOARD_LIFT_M, boardModel, boardSignature, drawStudioBoard, pickBoards, type BoardLabels } from "./studioBoardContent";-import { boardWatch, useTeamwork } from "./teamwork";--const CHECK_EVERY_S = 0.4;--function useBoardLabels(): BoardLabels {- const t = useT();- return useMemo(() => ({- pool: t("society.office.studio_pool"),- members: t("society.office.team_members"),- live: t("society.office.team_live"),- speaking: t("society.office.board_speaking"),- you: t("society.office.you"),- empty: t("society.office.board_empty"),- poolNote: t("society.office.board_pool_note"),- loading: t("society.office.board_loading"),- unavailable: t("society.office.board_unavailable"),- lead: t("society.office.team_lead"),- more: t("society.office.board_more"),- state: {- working: t("society.office.state_working"), waiting: t("society.office.state_waiting"),- idle: t("society.office.state_idle"), paused: t("society.office.state_paused"),- },- }), [t]);-}--function BoardFace({ studio, agents, labels, active }: {- studio: Studio; agents: ReadonlyMap<string, SocietyAgent>; labels: BoardLabels; active: boolean;-}) {- const board = studio.board;- const round = useTeamwork((s) => (studio.teamId ? s.rounds[studio.teamId] : undefined));- // The canvas exists from the first time the camera came close; a board never seen costs nothing.- const [seen, setSeen] = useState(active);- useEffect(() => { if (active) setSeen(true); }, [active]);- const surface = useMemo(() => {- if (!seen || typeof document === "undefined") return null;- const canvas = document.createElement("canvas");- const ctx = canvas.getContext("2d");- if (!ctx) return null;- canvas.width = BOARD_CANVAS.w; canvas.height = BOARD_CANVAS.h;- const texture = new CanvasTexture(canvas);- texture.colorSpace = SRGBColorSpace;- texture.anisotropy = 4;- return { ctx, texture };- }, [seen]);- useEffect(() => () => surface?.texture.dispose(), [surface]);- const model = useMemo(() => boardModel(studio, agents, round, labels), [studio, agents, round, labels]);- const signature = boardSignature(model, labels);- const drawnSignature = useRef("");- useEffect(() => {- // A board out of sight keeps its last face; it catches up when the camera returns.- if (!surface || !active || drawnSignature.current === signature) return;- drawnSignature.current = signature;- drawStudioBoard(surface.ctx, model, labels);- surface.texture.needsUpdate = true;- // `signature` covers the model and the labels.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [surface, active, signature]);- if (!board || !surface) return null;- // The same sheet the board shows at rest, a hair in front of it and lit the same way, so the writing simply appears on it.- const face = studioBoardFace(board);- const nx = Math.sin(face.rotationY), nz = Math.cos(face.rotationY);- return (- <mesh position={[face.position[0] + nx * BOARD_LIFT_M, face.position[1], face.position[2] + nz * BOARD_LIFT_M]}- rotation={[0, face.rotationY, 0]} raycast={() => null} userData={{ studioBoard: board.id }}>- <planeGeometry args={face.size} />- <meshStandardMaterial map={surface.texture} roughness={0.9} emissive="#ffffff" emissiveMap={surface.texture} emissiveIntensity={0.18} />- </mesh>- );-}--export function StudioBoards({ layout, agents, awake }: { layout: OfficeLayout; agents: ReadonlyMap<string, SocietyAgent>; awake: boolean }) {- const labels = useBoardLabels();- // This floor's own entry among the watched boards; another floor awake at the same time has its own.- const stage = useMemo(() => Symbol("studio-boards"), []);- const studios = useMemo(() => studiosOf(layout).filter((s) => s.board !== null), [layout]);- const [drawn, setDrawn] = useState<ReadonlySet<string>>(new Set());- const nextCheck = useRef(0);- useFrame(({ camera, clock }) => {- if (clock.elapsedTime < nextCheck.current) return;- nextCheck.current = clock.elapsedTime + CHECK_EVERY_S;- const picked = pickBoards(studios.map((s) => ({- id: s.board!.id, teamId: s.teamId,- distance: Math.hypot(camera.position.x - s.board!.x, camera.position.y - 1.2, camera.position.z - s.board!.z),- })));- boardWatch.set(stage, picked.live);- if (picked.drawn.size !== drawn.size || [...picked.drawn].some((id) => !drawn.has(id))) setDrawn(picked.drawn);- });- // Asleep or gone, this floor watches no board; what another floor watches is its own business.- useEffect(() => {- if (!awake) boardWatch.clear(stage);- return () => boardWatch.clear(stage);- }, [awake, stage]);- if (studios.length === 0) return null;- return (- <group>- {studios.map((studio) => (- <BoardFace key={studio.board!.id} studio={studio} agents={agents} labels={labels} active={drawn.has(studio.board!.id)} />- ))}- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/TeamBoardFace.tsx b/dodaios/ui/web/frontend/src/components/society/office/TeamBoardFace.tsxdeleted file mode 100644index 75849fca7e..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/TeamBoardFace.tsx+++ /dev/null@@ -1,120 +0,0 @@-/**- * The team room's whiteboard shows the real teams: up to four names with their- * member counts. A team whose round is answering right now (the backend's- * word, through teamwork's rounds) wears the green "Live" mark; a team the- * person merely called to the table or to its board wears a plain "Called"- * one — a gathering on the map is not a round. Without any team the board- * keeps its drawn org chart.- */-import { useEffect, useMemo } from "react";-import { CanvasTexture, SRGBColorSpace } from "three";-import { useT } from "@/i18n";-import { useSocietyChatGroups, type SocietyChatGroup } from "@/lib/societyChatGroups";-import type { Furniture } from "./officeLayout";-import { useOfficeStore } from "./officeStore";-import { teamMark, type TeamMark } from "./teamStatus";-import { useTeamwork } from "./teamwork";--const W = 1024, H = 478;-/** Board face in the teamBoard prop's local space (OfficeProps `TeamBoard`), a hair in front of the drawn panel. */-const FACE = { y: 1.25, z: -0.011, w: 2.4, h: 1.12 };-const MAX_ROWS = 4;-const NOTE_COLOURS = ["#fde68a", "#bbf7d0", "#bfdbfe", "#fbcfe8"];--function clipped(ctx: CanvasRenderingContext2D, text: string, maxWidth: number): string {- if (ctx.measureText(text).width <= maxWidth) return text;- let cut = text;- while (cut.length > 1 && ctx.measureText(`${cut}…`).width > maxWidth) cut = cut.slice(0, -1);- return `${cut}…`;-}--function drawBoard(ctx: CanvasRenderingContext2D, teams: SocietyChatGroup[], marks: Record<string, TeamMark>, labels: { title: string; members: string; live: string; called: string }) {- ctx.fillStyle = "#f4f4f0";- ctx.fillRect(0, 0, W, H);- ctx.fillStyle = "#2f3645";- ctx.font = "700 52px system-ui, sans-serif";- ctx.textBaseline = "middle";- ctx.fillText(clipped(ctx, labels.title, W - 100), 50, 58);- ctx.strokeStyle = "#3b4250";- ctx.lineWidth = 5;- ctx.lineCap = "round";- ctx.beginPath(); ctx.moveTo(50, 100); ctx.lineTo(W - 50, 100); ctx.stroke();- const rows = teams.slice(0, MAX_ROWS);- const rowH = (H - 130) / MAX_ROWS;- rows.forEach((team, i) => {- const y = 125 + i * rowH + rowH / 2 - 6;- const mark = marks[team.group_id] ?? null;- ctx.fillStyle = NOTE_COLOURS[i % NOTE_COLOURS.length];- ctx.fillRect(50, y - rowH / 2 + 10, 26, rowH - 20);- const count = labels.members.replace("{0}", String(team.members.length));- ctx.font = "500 32px system-ui, sans-serif";- const countW = ctx.measureText(count).width;- const liveW = mark ? 150 : 0;- ctx.fillStyle = "#1f2430";- ctx.font = "600 40px system-ui, sans-serif";- ctx.fillText(clipped(ctx, team.name, W - 190 - countW - liveW), 100, y);- ctx.font = "500 32px system-ui, sans-serif";- ctx.fillStyle = "#5b6475";- ctx.fillText(count, W - 50 - countW - liveW, y);- if (mark === "live") {- ctx.fillStyle = "#2f9e5b";- ctx.beginPath(); ctx.roundRect(W - 180, y - 24, 130, 48, 24); ctx.fill();- ctx.fillStyle = "#ffffff";- ctx.font = "700 28px system-ui, sans-serif";- ctx.fillText(clipped(ctx, labels.live, 100), W - 162, y + 1);- } else if (mark === "called") {- // An outlined, colourless mark: the team was asked to gather, nothing more.- ctx.strokeStyle = "#5b6475";- ctx.lineWidth = 3;- ctx.beginPath(); ctx.roundRect(W - 180, y - 24, 130, 48, 24); ctx.stroke();- ctx.fillStyle = "#3b4250";- ctx.font = "600 26px system-ui, sans-serif";- ctx.fillText(clipped(ctx, labels.called, 104), W - 166, y + 1);- }- });-}--export function TeamBoardFace({ board, enabled }: { board: Furniture; enabled: boolean }) {- const t = useT();- const groups = useSocietyChatGroups(enabled);- const gathering = useOfficeStore((s) => s.meeting);- const rounds = useTeamwork((s) => s.rounds);- const canvas = useMemo(() => {- const el = typeof document === "undefined" ? null : document.createElement("canvas");- if (el) { el.width = W; el.height = H; }- return el;- }, []);- const texture = useMemo(() => {- if (!canvas) return null;- const tex = new CanvasTexture(canvas);- tex.colorSpace = SRGBColorSpace;- tex.anisotropy = 4;- return tex;- }, [canvas]);- useEffect(() => () => texture?.dispose(), [texture]);- const teams = useMemo(() => [...(groups.data ?? [])].sort((a, b) => b.updated_ms - a.updated_ms), [groups.data]);- const labels = {- title: t("society.office.team_yours"), members: t("society.office.team_members"),- live: t("society.office.team_live"), called: t("society.office.team_called"),- };- const now = Date.now();- const marks = Object.fromEntries(teams.map((g) => [g.group_id, teamMark(g.group_id, rounds, gathering, now)]));- const signature = JSON.stringify([teams.map((g) => [g.group_id, g.name, g.members.length]), marks, labels]);- useEffect(() => {- const ctx = canvas?.getContext("2d");- if (!ctx || !texture) return;- drawBoard(ctx, teams, marks, labels);- texture.needsUpdate = true;- // `signature` covers teams, marks and labels.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [signature, canvas, texture]);- if (!texture || teams.length === 0) return null;- return (- <group position={[board.x, 0, board.z]} rotation={[0, board.rotationY, 0]}>- <mesh position={[0, FACE.y, FACE.z]}>- <planeGeometry args={[FACE.w, FACE.h]} />- <meshStandardMaterial map={texture} roughness={0.7} />- </mesh>- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/TeamRoomDecor.tsx b/dodaios/ui/web/frontend/src/components/society/office/TeamRoomDecor.tsxdeleted file mode 100644index 976399ae15..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/TeamRoomDecor.tsx+++ /dev/null@@ -1,610 +0,0 @@-/**- * The team room as a meeting room people like walking into: a solid walnut- * table with a cable-tray spine and an inset power rail, a walnut slat wall- * carrying the live team board, a video-conference display and felt panels,- * a travertine-topped credenza with books, fiddle-leaf figs in clay planters,- * a wool rug, and a pair of linear pendants that pool warm light on the table.- *- * Same rules as OfficeProps: every furniture piece is built in local space- * centred on the origin, front facing +z, inside its `FURNITURE_SIZE` box.- * Repeated parts (slats, leaves) are merged into one geometry per material,- * and canvas faces are drawn once and shared.- */-import { memo } from "react";-import {- BoxGeometry, BufferGeometry, CylinderGeometry, DoubleSide, Euler, Matrix4, MeshStandardMaterial, Quaternion, SphereGeometry, Vector3,-} from "three";-import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";-import { canvasMaterial } from "./canvasMaterials";-import { Box, GEO, MAT, matte, Rounded } from "./OfficeFurniture";-import { FURNITURE_SIZE, type Furniture, type FurnitureKind, type Room } from "./officeLayout";--type Vec3 = [number, number, number];--// ----------------------------------------------------------------------------// Materials: warm walnut, travertine, clay, sage and oat, soft warm light.-// -----------------------------------------------------------------------------const C = {- // The campus's oak: the keys keep the names the room was built with.- walnut: "#b99a72",- walnutDark: "#8e7252",- walnutLight: "#d2b68c",- travertine: "#e8dfd0",- clay: "#c4775a",- sage: "#8d9f86",- oat: "#ddd0ba",- cream: "#f1ebe1",- terracotta: "#b56a4c",- led: "#ffe2bd",-} as const;--const TM = {- walnut: matte(C.walnut, { roughness: 0.55 }),- walnutDark: matte(C.walnutDark, { roughness: 0.6 }),- walnutLight: matte(C.walnutLight, { roughness: 0.55 }),- travertine: matte(C.travertine, { roughness: 0.45 }),- alu: matte("#c3c7cc", { roughness: 0.35, metalness: 0.5 }),- brass: matte("#b08d5c", { roughness: 0.35, metalness: 0.6 }),- ceramic: matte(C.cream, { roughness: 0.4 }),- clay: matte(C.clay, { roughness: 0.8 }),- terracotta: matte(C.terracotta, { roughness: 0.75 }),- soil: matte("#3b2f26"),- trunk: matte("#6b5440"),- // Light strips: lit from within, so they read as light in any scene lighting.- led: new MeshStandardMaterial({ color: C.led, emissive: C.led, emissiveIntensity: 1.2, toneMapped: false }),- lens: matte("#0c0d10", { roughness: 0.15, metalness: 0.3 }),- glass: new MeshStandardMaterial({ color: "#e4f1f4", transparent: true, opacity: 0.35, roughness: 0.05, depthWrite: false }),- water: new MeshStandardMaterial({ color: "#bfe0ea", transparent: true, opacity: 0.55, roughness: 0.1, depthWrite: false }),- frosted: new MeshStandardMaterial({ color: "#f5f7f8", transparent: true, opacity: 0.55, roughness: 0.9, side: DoubleSide, depthWrite: false }),- frostedLine: new MeshStandardMaterial({ color: "#ffffff", transparent: true, opacity: 0.8, roughness: 0.9, side: DoubleSide, depthWrite: false }),- leaves: ["#3f7a45", "#2e5e37", "#5d9a58"].map((c) => matte(c, { flatShading: true, roughness: 0.7 })),- books: ["#c4775a", "#e9dcc4", "#51705c", "#2f3d56", "#d9a441", "#8b6246", "#7c8fa8"].map((c) => matte(c)),-};--// ----------------------------------------------------------------------------// Canvas faces-// -----------------------------------------------------------------------------type Ctx = CanvasRenderingContext2D;--/** Deterministic pseudo-random numbers, so drawn patterns never change between loads. */-function lcg(seed: number): () => number {- let state = seed >>> 0;- return () => {- state = (state * 1664525 + 1013904223) >>> 0;- return state / 0x1_0000_0000;- };-}--/** Team board without any team yet: an org chart on the left, sticky notes on the right. */-function drawTeamBoard(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#fbfbf8";- ctx.fillRect(0, 0, w, h);- // Org chart: one box on top, three below, joined by marker lines.- const node = (x: number, y: number, colour: string) => {- ctx.fillStyle = colour;- ctx.beginPath(); ctx.roundRect(x - 62, y - 26, 124, 52, 10); ctx.fill();- ctx.fillStyle = "rgba(255,255,255,0.85)";- ctx.fillRect(x - 40, y - 5, 80, 10);- };- ctx.strokeStyle = "#3b4250";- ctx.lineWidth = 5;- ctx.lineCap = "round";- ctx.beginPath();- ctx.moveTo(250, 120); ctx.lineTo(250, 200);- ctx.moveTo(90, 200); ctx.lineTo(410, 200);- for (const x of [90, 250, 410]) { ctx.moveTo(x, 200); ctx.lineTo(x, 262); }- ctx.stroke();- node(250, 100, "#4f7cac");- node(90, 288, "#5e9c76");- node(250, 288, "#c8553d");- node(410, 288, "#8d6cab");- // Marker scribbles under the chart.- ctx.strokeStyle = "#6b7280";- ctx.lineWidth = 4;- for (let i = 0; i < 3; i += 1) {- ctx.beginPath();- ctx.moveTo(40, 380 + i * 30);- ctx.lineTo(40 + 180 + ((i * 70) % 160), 380 + i * 30);- ctx.stroke();- }- // Sticky notes, slightly askew.- const notes = ["#fde68a", "#fbcfe8", "#bbf7d0", "#bfdbfe", "#fed7aa", "#fde68a"];- notes.forEach((colour, i) => {- const col = i % 3, row = Math.floor(i / 3);- ctx.save();- ctx.translate(620 + col * 135, 110 + row * 170);- ctx.rotate(((i * 37) % 9 - 4) * 0.02);- ctx.fillStyle = "rgba(0,0,0,0.12)";- ctx.fillRect(-52, -48, 110, 110);- ctx.fillStyle = colour;- ctx.fillRect(-55, -55, 110, 110);- ctx.fillStyle = "rgba(60,60,70,0.55)";- for (let line = 0; line < 3; line += 1) ctx.fillRect(-40, -30 + line * 22, 50 + ((i + line) * 17) % 30, 6);- ctx.restore();- });-}--/** Acoustic felt with vertical fluting in one colour. */-function drawFelt(colour: string) {- return (ctx: Ctx, w: number, h: number) => {- ctx.fillStyle = colour;- ctx.fillRect(0, 0, w, h);- for (let x = 0; x < w; x += 16) {- ctx.fillStyle = "rgba(0,0,0,0.16)";- ctx.fillRect(x, 0, 3, h);- ctx.fillStyle = "rgba(255,255,255,0.08)";- ctx.fillRect(x + 6, 0, 4, h);- }- };-}--/** A felt pinboard full of sticky notes with marker scribbles. */-function drawPinboard(ctx: Ctx, w: number, h: number): void {- const rand = lcg(4242);- ctx.fillStyle = C.oat;- ctx.fillRect(0, 0, w, h);- for (let i = 0; i < 900; i += 1) {- ctx.fillStyle = rand() > 0.5 ? "rgba(255,255,255,0.12)" : "rgba(90,70,50,0.08)";- ctx.fillRect(rand() * w, rand() * h, 2, 2);- }- const notes = ["#fde68a", "#fbcfe8", "#bbf7d0", "#bfdbfe", "#fed7aa"];- const cols = 2, rows = 4, cw = w / cols, ch = h / rows;- for (let r = 0; r < rows; r += 1) {- for (let c = 0; c < cols; c += 1) {- if ((r * cols + c) % 5 === 3) continue;- const size = 78 + rand() * 12;- ctx.save();- ctx.translate(c * cw + cw / 2 + (rand() - 0.5) * 16, r * ch + ch / 2 + (rand() - 0.5) * 16);- ctx.rotate((rand() - 0.5) * 0.18);- ctx.fillStyle = "rgba(60,40,20,0.18)";- ctx.fillRect(-size / 2 + 3, -size / 2 + 4, size, size);- ctx.fillStyle = notes[(r * cols + c) % notes.length];- ctx.fillRect(-size / 2, -size / 2, size, size);- ctx.strokeStyle = "#3b4250";- ctx.lineWidth = 3;- ctx.lineCap = "round";- for (let l = 0; l < 3; l += 1) {- ctx.beginPath();- ctx.moveTo(-size / 2 + 12, -size / 2 + 22 + l * 18);- ctx.lineTo(-size / 2 + 12 + (size - 30) * (0.5 + rand() * 0.5), -size / 2 + 22 + l * 18);- ctx.stroke();- }- ctx.fillStyle = "#b8412f";- ctx.beginPath(); ctx.arc(0, -size / 2 + 7, 4, 0, Math.PI * 2); ctx.fill();- ctx.restore();- }- }-}--/** A video call in progress: six participants in a grid, the speaker ringed in green, the call controls below. */-function drawCall(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#101216";- ctx.fillRect(0, 0, w, h);- const tiles = [- ["#3a4a5c", "#e0b48a", "#2d3440"], ["#5c4a3a", "#c98f6f", "#403428"], ["#3f5446", "#f0c9a4", "#2b3a30"],- ["#4b3f5c", "#a8745a", "#312a3e"], ["#5a5446", "#e8c29c", "#3c382e"], ["#3a5058", "#8d5a44", "#28383e"],- ];- const pad = 14, bar = 62, cols = 3, rows = 2;- const tw = (w - pad * (cols + 1)) / cols;- const th = (h - bar - pad * (rows + 1)) / rows;- tiles.forEach(([bg, skin, shirt], i) => {- const x = pad + (i % cols) * (tw + pad);- const y = pad + Math.floor(i / cols) * (th + pad);- const grad = ctx.createLinearGradient(x, y, x, y + th);- grad.addColorStop(0, bg);- grad.addColorStop(1, "#15181d");- ctx.fillStyle = grad;- ctx.beginPath(); ctx.roundRect(x, y, tw, th, 12); ctx.fill();- ctx.save();- ctx.beginPath(); ctx.roundRect(x, y, tw, th, 12); ctx.clip();- const cx = x + tw / 2;- ctx.fillStyle = shirt;- ctx.beginPath(); ctx.ellipse(cx, y + th + 10, tw * 0.28, th * 0.38, 0, 0, Math.PI * 2); ctx.fill();- ctx.fillStyle = skin;- ctx.beginPath(); ctx.arc(cx, y + th * 0.46, th * 0.17, 0, Math.PI * 2); ctx.fill();- ctx.restore();- ctx.fillStyle = "rgba(0,0,0,0.45)";- ctx.beginPath(); ctx.roundRect(x + 10, y + th - 30, 70 + (i % 3) * 18, 20, 10); ctx.fill();- if (i === 1) {- ctx.strokeStyle = "#4ade80";- ctx.lineWidth = 5;- ctx.beginPath(); ctx.roundRect(x + 2.5, y + 2.5, tw - 5, th - 5, 11); ctx.stroke();- }- });- const by = h - bar / 2 - 4;- [-96, -32, 32].forEach((dx) => {- ctx.fillStyle = "#2b2f36";- ctx.beginPath(); ctx.arc(w / 2 + dx, by, 20, 0, Math.PI * 2); ctx.fill();- ctx.fillStyle = "#c9ced6";- ctx.beginPath(); ctx.arc(w / 2 + dx, by, 6, 0, Math.PI * 2); ctx.fill();- });- ctx.fillStyle = "#e5484d";- ctx.beginPath(); ctx.roundRect(w / 2 + 64, by - 20, 64, 40, 20); ctx.fill();-}--/** A calm laptop screen: a sidebar and a few lines of a document. */-function drawLaptop(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#eef0f2";- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = "#d9dde2";- ctx.fillRect(0, 0, w * 0.26, h);- ctx.fillStyle = "#b9c0c8";- for (let i = 0; i < 5; i += 1) ctx.fillRect(w * 0.34, 14 + i * 12, w * (0.5 - (i % 2) * 0.15), 5);- ctx.fillStyle = C.clay;- ctx.fillRect(w * 0.34, h - 20, 26, 8);-}--/** Walnut door front with vertical fluting and a darker rim. */-function drawFluting(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = C.walnutLight;- ctx.fillRect(0, 0, w, h);- for (let x = 4; x < w; x += 10) {- ctx.fillStyle = "rgba(30,18,10,0.28)";- ctx.fillRect(x, 0, 2, h);- ctx.fillStyle = "rgba(255,230,200,0.08)";- ctx.fillRect(x + 3, 0, 3, h);- }- ctx.strokeStyle = "rgba(30,18,10,0.55)";- ctx.lineWidth = 4;- ctx.strokeRect(0, 0, w, h);-}--/** An abstract print: a clay sun over a sage hill on cream paper. */-function drawPrint(ctx: Ctx, w: number, h: number): void {- ctx.fillStyle = "#f4efe6";- ctx.fillRect(0, 0, w, h);- ctx.fillStyle = C.clay;- ctx.beginPath(); ctx.arc(w * 0.58, h * 0.4, w * 0.22, 0, Math.PI * 2); ctx.fill();- ctx.fillStyle = C.sage;- ctx.beginPath(); ctx.ellipse(w * 0.35, h * 0.95, w * 0.6, h * 0.35, 0, 0, Math.PI * 2); ctx.fill();- ctx.strokeStyle = "#2f3d56";- ctx.lineWidth = 3;- ctx.beginPath(); ctx.moveTo(w * 0.12, h * 0.2); ctx.lineTo(w * 0.4, h * 0.2); ctx.stroke();-}--/** Oat wool rug: a soft weave, a clay border band and a fine charcoal line. */-function drawRug(ctx: Ctx, w: number, h: number): void {- const rand = lcg(777);- ctx.fillStyle = "#e6dccb";- ctx.fillRect(0, 0, w, h);- for (let i = 0; i < 6000; i += 1) {- ctx.fillStyle = rand() > 0.5 ? "rgba(255,255,255,0.16)" : "rgba(120,96,70,0.09)";- ctx.fillRect(rand() * w, rand() * h, 2, 2);- }- // A faint diamond lattice across the field.- ctx.strokeStyle = "rgba(150,120,90,0.14)";- ctx.lineWidth = 2;- for (let x = -h; x < w + h; x += 48) {- ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x + h, h); ctx.stroke();- ctx.beginPath(); ctx.moveTo(x + h, 0); ctx.lineTo(x, h); ctx.stroke();- }- ctx.strokeStyle = C.clay;- ctx.lineWidth = 16;- ctx.strokeRect(22, 22, w - 44, h - 44);- ctx.strokeStyle = "#3a3632";- ctx.lineWidth = 3;- ctx.strokeRect(44, 44, w - 88, h - 88);- ctx.strokeStyle = "#e6dccb";- ctx.lineWidth = 12;- ctx.strokeRect(6, 6, w - 12, h - 12);-}--const faces = {- board: () => canvasMaterial("prop:teamBoard", 1024, 478, drawTeamBoard, { fallback: "#fbfbf8", roughness: 0.5 }),- feltClay: () => canvasMaterial("team:felt-clay", 128, 256, drawFelt(C.clay), { fallback: C.clay, roughness: 1 }),- feltSage: () => canvasMaterial("team:felt-sage", 128, 256, drawFelt(C.sage), { fallback: C.sage, roughness: 1 }),- pinboard: () => canvasMaterial("team:pinboard", 256, 512, drawPinboard, { fallback: C.oat, roughness: 0.95 }),- call: () => canvasMaterial("team:call", 1024, 576, drawCall, { glow: 0.9, fallback: "#1b2230", roughness: 0.35 }),- laptop: () => canvasMaterial("team:laptop", 160, 100, drawLaptop, { glow: 0.55, fallback: "#dde2e8", roughness: 0.4 }),- fluting: () => canvasMaterial("team:fluting", 128, 128, drawFluting, { fallback: C.walnutLight, roughness: 0.6 }),- print: () => canvasMaterial("team:print", 128, 160, drawPrint, { fallback: "#f4efe6", roughness: 0.8 }),- rug: () => canvasMaterial("team:rug", 512, 384, drawRug, { fallback: "#e6dccb", roughness: 1 }),-};--// ----------------------------------------------------------------------------// Shared geometry-// -----------------------------------------------------------------------------const TGEO = {- cyl: new CylinderGeometry(1, 1, 1, 20),- sphere: new SphereGeometry(1, 16, 12),- planter: new CylinderGeometry(0.27, 0.2, 0.52, 28),- vase: new CylinderGeometry(0.045, 0.07, 0.24, 20),-};--function Cyl({ radius, height, position, material, rotation, cast = true }: {- radius: number; height: number; position: Vec3; material: MeshStandardMaterial; rotation?: Vec3; cast?: boolean;-}) {- return <mesh geometry={TGEO.cyl} material={material} position={position} rotation={rotation} scale={[radius, height, radius]} castShadow={cast} receiveShadow />;-}--function Panel({ size, position, material, rotation }: { size: [number, number]; position: Vec3; material: MeshStandardMaterial; rotation?: Vec3 }) {- return <mesh position={position} rotation={rotation} material={material}><planeGeometry args={size} /></mesh>;-}--/** The slat wall's walnut slats, merged into one geometry: one draw call for 80 slats. */-const WALL = { w: FURNITURE_SIZE.teamWall.w, pitch: 0.1 };-const SLAT_GEOMETRY = (() => {- const count = Math.floor((WALL.w - 0.1) / WALL.pitch);- const parts = Array.from({ length: count }, (_, i) =>- new BoxGeometry(0.045, 1.9, 0.035).translate(-((count - 1) * WALL.pitch) / 2 + i * WALL.pitch, 1.03, -0.0175));- const merged = mergeGeometries(parts, false);- parts.forEach((p) => p.dispose());- return merged;-})();--/**- * A fiddle-leaf fig's leaves, spiralling up the stem on the golden angle and- * lifting towards the top; merged per leaf tone, three draw calls a plant.- */-const LEAF_GEOMETRIES: BufferGeometry[] = (() => {- const base = new SphereGeometry(1, 10, 6);- const tones: BufferGeometry[][] = [[], [], []];- const matrix = new Matrix4(), rotation = new Quaternion(), euler = new Euler(0, 0, 0, "YXZ");- const at = new Vector3(), scale = new Vector3();- const count = 38;- for (let i = 0; i < count; i += 1) {- const t = i / (count - 1);- const angle = i * 2.39996;- const half = 0.125 - 0.035 * t;- const radius = 0.05 + 0.09 * Math.sin(Math.PI * (0.2 + t * 0.7));- const lift = -0.2 + 0.75 * t;- const reach = radius + half * Math.cos(lift);- at.set(Math.sin(angle) * reach, 0.98 + t * 0.9 + half * Math.sin(lift), Math.cos(angle) * reach);- euler.set(-lift, angle, ((i % 3) - 1) * 0.35);- rotation.setFromEuler(euler);- scale.set(half * 0.72, 0.012, half);- matrix.compose(at, rotation, scale);- tones[i % 3].push(base.clone().applyMatrix4(matrix));- }- base.dispose();- return tones.map((parts) => {- const merged = mergeGeometries(parts, false);- parts.forEach((p) => p.dispose());- return merged;- });-})();--// ----------------------------------------------------------------------------// Furniture-// -----------------------------------------------------------------------------/** An open laptop; the hinge is on its -z side and the screen faces +z. */-function Laptop({ position, rotationY = 0 }: { position: Vec3; rotationY?: number }) {- return (- <group position={position} rotation={[0, rotationY, 0]}>- <Box size={[0.32, 0.012, 0.22]} position={[0, 0.006, 0]} material={TM.alu} />- <Box size={[0.26, 0.002, 0.09]} position={[0, 0.013, 0.02]} material={MAT.keyboard} cast={false} />- <group position={[0, 0.012, -0.108]} rotation={[-0.28, 0, 0]}>- <Box size={[0.32, 0.21, 0.008]} position={[0, 0.105, 0]} material={TM.alu} />- <Panel size={[0.3, 0.19]} position={[0, 0.105, 0.0045]} material={faces.laptop()} />- </group>- </group>- );-}--/**- * Solid walnut conference table: a thick top with a flush power rail down the- * middle, a black cable-tray spine under it fed by a riser from the floor, and- * two slab legs on steel shoes. On top: laptops for either side, notebooks, a- * speakerphone puck, a carafe with glasses and a bud vase.- */-function TeamTable() {- return (- <group>- {/* Legs and the cable spine. */}- {[-1.42, 1.42].map((x) => (- <group key={x}>- <Box size={[0.08, 0.68, 1.16]} position={[x, 0.37, 0]} material={TM.walnutDark} />- <Box size={[0.12, 0.03, 1.24]} position={[x, 0.015, 0]} material={MAT.steel} />- </group>- ))}- <Box size={[2.76, 0.07, 0.18]} position={[0, 0.665, 0]} material={MAT.steel} />- <Box size={[0.1, 0.63, 0.1]} position={[0, 0.315, 0]} material={MAT.steel} />- <Box size={[0.3, 0.012, 0.2]} position={[0, 0.006, 0]} material={MAT.steel} cast={false} />- {/* The top and its inset power rail with five sockets. */}- <Rounded size={[3.56, 0.056, 1.52]} radius={0.025} position={[0, 0.732, 0]} material={TM.walnut} />- <Box size={[2.0, 0.004, 0.12]} position={[0, 0.7605, 0]} material={MAT.monitor} cast={false} />- {[-0.8, -0.4, 0, 0.4, 0.8].map((x) => (- <Box key={x} size={[0.09, 0.004, 0.06]} position={[x, 0.7625, 0]} material={TM.alu} cast={false} />- ))}- {/* Laptops face the chairs on either side; notebooks with pens. */}- <Laptop position={[-0.55, 0.76, 0.42]} />- <Laptop position={[0.55, 0.76, -0.42]} rotationY={Math.PI} />- <Box size={[0.22, 0.01, 0.3]} position={[0.62, 0.765, 0.44]} material={MAT.mug} cast={false} />- <Box size={[0.012, 0.008, 0.16]} position={[0.77, 0.775, 0.44]} material={TM.books[3]} cast={false} />- <Box size={[0.22, 0.01, 0.3]} position={[-0.62, 0.765, -0.44]} material={TM.books[1]} cast={false} />- {/* Speakerphone puck with a lit ring. */}- <Cyl radius={0.1} height={0.028} position={[-1.3, 0.774, 0]} material={MAT.monitor} />- <Cyl radius={0.06} height={0.004} position={[-1.3, 0.79, 0]} material={TM.led} cast={false} />- {/* Carafe and two glasses, a bud vase with a sprig. */}- <Cyl radius={0.05} height={0.2} position={[1.25, 0.86, 0.14]} material={TM.glass} cast={false} />- <Cyl radius={0.045} height={0.13} position={[1.25, 0.825, 0.14]} material={TM.water} cast={false} />- <Cyl radius={0.032} height={0.09} position={[1.08, 0.805, -0.12]} material={TM.glass} cast={false} />- <Cyl radius={0.032} height={0.09} position={[1.4, 0.805, -0.14]} material={TM.glass} cast={false} />- <Cyl radius={0.028} height={0.1} position={[0.05, 0.81, 0.24]} material={TM.ceramic} />- <mesh geometry={GEO.blob} material={MAT.leaf} position={[0.05, 0.9, 0.24]} scale={[0.05, 0.05, 0.05]} castShadow />- </group>- );-}--/**- * The team whiteboard, hung on the slat wall: a white face in a thin walnut- * frame, an aluminium marker tray and a picture light washing it from above.- * The face stays where `TeamBoardFace` expects it.- */-function TeamBoard() {- return (- <group>- <Rounded size={[2.52, 1.24, 0.05]} radius={0.015} position={[0, 1.25, -0.04]} material={TM.walnutLight} />- <Panel size={[2.4, 1.12]} position={[0, 1.25, -0.0135]} material={faces.board()} />- <Box size={[1.7, 0.025, 0.07]} position={[0, 0.615, -0.01]} material={TM.alu} />- {[TM.books[0], TM.books[3], TM.books[2]].map((material, i) => (- <Box key={i} size={[0.13, 0.02, 0.02]} position={[-0.25 + i * 0.18, 0.637, 0]} material={material} cast={false} />- ))}- {/* Picture light: two slim arms and a bar with a warm strip underneath. */}- {[-0.6, 0.6].map((x) => <Box key={x} size={[0.015, 0.015, 0.12]} position={[x, 1.9, -0.02]} material={MAT.steel} cast={false} />)}- <Rounded size={[1.6, 0.035, 0.06]} radius={0.012} position={[0, 1.9, 0.05]} material={MAT.steel} />- <Box size={[1.54, 0.006, 0.03]} position={[0, 1.8795, 0.05]} material={TM.led} cast={false} />- </group>- );-}--/**- * The north wall: a walnut slat wall under a warm cove light. West of the- * board three panels — clay felt, a pinboard of sticky notes, sage felt; east- * of it a video-conference display with its camera bar on top.- */-function TeamWall() {- return (- <group>- <Box size={[WALL.w, 1.98, 0.025]} position={[0, 1.01, -0.0475]} material={TM.walnutDark} />- <mesh geometry={SLAT_GEOMETRY} material={TM.walnut} castShadow receiveShadow />- <Box size={[WALL.w, 0.08, 0.1]} position={[0, 0.04, -0.01]} material={TM.walnutDark} />- <Box size={[WALL.w, 0.04, 0.1]} position={[0, 2.0, -0.01]} material={TM.walnutDark} />- <Box size={[WALL.w - 0.16, 0.008, 0.02]} position={[0, 1.976, 0.028]} material={TM.led} cast={false} />- {/* Felt, pinboard, felt. */}- {[faces.feltClay(), faces.pinboard(), faces.feltSage()].map((material, i) => (- <group key={i} position={[-3.44 + i * 0.74, 1.12, 0.012]}>- <Box size={[0.68, 1.36, 0.024]} position={[0, 0, 0]} material={material} />- </group>- ))}- {/* The display and the camera bar. */}- <Rounded size={[2.02, 1.16, 0.035]} radius={0.012} position={[2.7, 1.36, 0.0225]} material={MAT.monitor} />- <Panel size={[1.96, 1.1]} position={[2.7, 1.36, 0.0405]} material={faces.call()} />- <Rounded size={[0.62, 0.055, 0.05]} radius={0.015} position={[2.7, 1.975, 0.035]} material={MAT.monitor} />- <mesh position={[2.7, 1.975, 0.0605]} material={TM.lens}><circleGeometry args={[0.016, 20]} /></mesh>- <mesh position={[2.79, 1.975, 0.0605]} material={TM.led}><circleGeometry args={[0.004, 8]} /></mesh>- </group>- );-}--/**- * Low walnut credenza on black steel legs: four fluted doors with brass pulls- * under a travertine top carrying books, a leaning print, a small clay- * sculpture and a ceramic vase with branches.- */-function Credenza() {- return (- <group>- {[-1.0, 1.0].flatMap((x) => [-0.17, 0.17].map((z) => (- <Box key={`${x}:${z}`} size={[0.03, 0.12, 0.03]} position={[x, 0.06, z]} material={MAT.steel} />- )))}- <Box size={[2.16, 0.46, 0.42]} position={[0, 0.35, -0.01]} material={TM.walnutDark} />- {[-0.81, -0.27, 0.27, 0.81].map((x) => (- <Panel key={x} size={[0.52, 0.42]} position={[x, 0.35, 0.2005]} material={faces.fluting()} />- ))}- {[-0.56, -0.02, 0.02, 0.56].map((x) => <Box key={x} size={[0.012, 0.12, 0.014]} position={[x, 0.4, 0.212]} material={TM.brass} cast={false} />)}- <Box size={[2.2, 0.03, 0.46]} position={[0, 0.595, 0]} material={TM.travertine} />- {/* Books upright between two bookends. */}- {[0.045, 0.035, 0.05, 0.04, 0.038, 0.048].reduce<{ x: number; w: number; h: number; i: number }[]>((acc, w, i) => {- const prev = acc[acc.length - 1];- acc.push({ x: prev ? prev.x + prev.w / 2 + w / 2 + 0.004 : -0.96, w, h: 0.2 + ((i * 5) % 4) * 0.02, i });- return acc;- }, []).map((b) => (- <Box key={b.i} size={[b.w, b.h, 0.17]} position={[b.x, 0.61 + b.h / 2, -0.02]} material={TM.books[b.i % TM.books.length]} />- ))}- <Box size={[0.012, 0.14, 0.12]} position={[-0.992, 0.68, -0.02]} material={MAT.steel} />- <Box size={[0.012, 0.14, 0.12]} position={[-0.68, 0.68, -0.02]} material={MAT.steel} />- {/* A stack of books under a clay sphere. */}- <Box size={[0.28, 0.035, 0.2]} position={[-0.32, 0.6275, 0.02]} material={TM.books[3]} />- <Box size={[0.25, 0.03, 0.18]} position={[-0.31, 0.66, 0.02]} material={TM.books[1]} />- <Box size={[0.23, 0.04, 0.17]} position={[-0.33, 0.695, 0.02]} material={TM.books[0]} />- <mesh geometry={TGEO.sphere} material={TM.clay} position={[-0.32, 0.765, 0.02]} scale={0.05} castShadow />- {/* A print leaning on the wall. */}- <group position={[0.3, 0.61, -0.12]} rotation={[-0.12, 0, 0]}>- <Box size={[0.3, 0.38, 0.02]} position={[0, 0.19, 0]} material={TM.walnutDark} />- <Panel size={[0.25, 0.33]} position={[0, 0.19, 0.0105]} material={faces.print()} />- </group>- {/* Ceramic vase with three branches. */}- <mesh geometry={TGEO.vase} material={TM.ceramic} position={[0.86, 0.73, 0]} castShadow receiveShadow />- {[-0.35, 0.05, 0.4].map((tilt, i) => (- <group key={i} position={[0.86, 0.84, 0]} rotation={[tilt * 0.4, i * 1.2, tilt]}>- <Box size={[0.008, 0.26, 0.008]} position={[0, 0.13, 0]} material={TM.trunk} cast={false} />- <mesh geometry={GEO.blob} material={TM.leaves[i]} position={[0, 0.24, 0]} scale={[0.045, 0.03, 0.045]} castShadow />- <mesh geometry={GEO.blob} material={TM.leaves[(i + 1) % 3]} position={[0, 0.16, 0]} scale={[0.035, 0.022, 0.035]} castShadow />- </group>- ))}- </group>- );-}--/** A fiddle-leaf fig in a tapered clay planter, nearly two metres tall. */-function DesignerPlant() {- return (- <group>- <mesh geometry={TGEO.planter} material={TM.terracotta} position={[0, 0.26, 0]} castShadow receiveShadow />- <Cyl radius={0.275} height={0.03} position={[0, 0.52, 0]} material={TM.terracotta} />- <Cyl radius={0.25} height={0.01} position={[0, 0.531, 0]} material={TM.soil} cast={false} />- <Cyl radius={0.022} height={1.3} position={[0, 1.18, 0]} material={TM.trunk} />- <Cyl radius={0.016} height={0.7} position={[0.06, 1.0, 0.02]} rotation={[0, 0, -0.18]} material={TM.trunk} />- {LEAF_GEOMETRIES.map((geometry, i) => (- <mesh key={i} geometry={geometry} material={TM.leaves[i]} castShadow receiveShadow />- ))}- </group>- );-}--/** A wool rug with a clay border, sized per instance. */-function TeamRug({ w, d }: { w: number; d: number }) {- return <Box size={[w, 0.016, d]} position={[0, 0.008, 0]} material={faces.rug()} cast={false} />;-}--/** Renderers of the team room's furniture kinds; merged into OfficeProps' exhaustive table. */-export const TEAM_RENDERERS = {- meetingTable: () => <TeamTable />,- teamBoard: () => <TeamBoard />,- teamWall: () => <TeamWall />,- credenza: () => <Credenza />,- designerPlant: () => <DesignerPlant />,- teamRug: ({ item }: { item: Furniture }) => {- const size = item.size ?? FURNITURE_SIZE.teamRug;- return <TeamRug w={size.w} d={size.d} />;- },-} satisfies Partial<Record<FurnitureKind, (props: { item: Furniture }) => JSX.Element>>;--// ----------------------------------------------------------------------------// Room fittings: pendants and their light, the frosted band on the glass-// -----------------------------------------------------------------------------/** Height of the frosted band's centre on the glass, and its height. */-const BAND = { y: 1.2, h: 0.46 };--/**- * What hangs in the room rather than stands in it: two linear pendants over- * the table with one warm light between them, and a frosted privacy band on- * the glass front either side of the door.- */-export const TeamRoomFittings = memo(function TeamRoomFittings({ room, table }: { room: Room; table: Furniture }) {- const door = room.doors.find((d) => d.side === "south");- const bands = door- ? [[room.minX, door.at - door.width / 2], [door.at + door.width / 2, room.maxX]]- : [[room.minX, room.maxX]];- return (- <group>- <group position={[table.x, 0, table.z]} rotation={[0, table.rotationY, 0]}>- {[-0.78, 0.78].map((x) => (- <group key={x} position={[x, 0, 0]}>- <Rounded size={[1.3, 0.04, 0.07]} radius={0.015} position={[0, 1.97, 0]} material={MAT.steel} />- <Box size={[1.24, 0.006, 0.045]} position={[0, 1.948, 0]} material={TM.led} cast={false} />- {[-0.55, 0.55].map((cx) => <Box key={cx} size={[0.006, 0.8, 0.006]} position={[cx, 2.39, 0]} material={MAT.steel} cast={false} />)}- </group>- ))}- <pointLight position={[0, 1.8, 0]} color="#ffd9ad" intensity={5} distance={5.5} decay={2} />- </group>- {bands.map(([from, to]) => {- const length = to - from - 0.08;- if (length <= 0) return null;- const x = (from + to) / 2;- return (- <group key={from} position={[x, 0, room.maxZ]}>- <Box size={[length, BAND.h, 0.03]} position={[0, BAND.y, 0]} material={TM.frosted} cast={false} />- <Box size={[length, 0.012, 0.032]} position={[0, BAND.y + BAND.h / 2 + 0.03, 0]} material={TM.frostedLine} cast={false} />- </group>- );- })}- </group>- );-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/TeamRoomPanel.test.tsx b/dodaios/ui/web/frontend/src/components/society/office/TeamRoomPanel.test.tsxdeleted file mode 100644index c09e79c00e..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/TeamRoomPanel.test.tsx+++ /dev/null@@ -1,278 +0,0 @@-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";-import { afterEach, beforeAll, beforeEach, describe, expect, test, vi } from "vitest";-import { loadLocaleChunk } from "@/i18n";-import type { SocietyAgent } from "../data";-import type { SocietyChatGroup } from "@/lib/societyChatGroups";-import { buildOfficeLayout } from "./officeLayout";-import { buildNavGrid } from "./officeNav";-import { useOfficeStore } from "./officeStore";-import { emptyRound, useTeamwork } from "./teamwork";-import { TeamRoomPanel } from "./TeamRoomPanel";--const agents = [- { agentId: "a1", name: "Ada Lovelace", title: "Research", state: "idle", palette: { primary: "#4f7cac" } },- { agentId: "a2", name: "Bo", title: "Writer", state: "working", palette: { primary: "#c8553d" } },- { agentId: "a3", name: "Cy", title: "", state: "idle", palette: { primary: "#5e9c76" } },-] as SocietyAgent[];-const layout = buildOfficeLayout(agents.map((a, i) => ({- agentId: a.agentId, name: a.name, tier: "specialist" as const, providerLabel: "Codex", state: a.state, createdMs: i,-})));--beforeAll(async () => { await loadLocaleChunk("society"); });--let groups: SocietyChatGroup[];-const calls: { method: string; url: string; body: unknown }[] = [];--beforeEach(() => {- groups = [{ group_id: "g1", name: "Launch crew", members: ["a1", "a2"], created_ms: 1, updated_ms: 1 }];- calls.length = 0;- vi.stubGlobal("fetch", async (url: string, init?: RequestInit) => {- const method = init?.method ?? "GET";- const body = init?.body ? JSON.parse(String(init.body)) : null;- calls.push({ method, url, body });- if (method === "POST") {- const group = { group_id: "g2", name: body.name, members: body.members, created_ms: 2, updated_ms: 2 };- groups = [...groups, group];- return new Response(JSON.stringify({ group }));- }- if (method === "PATCH") {- groups = groups.map((g) => (url.endsWith(g.group_id) ? { ...g, name: body.name, members: body.members } : g));- return new Response(JSON.stringify({ group: groups.find((g) => url.endsWith(g.group_id)) }));- }- if (method === "DELETE") {- groups = groups.filter((g) => !url.endsWith(g.group_id));- return new Response("{}");- }- return new Response(JSON.stringify({ groups }));- });- useOfficeStore.setState({ meeting: null, summons: {}, teamDraft: [], selection: null, walkTo: null });- useTeamwork.setState({ rounds: {} });-});--afterEach(() => { cleanup(); vi.unstubAllGlobals(); });--function mount(props: Partial<Parameters<typeof TeamRoomPanel>[0]> = {}, onOpenGroup = vi.fn()) {- render(- <QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>- <TeamRoomPanel agents={agents} layout={layout} sample={false} actions={{ onOpenAgent: vi.fn(), onOpenLedger: vi.fn(), onOpenGroup }} {...props} />- </QueryClientProvider>,- );- return onOpenGroup;-}--describe("team room panel", () => {- test("shows each team with its members and seats them at the table on Meet", async () => {- mount();- expect(await screen.findByText("Launch crew")).toBeTruthy();- expect(screen.getByText(/2 members · 1 working/)).toBeTruthy();- // Every member shows as a face that names the agent and its state.- expect(screen.getByTitle("Ada Lovelace · Idle")).toBeTruthy();- expect(screen.getByTitle("Bo · Working")).toBeTruthy();-- fireEvent.click(screen.getByRole("button", { name: "Meet with Launch crew at the table" }));- const { meeting, summons } = useOfficeStore.getState();- expect(meeting?.groupId).toBe("g1");- expect(summons.a1.spotId).toMatch(/^meeting-/);- expect(summons.a2.spotId).toMatch(/^meeting-/);- // The running meeting shows up top, and ending it releases everyone.- // The gathering is named for what it is, with no live mark: nothing was posted and no round runs.- expect(await screen.findByText("Launch crew · called to the table")).toBeTruthy();- expect(screen.getByText(/nothing is posted to the team's chat/)).toBeTruthy();- expect(screen.queryByText("Live")).toBeNull();- expect((screen.getByRole("button", { name: "Meet with Launch crew at the table" }) as HTMLButtonElement).textContent).toBe("Called");- expect(screen.getByText(/Working, so they stay at their desk: Bo/)).toBeTruthy();- fireEvent.click(screen.getByRole("button", { name: "Send them back" }));- expect(useOfficeStore.getState().meeting).toBeNull();- expect(useOfficeStore.getState().summons).toEqual({});- });-- test("renames a team and changes its members", async () => {- mount();- fireEvent.click(await screen.findByRole("button", { name: "Edit" }));- fireEvent.change(screen.getByDisplayValue("Launch crew"), { target: { value: "Crew two" } });- fireEvent.click(screen.getAllByRole("checkbox", { name: /Cy/ })[0]);- fireEvent.click(screen.getByRole("button", { name: "Save" }));- await waitFor(() => expect(calls.some((c) => c.method === "PATCH")).toBe(true));- expect(calls.find((c) => c.method === "PATCH")?.body).toEqual({ name: "Crew two", members: ["a1", "a2", "a3"] });- });-- test("deletes a team only after a second, explicit click", async () => {- mount();- fireEvent.click(await screen.findByRole("button", { name: "Edit" }));- fireEvent.click(screen.getByRole("button", { name: "Delete team" }));- expect(calls.some((c) => c.method === "DELETE")).toBe(false);- fireEvent.click(screen.getByRole("button", { name: "Really delete?" }));- await waitFor(() => expect(calls.some((c) => c.method === "DELETE" && c.url.endsWith("/g1"))).toBe(true));- });-- test("puts a new team together from the free agents and starts its meeting", async () => {- mount();- fireEvent.click(await screen.findByRole("button", { name: "New team" }));- fireEvent.click(screen.getByRole("button", { name: "All free agents" }));- expect(screen.getByText("2 selected")).toBeTruthy();- fireEvent.click(screen.getByRole("button", { name: "Create team and meet (2)" }));- await waitFor(() => expect(useOfficeStore.getState().meeting?.groupId).toBe("g2"));- expect(calls.find((c) => c.method === "POST")?.body).toEqual({ name: "Ada Lovelace + Cy", members: ["a1", "a3"] });- expect(useOfficeStore.getState().teamDraft).toEqual([]);- });-- test("with no team yet it opens straight on the new-team form, with nothing to cancel back to", async () => {- groups = [];- mount();- expect(await screen.findByRole("region", { name: "New team" })).toBeTruthy();- expect(screen.getByRole("heading", { name: "New team" })).toBeTruthy();- expect(screen.queryByRole("button", { name: "Cancel" })).toBeNull();- const create = screen.getByRole("button", { name: "Create team and meet (0)" }) as HTMLButtonElement;- expect(create.disabled).toBe(true);- expect(screen.getByText("Pick at least two agents to create a team.")).toBeTruthy();- fireEvent.click(screen.getByRole("checkbox", { name: /Ada Lovelace/ }));- fireEvent.click(screen.getByRole("checkbox", { name: /Cy/ }));- expect((screen.getByRole("button", { name: "Create team and meet (2)" }) as HTMLButtonElement).disabled).toBe(false);- });-- test("eight teams are eight rows, and the new-team form takes the sheet to itself", async () => {- groups = Array.from({ length: 8 }, (_, i) => ({ group_id: `g${i}`, name: `Team ${i}`, members: ["a1", "a2"], created_ms: i, updated_ms: i }));- mount();- expect(await screen.findByText("Team 7")).toBeTruthy();- expect(screen.getAllByRole("listitem")).toHaveLength(8);- expect(screen.getAllByRole("button", { name: /^Meet with Team \d at the table$/ })).toHaveLength(8);- fireEvent.click(screen.getByRole("button", { name: "New team" }));- // One job at a time: the list steps aside, so the form's buttons are never pushed off the sheet.- expect(screen.queryByText("Team 7")).toBeNull();- expect(screen.getByRole("button", { name: "Create team and meet (0)" })).toBeTruthy();- fireEvent.click(screen.getByRole("button", { name: "Cancel" }));- expect(screen.getByText("Team 7")).toBeTruthy();- });-- test("forty agents: the picker scrolls on its own, searches, and the buttons stay outside the list", async () => {- const many = Array.from({ length: 40 }, (_, i) => ({- agentId: `m${i}`, name: `Agent ${String(i).padStart(2, "0")}`, title: i % 2 ? "Writer" : "Research",- state: i % 4 === 0 ? "working" : "idle", palette: { primary: "#4f7cac" },- })) as SocietyAgent[];- groups = [];- mount({ agents: many });- const list = await screen.findByRole("group", { name: "Members" });- expect(list.className).toContain("team-picker-list");- expect(within(list).getAllByRole("checkbox")).toHaveLength(40);- // The buttons are not inside the scrolling list: they sit in the footer that stays at the sheet's edge.- const create = screen.getByRole("button", { name: "Create team and meet (0)" });- expect(list.contains(create)).toBe(false);- expect(create.closest(".team-footer")).toBeTruthy();-- fireEvent.change(screen.getByRole("searchbox", { name: "Find an agent" }), { target: { value: "agent 07" } });- expect(within(list).getAllByRole("checkbox")).toHaveLength(1);- fireEvent.click(within(list).getByRole("checkbox", { name: /Agent 07/ }));- fireEvent.change(screen.getByRole("searchbox", { name: "Find an agent" }), { target: { value: "nobody" } });- expect(screen.getByText("No agent matches.")).toBeTruthy();- // The pick survives the search.- expect(screen.getByText("1 selected")).toBeTruthy();- fireEvent.change(screen.getByRole("searchbox", { name: "Find an agent" }), { target: { value: "" } });- fireEvent.click(screen.getByRole("button", { name: "All free agents" }));- expect(screen.getByText("30 selected")).toBeTruthy();- expect(screen.getByRole("button", { name: "Create team and meet (30)" })).toBeTruthy();- });-- test("a working agent's face is its symbol, never the three thinking dots", async () => {- mount();- await screen.findByText("Launch crew");- // A face is the agent's pixel creature, or its shape as a symbol or a 3D figure.- const drawn = "[data-agent-creature], [data-agent-symbol], [data-agent-figure]";- const face = screen.getByTitle("Bo · Working");- expect(face.querySelector(drawn)).toBeTruthy();- expect(face.querySelector("[data-thinking='true']")).toBeNull();- expect(face.querySelector("[data-creature-state]")?.getAttribute("data-creature-state") ?? "idle").toBe("idle");- // Every face sits on the neutral tile, so a white or black symbol never vanishes into the dialog.- expect(face.querySelector(".office-face")?.querySelector(drawn)).toBeTruthy();- fireEvent.click(screen.getByRole("button", { name: "Edit" }));- const picker = screen.getByRole("group", { name: "Members" });- expect([...picker.querySelectorAll(".office-face")].filter(tile => tile.querySelector(drawn))).toHaveLength(agents.length);- });-- test("opened to start a team it shows the new-team form at once, and Cancel leads to the teams", async () => {- mount({ compose: true });- expect(await screen.findByRole("region", { name: "New team" })).toBeTruthy();- expect(screen.getByRole("button", { name: "Create team and meet (0)" })).toBeTruthy();- await waitFor(() => expect(screen.getByRole("button", { name: "Cancel" })).toBeTruthy());- expect(screen.queryByText("Launch crew")).toBeNull();- fireEvent.click(screen.getByRole("button", { name: "Cancel" }));- expect(screen.getByText("Launch crew")).toBeTruthy();- });-- test("a team is marked live only while the backend says its round is answering", async () => {- mount();- await screen.findByText("Launch crew");- expect(screen.queryByText("Live")).toBeNull();- act(() => useTeamwork.getState().setRound({ ...emptyRound("g1"), running: true }));- expect(screen.getByText("Live")).toBeTruthy();- // The round ended: the mark goes, whatever the person has called together on the map.- act(() => useTeamwork.getState().setRound({ ...emptyRound("g1"), running: false }));- fireEvent.click(screen.getByRole("button", { name: "Meet with Launch crew at the table" }));- expect(await screen.findByText("Launch crew · called to the table")).toBeTruthy();- expect(screen.queryByText("Live")).toBeNull();- });-- test("opens the real team chat from a team's row", async () => {- const onOpenGroup = mount();- fireEvent.click(await screen.findByRole("button", { name: "Open the chat of Launch crew" }));- expect(onOpenGroup).toHaveBeenCalledWith("g1");- });-- test("steps aside when a team is sent to the table, so the person sees it gather", async () => {- const onMeet = vi.fn();- mount({ onMeet });- fireEvent.click(await screen.findByRole("button", { name: "Meet with Launch crew at the table" }));- expect(onMeet).toHaveBeenCalledOnce();- });-- test("a studio board opens its own team with every member, and the other teams one step away", async () => {- groups = [...groups, { group_id: "g9", name: "Night shift", members: ["a2", "a3"], created_ms: 3, updated_ms: 3 }];- mount({ focus: { teamId: "g1", members: ["a1", "a2"] } });- expect(await screen.findByText("Launch crew")).toBeTruthy();- expect(screen.getByText("This team")).toBeTruthy();- expect(screen.queryByText("Night shift")).toBeNull();- // The members are listed by name, each with a way to talk to them.- fireEvent.click(screen.getByRole("button", { name: "Talk to Ada Lovelace" }));- expect(useOfficeStore.getState().selection).toEqual({ kind: "agent", id: "a1" });- fireEvent.click(screen.getByRole("button", { name: "All teams (2)" }));- expect(screen.getByText("Night shift")).toBeTruthy();- expect(screen.getByText("Your teams")).toBeTruthy();- });-- test("from its own studio board a team meets at that board, not at the team room's table", async () => {- const campus = buildOfficeLayout(agents.map((a, i) => ({- agentId: a.agentId, name: a.name, tier: "specialist" as const, providerLabel: "Codex", state: a.state, createdMs: i,- })), { teams: [{ id: "g1", name: "Launch crew", members: ["a1", "a2"], createdMs: 1 }] });- const studio = campus.studios!.find((s) => s.teamId === "g1")!;- expect(studio.board).toBeTruthy();- groups = [...groups, { group_id: "g9", name: "Night shift", members: ["a2", "a3"], created_ms: 3, updated_ms: 3 }];- mount({ layout: campus, focus: { teamId: "g1", members: studio.members, studio, grid: buildNavGrid(campus) } });- expect(await screen.findByText("Launch crew")).toBeTruthy();- expect(screen.queryByRole("button", { name: "Meet with Launch crew at the table" })).toBeNull();- // Another team, reached through "All teams", has no board here: it still meets at the table.- fireEvent.click(screen.getByRole("button", { name: "All teams (2)" }));- expect(screen.getByRole("button", { name: "Meet with Night shift at the table" })).toBeTruthy();-- fireEvent.click(screen.getByRole("button", { name: "Meet with Launch crew at the board" }));- const { meeting, summons } = useOfficeStore.getState();- expect(meeting).toMatchObject({ groupId: "g1", boardId: studio.board!.id });- // Each member is called to a standing place in the arcs in front of the studio's board.- expect(summons.a1.spotId).toMatch(new RegExp(`^fan:${studio.deptId}:`));- expect(summons.a2.spotId).toMatch(new RegExp(`^fan:${studio.deptId}:`));- expect(summons.a1.spotId).not.toBe(summons.a2.spotId);- // The running meeting says where it is, and "go there" walks to that board.- expect(await screen.findByText(/of 2 at the board/)).toBeTruthy();- fireEvent.click(screen.getByRole("button", { name: "Go to the board" }));- const goal = useOfficeStore.getState().walkTo!.point;- expect(Math.hypot(goal.x - studio.board!.x, goal.z - studio.board!.z)).toBeLessThan(2);- });-- test("the board of agents without a team offers to make them one", async () => {- mount({ focus: { teamId: null, members: ["a2", "a3"] } });- expect(await screen.findByText(/not in a team yet/)).toBeTruthy();- fireEvent.click(screen.getByRole("button", { name: "New team" }));- // The people sitting there are picked already.- expect(useOfficeStore.getState().teamDraft).toEqual(["a2", "a3"]);- expect(screen.getByRole("button", { name: "Create team and meet (2)" })).toBeTruthy();- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/TeamRoomPanel.tsx b/dodaios/ui/web/frontend/src/components/society/office/TeamRoomPanel.tsxdeleted file mode 100644index 7c63180295..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/TeamRoomPanel.tsx+++ /dev/null@@ -1,434 +0,0 @@-/**- * Teams in the office. The team room's board opens every team; a team- * studio's board opens that studio's team. Either way this is the same sheet:- * who is in the team and what they do right now, meet at the table, open the- * team's real chat, rename it, change its members, delete it, and put a new- * team together.- *- * Teams are the existing society chat groups; the office adds no backend- * contract. A meeting is purely spatial — members walk to the team room and- * sit down — and never interrupts an agent that is working.- */-import { useEffect, useMemo, useRef, useState } from "react";-import { useQueryClient } from "@tanstack/react-query";-import { MessagesSquare, Pencil, Plus, Users } from "lucide-react";-import { useT } from "@/i18n";-import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import {- createSocietyChatGroup, deleteSocietyChatGroup, updateSocietyChatGroup, useSocietyChatGroups, type SocietyChatGroup,-} from "@/lib/societyChatGroups";-import { cn } from "@/lib/utils";-import type { SocietyAgent } from "../data";-import type { OfficeLayout, Point, Studio } from "./officeLayout";-import type { NavGrid } from "./officeNav";-import { stationOf } from "./stations";-import { useOfficeStore } from "./officeStore";-import { agentPositions } from "./walkerRegistry";-import { boardSeats, MEETING_MS, meetingProgress, meetingSeats, minutesLeft } from "./teamMeeting";-import type { OfficeActions } from "./OfficePanels";-import { AgentFace } from "./AgentFace";-import { useTeamwork } from "./teamwork";-import "./teamRoom.css";--const GROUPS_KEY = ["society", "chat-groups"] as const;-/** Above this many agents the picker gets a search field. */-const SEARCH_FROM = 7;-/** Faces shown in a team's row before the rest fold into "+n". */-const STACK_MAX = 6;--/** The studio whose board was used: its team (null = the studio of agents without a team) and who sits there. */-export interface TeamFocus {- teamId: string | null; members: readonly string[];- /** The studio itself: its team meets at its own board instead of the table. `grid` is the floor's nav grid when the host has it. */- studio?: Studio; grid?: NavGrid;-}--function errorText(err: unknown): string {- return err instanceof Error ? err.message : String(err);-}--function StateDot({ state }: { state: SocietyAgent["state"] }) {- return <i className="office-dot" data-state={state} aria-hidden />;-}--/** An agent's face in these lists: its symbol on the neutral tile (AgentFace.tsx). */-const Face = AgentFace;--/** A team's members as overlapping faces, each with its state dot. */-function MemberStack({ agents }: { agents: SocietyAgent[] }) {- const t = useT();- const shown = agents.slice(0, STACK_MAX);- return (- <span className="team-stack">- {shown.map((agent) => (- <span key={agent.agentId} className="team-face" title={`${agent.name} · ${t(`society.office.state_${agent.state}`)}`}>- <Face agent={agent} />- <StateDot state={agent.state} />- </span>- ))}- {agents.length > shown.length && <span className="team-face team-face-more office-face" aria-hidden>+{agents.length - shown.length}</span>}- </span>- );-}--/** Where the person stands to join a meeting: just south of the chairs, facing the table. */-function tableApproach(layout: OfficeLayout): Point | null {- const table = layout.furniture.find((f) => f.kind === "meetingTable");- return table ? { x: table.x, z: table.z + 2.1 } : null;-}--/** Checkbox list of agents with an optional search field and quick picks. */-function MemberPicker({ agents, selected, onToggle, onSet }: {- agents: SocietyAgent[]; selected: string[]; onToggle: (id: string) => void; onSet: (ids: string[]) => void;-}) {- const t = useT();- const [query, setQuery] = useState("");- const needle = query.trim().toLowerCase();- const shown = needle ? agents.filter((a) => `${a.name} ${a.title}`.toLowerCase().includes(needle)) : agents;- const free = agents.filter((a) => a.state === "idle").map((a) => a.agentId);- return (- <div className="grid gap-2">- <div className="flex flex-wrap items-center gap-2">- <span className="text-sm font-medium">{t("society.office.team_members_label")}</span>- <span className="text-xs text-muted-foreground" aria-live="polite">{t("society.office.team_selected").replace("{0}", String(selected.length))}</span>- <span className="ml-auto flex gap-1">- <Button type="button" variant="ghost" size="sm" disabled={free.length === 0} onClick={() => onSet([...new Set([...selected, ...free])])}>- {t("society.office.team_pick_idle")}- </Button>- <Button type="button" variant="ghost" size="sm" disabled={selected.length === 0} onClick={() => onSet([])}>- {t("society.office.team_pick_clear")}- </Button>- </span>- </div>- {agents.length >= SEARCH_FROM && (- <Input type="search" value={query} onChange={(e) => setQuery(e.target.value)} placeholder={t("society.office.team_search")}- aria-label={t("society.office.team_search")} />- )}- {shown.length === 0 ? <p className="text-sm text-muted-foreground">{t("society.office.team_no_match")}</p> : (- <div className="team-picker-list min-h-0 overflow-y-auto rounded-md border border-border p-1" role="group" aria-label={t("society.office.team_members_label")}>- {shown.map((agent) => (- <label key={agent.agentId} className="flex cursor-pointer items-center gap-3 rounded-md px-2 py-1.5 hover:bg-secondary">- <input type="checkbox" className="accent-primary" checked={selected.includes(agent.agentId)} onChange={() => onToggle(agent.agentId)} />- <Face agent={agent} />- <span className="min-w-0 flex-1 truncate text-sm">{agent.name}</span>- {agent.title && <span className="max-w-[40%] truncate text-xs text-muted-foreground">{agent.title}</span>}- <StateDot state={agent.state} />- </label>- ))}- </div>- )}- </div>- );-}--/**- * The team the person called together right now: who stands or sits there,- * who is coming, who keeps working. It is a gathering on the map and says so- * — nothing is posted to the team and no round runs because of it, so it- * carries no "live" mark (that belongs to a real round, see teamStatus.ts).- * The sheet shows it as a banner; the HUD shows it as a small card while the- * sheet is closed, and also lets the team go when its time is up.- */-export function MeetingStatus({ agents, layout, actions, compact = false }: {- agents: readonly SocietyAgent[]; layout: OfficeLayout; actions: OfficeActions; compact?: boolean;-}) {- const t = useT();- const meeting = useOfficeStore((s) => s.meeting);- const summons = useOfficeStore((s) => s.summons);- const endMeeting = useOfficeStore((s) => s.endMeeting);- const requestWalk = useOfficeStore((s) => s.requestWalk);- const [now, setNow] = useState(() => Date.now());- // Positions live outside React; a one-second tick keeps the seat count honest.- useEffect(() => {- if (!meeting) return;- const timer = window.setInterval(() => setNow(Date.now()), 1000);- return () => window.clearInterval(timer);- }, [meeting]);- useEffect(() => { if (meeting && meeting.untilMs <= now) endMeeting(); }, [meeting, now, endMeeting]);- if (!meeting || meeting.untilMs <= now) return null;- const progress = meetingProgress(meeting, agents, summons, agentPositions);- const present = meeting.members.length - progress.missing.length;- const nameOf = (id: string) => agents.find((a) => a.agentId === id)?.name ?? id;- // A meeting at a studio's board is joined in front of that board; any other at the team room's table.- const atBoard = !!meeting.boardId;- const approach = atBoard ? stationOf(layout, { kind: "team", id: meeting.boardId as string })?.approach ?? null : tableApproach(layout);- return (- <section className={cn("team-meeting", compact && "office-card")} data-compact={compact || undefined} data-office-ui aria-live="polite">- <p className="team-meeting-title">{t(atBoard ? "society.office.gather_board" : "society.office.gather_table").replace("{0}", meeting.name)}</p>- <p className="team-meeting-line">- {t(atBoard ? "society.office.meeting_status_board" : "society.office.meeting_status")- .replace("{0}", String(progress.seated.length)).replace("{1}", String(present))- .replace("{2}", String(minutesLeft(meeting, now)))}- </p>- {progress.busy.length > 0 && (- <p className="team-meeting-line">{t("society.office.meeting_busy").replace("{0}", progress.busy.map(nameOf).join(", "))}</p>- )}- {!compact && <p className="team-meeting-line">{t("society.office.gather_note")}</p>}- <div className="flex flex-wrap gap-2 pt-1">- {actions.onOpenGroup && (- <Button type="button" size="sm" onClick={() => actions.onOpenGroup?.(meeting.groupId)}>{t("society.office.team_chat")}</Button>- )}- {approach && <Button type="button" size="sm" variant="outline" onClick={() => requestWalk(approach)}>{t(atBoard ? "society.office.meeting_join_board" : "society.office.meeting_join")}</Button>}- <Button type="button" size="sm" variant="outline" onClick={endMeeting}>{t("society.office.gather_end")}</Button>- </div>- </section>- );-}--/** One team: who is in it, meet / chat, and an editor that unfolds in place. `detail` also lists every member. */-function TeamCard({ group, agents, layout, sample, actions, detail = false, onMeet, board = null }: {- group: SocietyChatGroup; agents: SocietyAgent[]; layout: OfficeLayout; sample: boolean; actions: OfficeActions;- detail?: boolean; onMeet?: () => void;- /** This team's own studio, when the sheet was opened from its board: the team meets there. */- board?: { studio: Studio; grid?: NavGrid } | null;-}) {- const t = useT();- const client = useQueryClient();- const meeting = useOfficeStore((s) => s.meeting);- const startMeeting = useOfficeStore((s) => s.startMeeting);- const [editing, setEditing] = useState(false);- const [name, setName] = useState(group.name);- const [members, setMembers] = useState<string[]>(group.members);- const [confirmDelete, setConfirmDelete] = useState(false);- const [busy, setBusy] = useState(false);- const [error, setError] = useState("");- const present = group.members.map((id) => agents.find((a) => a.agentId === id)).filter((a): a is SocietyAgent => !!a);- const working = present.filter((a) => a.state === "working").length;- const lead = present.find((a) => a.agentId === group.lead_agent_id);- const inMeeting = !!meeting && meeting.groupId === group.group_id && meeting.untilMs > Date.now();- // A round of this team is answering right now (the backend's word): the only thing that is called live.- const live = useTeamwork((s) => !!s.rounds[group.group_id]?.running);-- const meet = () => {- const ids = present.map((a) => a.agentId);- const meeting = { groupId: group.group_id, name: group.name, members: ids, untilMs: Date.now() + MEETING_MS };- // From its own studio board the team gathers right there; from the team room it sits down at the table.- if (board?.studio.board) startMeeting({ ...meeting, boardId: board.studio.board.id }, boardSeats(layout, board.studio, ids, board.grid));- else startMeeting(meeting, meetingSeats(layout, ids));- onMeet?.();- };- const editor = useRef<HTMLDivElement>(null);- const openEditor = () => { setName(group.name); setMembers(group.members); setConfirmDelete(false); setError(""); setEditing(true); };- // A team far down the list: its editor, with the Save button, comes into view.- useEffect(() => { if (editing) editor.current?.scrollIntoView?.({ block: "nearest" }); }, [editing]);- const save = async () => {- if (members.length < 2 || busy) return;- setBusy(true); setError("");- try {- await updateSocietyChatGroup(group.group_id, name.trim() || group.name, members);- await client.invalidateQueries({ queryKey: GROUPS_KEY });- setEditing(false);- } catch (err) {- setError(errorText(err));- } finally {- setBusy(false);- }- };- const remove = async () => {- if (busy) return;- setBusy(true); setError("");- try {- await deleteSocietyChatGroup(group.group_id);- if (inMeeting) useOfficeStore.getState().endMeeting();- await client.invalidateQueries({ queryKey: GROUPS_KEY });- } catch (err) {- setError(errorText(err));- setBusy(false);- }- };-- return (- <li className="team-card rounded-xl border border-border bg-background" data-live={live || undefined} data-called={inMeeting || undefined}>- <div className="flex flex-wrap items-center gap-x-3 gap-y-2 p-4">- <MemberStack agents={present} />- <div className="grid min-w-0 flex-1 gap-0.5">- <span className="flex min-w-0 items-center gap-2">- <span className="truncate text-sm font-semibold" title={group.name}>{group.name}</span>- {live && <span className="team-live-mark"><i aria-hidden />{t("society.office.team_live")}</span>}- </span>- <span className="text-xs text-muted-foreground">- {t("society.office.team_members").replace("{0}", String(present.length))}- {working > 0 ? ` · ${t("society.office.team_working").replace("{0}", String(working))}` : ""}- {lead ? ` · ${t("society.office.team_lead").replace("{0}", lead.name)}` : ""}- </span>- </div>- <div className="flex flex-wrap gap-2">- <Button type="button" size="sm" disabled={inMeeting || present.length === 0}- aria-label={t(board ? "society.office.team_gather_board_label" : "society.office.team_gather_label").replace("{0}", group.name)} onClick={meet}>- <Users aria-hidden />{inMeeting ? t("society.office.team_called") : t(board ? "society.office.team_meet_board" : "society.office.team_meet")}- </Button>- {actions.onOpenGroup && (- <Button type="button" size="sm" variant="outline" aria-label={t("society.office.team_open_label").replace("{0}", group.name)}- onClick={() => actions.onOpenGroup?.(group.group_id)}><MessagesSquare aria-hidden />{t("society.office.team_chat")}</Button>- )}- {!sample && !editing && (- <Button type="button" size="sm" variant="ghost" onClick={openEditor}><Pencil aria-hidden />{t("society.office.team_edit")}</Button>- )}- </div>- </div>- {detail && !editing && present.length > 0 && (- <ul className="grid gap-0.5 border-t border-border p-2">- {present.map((agent) => (- <li key={agent.agentId} className="flex items-center gap-3 rounded-md px-2 py-1.5">- <Face agent={agent} />- <span className="min-w-0 flex-1 truncate text-sm">{agent.name}</span>- <span className="flex items-center gap-1.5 text-xs text-muted-foreground"><StateDot state={agent.state} />{t(`society.office.state_${agent.state}`)}</span>- <Button type="button" size="sm" variant="ghost" aria-label={t("society.office.prompt_agent").replace("{0}", agent.name)}- onClick={() => useOfficeStore.getState().select({ kind: "agent", id: agent.agentId })}>{t("society.office.action_talk")}</Button>- </li>- ))}- </ul>- )}- {editing && (- <div ref={editor} className="grid gap-3 border-t border-border p-4">- <label className="grid gap-1 text-sm font-medium">- {t("society.office.team_name")}- <Input value={name} maxLength={60} onChange={(e) => setName(e.target.value)}- onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); void save(); } }} />- </label>- <MemberPicker agents={agents} selected={members}- onToggle={(id) => setMembers((m) => (m.includes(id) ? m.filter((x) => x !== id) : [...m, id]))} onSet={setMembers} />- {members.length < 2 && <p className="text-xs text-muted-foreground">{t("society.office.team_edit_need_more")}</p>}- <div className="flex flex-wrap items-center gap-2">- <Button type="button" size="sm" disabled={busy || members.length < 2} aria-busy={busy} onClick={() => void save()}>{t("society.office.team_save")}</Button>- <Button type="button" size="sm" variant="outline" disabled={busy} onClick={() => setEditing(false)}>{t("society.office.team_cancel")}</Button>- <span className="ml-auto">- {confirmDelete ? (- <Button type="button" size="sm" variant="destructive" disabled={busy} onClick={() => void remove()}>{t("society.office.team_delete_confirm")}</Button>- ) : (- <button type="button" className="text-xs text-destructive underline underline-offset-2 disabled:opacity-50" disabled={busy}- onClick={() => setConfirmDelete(true)}>{t("society.office.team_delete")}</button>- )}- </span>- </div>- </div>- )}- {error && <p role="alert" className="px-4 pb-3 text-xs text-destructive">{error}</p>}- </li>- );-}--export function TeamRoomPanel({ agents, layout, sample, actions, focus = null, onMeet, compose = false }: {- agents: SocietyAgent[]; layout: OfficeLayout; sample: boolean; actions: OfficeActions;- /** Opened from a team studio's board: show that studio's team first. */- focus?: TeamFocus | null;- /** A team was sent to the table (the sheet steps aside so the person sees them gather). */- onMeet?: () => void;- /** Open on the new-team form (the free plot's stand: "start a team here"). */- compose?: boolean;-}) {- const t = useT();- const client = useQueryClient();- const teamDraft = useOfficeStore((s) => s.teamDraft);- const toggleDraft = useOfficeStore((s) => s.toggleDraft);- const clearDraft = useOfficeStore((s) => s.clearDraft);- const groups = useSocietyChatGroups(!sample);- const [name, setName] = useState("");- const [busy, setBusy] = useState(false);- const [error, setError] = useState("");- const [created, setCreated] = useState("");- const [everyTeam, setEveryTeam] = useState(false);- const teams = useMemo(() => [...(groups.data ?? [])].sort((a, b) => b.updated_ms - a.updated_ms), [groups.data]);- const members = teamDraft.filter((id) => agents.some((a) => a.agentId === id));- // The new-team form stays folded behind a button once teams exist, unless agents were already picked on the map.- const [composing, setComposing] = useState(compose);- const studioTeam = focus?.teamId ? teams.find((g) => g.group_id === focus.teamId) ?? null : null;- const studioOnly = !!focus && !everyTeam;- const showComposer = composing || members.length > 0 || (!studioOnly && teams.length === 0 && !groups.isLoading && !groups.isError);- const canCreate = !sample && !busy && members.length >= 2;-- const setDraft = (ids: string[]) => {- clearDraft();- ids.forEach((id) => toggleDraft(id));- };- const create = async () => {- if (!canCreate) return;- setBusy(true); setError(""); setCreated("");- try {- const names = members.map((id) => agents.find((a) => a.agentId === id)?.name ?? id);- const group = await createSocietyChatGroup(name.trim() || names.join(" + "), members);- await client.invalidateQueries({ queryKey: GROUPS_KEY });- useOfficeStore.getState().startMeeting(- { groupId: group.group_id, name: group.name, members, untilMs: Date.now() + MEETING_MS }, meetingSeats(layout, members));- clearDraft();- setName("");- setComposing(false);- setCreated(group.name);- } catch (err) {- setError(errorText(err));- } finally {- setBusy(false);- }- };- const poolMembers = focus && !focus.teamId ? agents.filter((a) => focus.members.includes(a.agentId)) : [];- const shownTeams = studioOnly ? (studioTeam ? [studioTeam] : []) : teams;-- return (- <>- <MeetingStatus agents={agents} layout={layout} actions={actions} />- {sample && <p className="text-sm text-muted-foreground">{t("society.office.sample")}</p>}- {created && <p className="text-sm" role="status">{t("society.office.team_created").replace("{0}", created)}</p>}-- <section className="grid gap-3">- <div className="flex flex-wrap items-center justify-between gap-2">- <h3 className="text-sm font-semibold">{t(showComposer ? "society.office.team_new" : studioOnly ? "society.office.team_this" : "society.office.team_yours")}</h3>- {!showComposer && !sample && (- <Button type="button" size="sm" variant="outline" onClick={() => {- // From the studio of agents without a team, the people sitting there are the obvious first pick.- if (studioOnly && poolMembers.length > 0 && members.length === 0) setDraft(poolMembers.map((a) => a.agentId));- setComposing(true);- }}><Plus aria-hidden />{t("society.office.team_new")}</Button>- )}- </div>- {groups.isError && <p role="alert" className="text-sm text-destructive">{t("society.office.team_load_error").replace("{0}", errorText(groups.error))}</p>}-- {showComposer && (- <section className="grid gap-3" aria-label={t("society.office.team_new")}>- <p className="text-sm text-muted-foreground">{t("society.office.team_body")}</p>- {agents.length === 0 ? <p className="text-sm text-muted-foreground">{t("society.office.manage_empty")}</p> : (- <>- <label className="grid gap-1 text-sm font-medium">- {t("society.office.team_name")}- <Input value={name} maxLength={60} onChange={(e) => setName(e.target.value)} placeholder={t("society.office.team_name_placeholder")}- onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); void create(); } }} />- </label>- <MemberPicker agents={agents} selected={members} onToggle={toggleDraft} onSet={setDraft} />- </>- )}- {error && <p role="alert" className="text-xs text-destructive">{error}</p>}- {/* Pinned to the sheet's lower edge, so the button is in reach however long the list above it is. */}- <div className="team-footer">- <Button type="button" size="sm" disabled={!canCreate} aria-busy={busy} onClick={() => void create()}>- {t("society.office.team_create").replace("{0}", String(members.length))}- </Button>- {(teams.length > 0 || studioOnly) && (- <Button type="button" size="sm" variant="outline" onClick={() => { setComposing(false); clearDraft(); }}>{t("society.office.team_cancel")}</Button>- )}- {!sample && members.length < 2 && agents.length >= 2 && <span className="text-xs text-muted-foreground">{t("society.office.team_need_more")}</span>}- </div>- </section>- )}-- {!showComposer && shownTeams.length > 0 && (- <ul className="grid list-none gap-3 p-0">- {shownTeams.map((group) => (- <TeamCard key={group.group_id} group={group} agents={agents} layout={layout} sample={sample} actions={actions}- detail={studioOnly} onMeet={onMeet}- board={focus?.studio?.board && group.group_id === focus.teamId ? { studio: focus.studio, grid: focus.grid } : null} />- ))}- </ul>- )}- {!showComposer && studioOnly && !studioTeam && !groups.isLoading && (- <div className="grid gap-2 rounded-lg border border-dashed border-border p-4">- <p className="text-sm text-muted-foreground">{t(focus?.teamId ? "society.office.team_gone" : "society.office.team_pool_body")}</p>- {poolMembers.length > 0 && <MemberStack agents={poolMembers} />}- </div>- )}- {!showComposer && studioOnly && teams.length > (studioTeam ? 1 : 0) && (- <div><Button type="button" size="sm" variant="ghost" onClick={() => setEveryTeam(true)}>{t("society.office.team_all").replace("{0}", String(teams.length))}</Button></div>- )}- </section>- </>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/TerminalMonitors.tsx b/dodaios/ui/web/frontend/src/components/society/office/TerminalMonitors.tsxdeleted file mode 100644index b31ffd71dd..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/TerminalMonitors.tsx+++ /dev/null@@ -1,148 +0,0 @@-/**- * Desk monitors on the coding floor: each shows its pane live, drawn as the- * Agentic IDE draws it — the pane's header (status, CLI mark, title, what it is- * doing) over its terminal in the IDE's font and colours — while the agent- * sits at the desk, and the header over a quiet screen otherwise. A click on a- * screen opens that agent's command panel, where it can be prompted.- */-import { useEffect, useMemo, useRef, useState } from "react";-import { useFrame, type ThreeEvent } from "@react-three/fiber";-import { CanvasTexture, SRGBColorSpace } from "three";-import { useT } from "@/i18n";-import { useThemeValue } from "@/hooks/useTheme";-import { useCanvasInterval } from "@/hooks/useCanvasInterval";-import type { PaneScreen } from "@/lib/paneScreensApi";-import { usePaneTitle } from "@/store/paneRecaps";-import { storedTerminalAppearance } from "@/components/agentic/terminalThemes";-import type { DeskSlot, Point } from "./officeLayout";-import type { PaneOccupant } from "./codingFloor";-import { drawTerminalScreen, monitorPalette, paneDot, TERMINAL_H, TERMINAL_W, type MonitorPalette } from "./terminalScreen";-import { useAgentMark } from "./monitorMarks";-import { MAX_SCREEN_TARGETS, usePaneScreens, type PaneScreenTarget } from "./usePaneScreens";-import { seatedAtDesk } from "./walkerRegistry";--/** Mirrors LiveMonitors: same place as the instanced screen, a hair in front of it. */-const SCREEN_Y = 1.18, SCREEN_Z = -0.2095, SCREEN_W = 0.66, SCREEN_H = 0.38;-/** How often the nearest-seated set is re-read, in seconds. */-const NEAR_CHECK_S = 0.4;-/** The "for 3 min" in the headers moves on this clock. */-const META_TICK_MS = 30_000;--/** "Working · 3 min": the pane's state and how long it has held it at `nowMs`, as the IDE header says it. */-function useMeta(occupant: PaneOccupant, nowMs: number): string {- const t = useT();- const state = t(`society.office.pane_state_${occupant.stateKey}`);- const at = occupant.pane.activity_since;- if (!at) return state;- const seconds = Math.max(0, nowMs / 1000 - at);- const since = seconds < 60 ? t("society.office.since_now")- : seconds < 3600 ? t("society.office.since_minutes").replace("{0}", String(Math.floor(seconds / 60)))- : seconds < 86400 ? t("society.office.since_hours").replace("{0}", String(Math.floor(seconds / 3600)))- : t("society.office.since_days").replace("{0}", String(Math.floor(seconds / 86400)));- return `${state} · ${since}`;-}--/** The nearest seated agents to the camera, at most `limit`, as a sorted id list. Pure. */-export function nearestSeated(candidates: { id: string; distance: number }[], limit = MAX_SCREEN_TARGETS): string[] {- return [...candidates].sort((a, b) => a.distance - b.distance).slice(0, limit).map((c) => c.id).sort();-}--function Screen({ desk, occupant, screen, palette, nowMs, onOpen }: {- desk: DeskSlot; occupant: PaneOccupant; screen: PaneScreen | undefined; palette: MonitorPalette; nowMs: number;- onOpen: (agentId: string, screen: Point & { y: number }, facing: number) => void;-}) {- const hovered = useRef(false);- const agentId = occupant.agent.agentId;- const [seated, setSeated] = useState(() => seatedAtDesk.has(agentId));- const turn = desk.facing === "north" ? 0 : Math.PI;- const surface = useMemo(() => {- const canvas = typeof document !== "undefined" ? document.createElement("canvas") : null;- const ctx = canvas?.getContext("2d") ?? null;- if (!canvas || !ctx) return null;- canvas.width = TERMINAL_W; canvas.height = TERMINAL_H;- const texture = new CanvasTexture(canvas);- texture.colorSpace = SRGBColorSpace;- texture.anisotropy = 4;- return { ctx, texture };- }, []);- useEffect(() => () => {- surface?.texture.dispose();- if (hovered.current) document.body.style.cursor = "";- }, [surface]);- const { pane } = occupant;- // The header reads exactly like the pane's IDE header: its title, else its topic, else the agent.- const title = usePaneTitle(pane.workspace_id, pane.name) || pane.recap.trim() || occupant.agent.name;- const meta = useMeta(occupant, nowMs);- const mark = useAgentMark(pane.agent, palette.ink);- const dot = paneDot(pane);- const shown = seated ? screen : undefined;- useEffect(() => {- if (!surface) return;- drawTerminalScreen(surface.ctx, { title, meta, dot, mark, palette }, shown);- surface.texture.needsUpdate = true;- }, [surface, title, meta, dot, mark, palette, shown]);- // Seating is a per-frame module set; only its flips reach React.- useFrame(() => {- const now = seatedAtDesk.has(agentId);- if (now !== seated) setSeated(now);- });- if (!surface) return null;- // World position of the screen centre, for the zoom.- const sx = desk.x + Math.sin(turn) * SCREEN_Z, sz = desk.z + Math.cos(turn) * SCREEN_Z;- const click = (event: ThreeEvent<MouseEvent>) => {- if (event.delta > 6) return;- event.stopPropagation();- onOpen(agentId, { x: sx, y: SCREEN_Y, z: sz }, turn);- };- return (- <group position={[desk.x, 0, desk.z]} rotation={[0, turn, 0]}>- <mesh position={[0, SCREEN_Y, SCREEN_Z]} onClick={click}- onPointerOver={() => { hovered.current = true; document.body.style.cursor = "pointer"; }}- onPointerOut={() => { hovered.current = false; document.body.style.cursor = ""; }}>- <planeGeometry args={[SCREEN_W, SCREEN_H]} />- <meshBasicMaterial map={surface.texture} toneMapped={false} />- </mesh>- </group>- );-}--export function TerminalMonitors({ desks, occupants, awake, onOpen }: {- desks: DeskSlot[]; occupants: ReadonlyMap<string, PaneOccupant>; awake: boolean;- onOpen: (agentId: string, screen: Point & { y: number }, facing: number) => void;-}) {- const [near, setNear] = useState<string[]>([]);- const nextCheck = useRef(0);- useFrame(({ camera, clock }) => {- if (clock.elapsedTime < nextCheck.current) return;- nextCheck.current = clock.elapsedTime + NEAR_CHECK_S;- const candidates: { id: string; distance: number }[] = [];- for (const desk of desks) {- if (!desk.agentId || !occupants.has(desk.agentId) || !seatedAtDesk.has(desk.agentId)) continue;- candidates.push({ id: desk.agentId, distance: Math.hypot(camera.position.x - desk.x, camera.position.y - SCREEN_Y, camera.position.z - desk.z) });- }- const next = nearestSeated(candidates);- if (next.length !== near.length || next.some((id, i) => id !== near[i])) setNear(next);- });- const targets = useMemo<PaneScreenTarget[]>(() => near.flatMap((agentId) => {- const pane = occupants.get(agentId)?.pane;- return pane ? [{ agentId, workspaceId: pane.workspace_id, key: pane.key }] : [];- }), [near, occupants]);- const screens = usePaneScreens(targets, awake);- // The IDE's pane appearance: the reader's stored choice, else the app's theme.- const appTheme = useThemeValue();- const appearance = storedTerminalAppearance() ?? appTheme;- const palette = useMemo(() => monitorPalette(appearance), [appearance]);- const [nowMs, setNowMs] = useState(() => Date.now());- useCanvasInterval(() => setNowMs(Date.now()), META_TICK_MS, awake);- return (- <group>- {desks.map((desk) => {- const occupant = desk.agentId ? occupants.get(desk.agentId) : undefined;- return occupant- ? <Screen key={desk.id} desk={desk} occupant={occupant} screen={screens.get(occupant.agent.agentId)}- palette={palette} nowMs={nowMs} onOpen={onOpen} />- : null;- })}- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/ToyFigure.rebake.test.tsx b/dodaios/ui/web/frontend/src/components/society/office/ToyFigure.rebake.test.tsxdeleted file mode 100644index b80953b7d4..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/ToyFigure.rebake.test.tsx+++ /dev/null@@ -1,128 +0,0 @@-/**- * A figure's merged parts are baked again only when what it wears changes.- * The level store takes a freshly parsed snapshot about once a minute; the- * regalia built from it are then new JSX with the same content, and must not- * make every dressed figure on the floor bake all its parts again.- */-import { afterEach, describe, expect, it } from "vitest";-import { act, createRoot, extend, type ReconcilerRoot } from "@react-three/fiber";-import * as THREE from "three";-import type { Mesh, Object3D } from "three";-import { loadProfile, playerLook } from "./playerProfile";-import { PERSON_SUBJECT, type ProgressionSnapshot, type RewardRow } from "../progression/progressionApi";-import { useProgression } from "../progression/progressionStore";-import { regaliaFor, useDressedFigure } from "../progression/regalia/dress";-import { contentKey, ToyFigure, type FigureRegalia } from "./ToyFigure";--/** Just enough of a WebGLRenderer for R3F to mount a scene graph without a GPU. */-function fakeRenderer(canvas: HTMLCanvasElement) {- const noop = () => undefined;- return {- domElement: canvas,- render: noop, setSize: noop, setPixelRatio: noop, setAnimationLoop: noop, dispose: noop,- getPixelRatio: () => 1,- shadowMap: { enabled: false, type: 0, needsUpdate: false },- xr: { enabled: false, isPresenting: false, addEventListener: noop, removeEventListener: noop, setAnimationLoop: noop },- outputColorSpace: "srgb", toneMapping: 0, toneMappingExposure: 1,- info: { render: {}, memory: {} },- };-}--extend(THREE);--let root: ReconcilerRoot<HTMLCanvasElement> | null = null;-let scene: Object3D | null = null;--/** Render into one root, so a second call updates what the first one mounted. */-async function render(element: JSX.Element): Promise<Object3D> {- if (!root) {- const canvas = document.createElement("canvas");- root = createRoot(canvas);- root.configure({- // Test double: R3F only needs the renderer's shape here, nothing is drawn.- gl: fakeRenderer(canvas) as unknown as NonNullable<Parameters<typeof root.configure>[0]>["gl"],- frameloop: "never",- size: { width: 100, height: 100, top: 0, left: 0 },- });- }- const current = root;- await act(async () => { current.render(<group ref={(g) => { if (g) scene = g; }}>{element}</group>); });- if (!scene) throw new Error("the element did not mount");- return scene;-}--afterEach(() => {- root?.unmount();- root = null;- scene = null;-});--/** The merged meshes a figure is drawn with right now; a bake replaces every one of them. */-function merged(node: Object3D): Mesh[] {- const out: Mesh[] = [];- node.traverse((child) => { if ((child as Mesh).isMesh && child.userData.staticBatched && child.visible) out.push(child as Mesh); });- return out;-}--const REWARDS: RewardRow[] = [- { rewardId: "decoration_ribbon_bar", slot: "decoration", levels: { person: 3, agent: 3, pet: null } },- { rewardId: "headwear_patrol_cap", slot: "headwear", levels: { person: 7, agent: null, pet: null } },-];-const BANDS = [{ level: 1, title: "private" }, { level: 2, title: "private_second_class" }, { level: 4, title: "private_first_class" }];--/** A snapshot as the server sends it: parsed afresh every time, so no array in it is ever the same object twice. */-function snapshot(level: number, xp: number): ProgressionSnapshot {- return {- subjects: [{ subjectId: PERSON_SUBJECT, kind: "person", xp, level, xpIntoLevel: 0, xpForNext: 90, title: "private_first_class" }],- petId: "ember", recent: [], latestSeq: 0, maxLevel: 50, levelXp: [0, 40, 105, 195, 310, 450, 600, 760], rules: [],- rewards: REWARDS.map((row) => ({ ...row, levels: { ...row.levels } })),- titles: { person: BANDS.map((b) => ({ ...b })), agent: BANDS.map((b) => ({ ...b })), pet: BANDS.map((b) => ({ ...b })) },- looks: { cap: 1, suit: 4, crown: 10 },- };-}--const still = { current: { mode: "idle" as const, speed: 0 } };-const look = playerLook(loadProfile());--describe("a dressed figure", () => {- it("does not bake its parts again when the level store takes an equal snapshot, and does when it wears something new", async () => {- const seen: FigureRegalia[] = [];- function Dressed() {- const dressed = useDressedFigure("person", PERSON_SUBJECT, look);- seen.push(dressed.regalia);- return <ToyFigure look={dressed.look} regalia={dressed.regalia} drive={still} paused />;- }- useProgression.getState().hydrate(snapshot(4, 200), []);- const figure = await render(<Dressed />);- const first = merged(figure);- expect(first.length).toBeGreaterThan(4);- expect(seen[seen.length - 1].chest).toBeTruthy();-- // The minute's re-read: the same levels and rewards in new objects.- await act(async () => { useProgression.getState().hydrate(snapshot(4, 200), []); });- // The regalia are new JSX (which is what made the figure bake again)...- expect(seen[seen.length - 1].chest).not.toBe(seen[0].chest);- // ...with the same content, so every merged mesh is still the one from before.- expect(merged(figure)).toHaveLength(first.length);- expect(merged(figure).every((mesh, i) => mesh === first[i])).toBe(true);-- // A new rank and a cap: now the figure is baked again.- await act(async () => { useProgression.getState().hydrate(snapshot(7, 700), []); });- expect(seen[seen.length - 1].hat).toBeTruthy();- const dressedAnew = merged(figure);- expect(dressedAnew.some((mesh) => first.includes(mesh))).toBe(false);- });-- it("names what is worn by its content, not by the JSX object", () => {- const a = regaliaFor("private_first_class", { decoration: "decoration_ribbon_bar", headwear: "headwear_patrol_cap" });- const b = regaliaFor("private_first_class", { decoration: "decoration_ribbon_bar", headwear: "headwear_patrol_cap" });- expect(a.hat).not.toBe(b.hat);- expect(contentKey([a.hat, a.chest, a.shoulder, a.sleeve])).toBe(contentKey([b.hat, b.chest, b.shoulder, b.sleeve]));- const bare = regaliaFor("private_first_class", { decoration: "decoration_ribbon_bar" });- expect(contentKey([bare.hat, bare.chest])).not.toBe(contentKey([a.hat, a.chest]));- const other = regaliaFor("private", { decoration: "decoration_ribbon_bar", headwear: "headwear_patrol_cap" });- expect(contentKey([other.hat, other.sleeve, other.shoulder])).not.toBe(contentKey([a.hat, a.sleeve, a.shoulder]));- // Nothing worn has an empty name, whatever shape "nothing" takes.- expect(contentKey([undefined, null, false])).toBe(contentKey([undefined, undefined, undefined]));- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/WardrobePanel.tsx b/dodaios/ui/web/frontend/src/components/society/office/WardrobePanel.tsxdeleted file mode 100644index 574b21f84b..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/WardrobePanel.tsx+++ /dev/null@@ -1,192 +0,0 @@-/**- * The wardrobe mirror: dress your own character or any agent on foot —- * office outfits in curated colourways, hair style and colour, skin tone and- * eyewear. Your own look saves in this browser at once; an agent's look is a- * draft with a live preview until you save it to the roster (the same- * `avatar` PATCH the appearance editor uses).- */-import { lazy, Suspense, useId, useMemo, useState, type ReactNode } from "react";-import { useQueryClient } from "@tanstack/react-query";-import { useT } from "@/i18n";-import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import type { SocietyAgent } from "../data";-import type { FigureRecipe } from "../figures/figureRecipe";-import { playerLook, playerRecipe, type PlayerProfile } from "./playerProfile";-import { EYEWEAR, HAIR_STYLES, toyLookFor, type OutfitId } from "./toyFigureModel";-import {- colourwayIndexOf, dressIn, HAIR_COLOURS, OUTFITS, outfitById, randomLook, SKIN_TONES,- withEyewear, withHair, withHairColour, withSkin,-} from "./wardrobe";-import "./wardrobe.css";--const AgentFigureViewer = lazy(() => import("../figures/AgentFigureViewer").then((m) => ({ default: m.AgentFigureViewer })));--const YOU = "__you__";--function Section({ label, children }: { label: string; children: ReactNode }) {- const id = useId();- return (- <div className="wardrobe-section">- <p className="office-subhead" id={id}>{label}</p>- <div className="wardrobe-row" role="group" aria-labelledby={id}>{children}</div>- </div>- );-}--function Swatch({ colours, label, pressed, onClick }: { colours: string[]; label: string; pressed: boolean; onClick: () => void }) {- const background = colours.length > 1- ? `linear-gradient(135deg, ${colours[0]} 0 50%, ${colours[1]} 50% 100%)`- : colours[0];- return <button type="button" className="wardrobe-swatch" style={{ background }} aria-label={label} title={label} aria-pressed={pressed} onClick={onClick} />;-}--/** The editor itself: works on any biped recipe and reports every change. */-function LookEditor({ recipe, onChange }: { recipe: FigureRecipe; onChange: (next: FigureRecipe) => void }) {- const t = useT();- const look = toyLookFor(recipe, "");- const way = colourwayIndexOf(recipe);- const outfit = outfitById(look.outfit);- const same = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();- return (- <>- <Section label={t("society.office.wardrobe_outfit")}>- <div className="wardrobe-outfits">- {OUTFITS.map((o) => (- <button key={o.id} type="button" className="wardrobe-outfit" aria-pressed={look.outfit === o.id}- onClick={() => onChange(dressIn(recipe, o.id as OutfitId, 0))}>- <i aria-hidden style={{ background: `linear-gradient(135deg, ${o.colourways[0].primary} 0 55%, ${o.colourways[0].inner} 55% 100%)` }} />- {t(`society.office.outfit_${o.id}`)}- </button>- ))}- </div>- </Section>- <Section label={t("society.office.wardrobe_colourway")}>- {outfit.colourways.map((w, i) => (- <Swatch key={w.id} colours={[w.primary, w.inner === w.primary ? w.secondary : w.inner]} pressed={way === i}- label={t(`society.office.colourway_${w.id}`)} onClick={() => onChange(dressIn(recipe, look.outfit, i))} />- ))}- </Section>- <Section label={t("society.office.hair_label")}>- {HAIR_STYLES.map((style) => (- <button key={style} type="button" className="office-chip" aria-pressed={look.hairStyle === style} onClick={() => onChange(withHair(recipe, style))}>- {t(`society.office.hair_${style}`)}- </button>- ))}- </Section>- <Section label={t("society.office.wardrobe_hair_colour")}>- {HAIR_COLOURS.map((c, i) => (- <Swatch key={c} colours={[c]} pressed={same(look.hair, c)} label={`${t("society.office.wardrobe_hair_colour")} ${i + 1}`}- onClick={() => onChange(withHairColour(recipe, c))} />- ))}- </Section>- <Section label={t("society.office.wardrobe_skin")}>- {SKIN_TONES.map((c, i) => (- <Swatch key={c} colours={[c]} pressed={same(look.skin, c)} label={`${t("society.office.wardrobe_skin")} ${i + 1}`}- onClick={() => onChange(withSkin(recipe, c))} />- ))}- </Section>- <Section label={t("society.office.wardrobe_eyewear")}>- {EYEWEAR.map((e) => (- <button key={e} type="button" className="office-chip" aria-pressed={look.eyewear === e} onClick={() => onChange(withEyewear(recipe, e))}>- {t(`society.office.eyewear_${e}`)}- </button>- ))}- </Section>- </>- );-}--/** Agents the wardrobe can dress: two-legged figures (Gigi and other spirits fly in their own shape). */-function dressable(agents: SocietyAgent[]): SocietyAgent[] {- return agents.filter((a) => a.figure?.archetype === "biped" && !a.figure.model);-}--export function WardrobePanel({ profile, onProfile, agents, sample }: {- profile: PlayerProfile; onProfile: (next: PlayerProfile) => void; agents: SocietyAgent[]; sample: boolean;-}) {- const t = useT();- const client = useQueryClient();- const [target, setTarget] = useState<string>(YOU);- const [drafts, setDrafts] = useState<Record<string, FigureRecipe>>({});- const [saving, setSaving] = useState(false);- const [status, setStatus] = useState<"idle" | "saved" | "error">("idle");- const people = useMemo(() => dressable(agents), [agents]);- const agent = people.find((a) => a.agentId === target) ?? null;-- const yours: FigureRecipe = { ...playerRecipe(profile), hairStyle: playerLook(profile).hairStyle };- const recipe = agent ? drafts[agent.agentId] ?? agent.figure! : yours;- const dirty = agent ? Boolean(drafts[agent.agentId]) && JSON.stringify(drafts[agent.agentId]) !== JSON.stringify(agent.figure) : false;-- const change = (next: FigureRecipe) => {- setStatus("idle");- // Your own look: saved at once. The legacy profile-level hair moves into the recipe.- if (!agent) onProfile({ ...profile, recipe: next, hairStyle: undefined });- else setDrafts((d) => ({ ...d, [agent.agentId]: next }));- };-- const save = async () => {- if (!agent) return;- setSaving(true);- setStatus("idle");- try {- const response = await fetch(`/api/society/agents/${encodeURIComponent(agent.agentId)}`, {- method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ avatar: recipe }),- });- if (!response.ok) throw new Error(`wardrobe save ${response.status}`);- await Promise.all([client.invalidateQueries({ queryKey: ["society", "roster"] }), client.invalidateQueries({ queryKey: ["mars"] })]);- setDrafts((d) => { const { [agent.agentId]: _saved, ...rest } = d; return rest; });- setStatus("saved");- } catch (error) {- // Keep the draft so nothing is lost; the message offers another try.- console.warn("Wardrobe could not save the agent's look", error);- setStatus("error");- } finally {- setSaving(false);- }- };-- return (- <>- {people.length > 0 && (- <Section label={t("society.office.wardrobe_who")}>- <button type="button" className="office-chip" aria-pressed={target === YOU} onClick={() => { setTarget(YOU); setStatus("idle"); }}>- {t("society.office.wardrobe_you")}- </button>- {people.map((a) => (- <button key={a.agentId} type="button" className="office-chip" aria-pressed={target === a.agentId} title={a.name}- onClick={() => { setTarget(a.agentId); setStatus("idle"); }}>- <span className="wardrobe-chip-name">{a.name}</span>- </button>- ))}- </Section>- )}- {agent ? (- <div className="wardrobe-preview">- <Suspense fallback={null}><AgentFigureViewer recipe={recipe} quiet /></Suspense>- </div>- ) : (- <label className="grid gap-1 text-sm font-medium">- {t("society.office.wardrobe_name")}- <Input value={profile.name} maxLength={40} placeholder={t("society.office.you")} autoComplete="off" spellCheck={false}- onChange={(e) => onProfile({ ...profile, name: e.target.value })} />- <span className="text-xs font-normal text-muted-foreground">{t("society.office.wardrobe_saved")}</span>- </label>- )}- <LookEditor recipe={recipe} onChange={change} />- <Button type="button" size="sm" variant="outline" onClick={() => change(randomLook(recipe, `${target}:${Math.random()}`))}>- {t("society.office.wardrobe_random")}- </Button>- {agent && (- <>- <Button type="button" size="sm" disabled={!dirty || saving || sample} aria-busy={saving} onClick={() => void save()}>- {t(saving ? "society.card.saving" : "society.office.wardrobe_save_agent").replace("{0}", agent.name)}- </Button>- {sample && <p className="office-hint">{t("society.office.wardrobe_sample_hint")}</p>}- {status === "saved" && <p className="office-success" role="status">{t("society.office.wardrobe_saved_agent").replace("{0}", agent.name)}</p>}- {status === "error" && <p className="office-error" role="alert">{t("society.office.wardrobe_save_error")}</p>}- </>- )}- </>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/WardrobeRoom.tsx b/dodaios/ui/web/frontend/src/components/society/office/WardrobeRoom.tsxdeleted file mode 100644index cb99ef5496..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/WardrobeRoom.tsx+++ /dev/null@@ -1,548 +0,0 @@-/**- * The agents floor's wardrobe as a small boutique atelier: a light-oak- * wardrobe wall with open hanging rails, folded knits, shoes and hats in the- * real outfit colourways, a tall dressing mirror framed in warm bulbs, a- * tailor's dummy wearing a half-finished jacket, a tufted sage bench, a brass- * coat stand, a round wool rug and a brass ring pendant over it.- *- * Same rules as OfficeProps: every furniture piece is built in local space- * centred on the origin, front facing +z, inside its `FURNITURE_SIZE` box.- * The garments, folded clothes, shoes and hats of the wardrobe wall are merged- * into one vertex-coloured geometry (one draw call); the oak carcass, the- * brass and the light strips are one merged geometry each.- */-import { memo } from "react";-import {- BoxGeometry, BufferGeometry, Color, CylinderGeometry, Float32BufferAttribute, LatheGeometry, MeshStandardMaterial,- SphereGeometry, TorusGeometry, Vector2,-} from "three";-import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";-import { RoundedBoxGeometry } from "three-stdlib";-import { canvasMaterial } from "./canvasMaterials";-import { Box, matte, Rounded } from "./OfficeFurniture";-import { FURNITURE_SIZE, type Furniture, type FurnitureKind } from "./officeLayout";-import { OUTFITS } from "./outfitCatalog";--type Vec3 = [number, number, number];--// ----------------------------------------------------------------------------// Materials: pale Scandinavian oak, sage, linen and brass under warm light.-// -----------------------------------------------------------------------------const C = {- oak: "#d2b187",- oakDark: "#a88660",- backPanel: "#dfe3d6",- linen: "#e8dfcf",- sage: "#8d9f86",- velvet: "#7e9378",- brass: "#b08d5c",- led: "#ffe2bd",- bulb: "#fff0d2",-} as const;--const WM = {- oak: matte(C.oak, { roughness: 0.6 }),- oakDark: matte(C.oakDark, { roughness: 0.6 }),- backPanel: matte(C.backPanel, { roughness: 0.95 }),- linen: matte(C.linen, { roughness: 0.9 }),- velvet: matte(C.velvet, { roughness: 1 }),- brass: matte(C.brass, { roughness: 0.3, metalness: 0.65 }),- // Everything textile on the wardrobe wall carries its own colour per vertex.- textile: new MeshStandardMaterial({ color: "#ffffff", vertexColors: true, roughness: 0.9 }),- // Light strips and bulbs: lit from within, so they read as light in any scene lighting.- led: new MeshStandardMaterial({ color: C.led, emissive: C.led, emissiveIntensity: 1.2, toneMapped: false }),- bulb: new MeshStandardMaterial({ color: C.bulb, emissive: C.bulb, emissiveIntensity: 1.6, toneMapped: false }),- glass: new MeshStandardMaterial({ color: "#f3e6d0", transparent: true, opacity: 0.45, roughness: 0.05, depthWrite: false }),- tape: matte("#e8c24a", { roughness: 0.7 }),- leather: matte("#5c3622", { roughness: 0.55 }),- scarf: matte("#b56a4c", { roughness: 1 }),-};--// ----------------------------------------------------------------------------// Canvas faces-// -----------------------------------------------------------------------------type Ctx = CanvasRenderingContext2D;--/** Deterministic pseudo-random numbers, so drawn patterns never change between loads. */-function lcg(seed: number): () => number {- let state = seed >>> 0;- return () => {- state = (state * 1664525 + 1013904223) >>> 0;- return state / 0x1_0000_0000;- };-}--/** Mirror glass: a warm soft reflection of the room (an oak rail, a lit doorway) under two diagonal highlights. */-function drawMirror(ctx: Ctx, w: number, h: number): void {- const grad = ctx.createLinearGradient(0, 0, 0, h);- grad.addColorStop(0, "#d9e1e2");- grad.addColorStop(0.55, "#b9c4c6");- grad.addColorStop(1, "#a39d90");- ctx.fillStyle = grad;- ctx.fillRect(0, 0, w, h);- // The reflected room, blurred: a doorway of warm light and an oak rail with garments.- ctx.filter = "blur(6px)";- ctx.fillStyle = "rgba(255,226,180,0.55)";- ctx.fillRect(w * 0.55, h * 0.18, w * 0.3, h * 0.55);- ctx.fillStyle = "rgba(168,134,96,0.45)";- ctx.fillRect(0, h * 0.3, w * 0.45, h * 0.035);- ["#3a3d44", "#5c3622", "#23304f", "#b08a5a", "#2f4a3a"].forEach((colour, i) => {- ctx.fillStyle = colour;- ctx.globalAlpha = 0.35;- ctx.fillRect(i * w * 0.085, h * 0.34, w * 0.07, h * (0.2 + (i % 2) * 0.06));- });- ctx.globalAlpha = 1;- ctx.filter = "none";- ctx.fillStyle = "rgba(255,255,255,0.22)";- ctx.beginPath();- ctx.moveTo(w * 0.1, h); ctx.lineTo(w * 0.42, 0); ctx.lineTo(w * 0.56, 0); ctx.lineTo(w * 0.24, h);- ctx.fill();- ctx.fillStyle = "rgba(255,255,255,0.12)";- ctx.beginPath();- ctx.moveTo(w * 0.34, h); ctx.lineTo(w * 0.66, 0); ctx.lineTo(w * 0.72, 0); ctx.lineTo(w * 0.4, h);- ctx.fill();-}--/** Round wool rug: a cream field, a broad sage ring, a fine brass line and a soft inner medallion. */-function drawRoundRug(ctx: Ctx, w: number, h: number): void {- const rand = lcg(2718);- const cx = w / 2, cy = h / 2, r = w / 2;- ctx.fillStyle = "#efe8da";- ctx.fillRect(0, 0, w, h);- for (let i = 0; i < 7000; i += 1) {- ctx.fillStyle = rand() > 0.5 ? "rgba(255,255,255,0.18)" : "rgba(120,100,70,0.08)";- ctx.fillRect(rand() * w, rand() * h, 2, 2);- }- const ring = (radius: number, width: number, colour: string) => {- ctx.strokeStyle = colour;- ctx.lineWidth = width;- ctx.beginPath(); ctx.arc(cx, cy, radius, 0, Math.PI * 2); ctx.stroke();- };- ring(r * 0.86, r * 0.1, C.sage);- ring(r * 0.76, 3, C.brass);- ring(r * 0.95, 3, "#b9ab92");- // A medallion of eight soft petals round the centre.- ctx.fillStyle = "rgba(141,159,134,0.28)";- for (let i = 0; i < 8; i += 1) {- const a = (i / 8) * Math.PI * 2;- ctx.beginPath();- ctx.ellipse(cx + Math.cos(a) * r * 0.22, cy + Math.sin(a) * r * 0.22, r * 0.14, r * 0.06, a, 0, Math.PI * 2);- ctx.fill();- }- ring(r * 0.4, 2, "rgba(201,162,90,0.8)");-}--const faces = {- mirror: () => canvasMaterial("wardrobe:mirror", 160, 384, drawMirror, { glow: 0.2, fallback: "#b9c4c6", roughness: 0.08 }),- rug: () => canvasMaterial("wardrobe:round-rug", 512, 512, drawRoundRug, { fallback: "#efe8da", roughness: 1 }),-};--// ----------------------------------------------------------------------------// Shared geometry-// -----------------------------------------------------------------------------/** The dress form's torso as a lathe profile (radius, height): shoulders, bust, waist, hips. */-const TORSO_PROFILE = [- [0, 0.84], [0.12, 0.85], [0.155, 0.93], [0.15, 1.02], [0.125, 1.12], [0.13, 1.2], [0.16, 1.3], [0.168, 1.38],- [0.158, 1.46], [0.11, 1.52], [0.05, 1.55], [0.042, 1.6], [0.04, 1.64], [0, 1.65],-] as const;--const GEO = {- cyl: new CylinderGeometry(1, 1, 1, 20),- torso: new LatheGeometry(TORSO_PROFILE.map(([r, y]) => new Vector2(r, y)), 32).scale(1, 1, 0.72),- // A half-made jacket: the upper torso a little wider, covering the front and one side.- jacket: new LatheGeometry(TORSO_PROFILE.slice(4, 11).map(([r, y]) => new Vector2(r + 0.012, y)), 24, -0.2, Math.PI * 1.15).scale(1, 1, 0.74),- watch: new TorusGeometry(0.028, 0.006, 8, 20),- ring: new TorusGeometry(0.42, 0.016, 10, 64),- ringLight: new TorusGeometry(0.42, 0.007, 8, 64),- rug: new CylinderGeometry(0.5, 0.5, 1, 72),- button: new SphereGeometry(1, 8, 6),-};--// ----------------------------------------------------------------------------// Merged geometry helpers-// -----------------------------------------------------------------------------/** A unit-free box placed at (x, y, z), optionally turned about y. */-function box(w: number, h: number, d: number, x: number, y: number, z: number, rotY = 0): BufferGeometry {- const geometry = new BoxGeometry(w, h, d);- if (rotY) geometry.rotateY(rotY);- return geometry.translate(x, y, z);-}--function rounded(w: number, h: number, d: number, r: number, x: number, y: number, z: number): BufferGeometry {- return new RoundedBoxGeometry(w, h, d, 2, r).translate(x, y, z);-}--function cyl(rTop: number, rBottom: number, h: number, x: number, y: number, z: number, segments = 20): BufferGeometry {- return new CylinderGeometry(rTop, rBottom, h, segments).translate(x, y, z);-}--/** Merge parts into one geometry; indexed and non-indexed parts may mix. */-function merge(parts: BufferGeometry[]): BufferGeometry {- const flat = parts.map((p) => (p.index ? p.toNonIndexed() : p));- const merged = mergeGeometries(flat, false);- parts.forEach((p) => p.dispose());- flat.forEach((p) => p.dispose());- return merged;-}--/** Merge parts that each carry one colour into a single vertex-coloured geometry. */-function mergePainted(parts: [BufferGeometry, string][]): BufferGeometry {- const colour = new Color();- return merge(parts.map(([part, hex]) => {- const geometry = part.index ? part.toNonIndexed() : part;- if (geometry !== part) part.dispose();- colour.set(hex).convertSRGBToLinear();- const count = geometry.getAttribute("position").count;- const colours = new Float32Array(count * 3);- for (let i = 0; i < count; i += 1) colours.set([colour.r, colour.g, colour.b], i * 3);- geometry.setAttribute("color", new Float32BufferAttribute(colours, 3));- return geometry;- }));-}--// ----------------------------------------------------------------------------// The wardrobe wall-// -----------------------------------------------------------------------------const WALL = FURNITURE_SIZE.wardrobeWall;-const UPRIGHT = 0.03;-/** Interior widths of the four bays, west to east: long rail, shelves, double rail, drawers + shoe display. */-const BAY_WIDTHS = [1.25, 0.86, 1.25, 0.85] as const;-const BAYS = BAY_WIDTHS.reduce<{ minX: number; maxX: number; cx: number }[]>((acc, width) => {- const minX = (acc.length ? acc[acc.length - 1].maxX : -WALL.w / 2) + UPRIGHT;- acc.push({ minX, maxX: minX + width, cx: minX + width / 2 });- return acc;-}, []);-const CARCASS = { back: -0.28, front: 0.29, plinth: 0.08, top: 1.97 } as const;-/** Shelf tops in the shelving bay and in the display bay. */-const SHELVES_B = [0.46, 0.86, 1.26, 1.66];-const SHELVES_D = [0.74, 1.06, 1.38, 1.7];--const colourways = (id: string) => OUTFITS.find((o) => o.id === id)?.colourways ?? [];-const unique = (list: string[]) => [...new Set(list.map((c) => c.toLowerCase()))];--/**- * Order items so light and dark colours alternate along a rail: the catalogue- * lists each outfit's dark colourways together, which reads as a black band.- */-function byLightness<T>(items: T[], colour: (item: T) => string): T[] {- const tone = new Color();- const lum = (item: T) => {- tone.set(colour(item));- return tone.r * 0.3 + tone.g * 0.59 + tone.b * 0.11;- };- const sorted = [...items].sort((a, b) => lum(b) - lum(a));- const out: T[] = [];- for (let lo = 0, hi = sorted.length - 1; lo <= hi; lo += 1, hi -= 1) {- out.push(sorted[lo]);- if (hi !== lo) out.push(sorted[hi]);- }- return out;-}--/** Hanging garments on a rail at `railY`, seen edge-on: body, a lapel of the shirt underneath, a hanger. */-function railGarments(- bay: { cx: number }, railY: number, garments: { colour: string; inner?: string; length: number }[],-): [BufferGeometry, string][] {- const pitch = 0.108;- const start = bay.cx - ((garments.length - 1) * pitch) / 2;- return garments.flatMap(({ colour, inner, length }, i) => {- const top = railY - 0.05;- const parts: [BufferGeometry, string][] = [- [rounded(0.06, length, 0.44, 0.025, 0, top - length / 2, 0), colour],- // Shoulders: a slightly wider band at the top, so each piece reads as a garment and not a board.- [rounded(0.07, 0.08, 0.46, 0.03, 0, top - 0.05, 0), colour],- [box(0.012, 0.02, 0.4, 0, railY - 0.035, 0), C.oakDark],- [box(0.008, 0.05, 0.008, 0, railY - 0.005, 0), C.brass],- ];- if (inner) parts.push([box(0.062, 0.22, 0.02, 0, top - 0.2, 0.215), inner]);- // Each piece hangs a little askew, as on a rail people actually browse.- const turn = (((i * 37) % 5) - 2) * 0.07;- for (const [geometry] of parts) geometry.rotateY(turn).translate(start + i * pitch, 0, 0);- return parts;- });-}--/** A stack of folded clothes, bottom first, on a shelf top at `y`. */-function foldedStack(x: number, y: number, z: number, colours: string[]): [BufferGeometry, string][] {- return colours.map((colour, i) => [rounded(0.3 - (i % 2) * 0.01, 0.05, 0.27, 0.018, x + ((i * 7) % 3 - 1) * 0.006, y + 0.026 + i * 0.052, z), colour]);-}--/** A pair of shoes side by side, toes to +z, on a surface at `y`. */-function shoePair(x: number, y: number, z: number, colour: string, sole = "#2a2522"): [BufferGeometry, string][] {- return [-0.05, 0.05].flatMap((dx) => [- [rounded(0.085, 0.07, 0.24, 0.03, x + dx, y + 0.045, z), colour],- [box(0.09, 0.014, 0.25, x + dx, y + 0.007, z), sole],- ] satisfies [BufferGeometry, string][]);-}--/** A fedora: a crown with a band on a flat brim. */-function hat(x: number, y: number, z: number, colour: string, band: string): [BufferGeometry, string][] {- return [- [cyl(0.15, 0.15, 0.012, x, y + 0.006, z, 28), colour],- [cyl(0.075, 0.09, 0.1, x, y + 0.062, z), colour],- [cyl(0.092, 0.092, 0.022, x, y + 0.024, z), band],- ];-}--/** Every textile on the wall, coloured from the outfit catalogue, as one geometry. */-const TEXTILE_GEOMETRY = (() => {- const [bayA, bayB, bayC, bayD] = BAYS;- const parts: [BufferGeometry, string][] = [];- // Bay A: jackets, suits and leather in their real colourways, lapels showing the shirt beneath.- const long = byLightness([...colourways("suit"), ...colourways("blazer"), ...colourways("leather")], (w) => w.primary).slice(0, 10);- parts.push(...railGarments(bayA, 1.8, long.map((w, i) => ({ colour: w.primary, inner: w.inner, length: 0.78 + ((i * 5) % 4) * 0.07 }))));- // Under the jackets, the shoes that go with them on a low oak rack.- unique(long.map((w) => w.shoes)).slice(0, 4).forEach((colour, i) => {- parts.push(...shoePair(bayA.minX + 0.18 + i * 0.3, 0.13, 0.06, colour));- });- // Bay B: folded knits and tees, trainers at the bottom, hats on the top shelf.- const knits = [...colourways("turtleneck"), ...colourways("hoodie"), ...colourways("tee")].map((w) => w.primary);- const stacks = [knits.slice(0, 4), knits.slice(4, 8), knits.slice(8, 11), [knits[1], knits[5], knits[9]]];- [SHELVES_B[0], SHELVES_B[1]].forEach((y, row) => {- parts.push(...foldedStack(bayB.cx - 0.2, y, 0.02, stacks[row * 2]));- parts.push(...foldedStack(bayB.cx + 0.2, y, 0.02, stacks[row * 2 + 1]));- });- parts.push(...foldedStack(bayB.cx - 0.2, SHELVES_B[2], 0.02, colourways("quarterzip").map((w) => w.primary)));- // A woven basket of rolled ties beside the quarter-zips.- parts.push([rounded(0.28, 0.16, 0.26, 0.02, bayB.cx + 0.2, SHELVES_B[2] + 0.08, 0.02), "#c7a57a"]);- unique(OUTFITS.flatMap((o) => o.colourways.map((w) => w.accent))).slice(0, 4).forEach((colour, i) => {- parts.push([cyl(0.028, 0.028, 0.06, bayB.cx + 0.1 + i * 0.065, SHELVES_B[2] + 0.18, 0.02, 12), colour]);- });- parts.push(...shoePair(bayB.cx - 0.2, CARCASS.plinth, 0.04, "#f4f4f2", "#d9d6cf"));- parts.push(...shoePair(bayB.cx + 0.2, CARCASS.plinth, 0.04, "#3b2418"));- parts.push(...hat(bayB.cx - 0.2, SHELVES_B[3], 0.0, "#b08a5a", "#3b2418"));- parts.push(...hat(bayB.cx + 0.2, SHELVES_B[3], 0.0, "#2b2f38", "#8b1e2d"));- // Bay C: a double hang — shirts and quarter-zips above, trousers folded over hangers below.- const tops = byLightness([- ...colourways("vest").map((w) => ({ colour: w.primary, inner: w.inner })),- ...colourways("quarterzip").map((w) => ({ colour: w.primary, inner: w.inner })),- ...colourways("turtleneck").map((w) => ({ colour: w.primary })),- ...unique(colourways("suit").map((w) => w.inner)).map((colour) => ({ colour })),- ], (g) => g.colour).slice(0, 10).map((g, i) => ({ ...g, length: 0.6 + ((i * 3) % 3) * 0.04 }));- parts.push(...railGarments(bayC, 1.86, tops));- const trousers = byLightness(unique(OUTFITS.flatMap((o) => o.colourways.map((w) => w.secondary))), (c) => c).slice(0, 10);- parts.push(...railGarments(bayC, 1.0, trousers.map((colour) => ({ colour, length: 0.42 }))));- // Bay D: shoes displayed on lit shelves, folded scarves and a leather tote on top.- const dress = unique(OUTFITS.flatMap((o) => o.colourways.map((w) => w.shoes)));- [SHELVES_D[0], SHELVES_D[1], SHELVES_D[2]].forEach((y, row) => {- parts.push(...shoePair(bayD.cx - 0.19, y, 0.03, dress[(row * 2) % dress.length]));- parts.push(...shoePair(bayD.cx + 0.19, y, 0.03, dress[(row * 2 + 3) % dress.length]));- });- parts.push(...foldedStack(bayD.cx - 0.2, SHELVES_D[3], 0.02, [C.sage, "#b56a4c", C.linen]));- parts.push([rounded(0.26, 0.2, 0.1, 0.02, bayD.cx + 0.2, SHELVES_D[3] + 0.1, 0.0), "#5c3622"]);- return mergePainted(parts);-})();--/** The oak carcass: uprights, shelves, a plinth, a cornice and three drawer fronts. */-const OAK_GEOMETRY = (() => {- const depth = CARCASS.front - CARCASS.back;- const midZ = (CARCASS.front + CARCASS.back) / 2;- const parts: BufferGeometry[] = [];- const edges = [-WALL.w / 2 + UPRIGHT / 2, ...BAYS.map((b) => b.maxX + UPRIGHT / 2)];- for (const x of edges) parts.push(box(UPRIGHT, CARCASS.top, depth, x, CARCASS.top / 2, midZ));- parts.push(box(WALL.w, CARCASS.plinth, depth - 0.03, 0, CARCASS.plinth / 2, midZ - 0.015));- parts.push(box(WALL.w, 0.05, depth + 0.02, 0, CARCASS.top + 0.025, midZ + 0.01));- const [bayA, bayB, , bayD] = BAYS;- for (const y of SHELVES_B) parts.push(box(BAY_WIDTHS[1], 0.022, depth - 0.02, bayB.cx, y - 0.011, midZ));- for (const y of SHELVES_D) parts.push(box(BAY_WIDTHS[3], 0.022, depth - 0.02, bayD.cx, y - 0.011, midZ));- // The low shoe rack under the jackets, tilted towards the room.- parts.push(box(BAY_WIDTHS[0] - 0.04, 0.02, 0.3, bayA.cx, 0.12, 0.06));- // Drawers in the display bay.- for (let i = 0; i < 3; i += 1) parts.push(box(BAY_WIDTHS[3] - 0.02, 0.19, 0.02, bayD.cx, CARCASS.plinth + 0.105 + i * 0.205, CARCASS.front - 0.01));- return merge(parts);-})();--/** Brass: hanging rails, drawer pulls and the thin edge on the cornice. */-const BRASS_GEOMETRY = (() => {- const [bayA, , bayC, bayD] = BAYS;- const rail = (bay: { cx: number }, y: number) => new CylinderGeometry(0.011, 0.011, BAY_WIDTHS[0], 12).rotateZ(Math.PI / 2).translate(bay.cx, y, 0);- const parts: BufferGeometry[] = [rail(bayA, 1.8), rail(bayC, 1.86), rail(bayC, 1.0)];- for (let i = 0; i < 3; i += 1) parts.push(box(0.16, 0.014, 0.018, bayD.cx, CARCASS.plinth + 0.15 + i * 0.205, CARCASS.front + 0.009));- parts.push(box(WALL.w, 0.008, 0.008, 0, CARCASS.top + 0.004, CARCASS.front + 0.016));- return merge(parts);-})();--/** Warm light strips under the cornice of every bay and under the display shelves. */-const LED_GEOMETRY = (() => {- const parts = BAYS.map((b, i) => box(BAY_WIDTHS[i] - 0.06, 0.006, 0.02, b.cx, CARCASS.top - 0.004, CARCASS.front - 0.05));- const bayD = BAYS[3];- for (const y of SHELVES_D.slice(1)) parts.push(box(BAY_WIDTHS[3] - 0.06, 0.005, 0.015, bayD.cx, y - 0.025, CARCASS.front - 0.05));- return merge(parts);-})();--/**- * The north wall: an open light-oak wardrobe on a pale sage back panel. West- * to east — a long rail of jackets and suits over a shoe rack; shelves of- * folded knits with hats on top; a double rail of shirts over trousers;- * drawers under a lit shoe display. Every colour is a real outfit colourway.- */-function WardrobeWall() {- return (- <group>- <Box size={[WALL.w, CARCASS.top, 0.025]} position={[0, CARCASS.top / 2, CARCASS.back - 0.0125]} material={WM.backPanel} />- <mesh geometry={OAK_GEOMETRY} material={WM.oak} castShadow receiveShadow />- <mesh geometry={BRASS_GEOMETRY} material={WM.brass} castShadow />- <mesh geometry={TEXTILE_GEOMETRY} material={WM.textile} castShadow receiveShadow />- <mesh geometry={LED_GEOMETRY} material={WM.led} />- </group>- );-}--// ----------------------------------------------------------------------------// Mirror, dummy, bench, coat stand, rug-// -----------------------------------------------------------------------------const MIRROR = { frameW: 0.86, frameH: 1.84, y: 1.0, bulbX: 0.48 } as const;--/** Hollywood bulbs up both sides of the mirror and across its top, merged into one geometry. */-const BULB_GEOMETRY = (() => {- const parts: BufferGeometry[] = [];- for (let i = 0; i < 7; i += 1) {- const y = 0.32 + i * 0.24;- for (const x of [-MIRROR.bulbX, MIRROR.bulbX]) parts.push(new SphereGeometry(0.028, 12, 8).translate(x, y, -0.085));- }- for (let i = 0; i < 5; i += 1) parts.push(new SphereGeometry(0.028, 12, 8).translate(-0.36 + i * 0.18, 1.99, -0.085));- return merge(parts);-})();--/**- * A tall free-standing dressing mirror: an oak frame on two splayed feet, a- * row of warm bulbs on brass strips round three sides, and a small ledge- * with a perfume bottle and a watch; the glass faces +z.- */-function DressingMirror() {- return (- <group>- {[-0.4, 0.4].map((x) => <Box key={x} size={[0.06, 0.04, 0.28]} position={[x, 0.02, 0]} material={WM.oakDark} />)}- <Rounded size={[MIRROR.frameW, MIRROR.frameH, 0.05]} radius={0.02} position={[0, MIRROR.y, -0.12]} material={WM.oak} />- <mesh position={[0, MIRROR.y, -0.0945]} material={faces.mirror()}><planeGeometry args={[MIRROR.frameW - 0.1, MIRROR.frameH - 0.1]} /></mesh>- {[-MIRROR.bulbX, MIRROR.bulbX].map((x) => (- <Box key={x} size={[0.04, 1.72, 0.03]} position={[x, 1.06, -0.12]} material={WM.brass} />- ))}- <Box size={[0.96, 0.035, 0.03]} position={[0, 1.99, -0.12]} material={WM.brass} />- <mesh geometry={BULB_GEOMETRY} material={WM.bulb} />- {/* The ledge with a perfume bottle and a watch. */}- <Box size={[0.62, 0.022, 0.13]} position={[0, 0.92, -0.035]} material={WM.oakDark} />- <mesh geometry={GEO.cyl} material={WM.glass} position={[-0.18, 0.98, -0.04]} scale={[0.03, 0.1, 0.03]} />- <mesh geometry={GEO.cyl} material={WM.brass} position={[-0.18, 1.04, -0.04]} scale={[0.012, 0.025, 0.012]} />- <mesh geometry={GEO.watch} material={WM.leather} position={[0.14, 0.935, -0.03]} rotation={[Math.PI / 2, 0, 0]} />- <mesh geometry={GEO.cyl} material={WM.brass} position={[0.14, 0.94, -0.03]} scale={[0.022, 0.008, 0.022]} />- </group>- );-}--/**- * A tailor's dummy on an oak tripod: a linen torso on a brass pole, wearing- * the front of a sage jacket in progress, a yellow tape measure round the- * neck and a brass knob on top.- */-function TailorDummy() {- return (- <group>- {[0, 1, 2].map((i) => (- <group key={i} rotation={[0, (i * Math.PI * 2) / 3 + Math.PI / 6, 0]}>- <Box size={[0.035, 0.03, 0.24]} position={[0, 0.06, 0.11]} material={WM.oakDark} />- </group>- ))}- <mesh geometry={GEO.cyl} material={WM.oakDark} position={[0, 0.1, 0]} scale={[0.04, 0.08, 0.04]} castShadow />- <mesh geometry={GEO.cyl} material={WM.brass} position={[0, 0.48, 0]} scale={[0.012, 0.76, 0.012]} castShadow />- <mesh geometry={GEO.torso} material={WM.linen} castShadow receiveShadow />- <mesh geometry={GEO.jacket} material={WM.velvet} castShadow />- <mesh geometry={GEO.button} material={WM.brass} position={[0, 1.7, 0]} scale={0.04} castShadow />- {[-0.055, 0.055].map((x) => (- <group key={x} position={[x, 1.4, 0.1]} rotation={[-0.2, 0, x > 0 ? -0.08 : 0.08]}>- <Box size={[0.014, 0.3, 0.004]} position={[0, 0, 0]} material={WM.tape} cast={false} />- </group>- ))}- </group>- );-}--/** Tufting buttons on the bench cushion: two rows of five. */-const TUFT_GEOMETRY = merge(Array.from({ length: 10 }, (_, i) =>- new SphereGeometry(0.014, 8, 6).translate(-0.48 + (i % 5) * 0.24, 0.44, i < 5 ? -0.1 : 0.1)));--/**- * An upholstered bench: a tufted sage velvet cushion on an oak frame with a- * slatted shoe shelf below; a folded sweater on top, loafers underneath.- */-function DressingBench() {- return (- <group>- {[-0.58, 0.58].flatMap((x) => [-0.19, 0.19].map((z) => (- <Box key={`${x}:${z}`} size={[0.045, 0.3, 0.045]} position={[x, 0.15, z]} material={WM.oak} />- )))}- <Box size={[1.22, 0.04, 0.42]} position={[0, 0.28, 0]} material={WM.oak} />- {[-0.12, 0, 0.12].map((z) => <Box key={z} size={[1.16, 0.015, 0.08]} position={[0, 0.09, z]} material={WM.oak} />)}- <Rounded size={[1.28, 0.14, 0.48]} radius={0.05} position={[0, 0.37, 0]} material={WM.velvet} />- <mesh geometry={TUFT_GEOMETRY} material={WM.velvet} />- <Rounded size={[0.34, 0.05, 0.28]} radius={0.018} position={[0.36, 0.465, 0]} material={WM.linen} />- {[-0.05, 0.05].map((x) => (- <Rounded key={x} size={[0.085, 0.07, 0.24]} radius={0.03} position={[-0.3 + x, 0.14, 0]} material={WM.leather} />- ))}- </group>- );-}--/** A brass-and-oak coat stand with a fedora on top, a rust scarf and a leather tote on its hooks. */-function CoatStand() {- return (- <group>- <mesh geometry={GEO.cyl} material={WM.oakDark} position={[0, 0.015, 0]} scale={[0.2, 0.03, 0.2]} castShadow receiveShadow />- <mesh geometry={GEO.cyl} material={WM.oak} position={[0, 0.88, 0]} scale={[0.02, 1.72, 0.02]} castShadow />- {[0, 1, 2, 3].map((i) => (- <group key={i} position={[0, 1.6, 0]} rotation={[0, (i * Math.PI) / 2 + Math.PI / 4, 0]}>- <group rotation={[0.7, 0, 0]}><Box size={[0.012, 0.012, 0.14]} position={[0, 0, 0.07]} material={WM.brass} cast={false} /></group>- </group>- ))}- <mesh geometry={GEO.cyl} material={WM.oakDark} position={[0, 1.755, 0]} scale={[0.15, 0.012, 0.15]} castShadow />- <mesh geometry={GEO.cyl} material={WM.oakDark} position={[0, 1.81, 0]} scale={[0.085, 0.1, 0.085]} castShadow />- <mesh geometry={GEO.cyl} material={WM.leather} position={[0, 1.775, 0]} scale={[0.088, 0.022, 0.088]} />- <Box size={[0.07, 0.62, 0.02]} position={[0.12, 1.28, 0.06]} material={WM.scarf} />- <Box size={[0.2, 0.24, 0.07]} position={[-0.12, 1.22, -0.05]} material={WM.leather} />- <Box size={[0.012, 0.16, 0.012]} position={[-0.12, 1.42, -0.05]} material={WM.leather} cast={false} />- </group>- );-}--/** A round wool rug, sized per instance (w × d). */-function RoundRug({ w, d }: { w: number; d: number }) {- return <mesh geometry={GEO.rug} material={faces.rug()} position={[0, 0.007, 0]} scale={[w, 0.014, d]} receiveShadow />;-}--/** Renderers of the wardrobe's furniture kinds; merged into OfficeProps' exhaustive table. */-export const WARDROBE_RENDERERS = {- wardrobeWall: () => <WardrobeWall />,- dressingMirror: () => <DressingMirror />,- tailorDummy: () => <TailorDummy />,- dressingBench: () => <DressingBench />,- coatStand: () => <CoatStand />,- roundRug: ({ item }: { item: Furniture }) => {- const size = item.size ?? FURNITURE_SIZE.roundRug;- return <RoundRug w={size.w} d={size.d} />;- },-} satisfies Partial<Record<FurnitureKind, (props: { item: Furniture }) => JSX.Element>>;--/**- * What hangs in the wardrobe rather than stands in it: a brass ring pendant- * over the round rug with a warm light strip underneath and one warm light.- */-export const WardrobeFittings = memo(function WardrobeFittings({ rug }: { rug: Pick<Furniture, "x" | "z"> }) {- const at: Vec3 = [rug.x, 0, rug.z];- return (- <group position={at}>- <mesh geometry={GEO.ring} material={WM.brass} position={[0, 2.02, 0]} rotation={[Math.PI / 2, 0, 0]} castShadow />- <mesh geometry={GEO.ringLight} material={WM.led} position={[0, 2.0, 0]} rotation={[Math.PI / 2, 0, 0]} />- {[0, 1, 2].map((i) => {- const a = (i * Math.PI * 2) / 3;- return <Box key={i} size={[0.005, 0.7, 0.005]} position={[Math.cos(a) * 0.42, 2.37, Math.sin(a) * 0.42]} material={WM.brass} cast={false} />;- })}- <pointLight position={[0, 1.85, 0]} color="#ffd9ad" intensity={4.5} distance={5} decay={2} />- </group>- );-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/agentFace.css b/dodaios/ui/web/frontend/src/components/society/office/agentFace.cssdeleted file mode 100644index 9ec5db255f..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/agentFace.css+++ /dev/null@@ -1,6 +0,0 @@-/* An agent's face on a neutral tile (AgentFace.tsx). Theme tokens only: the tile is one step off the dialog's- ground in either theme, with a hairline rim. */-.office-face { display:inline-flex; flex:none; align-items:center; justify-content:center; border-radius:50%; background:hsl(var(--surface-raised)); box-shadow:inset 0 0 0 1px hsl(var(--border-strong) / .7); }-/* A hairline in the text colour round the symbol's own outline: dark round a white symbol in light mode, light- round a black one in dark mode. Two passes make a line of it instead of a haze. */-.office-face > * { filter:drop-shadow(0 0 .5px hsl(var(--foreground) / .55)) drop-shadow(0 0 .5px hsl(var(--foreground) / .35)); }diff --git a/dodaios/ui/web/frontend/src/components/society/office/agentsAmbience.test.ts b/dodaios/ui/web/frontend/src/components/society/office/agentsAmbience.test.tsdeleted file mode 100644index 867ccd13c8..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/agentsAmbience.test.ts+++ /dev/null@@ -1,183 +0,0 @@-import { describe, expect, it } from "vitest";--import { agentsRug, AGENTS_RUGS } from "./AgentsFloorLook";-import {- ambienceObstacles, bench, BENCH_DEPTH, BENCH_H, benchSeats, booth, BOOTH, boothPlace, counter, counterStands, highTable, HIGH_TABLE,- olive, OLIVE_BOX, OLIVE_H, ownSize, planter, PLANTER_H, screen, SCREEN, sofa, SOFA, sofaSeats, steps, STEPS, stepsSeats, tableStands,- toFloor, tree, TREE_BOX, yawOf,-} from "./agentsAmbience";-import { buildOfficeLayout, type OfficeAgentInput } from "./officeLayout";-import { DEPARTMENT_ZONES } from "./officePalette";--const agent = (id: string, provider: string): OfficeAgentInput => ({- agentId: id, name: id, tier: "specialist", providerLabel: provider, state: "working", createdMs: 0,-});-const near = (a: number, b: number) => expect(a).toBeCloseTo(b, 9);--describe("agents floor fittings as data", () => {- it("builds trees, benches and planters as boxes on the floor plan", () => {- const pot = olive("t", 2, -3);- expect([pot.kind, pot.h]).toEqual(["olive", OLIVE_H]);- near(pot.maxX - pot.minX, OLIVE_BOX);- near(pot.maxZ - pot.minZ, OLIVE_BOX);- expect([(pot.minX + pot.maxX) / 2, (pot.minZ + pot.maxZ) / 2]).toEqual([2, -3]);- const big = tree("b", 0, 0);- near(big.maxX - big.minX, TREE_BOX);- expect(big.h).toBeGreaterThan(pot.h);- // A bench runs north-south whichever end is named first, and faces east or west.- const seat = bench("b", 5, 4, 1, "west");- expect([seat.kind, seat.facing, seat.h]).toEqual(["bench", "west", BENCH_H]);- expect([seat.minZ, seat.maxZ]).toEqual([1, 4]);- near(seat.maxX - seat.minX, BENCH_DEPTH);- expect(benchSeats(seat).map((p) => p.z)).toEqual([1.75, 3.25]);- near(benchSeats(seat)[0].facing, -Math.PI / 2);- const box = planter("p", { minX: 0, maxX: 3, minZ: 1, maxZ: 1.34 });- expect([box.kind, box.h, box.minX, box.maxX, box.minZ, box.maxZ]).toEqual(["planter", PLANTER_H, 0, 3, 1, 1.34]);- // A screen is a thin box along its line, north-south or east-west, and may wear a studio's colour.- const line = screen("s", 4, 1, 4, 7, 3);- near(line.maxX - line.minX, SCREEN.t);- near(line.maxZ - line.minZ, 6 + SCREEN.t);- expect(line.tint).toBe(3);- expect("tint" in screen("n", 0, 0, 5, 0)).toBe(false);- });-- it("turns a piece's footprint with the way it faces, and finds its own frame on the floor", () => {- for (const facing of ["north", "south"] as const) {- const piece = sofa("s", 10, 20, facing);- near(piece.maxX - piece.minX, SOFA.w);- near(piece.maxZ - piece.minZ, SOFA.d);- }- for (const facing of ["east", "west"] as const) {- const piece = sofa("s", 10, 20, facing);- near(piece.maxX - piece.minX, SOFA.d);- near(piece.maxZ - piece.minZ, SOFA.w);- expect(ownSize(piece).w).toBeCloseTo(SOFA.w, 9);- }- // Local +z is the front: one metre in front of an east-facing piece is one metre east of it.- const east = sofa("e", 10, 20, "east"), north = sofa("n", 10, 20, "north");- near(toFloor(east, 0, 1).x, 11);- near(toFloor(east, 0, 1).z, 20);- near(toFloor(north, 0, 1).z, 19);- // Local +x is the piece's own right-hand side seen from behind it: south of an east-facing piece's middle is -x.- near(toFloor(east, 1, 0).z, 19);- expect(yawOf("south")).toBe(0);- near(yawOf("west"), -Math.PI / 2);- });-- it("gives every piece the places people use it from", () => {- // Two seats on a sofa, side by side, looking the way it faces.- const couch = sofa("s", 0, 0, "east");- const seats = sofaSeats(couch);- expect(seats).toHaveLength(2);- for (const seat of seats) {- expect(seat.x > couch.minX && seat.x < couch.maxX && seat.z > couch.minZ && seat.z < couch.maxZ).toBe(true);- near(seat.facing, Math.PI / 2);- }- near(Math.abs(seats[0].z - seats[1].z), 0.9);- // Standing places round a table look at it from just outside its top.- const table = highTable("t", 3, 3);- for (const stand of tableStands(table, [0, Math.PI / 2, Math.PI])) {- const d = Math.hypot(stand.x - 3, stand.z - 3);- expect(d).toBeGreaterThan(HIGH_TABLE.r + 0.3);- expect(d).toBeLessThan(HIGH_TABLE.r + 0.6);- near(stand.x + Math.sin(stand.facing) * d, 3);- near(stand.z + Math.cos(stand.facing) * d, 3);- }- // Step seating seats people on its lowest tier, at its front, looking out.- const flight = steps("f", 0, 0, 5, "east");- near(flight.maxX - flight.minX, STEPS.d);- near(flight.maxZ - flight.minZ, 5);- const tier = stepsSeats(flight);- expect(tier.length).toBeGreaterThanOrEqual(4);- for (const seat of tier) {- near(seat.x, flight.maxX - STEPS.tier / 2);- near(seat.facing, Math.PI / 2);- }- // In front of a counter, facing it.- const run = counter("c", 0, 0, 4, "east");- for (const stand of counterStands(run, [-1, 1])) {- expect(stand.x).toBeGreaterThan(run.maxX + 0.4);- near(Math.sin(stand.facing), -1);- }- });-- it("makes a focus booth three walls and an open front, so a person stands inside it", () => {- const box = booth("b", 0, 0, "south", 1);- const walls = ambienceObstacles(box);- expect(walls).toHaveLength(3);- const blocked = (x: number, z: number) => walls.some((w) => x >= w.minX && x <= w.maxX && z >= w.minZ && z <= w.maxZ);- // The back (north) and both sides are solid; the middle and the front (south) are not.- expect(blocked(0, -BOOTH.d / 2 + 0.02)).toBe(true);- expect(blocked(-BOOTH.w / 2 + 0.02, 0)).toBe(true);- expect(blocked(BOOTH.w / 2 - 0.02, 0)).toBe(true);- expect(blocked(0, 0)).toBe(false);- expect(blocked(0, BOOTH.d / 2 - 0.02)).toBe(false);- const inside = boothPlace(box);- expect(blocked(inside.x, inside.z)).toBe(false);- // The person looks at the shelf on the back wall.- near(Math.cos(inside.facing), -1);- // Turned east, the open side is the east one.- const turned = ambienceObstacles(booth("b", 0, 0, "east"));- expect(turned.some((w) => w.maxX >= BOOTH.d / 2 - 1e-9 && w.minZ < 0 && w.maxZ > 0)).toBe(false);- // Every other piece is simply its footprint.- const couch = sofa("s", 1, 2, "north");- expect(ambienceObstacles(couch)).toEqual([{ minX: couch.minX, maxX: couch.maxX, minZ: couch.minZ, maxZ: couch.maxZ }]);- });-});--describe("agents floor fittings on the campus", () => {- for (const count of [0, 12, 40]) {- const layout = buildOfficeLayout(Array.from({ length: count }, (_, i) => agent(`a${i}`, `P${i % 5}`)), {- teams: count > 0 ? [{ id: "t", name: "T", createdMs: 1, members: ["a1", "a2", "a3", "a4", "a5"] }] : [],- });- const items = layout.ambience!;-- it(`furnishes the atrium, the commons, every studio and the windows (${count} agents)`, () => {- const has = (prefix: string, kind: string) => items.some((i) => i.id.startsWith(prefix) && i.kind === kind);- expect(has("atrium-steps-west", "steps") && has("atrium-steps-east", "steps") && has("atrium-tree-", "tree")).toBe(true);- expect(has("median-west", "planter") && has("median-east-olive", "olive") && has("median-west-table", "hightable")).toBe(true);- expect(has("booth-", "booth") && has("booths-sofa", "sofa") && has("library-sofa", "sofa")).toBe(true);- expect(has("cafe-counter", "counter") && has("cafe-island", "island") && has("cafe-table-", "hightable") && has("cafe-sofa-", "sofa")).toBe(true);- expect(has("olive-west-0", "olive") && has("olive-east-0", "olive")).toBe(true);- // Every studio: screens, planted front, cabinet, sofa, standing table.- for (const dept of layout.departments) {- const mine = (part: string) => items.find((i) => i.id === `${dept.id}-${part}`);- expect([mine("front-w")?.kind, mine("front-e")?.kind, mine("cabinet")?.kind, mine("sofa")?.kind, mine("table")?.kind, mine("screen-e")?.kind])- .toEqual(["planter", "planter", "cabinet", "sofa", "hightable", "screen"]);- // The front planters leave the entrance between them.- expect(mine("front-e")!.minX - mine("front-w")!.maxX).toBeGreaterThan(4);- }- });-- it(`puts a bench and a planter beside each window, swapped between west and east (${count} agents)`, () => {- const kind = (id: string) => items.find((i) => i.id === id)?.kind;- expect([kind("bench-west-0"), kind("planter-west-0"), kind("planter-east-0"), kind("bench-east-0")]).toEqual(["bench", "planter", "planter", "bench"]);- const west = items.find((i) => i.id === "bench-west-0")!, westBox = items.find((i) => i.id === "planter-west-0")!;- expect(west.maxZ).toBeLessThan(westBox.minZ);- const east = items.find((i) => i.id === "bench-east-0")!, eastBox = items.find((i) => i.id === "planter-east-0")!;- expect(eastBox.maxZ).toBeLessThan(east.minZ);- expect([west.facing, east.facing]).toEqual(["east", "west"]);- });- }-- it("adds nothing to the coding floor", () => {- expect(buildOfficeLayout([], { variant: "coding" }).ambience).toBeUndefined();- });-});--describe("agents floor rugs", () => {- it("gives the twelve studios a floor can hold twelve different rugs", () => {- const rugs = Array.from({ length: 12 }, (_, i) => agentsRug(i));- expect(AGENTS_RUGS).toHaveLength(12);- expect(new Set(rugs.map((r) => `${r.weave}:${r.field}`)).size).toBe(12);- expect(new Set(rugs.map((r) => r.field)).size).toBe(12);- expect(new Set(rugs.map((r) => r.border)).size).toBe(12);- // Desk screens and seats take their zone from the same index.- expect(DEPARTMENT_ZONES).toHaveLength(AGENTS_RUGS.length);- });-- it("cycles for any tint index", () => {- expect(agentsRug(AGENTS_RUGS.length)).toBe(agentsRug(0));- expect(agentsRug(-1)).toBe(agentsRug(AGENTS_RUGS.length - 1));- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/agentsAmbience.ts b/dodaios/ui/web/frontend/src/components/society/office/agentsAmbience.tsdeleted file mode 100644index 3c73daedbe..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/agentsAmbience.ts+++ /dev/null@@ -1,211 +0,0 @@-/**- * The agents floor's fittings between the rooms, as data: what makes a team- * studio a place (low screens round it, a storage cabinet, a sofa, a standing- * table, planted front edges) and what furnishes the commons (the atrium's- * step seating, the café's kitchen run and island, focus booths, benches,- * planters, olive trees in pots and a few large trees).- *- * The campus plan (`campusLayout.ts`) places every piece, adds its footprint- * to the floor's obstacles and gives it the spots people use it from. Pure- * and shared: navigation reads the same boxes the renderer- * (`AgentsFloorAmbience.tsx`) builds each piece inside. Every piece is a few- * entries of instanced meshes there, so furnishing another studio costs no- * extra draw calls.- */-import type { Point, Rect } from "./officeLayout";--export type AgentsAmbienceKind =- | "olive" | "tree" | "bench" | "planter"- // A team studio's own pieces.- | "screen" | "cabinet" | "sofa" | "hightable"- // The commons.- | "booth" | "steps" | "counter" | "island"- // On the free plot: a stack of moving crates, waiting for a team.- | "crate";--export type Compass = "north" | "south" | "east" | "west";--export interface AgentsAmbienceItem extends Rect {- id: string;- kind: AgentsAmbienceKind;- /** The side the piece's front looks at. A bench runs north-south and faces east or west. */- facing: Compass;- /** Height of the piece in metres (a tree's crown top). */- h: number;- /** A team studio's colour index, for the pieces that wear it; absent = the floor's neutral oak and linen. */- tint?: number;-}--/** An olive pot's square footprint, and a large tree's. */-export const OLIVE_BOX = 0.8;-export const TREE_BOX = 1.2;-/** Depth of a bench (its seat, front to back) and of a planter box. */-export const BENCH_DEPTH = 0.4;-export const PLANTER_DEPTH = 0.34;--export const OLIVE_H = 2.3;-export const TREE_H = 4.2;-export const BENCH_H = 0.46;-export const PLANTER_H = 0.52;--/** A studio's low screen: felt below, glass above. */-export const SCREEN = { t: 0.08, h: 1.3 } as const;-export const CABINET = { w: 1.6, d: 0.45, h: 1.0 } as const;-/** A two-seat sofa; its seat is at the height a seated figure's couch pose expects. */-export const SOFA = { w: 2.0, d: 0.85, h: 0.8 } as const;-export const HIGH_TABLE = { r: 0.4, h: 1.08 } as const;-/** A focus booth: three felt walls, a roof and a glass front with the doorway. */-export const BOOTH = { w: 1.3, d: 1.3, h: 2.25, wall: 0.08 } as const;-/** Step seating: three tiers rising towards the back. */-export const STEPS = { d: 2.4, tier: 0.8, rise: 0.45, tiers: 3 } as const;-/** The café's kitchen run with its shelf wall, and the island in front of it. */-export const COUNTER = { d: 0.65, h: 2.1 } as const;-export const ISLAND = { w: 2.6, d: 0.9, h: 0.95 } as const;-export const CRATE = { w: 0.9, d: 0.6, h: 0.9 } as const;--/** Rotation about +y that turns a piece's front (its local +z) towards `facing`. */-export function yawOf(facing: Compass): number {- return facing === "south" ? 0 : facing === "east" ? Math.PI / 2 : facing === "north" ? Math.PI : -Math.PI / 2;-}--/** A piece's own width (along its front) and depth, whatever way it is turned. */-export function ownSize(item: Pick<AgentsAmbienceItem, "facing" | keyof Rect>): { w: number; d: number } {- const dx = item.maxX - item.minX, dz = item.maxZ - item.minZ;- return item.facing === "east" || item.facing === "west" ? { w: dz, d: dx } : { w: dx, d: dz };-}--/** A point of a piece's own frame (x along its front, z towards its front, origin in its middle) on the floor plan. */-export function toFloor(item: Pick<AgentsAmbienceItem, "facing" | keyof Rect>, lx: number, lz: number): Point {- const yaw = yawOf(item.facing), cos = Math.cos(yaw), sin = Math.sin(yaw);- return { x: (item.minX + item.maxX) / 2 + lx * cos + lz * sin, z: (item.minZ + item.maxZ) / 2 - lx * sin + lz * cos };-}--/** A piece w wide (along its front) and d deep, centred on (x, z), its front towards `facing`. */-function oriented(id: string, kind: AgentsAmbienceKind, x: number, z: number, w: number, d: number, facing: Compass, h: number, tint?: number): AgentsAmbienceItem {- const turned = facing === "east" || facing === "west";- const halfX = (turned ? d : w) / 2, halfZ = (turned ? w : d) / 2;- return { id, kind, facing, h, minX: x - halfX, maxX: x + halfX, minZ: z - halfZ, maxZ: z + halfZ, ...(tint === undefined ? {} : { tint }) };-}--/** An olive tree in its pot, centred on (x, z). */-export function olive(id: string, x: number, z: number): AgentsAmbienceItem {- return oriented(id, "olive", x, z, OLIVE_BOX, OLIVE_BOX, "south", OLIVE_H);-}--/** A large tree in a round stone planter; its crown spreads above head height, beyond its footprint. */-export function tree(id: string, x: number, z: number): AgentsAmbienceItem {- return oriented(id, "tree", x, z, TREE_BOX, TREE_BOX, "south", TREE_H);-}--/** A bench running north-south from z0 to z1, centred on x, its front towards `facing`. */-export function bench(id: string, x: number, z0: number, z1: number, facing: "east" | "west"): AgentsAmbienceItem {- return { id, kind: "bench", facing, h: BENCH_H, minX: x - BENCH_DEPTH / 2, maxX: x + BENCH_DEPTH / 2, minZ: Math.min(z0, z1), maxZ: Math.max(z0, z1) };-}--/** A planter box filling `rect`; it may run north-south or east-west. */-export function planter(id: string, rect: Rect): AgentsAmbienceItem {- return { id, kind: "planter", facing: "south", h: PLANTER_H, minX: rect.minX, maxX: rect.maxX, minZ: rect.minZ, maxZ: rect.maxZ };-}--/** A low screen along a straight line from (x0, z0) to (x1, z1) (north-south or east-west), in a studio's colour. */-export function screen(id: string, x0: number, z0: number, x1: number, z1: number, tint?: number): AgentsAmbienceItem {- const t = SCREEN.t / 2;- return {- id, kind: "screen", facing: "south", h: SCREEN.h, ...(tint === undefined ? {} : { tint }),- minX: Math.min(x0, x1) - t, maxX: Math.max(x0, x1) + t, minZ: Math.min(z0, z1) - t, maxZ: Math.max(z0, z1) + t,- };-}--export function cabinet(id: string, x: number, z: number, facing: Compass, tint?: number): AgentsAmbienceItem {- return oriented(id, "cabinet", x, z, CABINET.w, CABINET.d, facing, CABINET.h, tint);-}--export function sofa(id: string, x: number, z: number, facing: Compass, tint?: number): AgentsAmbienceItem {- return oriented(id, "sofa", x, z, SOFA.w, SOFA.d, facing, SOFA.h, tint);-}--export function highTable(id: string, x: number, z: number): AgentsAmbienceItem {- return oriented(id, "hightable", x, z, HIGH_TABLE.r * 2, HIGH_TABLE.r * 2, "south", HIGH_TABLE.h);-}--export function booth(id: string, x: number, z: number, facing: Compass, tint?: number): AgentsAmbienceItem {- return oriented(id, "booth", x, z, BOOTH.w, BOOTH.d, facing, BOOTH.h, tint);-}--/** Step seating `length` wide, centred on (x, z), its lowest tier towards `facing`. */-export function steps(id: string, x: number, z: number, length: number, facing: Compass): AgentsAmbienceItem {- return oriented(id, "steps", x, z, length, STEPS.d, facing, STEPS.rise * STEPS.tiers);-}--export function counter(id: string, x: number, z: number, length: number, facing: Compass): AgentsAmbienceItem {- return oriented(id, "counter", x, z, length, COUNTER.d, facing, COUNTER.h);-}--export function crate(id: string, x: number, z: number, facing: Compass): AgentsAmbienceItem {- return oriented(id, "crate", x, z, CRATE.w, CRATE.d, facing, CRATE.h);-}--export function island(id: string, x: number, z: number, facing: Compass): AgentsAmbienceItem {- return oriented(id, "island", x, z, ISLAND.w, ISLAND.d, facing, ISLAND.h);-}--/** The box round two points of a piece's own frame, on the floor plan. */-function boxOf(item: AgentsAmbienceItem, lx0: number, lz0: number, lx1: number, lz1: number): Rect {- const a = toFloor(item, lx0, lz0), b = toFloor(item, lx1, lz1);- return { minX: Math.min(a.x, b.x), maxX: Math.max(a.x, b.x), minZ: Math.min(a.z, b.z), maxZ: Math.max(a.z, b.z) };-}--/**- * What a walker bumps into at a piece: its footprint — except a focus booth,- * which is its back and its two side walls, so a person walks in through the- * front and stands inside.- */-export function ambienceObstacles(item: AgentsAmbienceItem): Rect[] {- if (item.kind !== "booth") return [{ minX: item.minX, maxX: item.maxX, minZ: item.minZ, maxZ: item.maxZ }];- const { w, d } = ownSize(item), t = BOOTH.wall;- return [- boxOf(item, -w / 2, -d / 2, w / 2, -d / 2 + t),- boxOf(item, -w / 2, -d / 2, -w / 2 + t, d / 2),- boxOf(item, w / 2 - t, -d / 2, w / 2, d / 2),- ];-}--/** A place at a piece, in the plan: where a figure is and the yaw it looks along. */-export interface AmbiencePlace extends Point { facing: number }--/** The two seats of a sofa. */-export function sofaSeats(item: AgentsAmbienceItem): AmbiencePlace[] {- return [-0.45, 0.45].map((lx) => ({ ...toFloor(item, lx, 0.05), facing: yawOf(item.facing) }));-}--/** Seats along a bench, one per 1.1 m, looking the way the bench faces. */-export function benchSeats(item: AgentsAmbienceItem): AmbiencePlace[] {- const length = item.maxZ - item.minZ, count = Math.max(1, Math.floor(length / 1.1));- const x = (item.minX + item.maxX) / 2;- return Array.from({ length: count }, (_, i) => ({ x, z: item.minZ + (length * (i + 0.5)) / count, facing: yawOf(item.facing) }));-}--/** Standing places round a high table, each looking at it; `angles` are compass yaws from the table (0 = south of it). */-export function tableStands(item: AgentsAmbienceItem, angles: readonly number[]): AmbiencePlace[] {- const cx = (item.minX + item.maxX) / 2, cz = (item.minZ + item.maxZ) / 2, reach = HIGH_TABLE.r + 0.42;- return angles.map((a) => ({ x: cx + Math.sin(a) * reach, z: cz + Math.cos(a) * reach, facing: a + Math.PI }));-}--/** Seats on the lowest tier of step seating, 0.9 m apart. */-export function stepsSeats(item: AgentsAmbienceItem): AmbiencePlace[] {- const { w, d } = ownSize(item), count = Math.max(1, Math.floor((w - 0.6) / 0.9));- return Array.from({ length: count }, (_, i) => ({- ...toFloor(item, (i - (count - 1) / 2) * 0.9, d / 2 - STEPS.tier / 2), facing: yawOf(item.facing),- }));-}--/** Inside a focus booth, at its shelf. */-export function boothPlace(item: AgentsAmbienceItem): AmbiencePlace {- return { ...toFloor(item, 0, 0.12), facing: yawOf(item.facing) + Math.PI };-}--/** Standing places in front of a counter or an island, each looking at it. */-export function counterStands(item: AgentsAmbienceItem, offsets: readonly number[]): AmbiencePlace[] {- const { d } = ownSize(item);- return offsets.map((lx) => ({ ...toFloor(item, lx, d / 2 + 0.55), facing: yawOf(item.facing) + Math.PI }));-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/blendingLayer.test.ts b/dodaios/ui/web/frontend/src/components/society/office/blendingLayer.test.tsdeleted file mode 100644index 137c5890e8..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/blendingLayer.test.ts+++ /dev/null@@ -1,9 +0,0 @@-import { describe, expect, it } from "vitest";-import { blendingCanvasZ } from "./blendingLayer";--describe("blendingCanvasZ", () => {- it("matches the canvas z-index drei gives a blending <Html>", () => {- expect(blendingCanvasZ([10, 0])).toBe("5");- expect(blendingCanvasZ([7, 0])).toBe("3");- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/blendingLayer.ts b/dodaios/ui/web/frontend/src/components/society/office/blendingLayer.tsdeleted file mode 100644index e9708528a9..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/blendingLayer.ts+++ /dev/null@@ -1,29 +0,0 @@-/**- * drei's <Html occlude="blending"> draws its page BEHIND the canvas: it lifts- * the canvas above the HTML layer (z-index, absolute) and punches a clear hole- * where the screen is, so anything in front of the screen still covers it.- *- * Every other <Html> (a name label, a hint) resets those canvas styles when it- * mounts. A label that appears after a live screen therefore drops the canvas- * back under the screen, and the screen shows through every wall in front of- * it. While a blending screen is mounted, re-assert the lift each frame.- */-import { useFrame, useThree } from "@react-three/fiber";--/** The canvas z-index drei gives a blending <Html> with this `zIndexRange`. Pure. */-export function blendingCanvasZ(zIndexRange: readonly [number, number]): string {- return String(Math.floor(zIndexRange[0] / 2));-}--/** Keep the canvas above the blending screens' HTML layer while the caller is mounted. */-export function useBlendingCanvasLayer(zIndexRange: readonly [number, number]): void {- const gl = useThree((s) => s.gl);- const z = blendingCanvasZ(zIndexRange);- useFrame(() => {- const style = gl.domElement.style;- if (style.zIndex === z) return;- style.zIndex = z;- style.position = "absolute";- style.pointerEvents = "none";- });-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/campusFittings.test.ts b/dodaios/ui/web/frontend/src/components/society/office/campusFittings.test.tsdeleted file mode 100644index 34e381eb8e..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/campusFittings.test.ts+++ /dev/null@@ -1,41 +0,0 @@-import { describe, expect, it } from "vitest";--import { steps, type Compass } from "./agentsAmbience";-import { fittingParts } from "./CampusFittings";-import type { Placement } from "./CodingFloorAmbience";--type Bounds = { min: [number, number, number]; max: [number, number, number] };--/** World bounds of a unit box placed with a quarter-turn yaw (the fittings only ever turn by quarter turns). */-function boundsOf({ position, scale, rotation }: Placement): Bounds {- const quarter = Math.round(Math.abs(rotation?.[1] ?? 0) / (Math.PI / 2)) % 2 === 1;- const sx = quarter ? scale[2] : scale[0], sz = quarter ? scale[0] : scale[2];- const half = [sx / 2, scale[1] / 2, sz / 2];- return {- min: [position[0] - half[0], position[1] - half[1], position[2] - half[2]],- max: [position[0] + half[0], position[1] + half[1], position[2] + half[2]],- };-}--const EPS = 1e-6;--/** Whether two boxes share a face plane, facing the same way, over an area: the pattern that z-fights into stripes. */-function flushOverArea(a: Bounds, b: Bounds): boolean {- for (let axis = 0; axis < 3; axis += 1) {- const others = [0, 1, 2].filter((o) => o !== axis);- const overlap = others.every((o) => Math.min(a.max[o], b.max[o]) - Math.max(a.min[o], b.min[o]) > EPS);- if (!overlap) continue;- if (Math.abs(a.min[axis] - b.min[axis]) < EPS || Math.abs(a.max[axis] - b.max[axis]) < EPS) return true;- }- return false;-}--describe("campus fittings", () => {- it.each<Compass>(["north", "south", "east", "west"])("step seating facing %s has no steel cheek flush with a tread", (facing) => {- const parts = fittingParts([steps("s", 3, -2, 6, facing)]);- expect(parts.steel.length).toBe(2);- for (const cheek of parts.steel.map(boundsOf)) {- for (const tread of parts.oak.map(boundsOf)) expect(flushOverArea(cheek, tread)).toBe(false);- }- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/campusLayout.test.ts b/dodaios/ui/web/frontend/src/components/society/office/campusLayout.test.tsdeleted file mode 100644index b62aba4007..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/campusLayout.test.ts+++ /dev/null@@ -1,653 +0,0 @@-import { describe, expect, it } from "vitest";-import { ambienceObstacles, type AgentsAmbienceKind } from "./agentsAmbience";-import { CAMPUS, MAX_STUDIOS, planStudios, STUDIO_SEAT_CAP, studioShape, studioWallRect } from "./campusLayout";-import {- allDesks, ARCH, archPosts, benchPlanters, buildOfficeLayout, deskRect, FLOOR_EDGE, footprint, FURNITURE_SIZE, leadDesks, seatedCount, seatOf, standOf, STUDIO_BOARD_FACE, studioBoardFace,- type OfficeAgentInput, type OfficeLayout, type OfficeTeamInput, type Point, type Rect,-} from "./officeLayout";-import { buildNavGrid, findPath, isWalkable } from "./officeNav";--const agent = (n: number, extra: Partial<OfficeAgentInput> = {}): OfficeAgentInput => ({- agentId: `a${n}`, name: `Agent ${n}`, tier: "specialist", providerLabel: n % 2 ? "Codex" : "Claude", state: "idle", createdMs: n, ...extra,-});-const staff = (count: number): OfficeAgentInput[] => Array.from({ length: count }, (_, i) => agent(i + 1));-const team = (n: number, members: number[], extra: Partial<OfficeTeamInput> = {}): OfficeTeamInput => ({- id: `team-${n}`, name: `Team ${n}`, members: members.map((m) => `a${m}`), createdMs: n * 10, ...extra,-});-/** `count` teams of `size`, filled with consecutive agents from a1 on. */-const teamsOf = (count: number, size: number): OfficeTeamInput[] =>- Array.from({ length: count }, (_, t) => team(t + 1, Array.from({ length: size }, (_, i) => t * size + i + 1)));--const overlaps = (a: Rect, b: Rect) => a.minX < b.maxX - 1e-9 && b.minX < a.maxX - 1e-9 && a.minZ < b.maxZ - 1e-9 && b.minZ < a.maxZ - 1e-9;-const inside = (p: Point, r: Rect) => p.x >= r.minX && p.x <= r.maxX && p.z >= r.minZ && p.z <= r.maxZ;-const area = (r: Rect) => (r.maxX - r.minX) * (r.maxZ - r.minZ);-const size = (layout: OfficeLayout) => ({ w: layout.bounds.maxX - layout.bounds.minX, d: layout.bounds.maxZ - layout.bounds.minZ });-const seatOfAgent = (layout: OfficeLayout, id: string) => allDesks(layout).find((d) => d.agentId === id)?.id;-const kindsOf = (layout: OfficeLayout, ...kinds: string[]) => layout.zones!.filter((z) => kinds.includes(z.kind)).map((z) => z.kind);--/** The three sizes the floor must look right at: 5, 15 and 40 people. */-const SIZES: [string, OfficeAgentInput[], OfficeTeamInput[]][] = [- ["5 agents, no team", staff(5), []],- ["15 agents, 3 teams", staff(15), teamsOf(3, 4)],- ["40 agents, 8 teams", staff(40), teamsOf(8, 4)],-];--describe("campus: who sits where", () => {- it("gives every team a studio of its own and puts everyone else in the pool", () => {- const layout = buildOfficeLayout(staff(9), { teams: [team(1, [1, 2, 3]), team(2, [4, 5])] });- expect(layout.departments.map((d) => [d.id, d.label, d.teamId])).toEqual([- ["studio-pool", "", null], ["studio-team-1", "Team 1", "team-1"], ["studio-team-2", "Team 2", "team-2"],- ]);- const studios = layout.studios!;- expect(studios.map((s) => [s.deptId, s.teamId, s.name, s.members])).toEqual([- ["studio-pool", null, "", ["a6", "a7", "a8", "a9"]],- ["studio-team-1", "team-1", "Team 1", ["a1", "a2", "a3"]],- ["studio-team-2", "team-2", "Team 2", ["a4", "a5"]],- ]);- // Each agent sits in its own studio's desks, in arrival order.- for (const studio of studios) {- const dept = layout.departments.find((d) => d.id === studio.deptId)!;- expect(dept.desks.map((d) => d.agentId).filter(Boolean)).toEqual(studio.members);- }- expect(seatedCount(layout)).toBe(9);- });-- it("seats an agent of several teams in the oldest one, ties by id", () => {- const teams = [team(2, [1, 2], { createdMs: 50 }), team(1, [2, 3], { createdMs: 20 }), team(3, [3, 4], { createdMs: 20 })];- const plans = planStudios(staff(4), teams);- // Oldest first: team-1 and team-3 share an age, team-1 wins by id; team-2 is the youngest.- expect(plans.map((p) => [p.teamId, p.members.map((a) => a.agentId)])).toEqual([- [null, []], ["team-1", ["a2", "a3"]], ["team-3", ["a4"]], ["team-2", ["a1"]],- ]);- // The input order of the teams does not matter.- expect(planStudios(staff(4), [...teams].reverse())).toEqual(plans);- });-- it("keeps a studio for a team whose members are unknown, and never guesses a team lead", () => {- const layout = buildOfficeLayout(staff(3), { teams: [team(1, [41, 42]), team(2, [1], { leadId: "a1" })] });- const ghost = layout.studios!.find((s) => s.teamId === "team-1")!;- expect(ghost.members).toEqual([]);- expect(ghost.leadId).toBeNull();- expect(layout.departments.find((d) => d.id === ghost.deptId)!.desks).toHaveLength(4);- expect(layout.studios!.find((s) => s.teamId === "team-2")!.leadId).toBe("a1");- expect(layout.studios![0].members).toEqual(["a2", "a3"]);- });-- it("keeps lead-tier agents in the lead office even when a team lists them", () => {- const roster = [agent(1, { tier: "lead" }), agent(2), agent(3)];- const layout = buildOfficeLayout(roster, { teams: [team(1, [1, 2])] });- expect(layout.lead.desks.map((d) => d.agentId)).toEqual(["a1"]);- expect(layout.studios!.find((s) => s.teamId === "team-1")!.members).toEqual(["a2"]);- // A third lead has no place in the office for two: it works from the pool.- const three = buildOfficeLayout([1, 2, 3].map((n) => agent(n, { tier: "lead" })));- expect(three.lead.desks.map((d) => d.agentId)).toEqual(["a1", "a2"]);- expect(three.studios![0].members).toEqual(["a3"]);- });-- it("never re-seats anyone while roster and teams are unchanged", () => {- const roster = staff(23), teams = [team(1, [1, 2, 3, 4, 5]), team(2, [6, 7]), team(3, [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19])];- const before = buildOfficeLayout(roster, { teams });- // A refetch: other object identities, another order, other run states, members listed in another order.- const again = buildOfficeLayout([...roster].reverse().map((a) => ({ ...a, state: "working" as const })),- { teams: [...teams].reverse().map((t) => ({ ...t, members: [...t.members].reverse() })) });- expect(again).toEqual(before);- // A newcomer without a team takes a pool desk; nobody in a team moves.- const grown = buildOfficeLayout([...roster, agent(24)], { teams });- for (const id of teams.flatMap((t) => t.members)) expect(seatOfAgent(grown, id), id).toBe(seatOfAgent(before, id));- for (const dept of before.departments.filter((d) => d.teamId)) {- const now = grown.departments.find((d) => d.id === dept.id)!;- expect([now.minX, now.minZ, now.maxX, now.maxZ]).toEqual([dept.minX, dept.minZ, dept.maxX, dept.maxZ]);- }- });-- it("folds teams beyond the last cell into the pool and a team too large for one studio spills there", () => {- const many = buildOfficeLayout(staff(30), { teams: teamsOf(14, 2) });- expect(many.departments).toHaveLength(MAX_STUDIOS);- expect(many.departments.filter((d) => d.teamId !== null)).toHaveLength(MAX_STUDIOS - 1);- expect(seatedCount(many)).toBe(30);- expect(many.studios![0].members).toEqual(["a23", "a24", "a25", "a26", "a27", "a28", "a29", "a30"]);- const huge = buildOfficeLayout(staff(40), { teams: [team(1, Array.from({ length: 40 }, (_, i) => i + 1))] });- expect(huge.studios!.find((s) => s.teamId === "team-1")!.members).toHaveLength(STUDIO_SEAT_CAP);- expect(huge.studios![0].members).toHaveLength(40 - STUDIO_SEAT_CAP);- expect(seatedCount(huge)).toBe(40);- });-- it("opens a second pool studio only when the pool outgrows one", () => {- const layout = buildOfficeLayout(staff(40));- expect(layout.departments.map((d) => [d.id, d.teamId])).toEqual([["studio-pool", null], ["studio-pool-2", null]]);- expect(seatedCount(layout)).toBe(40);- expect(buildOfficeLayout(staff(STUDIO_SEAT_CAP)).departments).toHaveLength(1);- });-});--describe("campus: a studio", () => {- it("sizes the desks to the team: one free desk, whole pairs, as few benches as hold them", () => {- const shape = (n: number) => studioShape(n).benches;- expect(shape(0)).toEqual([2]);- expect(shape(2)).toEqual([2]);- expect(shape(5)).toEqual([3]);- expect(shape(7)).toEqual([4]);- expect(shape(8)).toEqual([3, 2]);- expect(shape(12)).toEqual([4, 3]);- expect(shape(STUDIO_SEAT_CAP)).toEqual([4, 4, 4, 4]);- for (let n = 0; n <= STUDIO_SEAT_CAP; n += 1) {- const s = studioShape(n);- expect(s.seats, `${n} members`).toBeGreaterThanOrEqual(n);- // Never a row of empty benches: at most three free desks, and that only in the smallest studio.- expect(s.seats - n, `${n} members`).toBeLessThanOrEqual(n === 0 ? 4 : n < STUDIO_SEAT_CAP ? 3 : 0);- }- // Only the desks grow with the team: the huddle zone and the front zone are the same in every studio.- expect(studioShape(12).depth - studioShape(2).depth).toBeCloseTo(4.2, 9);- expect(studioShape(2).depth).toBeCloseTo(CAMPUS.studioHeader + 4.2 + CAMPUS.studioFront, 9);- });-- it("has a name wall, a board on it, huddle places in front of the board and its own colour", () => {- const layout = buildOfficeLayout(staff(20), { teams: [team(1, [1, 2]), team(2, [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])] });- const grid = buildNavGrid(layout);- expect(new Set(layout.departments.map((d) => d.tint)).size).toBe(layout.departments.length);- for (const studio of layout.studios!) {- const dept = layout.departments.find((d) => d.id === studio.deptId)!;- const board = layout.furniture.find((f) => f.id === studio.board!.id)!;- expect(board.kind).toBe("studioBoard");- expect(board.id).toBe(`studio-board:${dept.id}`);- // The board stands inside the studio, right in front of the name wall, facing south.- const box = footprint(board), wall = studioWallRect(dept);- expect(box.minX).toBeGreaterThan(wall.minX);- expect(box.maxX).toBeLessThan(wall.maxX);- expect(box.minZ).toBeGreaterThanOrEqual(wall.maxZ);- expect(box.minZ - wall.maxZ).toBeLessThan(0.1);- expect(layout.obstacles.some((o) => o.minX === wall.minX && o.minZ === wall.minZ && o.maxX === wall.maxX)).toBe(true);- // Its face is where the layout says, inside the board's footprint.- const face = studioBoardFace(studio.board!);- expect(face.rotationY).toBe(0);- expect(face.size).toEqual([STUDIO_BOARD_FACE.w, STUDIO_BOARD_FACE.h]);- expect(face.position[0]).toBe(board.x);- expect(face.position[2] - board.z).toBeCloseTo(STUDIO_BOARD_FACE.z, 9);- expect(face.position[2]).toBeLessThan(box.maxZ);- // Huddle places: at least as many as the team (up to six), apart, walkable, facing the board, clear of the desks.- const spots = studio.huddleSpotIds.map((id) => layout.spots.find((s) => s.id === id)!);- expect(spots.length).toBeGreaterThanOrEqual(Math.max(4, Math.min(6, studio.members.length)));- spots.forEach((spot, n) => {- expect(spot.id).toBe(`huddle:${dept.id}:${n}`);- expect([spot.kind, spot.pose, spot.room]).toEqual(["huddle", "stand", "floor"]);- expect(isWalkable(grid, spot), spot.id).toBe(true);- expect(inside(spot, dept), spot.id).toBe(true);- const ahead = { x: spot.x + Math.sin(spot.facing) * 0.5, z: spot.z + Math.cos(spot.facing) * 0.5 };- expect(Math.hypot(ahead.x - studio.board!.x, ahead.z - studio.board!.z)).toBeLessThan(Math.hypot(spot.x - studio.board!.x, spot.z - studio.board!.z));- for (const other of spots) if (other !== spot) expect(Math.hypot(other.x - spot.x, other.z - spot.z)).toBeGreaterThanOrEqual(0.75);- for (const desk of dept.desks) expect(Math.hypot(seatOf(desk).x - spot.x, seatOf(desk).z - spot.z)).toBeGreaterThan(1.5);- });- expect(inside(studio.centre, dept)).toBe(true);- // Every desk stands inside its studio.- for (const desk of dept.desks) expect(inside(desk, dept), desk.id).toBe(true);- }- });-- it("is a furnished room at every team size: screens on both sides, a planted front with the entrance, sofa, table, storage", () => {- const layout = buildOfficeLayout(staff(15), { teams: [team(1, [1, 2, 3]), team(2, [4, 5, 6, 7, 8, 9, 10, 11, 12])] });- const grid = buildNavGrid(layout);- const item = (id: string) => layout.ambience!.find((i) => i.id === id);- for (const dept of layout.departments) {- const cx = (dept.minX + dept.maxX) / 2, cz = (dept.minZ + dept.maxZ) / 2;- // A whole cell, whatever the head count.- expect(dept.maxX - dept.minX).toBeCloseTo(CAMPUS.cellW, 9);- for (const part of ["cabinet", "sofa", "table", "front-w", "front-e", "screen-e"]) expect(item(`${dept.id}-${part}`), `${dept.id}-${part}`).toBeDefined();- for (const part of ["cabinet", "sofa", "table"]) {- const piece = item(`${dept.id}-${part}`)!;- expect(piece.minX >= dept.minX && piece.maxX <= dept.maxX && piece.minZ >= dept.minZ && piece.maxZ <= dept.maxZ, piece.id).toBe(true);- // In the studio's own colour where the piece wears one.- if (part !== "table") expect(piece.tint).toBe(dept.tint);- }- // Both sides are closed over the studio's whole depth; the middle of the front is the way in.- for (const x of [dept.minX + 0.06, dept.maxX - 0.06]) {- for (const z of [dept.minZ + 1, cz, dept.maxZ - 1]) expect(isWalkable(grid, { x, z }), `side ${x},${z}`).toBe(false);- }- for (const dz of [-0.9, -0.37, 0.6]) expect(isWalkable(grid, { x: cx, z: dept.maxZ + dz }), `entrance ${dz}`).toBe(true);- for (const x of [dept.minX + 1.5, dept.maxX - 1.5]) expect(isWalkable(grid, { x, z: dept.maxZ - 0.37 }), `front ${x}`).toBe(false);- // Somewhere to sit and somewhere to stand, each a spot of its own.- for (const id of [`${dept.id}-sofa-0`, `${dept.id}-sofa-1`, `${dept.id}-table-0`, `${dept.id}-table-1`]) {- const spot = layout.spots.find((s) => s.id === id)!;- expect(spot, id).toBeDefined();- expect(inside(spot, dept), id).toBe(true);- }- }- // Two studios shoulder to shoulder share one screen: the pool (west of the boulevard) stands alone, the two- // teams east of the boulevard... do not: the second team took the cell on the pool's other side.- const [pool, first, second] = layout.departments;- expect(first.minX).toBeCloseTo(CAMPUS.boulevard / 2, 9);- expect(pool.maxX).toBeCloseTo(-CAMPUS.boulevard / 2, 9);- expect(second.maxX).toBeCloseTo(pool.minX, 9);- // The shared screen stands on the line between the two and wears neither colour.- const shared = item(`${second.id}-screen-e`)!;- expect((shared.minX + shared.maxX) / 2).toBeCloseTo(pool.minX, 9);- expect(shared.tint).toBeUndefined();- expect(item(`${pool.id}-screen-w`)).toBeUndefined();- expect(item(`${second.id}-screen-w`)!.tint).toBe(second.tint);- });-});--describe("campus: a team's lead", () => {- const roster = staff(8);- const members = [1, 2, 3, 4, 5];- const plan = (leadId?: string | null, extra: OfficeTeamInput[] = []) =>- buildOfficeLayout(roster, { teams: [team(1, members, leadId === undefined ? {} : { leadId }), ...extra] });- const studioOf = (layout: OfficeLayout, teamId: string) => layout.studios!.find((s) => s.teamId === teamId)!;- /** Agent id -> desk id, for everyone seated on the floor. */- const seats = (layout: OfficeLayout) => new Map(allDesks(layout).filter((d) => d.agentId).map((d) => [d.agentId!, d.id] as const));- const moved = (a: OfficeLayout, b: OfficeLayout) => [...seats(a)].filter(([id, desk]) => seats(b).get(id) !== desk).map(([id]) => id).sort();-- it("sits at the head desk: the first desk of the bench nearest the name wall", () => {- const layout = plan("a3");- const studio = studioOf(layout, "team-1");- expect(studio.leadId).toBe("a3");- // The lead first, the earliest arrival in the lead's place, everyone else by arrival.- expect(studio.members).toEqual(["a3", "a2", "a1", "a4", "a5"]);- const dept = layout.departments.find((d) => d.id === studio.deptId)!;- const head = dept.desks[0];- expect(head.id).toBe("studio-team-1:0:north:0");- expect(head.agentId).toBe("a3");- // It is on the bench nearest the name wall, and no desk of that bench stands further west.- const nearest = Math.min(...dept.desks.map((d) => d.z));- expect(head.z - nearest).toBeLessThan(1);- expect(dept.desks.every((d) => d.x >= head.x - 1e-9)).toBe(true);- expect(leadDesks(layout).map(({ desk, dept: of }) => [desk.id, of.id])).toEqual([["studio-team-1:0:north:0", "studio-team-1"]]);- // The lead can be walked to like anyone else.- expect(findPath(buildNavGrid(layout), layout.spawn, standOf(head))).not.toBeNull();- });-- it("is the same plan for the same teams and lead, however the answer is ordered", () => {- const other = team(2, [6, 7], { leadId: "a7" });- const a = buildOfficeLayout(roster, { teams: [team(1, members, { leadId: "a3" }), other] });- const b = buildOfficeLayout([...roster].reverse(), { teams: [other, team(1, [...members].reverse(), { leadId: "a3" })] });- expect(b).toEqual(a);- expect(studioOf(a, "team-2").members).toEqual(["a7", "a6"]);- });-- it("is never guessed: a lead who is no member, not on the roster or in the lead office leaves the studio without one", () => {- const plain = plan();- for (const leadId of ["a7", "ghost", "", null]) {- const layout = plan(leadId);- expect(studioOf(layout, "team-1").leadId, String(leadId)).toBeNull();- expect(layout, String(leadId)).toEqual(plain);- expect(leadDesks(layout)).toEqual([]);- }- // A lead-tier agent sits in the lead office, whatever team names it lead.- const boss = agent(0, { tier: "lead" });- const withBoss = (leadId?: string) => buildOfficeLayout([boss, ...roster], { teams: [team(1, [0, ...members], leadId ? { leadId } : {})] });- expect(studioOf(withBoss("a0"), "team-1").leadId).toBeNull();- expect(withBoss("a0")).toEqual(withBoss());- expect(withBoss("a0").lead.desks[0].agentId).toBe("a0");- });-- it("moves only who has to move: two people when a lead is named, three at most when it changes", () => {- const none = plan(), third = plan("a3"), fifth = plan("a5"), first = plan("a1");- // Named: the lead and the earliest arrival change places.- expect(moved(none, third)).toEqual(["a1", "a3"]);- // The earliest arrival already sits at the head desk.- expect(moved(none, first)).toEqual([]);- expect(studioOf(first, "team-1").leadId).toBe("a1");- // Changed: the old lead goes back to its own place, the new one to the head, the earliest arrival to the new lead's place.- expect(moved(third, fifth)).toEqual(["a1", "a3", "a5"]);- expect(moved(third, first)).toEqual(["a1", "a3"]);- // Nobody outside the team moves, and the studio keeps its size.- for (const next of [third, fifth, first]) {- expect(next.bounds).toEqual(none.bounds);- expect(next.departments.map((d) => [d.id, d.desks.length])).toEqual(none.departments.map((d) => [d.id, d.desks.length]));- }- });-- it("sits with the team it leads, not with an older team it is only a member of", () => {- const older = team(1, [1, 2, 3]), younger = team(2, [3, 4], { leadId: "a3" });- const layout = buildOfficeLayout(roster, { teams: [older, younger] });- expect(studioOf(layout, "team-1").members).toEqual(["a1", "a2"]);- expect(studioOf(layout, "team-2").members).toEqual(["a3", "a4"]);- expect(studioOf(layout, "team-2").leadId).toBe("a3");- // Named lead of two teams: at the head of the older one; the other has no lead on the floor.- const both = buildOfficeLayout(roster, { teams: [{ ...older, leadId: "a3" }, younger] });- expect(studioOf(both, "team-1").members).toEqual(["a3", "a2", "a1"]);- expect(studioOf(both, "team-1").leadId).toBe("a3");- expect(studioOf(both, "team-2").leadId).toBeNull();- expect(studioOf(both, "team-2").members).toEqual(["a4"]);- expect(seatedCount(both)).toBe(roster.length);- });-- it("keeps its head desk in a studio that is full: the newest member sits in the pool instead", () => {- const crowd = staff(STUDIO_SEAT_CAP + 3), newest = `a${STUDIO_SEAT_CAP + 3}`;- const everyone = Array.from({ length: STUDIO_SEAT_CAP + 3 }, (_, i) => i + 1);- const layout = buildOfficeLayout(crowd, { teams: [team(1, everyone, { leadId: newest })] });- const studio = studioOf(layout, "team-1");- expect(studio.members).toHaveLength(STUDIO_SEAT_CAP);- expect(studio.members[0]).toBe(newest);- expect(studio.leadId).toBe(newest);- // Three do not fit: the newest three who are not the lead.- expect(layout.studios![0].members).toEqual([`a${STUDIO_SEAT_CAP}`, `a${STUDIO_SEAT_CAP + 1}`, `a${STUDIO_SEAT_CAP + 2}`]);- expect(seatedCount(layout)).toBe(crowd.length);- });-});--describe("campus: the plan", () => {- it("is four cells wide at every size and grows southwards by a row of studios", () => {- const [small, mid, large] = SIZES.map(([, roster, teams]) => buildOfficeLayout(roster, { teams }));- // Four cells, the boulevard, a walk along each window and the strip at the glass.- expect(CAMPUS.cellsPerRow * CAMPUS.cellW + CAMPUS.boulevard + 2 * CAMPUS.promenade + 2 * FLOOR_EDGE).toBeCloseTo(55.0, 6);- for (const layout of [small, mid, large]) expect(size(layout).w).toBeCloseTo(55.0, 6);- expect(size(small).d).toBeCloseTo(47.0, 6);- expect(size(mid).d).toBeCloseTo(47.0, 6);- expect(size(large).d).toBeCloseTo(81.2, 6);- // More than two and a half times the floor it replaces (24.4 m x 38.2 m for the same small roster).- expect(size(small).w * size(small).d).toBeGreaterThan(2.5 * 24.4 * 38.2);- // One row holds four studios; the fifth opens a second row.- const rows = (layout: OfficeLayout) => new Set(layout.departments.map((d) => d.minZ)).size;- expect(rows(buildOfficeLayout(staff(12), { teams: teamsOf(3, 3) }))).toBe(1);- expect(rows(buildOfficeLayout(staff(12), { teams: teamsOf(4, 3) }))).toBe(2);- expect(rows(large)).toBe(3);- });-- for (const [name, roster, teams] of SIZES) {- it(`is furnished, not circulation: rooms, studios and commons take most of the floor (${name})`, () => {- const layout = buildOfficeLayout(roster, { teams });- const plan = { minX: layout.bounds.minX + 1.6, maxX: layout.bounds.maxX - 1.6, minZ: layout.bounds.minZ + 1.6, maxZ: layout.bounds.maxZ - 1.6 };- const places = [...layout.rooms, ...layout.departments, ...layout.zones!.filter((z) => z.kind !== "boulevard" && z.kind !== "plaza")];- const furnished = places.reduce((sum, r) => sum + area(r), 0);- expect(furnished / area(plan)).toBeGreaterThan(0.68);- // Streets are streets: the boulevard and the streets between rows are a few metres wide, the plaza is the one wide one.- expect(CAMPUS.boulevard).toBeLessThanOrEqual(5);- expect(CAMPUS.street).toBeLessThan(4);- // Studios of a row stand shoulder to shoulder, their fronts in one line.- const rows = new Map<number, typeof layout.departments>();- for (const dept of layout.departments) rows.set(dept.minZ, [...(rows.get(dept.minZ) ?? []), dept]);- for (const row of rows.values()) {- expect(new Set(row.map((d) => d.maxZ)).size).toBe(1);- const sorted = [...row].sort((a, b) => a.minX - b.minX);- for (let i = 1; i < sorted.length; i += 1) {- const gap = sorted[i].minX - sorted[i - 1].maxX;- expect(gap === 0 || Math.abs(gap - CAMPUS.boulevard) < 1e-9 || Math.abs(gap - CAMPUS.cellW) < 1e-9 || gap > CAMPUS.cellW, `gap ${gap}`).toBe(true);- }- }- });-- it(`keeps studios, rooms, streets and fittings apart (${name})`, () => {- const layout = buildOfficeLayout(roster, { teams });- const zones = layout.zones!, streets = zones.filter((z) => z.kind === "boulevard" || z.kind === "plaza");- const blocks: Rect[] = [...layout.departments, ...layout.rooms];- for (const a of blocks) for (const b of blocks) if (a !== b) expect(overlaps(a, b)).toBe(false);- // Nothing is built on the boulevards, and no commons or plot overlaps a studio, a room or another commons.- for (const block of blocks) for (const street of streets) expect(overlaps(block, street)).toBe(false);- const commons = zones.filter((z) => z.kind !== "boulevard" && z.kind !== "plaza" && z.kind !== "atrium");- for (const zone of commons) {- for (const block of blocks) expect(overlaps(zone, block), zone.id).toBe(false);- for (const street of streets) expect(overlaps(zone, street), zone.id).toBe(false);- for (const other of commons) if (other !== zone) expect(overlaps(zone, other), `${zone.id} x ${other.id}`).toBe(false);- }- // Fittings never stand in a room or on a desk, and each one is solid.- const ambience = layout.ambience!;- expect(new Set(ambience.map((i) => i.id)).size).toBe(ambience.length);- const kinds: AgentsAmbienceKind[] = ["olive", "tree", "bench", "planter", "screen", "cabinet", "sofa", "hightable", "booth", "steps", "counter", "island"];- // The free plot's crates are there while a plot is.- expect(ambience.some((i) => i.kind === "crate")).toBe(layout.zones!.some((z) => z.kind === "plot"));- for (const kind of kinds) expect(ambience.some((i) => i.kind === kind), kind).toBe(true);- for (const item of ambience) {- for (const room of layout.rooms) expect(overlaps(item, room), item.id).toBe(false);- for (const desk of allDesks(layout)) expect(inside(desk, item), item.id).toBe(false);- for (const solid of ambienceObstacles(item)) {- expect(layout.obstacles.some((o) => o.minX === solid.minX && o.maxX === solid.maxX && o.minZ === solid.minZ && o.maxZ === solid.maxZ), item.id).toBe(true);- }- // The railing's base is 8 cm wide on a line 0.2 m in from the slab edge.- expect(item.minX, item.id).toBeGreaterThan(layout.bounds.minX + 0.24);- expect(item.maxX, item.id).toBeLessThan(layout.bounds.maxX - 0.24);- expect(item.minZ, item.id).toBeGreaterThan(layout.bounds.minZ + 0.24);- expect(item.maxZ, item.id).toBeLessThan(layout.bounds.maxZ - 0.24);- }- // Planting is a few deliberate groups, not rows: far fewer trees than studios and commons could hold.- const trees = ambience.filter((i) => i.kind === "olive" || i.kind === "tree").length;- expect(trees).toBeLessThanOrEqual(12 + 2 * layout.departments.length + 3 * kindsOf(layout, "garden").length);- expect(ambience.some((i) => i.kind === "tree") && ambience.some((i) => i.kind === "olive")).toBe(true);- });-- it(`never stands two solid things in the same place (${name})`, () => {- const layout = buildOfficeLayout([agent(0, { tier: "lead" }), agent(99, { tier: "lead" }), ...roster], { teams });- const solids: (Rect & { id: string })[] = [- ...layout.furniture.filter((f) => FURNITURE_SIZE[f.kind].solid).map((f) => ({ id: f.id, ...footprint(f) })),- ...layout.ambience!.map((i) => ({ ...i })),- ...allDesks(layout).map((d) => ({ id: `desk ${d.id}`, ...deskRect(d) })),- ...layout.departments.map((d) => ({ id: `wall ${d.id}`, ...studioWallRect(d) })),- ...layout.departments.flatMap(benchPlanters).map((p) => ({ id: `planter ${p.key}`, ...p.rect })),- ...layout.walls.map((w, n) => ({ id: `room wall ${n}`, minX: Math.min(w.x1, w.x2) - 0.06, maxX: Math.max(w.x1, w.x2) + 0.06, minZ: Math.min(w.z1, w.z2) - 0.06, maxZ: Math.max(w.z1, w.z2) + 0.06 })),- ];- const clashes: string[] = [];- for (let i = 0; i < solids.length; i += 1) {- for (let j = i + 1; j < solids.length; j += 1) {- if (solids[i].id.startsWith("room wall") && solids[j].id.startsWith("room wall")) continue;- if (overlaps(solids[i], solids[j])) clashes.push(`${solids[i].id} x ${solids[j].id}`);- }- }- // By design: the team board hangs on the team room's slat wall, so their footprints touch. Nothing else does.- expect(clashes).toEqual(["team-wall x team-board"]);- // Nothing solid stands in a doorway: one step inside and one outside every door is free.- const grid = buildNavGrid(layout);- for (const room of layout.rooms) {- for (const door of room.doors) {- const horizontal = door.side === "north" || door.side === "south";- const line = door.side === "north" ? room.minZ : door.side === "south" ? room.maxZ : door.side === "west" ? room.minX : room.maxX;- for (const step of [-0.8, 0, 0.8]) {- const p = horizontal ? { x: door.at, z: line + step } : { x: line + step, z: door.at };- expect(isWalkable(grid, p), `${room.kind} ${door.side} door ${step}`).toBe(true);- }- }- }- });-- it(`puts the spawn point in the atrium, where the boulevards cross (${name})`, () => {- const layout = buildOfficeLayout(roster, { teams });- const stop = layout.checkpoints.find((c) => c.id === "spawn")!;- const zone = (kind: string) => layout.zones!.find((z) => z.kind === kind)!;- const pad = layout.furniture.find((f) => f.kind === "spawnPad")!, terminal = layout.furniture.find((f) => f.kind === "spawnTerminal")!;- expect([pad.x, pad.z, terminal.x, terminal.z]).toEqual([stop.x, stop.z, stop.x, stop.z]);- expect(stop.x).toBe(0);- expect(stop.z).toBeCloseTo((zone("plaza").minZ + zone("plaza").maxZ) / 2, 9);- expect(inside(stop, zone("atrium")) && inside(stop, zone("boulevard"))).toBe(true);- // The plaza is the gap between two blocks nearest the floor's middle; the boulevard runs from the lobby to the team room's door.- expect(Math.abs(stop.z)).toBeLessThan(size(layout).d / 4);- const teamRoom = layout.rooms.find((r) => r.kind === "team")!, lobby = layout.rooms.find((r) => r.kind === "reception")!;- expect(teamRoom.doors[0].at).toBe(0);- expect(zone("boulevard").minZ).toBe(teamRoom.maxZ);- expect(zone("boulevard").maxZ).toBe(lobby.minZ);- expect((lobby.minX + lobby.maxX) / 2).toBe(0);- // The heart of the campus: step seating either side of the pad, facing it, with seats; the pad itself stays clear.- const padBox = footprint(pad);- for (const item of layout.ambience!) expect(overlaps(item, padBox), item.id).toBe(false);- const [west, east] = ["west", "east"].map((side) => layout.ambience!.find((i) => i.id === `atrium-steps-${side}`)!);- expect([west.kind, west.facing, east.kind, east.facing]).toEqual(["steps", "east", "steps", "west"]);- expect(inside({ x: (west.minX + west.maxX) / 2, z: (west.minZ + west.maxZ) / 2 }, zone("atrium"))).toBe(true);- const seats = layout.spots.filter((s) => s.id.startsWith("atrium-steps-"));- expect(seats.length).toBeGreaterThanOrEqual(8);- for (const seat of seats) {- expect([seat.kind, seat.pose]).toEqual(["couch", "sit"]);- // Looking at the spawn point.- expect(Math.sign(Math.sin(seat.facing))).toBe(seat.x < 0 ? 1 : -1);- }- expect(layout.arrival).toEqual(stop.approach);- expect(isWalkable(buildNavGrid(layout), layout.arrival)).toBe(true);- });- }-- it("shows the next team's place as a free plot and makes the other empty cells garden courts", () => {- const empty = buildOfficeLayout(staff(5));- expect(kindsOf(empty, "plot", "garden")).toEqual(["plot", "garden", "garden"]);- // The first team takes exactly the plot's cell; the plot moves on.- const plot = empty.zones!.find((z) => z.kind === "plot")!;- const one = buildOfficeLayout(staff(5), { teams: [team(1, [1, 2])] });- const studio = one.departments.find((d) => d.teamId === "team-1")!;- expect(overlaps(plot, studio) && plot.minX > studio.minX && plot.maxX < studio.maxX && plot.minZ > studio.minZ).toBe(true);- expect(kindsOf(one, "plot", "garden")).toEqual(["plot", "garden"]);- expect(kindsOf(buildOfficeLayout(staff(12), { teams: teamsOf(3, 3) }), "plot", "garden")).toEqual([]);- });-- it("furnishes the free plot: the stand where a team is started faces the street, crates and a plant wait behind it", () => {- const layout = buildOfficeLayout(staff(5));- const grid = buildNavGrid(layout);- const plot = layout.zones!.find((z) => z.kind === "plot")!;- const stands = layout.furniture.filter((f) => f.kind === "teamStand");- expect(stands.map((f) => [f.id, f.rotationY])).toEqual([["team-stand", 0]]);- const stand = stands[0];- expect(inside(stand, plot)).toBe(true);- expect(isWalkable(grid, stand)).toBe(false);- // The station layer stands the person 0.95 m in front of its face: on the plot, on open floor, within reach.- const front = { x: stand.x, z: stand.z + FURNITURE_SIZE.teamStand.d / 2 + 0.95 };- expect(inside(front, plot)).toBe(true);- expect(isWalkable(grid, front)).toBe(true);- expect(findPath(grid, layout.spawn, front)).not.toBeNull();- const crates = layout.ambience!.filter((i) => i.kind === "crate");- expect(crates.map((i) => i.id)).toEqual(["plot-crates"]);- expect(overlaps(crates[0], plot)).toBe(true);- expect(isWalkable(grid, { x: (crates[0].minX + crates[0].maxX) / 2, z: (crates[0].minZ + crates[0].maxZ) / 2 })).toBe(false);- expect(inside(layout.furniture.find((f) => f.id === "plot-plant")!, plot)).toBe(true);- // A full row has no plot: no stand, no crates.- const full = buildOfficeLayout(staff(12), { teams: teamsOf(3, 3) });- expect(full.furniture.some((f) => f.kind === "teamStand" || f.id === "plot-plant")).toBe(false);- expect(full.ambience!.some((i) => i.kind === "crate")).toBe(false);- });-- it("carries the lobby's name on an arch at the back of the reception desk, off the atrium", () => {- for (const [, roster, teams] of SIZES) {- const layout = buildOfficeLayout(roster, { teams });- const reception = layout.rooms.find((r) => r.kind === "reception")!;- const desk = footprint(layout.furniture.find((f) => f.kind === "receptionDesk")!);- const posts = archPosts(reception);- expect(posts).toHaveLength(2);- for (const post of posts) {- expect(inside(post, reception)).toBe(true);- // Behind the desk's back, within its width: the board reads as the desk's own sign.- expect(post.x).toBeGreaterThan(desk.minX);- expect(post.x).toBeLessThan(desk.maxX);- expect(desk.minZ - post.z).toBeGreaterThan(ARCH.post / 2);- expect(desk.minZ - post.z).toBeLessThan(0.3);- for (const zone of layout.zones!.filter((z) => z.kind === "atrium" || z.kind === "plaza")) expect(inside(post, zone)).toBe(false);- expect(isWalkable(buildNavGrid(layout), post)).toBe(false);- }- }- });-- for (const [name, roster, teams] of SIZES) {- it(`keeps a real walk along both windows, between the benches at the glass and the outer studios (${name})`, () => {- const layout = buildOfficeLayout(roster, { teams });- const grid = buildNavGrid(layout);- const band = layout.ambience!.filter((i) => /^(bench|planter)-(west|east)-\d+$/.test(i.id));- expect(band.length).toBeGreaterThanOrEqual(4);- for (const piece of band) {- const west = piece.id.includes("-west-");- // The nearest solid thing further into the floor, beside this piece.- const beside = layout.obstacles.filter((o) => o.minZ < piece.maxZ && o.maxZ > piece.minZ && (west ? o.minX >= piece.maxX : o.maxX <= piece.minX));- const clear = Math.min(...beside.map((o) => (west ? o.minX - piece.maxX : piece.minX - o.maxX)));- expect(clear, piece.id).toBeGreaterThanOrEqual(1.2);- }- // And it is one walk from the first row of studios to the last, on both sides.- const rows = [...layout.departments, ...layout.zones!.filter((z) => z.kind === "plot" || z.kind === "garden")];- const z0 = Math.min(...rows.map((r) => r.minZ)), z1 = Math.max(...rows.map((r) => r.maxZ));- for (const x of [layout.bounds.minX + FLOOR_EDGE + CAMPUS.promenade / 2, layout.bounds.maxX - FLOOR_EDGE - CAMPUS.promenade / 2]) {- for (let z = z0; z <= z1; z += 0.4) expect(isWalkable(grid, { x, z }), `walk ${x} at ${z}`).toBe(true);- }- });- }-- for (const [name, roster, teams] of SIZES) {- it(`has its commons at every size, each with places to use it (${name})`, () => {- const layout = buildOfficeLayout(roster, { teams });- expect(kindsOf(layout, "booths", "library", "cafe")).toEqual(["booths", "library", "cafe"]);- const grid = buildNavGrid(layout);- const spotsIn = (kind: string) => {- const zone = layout.zones!.find((z) => z.kind === kind)!;- return layout.spots.filter((s) => s.room === "floor" && inside(s, zone));- };- // Somewhere to sit and somewhere to stand in the café and the library; a booth each for three people.- for (const kind of ["cafe", "library", "booths"]) {- const spots = spotsIn(kind);- expect(spots.length, kind).toBeGreaterThanOrEqual(5);- expect(spots.some((s) => s.pose === "sit") && spots.some((s) => s.pose === "stand"), kind).toBe(true);- }- const booths = layout.spots.filter((s) => /^booth-\d$/.test(s.id));- expect(booths).toHaveLength(3);- // A person walks into a booth and stands inside it.- for (const spot of booths) {- expect(isWalkable(grid, spot), spot.id).toBe(true);- const box = layout.ambience!.find((i) => i.id === spot.id)!;- expect(inside(spot, box)).toBe(true);- expect(isWalkable(grid, { x: spot.x, z: box.minZ + 0.1 })).toBe(false);- }- // A garden court has a bench to sit on.- for (const zone of layout.zones!.filter((z) => z.kind === "garden")) {- expect(layout.spots.filter((s) => inside(s, zone) && s.pose === "sit").length, zone.id).toBeGreaterThanOrEqual(2);- }- // Every spot outside the rooms is a place a figure can be: on the open floor, or on a seat within a step of it.- for (const spot of layout.spots.filter((s) => s.room === "floor")) {- expect(findPath(grid, layout.spawn, spot), spot.id).not.toBeNull();- }- });- }-});--describe("campus: walking it", () => {- const cases: [string, OfficeAgentInput[], OfficeTeamInput[]][] = [- ["no team", staff(5), []],- ["one team of two", staff(6), [team(1, [1, 2])]],- ["three teams, one of twelve", staff(20), [team(1, [1, 2]), team(2, [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]), team(3, [15, 16, 17])]],- ["eight teams", staff(40), teamsOf(8, 4)],- ["an agent in two teams and a team of unknown ids", staff(8), [team(1, [1, 2, 3]), team(2, [3, 4]), team(3, [90, 91])]],- ];- for (const [name, roster, teams] of cases) {- it(`reaches every seat, spot, station and studio board from the elevator (${name})`, () => {- const layout = buildOfficeLayout([agent(0, { tier: "lead" }), ...roster], { teams });- const grid = buildNavGrid(layout);- const elevator = layout.checkpoints.find((c) => c.id === "elevator")!;- const targets: { name: string; p: Point }[] = [- ...allDesks(layout).flatMap((d) => [{ name: `seat ${d.id}`, p: seatOf(d) }, { name: `stand ${d.id}`, p: standOf(d) }]),- ...layout.spots.map((s) => ({ name: `spot ${s.id}`, p: s })),- ...layout.checkpoints.map((c) => ({ name: `station ${c.id}`, p: c.approach ?? c })),- // In front of every studio board, where the person reads it.- ...layout.studios!.map((s) => ({ name: `board ${s.deptId}`, p: { x: s.board!.x, z: s.board!.z + 1.0 } })),- ...layout.zones!.map((z) => ({ name: `zone ${z.id}`, p: { x: (z.minX + z.maxX) / 2 + 0.9, z: (z.minZ + z.maxZ) / 2 + 2.2 } })),- ];- for (const start of [layout.spawn, elevator]) {- expect(isWalkable(grid, start)).toBe(true);- for (const target of targets) {- if (!findPath(grid, start, target.p)) throw new Error(`${target.name} at ${target.p.x.toFixed(2)},${target.p.z.toFixed(2)} is unreachable`);- }- }- });-- it(`sends every route from the lobby to a studio or a room across the plaza (${name})`, () => {- const layout = buildOfficeLayout(roster, { teams });- const grid = buildNavGrid(layout);- const plaza = layout.zones!.find((z) => z.kind === "plaza")!;- const elevator = layout.checkpoints.find((c) => c.id === "elevator")!;- const north = [- ...layout.departments.filter((d) => d.maxZ <= plaza.minZ).map((d) => ({ x: (d.minX + d.maxX) / 2, z: d.minZ + 2.0 })),- ...layout.checkpoints.filter((c) => ["team", "lead", "wardrobe"].includes(c.id)),- ];- expect(north.length).toBeGreaterThan(3);- // The main boulevard runs from window to window: whoever goes north passes over it, in the middle or along a window.- const band = { ...plaza, minX: layout.floor.minX, maxX: layout.floor.maxX };- for (const target of north) {- const path = [elevator, ...findPath(grid, elevator, target)!];- expect(path.some((p, i) => i > 0 && (inside(p, band) || (path[i - 1].z > band.maxZ && p.z < band.minZ))), `${target.x},${target.z}`).toBe(true);- expect(path.every((p) => inside(p, layout.floor))).toBe(true);- }- });- }-- it("keeps the boulevard, the plaza and every street open from end to end", () => {- const layout = buildOfficeLayout(staff(40), { teams: teamsOf(8, 4) });- const grid = buildNavGrid(layout);- const boulevard = layout.zones!.find((z) => z.kind === "boulevard")!, plaza = layout.zones!.find((z) => z.kind === "plaza")!;- for (let z = boulevard.minZ + 0.3; z < boulevard.maxZ - 0.3; z += 0.4) {- // The boulevard's middle is free all the way, except where the spawn terminal stands on it.- if (Math.abs(z - (plaza.minZ + plaza.maxZ) / 2) < 1) continue;- expect(isWalkable(grid, { x: 0, z }), `axis at ${z}`).toBe(true);- }- // Past the step seating on both sides of the plaza, and along the street in front of every row of studios.- const streets = [plaza.minZ + 1.5, plaza.maxZ - 1.5, ...new Set(layout.departments.map((d) => d.maxZ + 1.2)), boulevard.minZ + CAMPUS.street / 2];- for (const z of streets) {- for (let x = layout.floor.minX + 1.5; x < layout.floor.maxX - 1.5; x += 0.4) expect(isWalkable(grid, { x, z }), `street ${z} at ${x}`).toBe(true);- }- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/campusLayout.ts b/dodaios/ui/web/frontend/src/components/society/office/campusLayout.tsdeleted file mode 100644index 5fdf30019d..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/campusLayout.ts+++ /dev/null@@ -1,700 +0,0 @@-/**- * The agents floor as a team campus.- *- * ┌ booths ┬── Lead office ──┬──── Team room ────┬─ Wardrobe ─┬─── library ───┐- * │ north street │- * │ studio ┃ studio ║ ║ studio ┃ studio │- * │ ┃ ║ boulevard ║ ┃ a street of team rooms │- * │═══════ main boulevard · ATRIUM: spawn point, step seating ═══════════════│- * │ café │ Reception + lobby (elevator) │ │ Break room │- * └─────────────────┴──────────────────────────────────┴─┴────────────────────┘- *- * Every team (a society chat group) has a studio: a room of its own with a- * name wall and the studio board at its back, low screens on both sides, a- * planted front with the entrance, the desks sized to the team, a huddle zone- * in front of the board, a sofa, a standing table and a storage cabinet.- * Agents without a team share the pool studio. Studios stand shoulder to- * shoulder in rows of four, two either side of the boulevard that runs from- * the lobby to the team room, and open onto the street in front of them. The- * main boulevard crosses at the atrium: the spawn point between two flights- * of step seating. Every route between the lobby, the rooms and the studios- * crosses that plaza.- *- * What is not a studio or a room is a commons people use: the café beside the- * lobby, the library and the focus booths in the north corners, and in a cell- * without a studio the free plot (the next team's place) or a garden court.- *- * The plan is four cells wide at every size; it grows southwards by a row of- * studios whenever a row is full. Pure and deterministic: the same roster and- * the same teams always give the same plan and the same seats.- */-import {- ambienceObstacles, bench, benchSeats, booth, boothPlace, cabinet, counter, counterStands, crate, highTable, island, olive, planter,- screen, sofa, sofaSeats, steps, stepsSeats, tableStands, tree, BENCH_DEPTH, PLANTER_DEPTH, SOFA,- type AgentsAmbienceItem, type AmbiencePlace,-} from "./agentsAmbience";-import {- ARCH, archPosts, BENCH_DEPTH_Z, benchPlanters, byArrival, chairRect, DESK_HALF_GAP, DESK_PITCH_X, deskRect,- executiveChairRect, EXECUTIVE_DESK_SIZE, FLOOR_EDGE, footprint, FURNITURE_SIZE, PARTNER_DESK_SIZE, RAIL_CLEARANCE,- seatOf, SPAWN, STUDIO_BOARD_FACE, wallRect, wallsOf,- type CampusZone, type Checkpoint, type Department, type DeskSlot, type Furniture, type FurnitureKind,- type OfficeAgentInput, type OfficeLayout, type OfficeTeamInput, type Point, type Rect, type Room, type RoomKind,- type Spot, type SpotKind, type SpotPose, type Studio, type WallSegment,-} from "./officeLayout";-import { skyPadFor } from "./skyPad";--/**- * The campus grid, in metres. A cell holds one studio; two cells stand- * shoulder to shoulder on each side of the boulevard. A street separates two- * rows, and the plaza is the main boulevard with the atrium at its heart.- */-export const CAMPUS = {- cellW: 11, boulevard: 5, street: 3.6, plaza: 9, atrium: 16,- /** The walk along both windows, between the benches at the glass and the outer studios. */- promenade: 1.4,- northDepth: 9.4, southDepth: 10.4,- /** A studio, north to south: the huddle zone between its name wall and the first desks, then the desks, then the front zone with the sofa and the entrance. */- studioHeader: 4, studioFront: 3.2,- /** The opening in a studio's planted front. */- studioDoor: 4.8,- cellsPerRow: 4,-} as const;--/** Desks come in facing pairs; a bench holds up to four pairs, a studio up to four benches. */-const PAIRS_PER_BENCH = 4;-const MAX_BENCHES = 4;-/** The most agents one studio seats; a larger team's newest members sit in the pool. */-export const STUDIO_SEAT_CAP = MAX_BENCHES * PAIRS_PER_BENCH * 2;-/** The most studios the campus builds (three rows); later teams fold into the pool. */-export const MAX_STUDIOS = 12;-/** A cell's column for each slot of a row: the two cells beside the boulevard fill first, west before east. */-const SLOT_COLUMNS = [1, 2, 0, 3] as const;-/** How far the walkable floor's west edge (the navigation grid's origin) is moved off the plan's 0.05 m raster. */-const GRID_NUDGE = 0.025;-/** Zone colour of the pool studio (neutral linen), and the cycle the team studios take theirs from. */-const POOL_TINT = 2;-const TEAM_TINTS = [0, 1, 3, 4, 5, 6, 7, 8, 9, 10, 11] as const;--/** Who sits in one studio, before it has a place on the floor. */-export interface StudioPlan {- id: string;- /** The team whose studio this is; null for the pool. */- teamId: string | null;- /** The team's name; "" for the pool (the renderer names it). */- name: string;- /** The team's lead when it sits here, at the head desk; see `Studio.leadId`. */- leadId: string | null;- /** Seated members in seating order: by arrival, with the lead (if any) and the earliest arrival having changed places. */- members: OfficeAgentInput[];-}--function slug(id: string): string {- return id.replace(/[^A-Za-z0-9_-]/g, "_");-}--/**- * Sort the roster into studios. The first two lead-tier agents keep the lead- * office. Teams are taken oldest first (then by id): an agent in several teams- * sits in the oldest one. A team keeps its studio even when none of its- * members can sit there (unknown ids, or everyone already seated elsewhere).- * Whoever has no team, or no room left in theirs, sits in the pool, which- * comes first and opens further pool studios only when it outgrows one.- *- * A team's lead sits at the head of the studio it leads: first in its seating- * order, where the earliest arrival would sit, who takes the lead's place in- * the order instead. So naming a lead moves two people, and changing one at- * most three (the old lead back to its own place, the new one to the head,- * the earliest arrival to the new lead's place); everyone else stays. Leading- * a team comes before "the oldest team" for an agent in several, and before- * the studio's seat cap. A lead must be a member the roster knows who is not- * in the lead office; whoever is named lead of several teams sits with the- * oldest of them, and the others have no lead on the floor.- */-export function planStudios(agents: readonly OfficeAgentInput[], teams: readonly OfficeTeamInput[]): StudioPlan[] {- const leads = agents.filter((a) => a.tier === "lead").sort(byArrival).slice(0, 2);- const inOffice = new Set(leads.map((a) => a.agentId));- const staff = agents.filter((a) => !inOffice.has(a.agentId)).sort(byArrival);- const byId = new Map(staff.map((a) => [a.agentId, a]));- const seen = new Set<string>();- const ordered = [...teams]- .sort((a, b) => a.createdMs - b.createdMs || a.id.localeCompare(b.id))- .filter((team) => (seen.has(team.id) ? false : (seen.add(team.id), true)))- .slice(0, MAX_STUDIOS - 1);-- // Agent id -> the team at whose head it sits.- const heads = new Map<string, string>();- for (const team of ordered) {- const lead = team.leadId;- if (lead && byId.has(lead) && team.members.includes(lead) && !heads.has(lead)) heads.set(lead, team.id);- }-- const claimed = new Set<string>();- const ids = new Set<string>(["studio-pool"]);- const teamPlans: StudioPlan[] = ordered.map((team) => {- const mine: OfficeAgentInput[] = [];- for (const memberId of new Set(team.members)) {- const agent = byId.get(memberId);- const headOf = heads.get(memberId);- // Whoever leads another team sits there.- if (!agent || claimed.has(memberId) || (headOf !== undefined && headOf !== team.id)) continue;- mine.push(agent);- }- mine.sort(byArrival);- const lead = team.leadId && heads.get(team.leadId) === team.id ? byId.get(team.leadId) ?? null : null;- let seated = mine.slice(0, STUDIO_SEAT_CAP);- // A lead who arrived after the studio was full still sits in it, in place of its newest member.- if (lead && !seated.includes(lead)) seated = [...seated.slice(0, STUDIO_SEAT_CAP - 1), lead];- if (lead) {- const at = seated.indexOf(lead);- [seated[0], seated[at]] = [seated[at], seated[0]];- }- for (const agent of seated) claimed.add(agent.agentId);- let id = `studio-${slug(team.id)}`;- for (let n = 2; ids.has(id); n += 1) id = `studio-${slug(team.id)}-${n}`;- ids.add(id);- return { id, teamId: team.id, name: team.name.trim(), leadId: lead?.agentId ?? null, members: seated };- });-- const pool = staff.filter((a) => !claimed.has(a.agentId));- const poolStudios = Math.min(MAX_STUDIOS - teamPlans.length, Math.max(1, Math.ceil(pool.length / STUDIO_SEAT_CAP)));- const pools: StudioPlan[] = Array.from({ length: poolStudios }, (_, n) => ({- id: n === 0 ? "studio-pool" : `studio-pool-${n + 1}`, teamId: null, name: "", leadId: null,- members: pool.slice(n * STUDIO_SEAT_CAP, (n + 1) * STUDIO_SEAT_CAP),- }));- return [pools[0], ...teamPlans, ...pools.slice(1)];-}--/** A studio's desk cluster and depth for a head count. */-export interface StudioShape {- /** Facing desk pairs per bench, north bench first. */- benches: number[];- seats: number;- /** North to south: huddle zone, benches, front zone. A studio is always one cell wide. */- depth: number;-}--/**- * The desk cluster a studio of `members` gets: one free desk to grow into,- * rounded up to whole pairs, spread evenly over as few benches as hold them.- * At least two pairs, so even a new team's studio is a place to work.- */-export function studioShape(members: number): StudioShape {- const want = Math.min(STUDIO_SEAT_CAP, Math.max(0, members) + 1);- const pairs = Math.max(2, Math.ceil(want / 2));- const count = Math.ceil(pairs / PAIRS_PER_BENCH);- const benches = Array.from({ length: count }, (_, i) => Math.floor(pairs / count) + (i < pairs % count ? 1 : 0));- return { benches, seats: pairs * 2, depth: CAMPUS.studioHeader + count * BENCH_DEPTH_Z + CAMPUS.studioFront };-}--/** The x-range of each of the four cells, west to east: two shoulder to shoulder on each side of the boulevard. */-function cellRanges(): [number, number][] {- const half = CAMPUS.boulevard / 2, w = CAMPUS.cellW;- return [[-half - 2 * w, -half - w], [-half - w, -half], [half, half + w], [half + w, half + 2 * w]];-}--/**- * Desk slots of a studio: bench by bench, each pair facing across the bench, filled in seating order. The first- * slot, on the bench nearest the name wall, is the head desk: the lead's when the team has one.- */-function studioDesks(id: string, cx: number, minZ: number, shape: StudioShape, members: readonly OfficeAgentInput[]): DeskSlot[] {- const desks: DeskSlot[] = [];- let seat = 0;- shape.benches.forEach((pairs, benchIndex) => {- const centreZ = minZ + CAMPUS.studioHeader + benchIndex * BENCH_DEPTH_Z + BENCH_DEPTH_Z / 2;- const west = cx - (pairs * DESK_PITCH_X) / 2;- for (let col = 0; col < pairs; col += 1) {- for (const facing of ["north", "south"] as const) {- // A north-facing agent sits on the south side of the pair, looking at its monitor.- const z = facing === "north" ? centreZ + DESK_HALF_GAP : centreZ - DESK_HALF_GAP;- desks.push({ id: `${id}:${benchIndex}:${facing}:${col}`, x: west + DESK_PITCH_X * (col + 0.5), z, facing, agentId: members[seat]?.agentId ?? null });- seat += 1;- }- }- });- return desks;-}--/** A studio's name wall along its north edge: solid, and what the studio board hangs in front of. */-export function studioWallRect(dept: Rect): Rect {- return { minX: dept.minX + 0.2, maxX: dept.maxX - 0.2, minZ: dept.minZ + 0.02, maxZ: dept.minZ + 0.2 };-}--/** Where a studio's name is lettered on its wall and where its board hangs: the west and the east half. */-export function studioWallParts(dept: Rect): { nameX: number; boardX: number; span: number } {- const span = dept.maxX - dept.minX - 0.4;- const cx = (dept.minX + dept.maxX) / 2;- return { nameX: cx - span / 4, boardX: cx + span / 4, span };-}--/** Standing places in front of a studio board: a front row of four and a back row of three. */-const HUDDLE_OFFSETS: readonly (readonly [number, number])[] = [- [-0.4, 1.45], [0.4, 1.45], [-1.2, 1.45], [1.2, 1.45], [0, 2.3], [-0.8, 2.3], [0.8, 2.3],-];--/** Wall runs of all rooms, each run once: two rooms sharing a wall line would otherwise both draw (and both block) it. */-function uniqueWalls(rooms: readonly Room[]): WallSegment[] {- const seen = new Set<string>();- return rooms.flatMap(wallsOf).filter((wall) => {- const key = [`${wall.x1.toFixed(3)},${wall.z1.toFixed(3)}`, `${wall.x2.toFixed(3)},${wall.z2.toFixed(3)}`].sort().join("|");- return seen.has(key) ? false : (seen.add(key), true);- });-}--/** Build the agents floor for a roster and its teams. */-export function buildCampusLayout(agents: readonly OfficeAgentInput[], teams: readonly OfficeTeamInput[]): OfficeLayout {- const plans = planStudios(agents, teams);- const shapes = plans.map((plan) => studioShape(plan.members.length));- const cells = cellRanges();- const planMinX = cells[0][0] - CAMPUS.promenade, planMaxX = cells[3][1] + CAMPUS.promenade;- const perRow = CAMPUS.cellsPerRow;- const rowCount = Math.max(1, Math.ceil(plans.length / perRow));- const minRowDepth = studioShape(0).depth;- // The studios of a row share its depth, so their fronts line up along the street.- const rowDepth = Array.from({ length: rowCount }, (_, r) =>- Math.max(minRowDepth, ...shapes.slice(r * perRow, (r + 1) * perRow).map((s) => s.depth)));-- // Depth: north strip, a street, the rows with a street after each — except one gap, which is the plaza.- const depth = CAMPUS.northDepth + CAMPUS.street + rowDepth.reduce((sum, d) => sum + d, 0)- + (rowCount - 1) * CAMPUS.street + CAMPUS.plaza + CAMPUS.southDepth;- const topZ = -depth / 2, bottomZ = depth / 2;- const northMaxZ = topZ + CAMPUS.northDepth, southMinZ = bottomZ - CAMPUS.southDepth;- /** Row starts and the plaza's centre line when the plaza follows row `after` (0-based). */- const place = (after: number) => {- const starts: number[] = [];- let z = northMaxZ + CAMPUS.street, plazaZ = 0;- for (let r = 0; r < rowCount; r += 1) {- starts.push(z);- z += rowDepth[r];- if (r === after) plazaZ = z + CAMPUS.plaza / 2;- z += r === after ? CAMPUS.plaza : CAMPUS.street;- }- return { starts, plazaZ };- };- // The plaza takes the gap nearest the floor's middle (the earlier one on a tie): with one row, the one in front of the lobby.- let plazaAfter = 0;- for (let r = 1; r < rowCount; r += 1) if (Math.abs(place(r).plazaZ) < Math.abs(place(plazaAfter).plazaZ) - 1e-9) plazaAfter = r;- const { starts: rowZ, plazaZ } = place(plazaAfter);- const half = CAMPUS.boulevard / 2;- const plaza: Point = { x: 0, z: plazaZ };- const plazaRect: Rect = { minX: planMinX, maxX: planMaxX, minZ: plazaZ - CAMPUS.plaza / 2, maxZ: plazaZ + CAMPUS.plaza / 2 };-- // ------------------------------------------------------------------ rooms- const lead: Room = { id: "lead", kind: "lead", walled: true, minX: -17.2, maxX: -6.2, minZ: topZ, maxZ: northMaxZ,- doors: [{ side: "south", at: -11.7, width: 1.8 }] };- // The team room closes the boulevard: its door stands on the axis.- const team: Room = { id: "team", kind: "team", walled: true, minX: -6.2, maxX: 6.2, minZ: topZ, maxZ: northMaxZ,- doors: [{ side: "south", at: 0, width: 2.4 }] };- const wardrobe: Room = { id: "wardrobe", kind: "wardrobe", walled: true, minX: 6.2, maxX: 14, minZ: topZ, maxZ: northMaxZ,- doors: [{ side: "south", at: 10.1, width: 1.6 }] };- // The lobby straddles the boulevard; the elevator, the brand wall and the award case stand along its west edge.- // Its name arch stands against the back of the reception desk and carries the name over it, instead of standing- // at the lobby's edge on the atrium.- const reception: Room = { id: "reception", kind: "reception", walled: false, minX: -10.6, maxX: 10.6, minZ: southMinZ, maxZ: bottomZ, doors: [],- arch: { x: -6, z: southMinZ + 1.95 } };- const breakRoom: Room = { id: "break", kind: "break", walled: true, minX: 13.1, maxX: planMaxX, minZ: southMinZ, maxZ: bottomZ,- doors: [{ side: "north", at: (13.1 + planMaxX) / 2, width: 2.4 }, { side: "west", at: southMinZ + CAMPUS.southDepth / 2, width: 2 }] };- const rooms = [lead, team, wardrobe, reception, breakRoom];-- const departments: Department[] = [];- const studios: Studio[] = [];- const furniture: Furniture[] = [];- const spots: Spot[] = [];- const ambience: AgentsAmbienceItem[] = [];- const zones: CampusZone[] = [- { id: "boulevard", kind: "boulevard", minX: -half, maxX: half, minZ: northMaxZ, maxZ: southMinZ },- { id: "plaza", kind: "plaza", ...plazaRect },- { id: "atrium", kind: "atrium", minX: -CAMPUS.atrium / 2, maxX: CAMPUS.atrium / 2, minZ: plazaRect.minZ, maxZ: plazaRect.maxZ },- ];- const piece = (id: string, kind: FurnitureKind, room: RoomKind | "floor", x: number, z: number, rotationY = 0, size?: { w: number; d: number }): Furniture =>- ({ id, kind, x, z, rotationY, room, ...(size ? { size } : {}) });- /** Places at a commons piece or in a studio become spots on the open floor. */- const use = (prefix: string, kind: SpotKind, pose: SpotPose, places: readonly AmbiencePlace[]) => {- places.forEach((p, n) => spots.push({ id: `${prefix}-${n}`, kind, pose, x: p.x, z: p.z, facing: p.facing, room: "floor" }));- };- const add = <T extends AgentsAmbienceItem>(item: T): T => { ambience.push(item); return item; };-- // --------------------------------------------------------------- studios- let teamIndex = 0;- let plotPlaced = false;- for (let r = 0; r < rowCount; r += 1) {- const z0 = rowZ[r], z1 = rowZ[r] + rowDepth[r];- /** The studio plan standing in column c of this row, if any. */- const planAt = (column: number) => plans[r * perRow + SLOT_COLUMNS.indexOf(column as 0 | 1 | 2 | 3)];- for (let slot = 0; slot < perRow; slot += 1) {- const column = SLOT_COLUMNS[slot];- const [x0, x1] = cells[column];- const cx = (x0 + x1) / 2, cz = (z0 + z1) / 2;- const index = r * perRow + slot;- const plan = plans[index];- if (!plan) {- // A cell without a studio: the first one is the free plot where the next team will stand, the others are garden courts.- if (!plotPlaced) {- plotPlaced = true;- zones.push({ id: "plot", kind: "plot", minX: x0 + 0.6, maxX: x1 - 0.6, minZ: z0 + 0.6, maxZ: z1 - 0.6 });- // A place a team could move into tomorrow: the stand where one is started, facing the street, a stack of- // moving crates and a plant already waiting at the back.- furniture.push(piece("team-stand", "teamStand", "floor", cx, z1 - 2.6));- furniture.push(piece("plot-plant", "plant", "floor", x1 - 1.7, z0 + 1.6));- add(crate("plot-crates", x0 + 1.9, z0 + 1.7, "south"));- continue;- }- const id = `garden-${r}-${slot}`;- zones.push({ id, kind: "garden", minX: x0, maxX: x1, minZ: z0, maxZ: z1 });- // A lawn with one large tree and two olives off to its sides, a bed of grasses along the back and two- // benches facing each other in the middle; mirrored on the east half of the floor.- const m = column >= 2 ? -1 : 1;- add(tree(`${id}-tree`, cx - m * 3.1, z0 + 2.7));- add(olive(`${id}-olive-a`, cx + m * 3.4, z0 + 2.1));- add(olive(`${id}-olive-b`, cx + m * 2.9, z1 - 2.3));- add(planter(`${id}-bed`, { minX: cx - 1.6, maxX: cx + 1.9, minZ: z0 + 0.8, maxZ: z0 + 0.8 + PLANTER_DEPTH }));- use(`${id}-bench-w`, "couch", "sit", benchSeats(add(bench(`${id}-bench-w`, cx - 0.95, cz - 0.4, cz + 2.0, "east"))));- use(`${id}-bench-e`, "couch", "sit", benchSeats(add(bench(`${id}-bench-e`, cx + 0.95, cz - 0.4, cz + 2.0, "west"))));- spots.push({ id: `${id}-stand`, kind: "window", pose: "stand", room: "floor", x: cx - m * 1.5, z: z0 + 3.2, facing: m > 0 ? -Math.PI / 2 : Math.PI / 2 });- continue;- }- const shape = shapes[index];- const tint = plan.teamId === null ? POOL_TINT : TEAM_TINTS[teamIndex % TEAM_TINTS.length];- if (plan.teamId !== null) teamIndex += 1;- const dept: Department = {- id: plan.id, label: plan.name, teamId: plan.teamId, tint,- minX: x0, maxX: x1, minZ: z0, maxZ: z1,- desks: studioDesks(plan.id, cx, z0, shape, plan.members),- };- departments.push(dept);-- // The studio board hangs in front of the east half of the name wall; the team gathers south of it.- const { boardX } = studioWallParts(dept);- const boardId = `studio-board:${dept.id}`;- const boardZ = z0 + 0.23 + FURNITURE_SIZE.studioBoard.d / 2;- furniture.push(piece(boardId, "studioBoard", "floor", boardX, boardZ));- const face: Point = { x: boardX, z: boardZ + STUDIO_BOARD_FACE.z };- const huddle: Spot[] = HUDDLE_OFFSETS.slice(0, Math.min(HUDDLE_OFFSETS.length, Math.max(4, plan.members.length + 1))).map(([dx, dz], n) => ({- id: `huddle:${dept.id}:${n}`, kind: "huddle", pose: "stand", room: "floor",- x: face.x + dx, z: face.z + dz, facing: Math.atan2(-dx, -dz),- }));- spots.push(...huddle);- studios.push({- deptId: dept.id, teamId: plan.teamId, name: plan.name, members: plan.members.map((a) => a.agentId), leadId: plan.leadId,- board: { id: boardId, x: face.x, z: face.z, facing: 0 }, huddleSpotIds: huddle.map((s) => s.id),- centre: { x: cx, z: cz },- });-- // Low screens close both sides. Two studios shoulder to shoulder share the one between them (the west- // studio builds it, in neutral oak); a side on the boulevard, the window or an empty cell has the studio's own.- const sideZ = [z0 + 0.22, z1 - 0.2] as const;- const westShared = (column === 1 || column === 3) && !!planAt(column - 1);- const eastShared = (column === 0 || column === 2) && !!planAt(column + 1);- if (!westShared) add(screen(`${dept.id}-screen-w`, x0 + 0.06, sideZ[0], x0 + 0.06, sideZ[1], tint));- if (eastShared) add(screen(`${dept.id}-screen-e`, x1, sideZ[0], x1, sideZ[1]));- else add(screen(`${dept.id}-screen-e`, x1 - 0.06, sideZ[0], x1 - 0.06, sideZ[1], tint));- // The front is planted, with the entrance in its middle.- const frontZ = { minZ: z1 - 0.2 - PLANTER_DEPTH, maxZ: z1 - 0.2 };- const wing = (CAMPUS.cellW - CAMPUS.studioDoor) / 2;- add(planter(`${dept.id}-front-w`, { minX: x0 + 0.3, maxX: x0 + wing, ...frontZ }));- add(planter(`${dept.id}-front-e`, { minX: x1 - wing, maxX: x1 - 0.3, ...frontZ }));- // Inside: storage in the corner under the name, a sofa along the west screen by the entrance and a standing table opposite.- add(cabinet(`${dept.id}-cabinet`, x0 + 0.42, z0 + 1.45, "east", tint));- use(`${dept.id}-sofa`, "couch", "sit", sofaSeats(add(sofa(`${dept.id}-sofa`, x0 + 0.24 + SOFA.d / 2, z1 - 2.1, "east", tint))));- use(`${dept.id}-table`, "coffee", "stand", tableStands(add(highTable(`${dept.id}-table`, x1 - 1.6, z1 - 2.1)), [-Math.PI / 2, Math.PI]));- }- }-- // ------------------------------------------------------ streets and plaza- // An olive tree closes every street at both windows, except the main boulevard's east end: it runs on as the- // bridge to the sky pad.- const streetZ = [northMaxZ + CAMPUS.street / 2, ...rowZ.map((z, r) => (r === plazaAfter ? plazaZ : z + rowDepth[r] + CAMPUS.street / 2))];- streetZ.forEach((z, i) => {- add(olive(`olive-west-${i}`, planMinX - 0.8, z));- if (z !== plazaZ) add(olive(`olive-east-${i}`, planMaxX + 0.8, z));- });- rowZ.forEach((z, r) => {- const z1 = z + rowDepth[r], zc = (z + z1) / 2;- // Along both windows: a bench on one side of the window spot and a planter on the other (swapped between west and east).- ([[z + 0.4, zc - 0.85], [zc + 0.85, z1 - 0.4]] as const).forEach(([a, b], run) => {- const out = 0.95;- if (run === 0) {- add(bench(`bench-west-${r}`, planMinX - out - BENCH_DEPTH / 2, a, b, "east"));- add(planter(`planter-east-${r}`, { minX: planMaxX + out, maxX: planMaxX + out + PLANTER_DEPTH, minZ: a, maxZ: b }));- } else {- add(planter(`planter-west-${r}`, { minX: planMinX - out - PLANTER_DEPTH, maxX: planMinX - out, minZ: a, maxZ: b }));- add(bench(`bench-east-${r}`, planMaxX + out + BENCH_DEPTH / 2, a, b, "west"));- }- });- spots.push({ id: `window-west-${r}`, kind: "window", pose: "stand", room: "floor", x: planMinX - FLOOR_EDGE + 0.9, z: zc, facing: -Math.PI / 2 });- spots.push({ id: `window-east-${r}`, kind: "window", pose: "stand", room: "floor", x: planMaxX + FLOOR_EDGE - 0.9, z: zc, facing: Math.PI / 2 });- });- // The atrium, the campus's heart: the spawn point between two flights of step seating that face it, a large- // tree behind each. Further out the main boulevard has a planted median with a standing table and an olive.- for (const sx of [-1, 1] as const) {- const name = sx < 0 ? "west" : "east";- use(`atrium-steps-${name}`, "couch", "sit", stepsSeats(add(steps(`atrium-steps-${name}`, sx * 5.6, plazaZ, 5, sx < 0 ? "east" : "west"))));- add(tree(`atrium-tree-${name}`, sx * 7.9, plazaZ));- const [a, b] = [sx * 12.4, sx * 17.2].sort((p, q) => p - q);- add(planter(`median-${name}`, { minX: a, maxX: b, minZ: plazaZ - PLANTER_DEPTH / 2, maxZ: plazaZ + PLANTER_DEPTH / 2 }));- add(olive(`median-${name}-olive`, sx * 18.3, plazaZ));- use(`median-${name}-table`, "coffee", "stand", tableStands(add(highTable(`median-${name}-table`, sx * 11.2, plazaZ)), [0, Math.PI]));- }-- // -------------------------------------------------------------- the commons- // North-west corner: the focus booths. Three booths under the window, a sofa on a rug and a standing table.- const boothsZone: CampusZone = { id: "booths", kind: "booths", minX: planMinX, maxX: lead.minX, minZ: topZ, maxZ: northMaxZ };- zones.push(boothsZone);- [0, 1, 2].forEach((n) => {- const item = add(booth(`booth-${n}`, planMinX + 1.0 + n * 1.65, topZ + 1.0, "south", [1, 3, 5][n]));- spots.push({ id: `booth-${n}`, kind: "window", pose: "stand", room: "floor", ...boothPlace(item) });- });- furniture.push(piece("booths-rug", "rug", "floor", planMinX + 2.9, topZ + 5.9, 0, { w: 4.4, d: 3.4 }));- use("booths-sofa", "couch", "sit", sofaSeats(add(sofa("booths-sofa", planMinX + 0.3 + SOFA.d / 2, topZ + 5.9, "east"))));- use("booths-table", "coffee", "stand", tableStands(add(highTable("booths-table", planMinX + 4.4, topZ + 5.6)), [-Math.PI / 2, 0]));- add(olive("booths-olive", lead.minX - 0.9, topZ + 1.2));-- // North-east corner: the library. Two bookcases under the window, reading chairs by the east window, a sofa and a- // low table on a rug.- const lx0 = wardrobe.maxX, lx1 = planMaxX;- zones.push({ id: "library", kind: "library", minX: lx0, maxX: lx1, minZ: topZ, maxZ: northMaxZ });- const nookSeat = (x: number, z: number): AmbiencePlace => ({ x: x - 0.14, z: z + 0.08, facing: -Math.PI / 2 });- furniture.push(- piece("library-shelf-w", "breakBookcase", "floor", lx0 + 2.3, topZ + 0.12 + FURNITURE_SIZE.breakBookcase.d / 2),- piece("library-shelf-e", "breakBookcase", "floor", lx0 + 5.7, topZ + 0.12 + FURNITURE_SIZE.breakBookcase.d / 2),- piece("library-rug", "rug", "floor", lx0 + 3.6, topZ + 4.7, 0, { w: 5.2, d: 3.6 }),- piece("library-table", "lobbyTable", "floor", lx0 + 2.6, topZ + 4.7, Math.PI / 2),- // The reading chairs turn their backs to the east window and face the room.- piece("library-nook-n", "readingNook", "floor", lx1 - 0.75, topZ + 3.4, -Math.PI / 2),- piece("library-nook-s", "readingNook", "floor", lx1 - 0.75, topZ + 6.0, -Math.PI / 2),- piece("library-plant", "designerPlant", "floor", lx1 - 0.8, topZ + 0.9),- );- use("library-sofa", "couch", "sit", sofaSeats(add(sofa("library-sofa", lx0 + 0.3 + SOFA.d / 2, topZ + 4.7, "east"))));- use("library-nook", "couch", "sit", [nookSeat(lx1 - 0.75, topZ + 3.4), nookSeat(lx1 - 0.75, topZ + 6.0)]);- use("library-shelf", "shelf", "stand", [{ x: lx0 + 2.3, z: topZ + 1.25, facing: Math.PI }, { x: lx0 + 5.7, z: topZ + 1.25, facing: Math.PI }]);-- // South-west, beside the lobby: the café. The kitchen run under the west window with the island in front of it,- // standing tables, two sofas along the south window, a large tree in two corners and grasses towards the plaza.- const cx0 = planMinX, cx1 = reception.minX, cz0 = southMinZ;- zones.push({ id: "cafe", kind: "cafe", minX: cx0, maxX: cx1, minZ: cz0, maxZ: bottomZ });- use("cafe-counter", "coffee", "stand", counterStands(add(counter("cafe-counter", cx0 + 0.45, cz0 + 5.4, 4.6, "east")), [-1.1, 1.1]));- use("cafe-island", "coffee", "stand", counterStands(add(island("cafe-island", cx0 + 2.7, cz0 + 5.4, "east")), [-0.7, 0.7]));- ([[5.6, 2.7], [8.0, 5.2], [5.8, 7.6]] as const).forEach(([dx, dz], n) => {- use(`cafe-table-${n}`, "coffee", "stand", tableStands(add(highTable(`cafe-table-${n}`, cx0 + dx, cz0 + dz)), [Math.PI / 2, -Math.PI / 2]));- });- use("cafe-sofa-w", "couch", "sit", sofaSeats(add(sofa("cafe-sofa-w", cx1 - 5.2, bottomZ - 0.25 - SOFA.d / 2, "north"))));- use("cafe-sofa-e", "couch", "sit", sofaSeats(add(sofa("cafe-sofa-e", cx1 - 2.7, bottomZ - 0.25 - SOFA.d / 2, "north"))));- add(tree("cafe-tree-n", cx1 - 1.4, cz0 + 1.3));- add(tree("cafe-tree-s", cx0 + 1.0, bottomZ - 1.1));- add(planter("cafe-bed", { minX: cx0 + 3.2, maxX: cx0 + 8.4, minZ: cz0 + 0.3, maxZ: cz0 + 0.3 + PLANTER_DEPTH }));-- // ------------------------------------------------------------- lead office- const leadAgents = agents.filter((a) => a.tier === "lead").sort(byArrival).slice(0, 2);- const ex0 = lead.minX, ex1 = lead.maxX, lcx = (ex0 + ex1) / 2, lz0 = topZ;- const leadDeskZ = lz0 + 2.6;- // The executive desk faces south, towards the door. A second lead gets a partner desk to its east; there is never an empty one.- const leadDesks: DeskSlot[] = [- { id: "lead:0", x: lcx, z: leadDeskZ, facing: "south", agentId: leadAgents[0]?.agentId ?? null, size: EXECUTIVE_DESK_SIZE },- ...(leadAgents[1] ? [{ id: "lead:1", x: lcx + 2.65, z: leadDeskZ, facing: "south" as const, agentId: leadAgents[1].agentId, size: PARTNER_DESK_SIZE }] : []),- ];- furniture.push(- // A panelled feature wall with lit bookcases and the star emblem, a rug under the executive desk, guest- // armchairs, the bar and a leather lounge along the west wall, a globe and a lamp in the east, palms by the door.- piece("lead-wall", "leadWall", "lead", lcx, lz0 + 0.1 + FURNITURE_SIZE.leadWall.d / 2),- piece("lead-rug", "executiveRug", "lead", lcx, lz0 + 3.55, 0, { w: 4.6, d: 3.9 }),- piece("lead-guest-w", "guestChair", "lead", lcx - 0.72, leadDeskZ + 1.2, Math.PI),- piece("lead-guest-e", "guestChair", "lead", lcx + 0.72, leadDeskZ + 1.2, Math.PI),- piece("lead-sofa", "chesterfield", "lead", ex0 + 0.6, lz0 + 4.55, Math.PI / 2),- piece("lead-table", "loungeTable", "lead", ex0 + 1.62, lz0 + 4.55, Math.PI / 2),- piece("lead-lamp", "floorLamp", "lead", ex0 + 0.4, lz0 + 3.1),- piece("lead-bar", "executiveBar", "lead", ex0 + 0.36, lz0 + 1.85, Math.PI / 2),- piece("lead-globe", "globe", "lead", ex1 - 0.75, lz0 + 4.3),- piece("lead-lamp-e", "floorLamp", "lead", ex1 - 0.34, lz0 + 2.9),- piece("lead-plant", "plant", "lead", ex0 + 0.55, northMaxZ - 0.55),- piece("lead-plant-e", "plant", "lead", ex1 - 0.55, northMaxZ - 0.55),- // The office dog's baskets: here beside the bookcase, in the team room and in the break room.- piece("lead-dog", "dogBed", "lead", ex1 - 0.58, lz0 + 0.98),- );- spots.push({ id: "shelf-lead", kind: "shelf", pose: "stand", x: lcx + 2.65, z: topZ + 1.05, facing: Math.PI, room: "lead" });-- // --------------------------------------------------------------- team room- const tableZ = topZ + 4.9;- furniture.push(- // A walnut table on a wool rug, the board on a slat wall, a credenza under the display and one along the- // west wall, fiddle-leaf figs in both corners by the door.- piece("team-rug", "teamRug", "team", 0, tableZ, 0, { w: 5.4, d: 4.0 }),- piece("team-table", "meetingTable", "team", 0, tableZ),- piece("team-wall", "teamWall", "team", 0, topZ + 0.06 + FURNITURE_SIZE.teamWall.d / 2),- piece("team-board", "teamBoard", "team", 0, topZ + 0.25),- piece("team-credenza", "credenza", "team", 2.7, topZ + 0.19 + FURNITURE_SIZE.credenza.d / 2),- piece("team-credenza-w", "credenza", "team", team.minX + 0.07 + FURNITURE_SIZE.credenza.d / 2, tableZ, Math.PI / 2),- piece("team-plant", "designerPlant", "team", team.maxX - 0.6, northMaxZ - 0.6),- piece("team-plant-w", "designerPlant", "team", team.minX + 0.6, northMaxZ - 0.6, Math.PI / 2),- piece("team-dog", "dogBed", "team", team.minX + 0.62, topZ + 0.95),- );- spots.push({ id: "board", kind: "board", pose: "stand", x: -0.6, z: topZ + 1.2, facing: Math.PI, room: "team" });- // Meeting chairs: three per long side of the team table.- for (let i = 0; i < 3; i += 1) {- const x = -1.1 + i * 1.1;- spots.push({ id: `meeting-n${i}`, kind: "meeting", pose: "sit", x, z: tableZ - 1.25, facing: 0, room: "team" });- spots.push({ id: `meeting-s${i}`, kind: "meeting", pose: "sit", x, z: tableZ + 1.25, facing: Math.PI, room: "team" });- }-- // ---------------------------------------------------------------- wardrobe- const wx0 = wardrobe.minX, wx1 = wardrobe.maxX, wcx = (wx0 + wx1) / 2;- const mirrorZ = topZ + 3.6;- // Where the person stands to change: on the round rug in front of the mirror.- const dressAt: Point = { x: wx0 + 2.0, z: mirrorZ };- furniture.push(- // An open oak wardrobe along the north wall, a bulb-lit mirror on the west wall with a round rug in front of- // it, a tailor's dummy, a bench on the east side, a fig and a coat stand by the door.- piece("wardrobe-wall", "wardrobeWall", "wardrobe", wcx, topZ + 0.06 + FURNITURE_SIZE.wardrobeWall.d / 2),- piece("wardrobe-rug", "roundRug", "wardrobe", dressAt.x, dressAt.z, 0, { w: 2.8, d: 2.8 }),- piece("wardrobe-mirror", "dressingMirror", "wardrobe", wx0 + 0.06 + FURNITURE_SIZE.dressingMirror.d / 2, mirrorZ, Math.PI / 2),- piece("wardrobe-dummy", "tailorDummy", "wardrobe", wx1 - 0.6, topZ + 1.4, -Math.PI / 4),- piece("wardrobe-bench", "dressingBench", "wardrobe", wx1 - 0.06 - FURNITURE_SIZE.dressingBench.d / 2, topZ + 3.9, -Math.PI / 2),- piece("wardrobe-plant", "designerPlant", "wardrobe", wx0 + 0.5, northMaxZ - 0.5),- piece("wardrobe-stand", "coatStand", "wardrobe", wx1 - 0.4, northMaxZ - 0.45),- );- spots.push({ id: "shelf-wardrobe", kind: "shelf", pose: "stand", x: wcx - 1.0, z: topZ + 1.3, facing: Math.PI, room: "wardrobe" });-- // ------------------------------------------------------------------- lobby- const rx0 = reception.minX, rx1 = reception.maxX;- const deskAt: Point = { x: reception.arch?.x ?? rx0 + 4.6, z: southMinZ + 2.5 };- const loungeX = 5.4, loungeZ = southMinZ + 5.6;- furniture.push(- // West edge, north to south: the brand wall, the way into the café, the elevator with its mat and the award- // case. The reception desk stands west of the boulevard's axis, the waiting lounge east of it.- piece("elevator", "elevator", "reception", rx0 + 0.25, bottomZ - 2.6, Math.PI / 2),- piece("reception-desk", "receptionDesk", "reception", deskAt.x, deskAt.z),- piece("lobby-brand-wall", "brandWall", "reception", rx0 + 0.22, southMinZ + 2.55, Math.PI / 2),- piece("lobby-awards", "awardCase", "reception", rx0 + 0.26, bottomZ - 0.7, Math.PI / 2),- piece("lobby-mat", "entranceMat", "reception", rx0 + 1.3, bottomZ - 2.6, 0, { w: 1.1, d: 1.9 }),- piece("lobby-olive-s", "oliveTree", "reception", rx0 + 2.9, bottomZ - 0.75),- piece("lobby-olive-se", "oliveTree", "reception", rx1 - 0.75, bottomZ - 0.75),- piece("lobby-rug", "lobbyRug", "reception", loungeX, loungeZ + 0.75, 0, { w: 4.8, d: 2.9 }),- piece("lobby-sofa", "lobbySofa", "reception", loungeX, loungeZ),- piece("lobby-table", "lobbyTable", "reception", loungeX, loungeZ + 1.05),- piece("lobby-chair-w", "lobbyArmchair", "reception", loungeX - 1.8, loungeZ + 1.1, Math.PI / 2),- piece("lobby-chair-e", "lobbyArmchair", "reception", loungeX + 1.8, loungeZ + 1.1, -Math.PI / 2),- piece("lobby-side-table", "sideTable", "reception", loungeX - 1.5, loungeZ - 0.05),- piece("lobby-lamp", "lobbyLamp", "reception", loungeX + 1.5, loungeZ - 0.1),- );- spots.push(- // Two on the sofa (facing south), one in each armchair (facing the table).- { id: "couch-lobby-1", kind: "couch", pose: "sit", x: loungeX - 0.55, z: loungeZ + 0.15, facing: 0, room: "reception" },- { id: "couch-lobby-2", kind: "couch", pose: "sit", x: loungeX + 0.55, z: loungeZ + 0.15, facing: 0, room: "reception" },- { id: "couch-lobby-w", kind: "couch", pose: "sit", x: loungeX - 1.78, z: loungeZ + 1.1, facing: Math.PI / 2, room: "reception" },- { id: "couch-lobby-e", kind: "couch", pose: "sit", x: loungeX + 1.78, z: loungeZ + 1.1, facing: -Math.PI / 2, room: "reception" },- );-- // -------------------------------------------------------------- break room- const bx0 = breakRoom.minX, bx1 = breakRoom.maxX, bz0 = southMinZ;- const barX = bx1 - 2.9;- furniture.push(- // An L-shaped sectional in the south-west round an oak coffee table on a kilim; the bookcase wall, the- // reading nook and the dog's basket in the north-west; the coffee bar with the treat jar on the north wall;- // foosball, beanbags, the water station and the arcade on its pixel mat in the east; monsteras in two corners.- piece("break-rug", "breakRug", "break", bx0 + 3.4, bottomZ - 3.1, 0, { w: 5.2, d: 4.2 }),- piece("break-sofa-a", "breakSofa", "break", bx0 + 3.3, bottomZ - 1.7, Math.PI),- piece("break-sofa-b", "breakSofa", "break", bx0 + 1.75, bottomZ - 3.25, Math.PI / 2),- piece("break-sofa-corner", "breakSofaCorner", "break", bx0 + 1.75, bottomZ - 1.7, Math.PI),- piece("break-table", "breakTable", "break", bx0 + 3.35, bottomZ - 3.2),- piece("coffee-bar", "coffeeBar", "break", barX, bz0 + 0.5),- piece("break-treats", "treatJar", "break", barX + 2.05, bz0 + 0.5),- piece("water-cooler", "waterCooler", "break", bx1 - 0.45, bz0 + 2.6, -Math.PI / 2),- piece("arcade", "arcade", "break", bx1 - 0.6, bottomZ - 0.7, -Math.PI / 2),- piece("arcade-mat", "arcadeMat", "break", bx1 - 1.5, bottomZ - 0.7, 0, { w: 1.1, d: 1.2 }),- piece("foosball", "foosball", "break", bx1 - 3.0, bz0 + 4.8),- piece("beanbag-a", "beanbag", "break", bx1 - 3.7, bottomZ - 1.9),- piece("beanbag-b", "beanbag", "break", bx1 - 2.5, bottomZ - 1.25),- piece("break-shelf", "breakBookcase", "break", bx0 + 2.4, bz0 + 0.06 + FURNITURE_SIZE.breakBookcase.d / 2),- piece("break-nook", "readingNook", "break", bx0 + 0.53, bz0 + 0.58),- piece("break-dog", "dogBed", "break", bx0 + 0.62, bz0 + 1.6),- piece("break-plant", "breakPlant", "break", bx0 + 0.6, bottomZ - 0.6),- piece("break-plant-e", "breakPlant", "break", bx1 - 0.45, bz0 + 7.0),- );- spots.push(- // Sofa module A faces north, module B faces east; the reading nook's armchair faces south, into the room.- { id: "couch-a1", kind: "couch", pose: "sit", x: bx0 + 2.7, z: bottomZ - 1.85, facing: Math.PI, room: "break" },- { id: "couch-a2", kind: "couch", pose: "sit", x: bx0 + 3.7, z: bottomZ - 1.85, facing: Math.PI, room: "break" },- { id: "couch-b1", kind: "couch", pose: "sit", x: bx0 + 1.9, z: bottomZ - 3.7, facing: Math.PI / 2, room: "break" },- { id: "couch-b2", kind: "couch", pose: "sleep", x: bx0 + 1.9, z: bottomZ - 2.65, facing: Math.PI / 2, room: "break" },- { id: "couch-nook", kind: "couch", pose: "sit", x: bx0 + 0.61, z: bz0 + 0.72, facing: 0, room: "break" },- { id: "coffee-1", kind: "coffee", pose: "stand", x: barX - 0.6, z: bz0 + 1.4, facing: Math.PI, room: "break" },- { id: "coffee-2", kind: "coffee", pose: "stand", x: barX + 0.6, z: bz0 + 1.4, facing: Math.PI, room: "break" },- { id: "cooler", kind: "cooler", pose: "stand", x: bx1 - 1.2, z: bz0 + 2.6, facing: Math.PI / 2, room: "break" },- { id: "arcade", kind: "arcade", pose: "stand", x: bx1 - 1.45, z: bottomZ - 0.7, facing: Math.PI / 2, room: "break" },- { id: "beanbag-a", kind: "beanbag", pose: "sit", x: bx1 - 3.7, z: bottomZ - 1.9, facing: Math.PI * 1.25, room: "break" },- { id: "beanbag-b", kind: "beanbag", pose: "sit", x: bx1 - 2.5, z: bottomZ - 1.25, facing: Math.PI * 1.25, room: "break" },- { id: "shelf-break", kind: "shelf", pose: "stand", x: bx0 + 2.2, z: bz0 + 1.1, facing: Math.PI, room: "break" },- );-- // ------------------------------------------------------------- spawn point- furniture.push(- // In the middle of the atrium: the pad, and the terminal on it facing the lobby.- piece("spawn-pad", "spawnPad", "floor", plaza.x, plaza.z),- piece("spawn-terminal", "spawnTerminal", "floor", plaza.x, plaza.z),- );-- // ---------------------------------------------------------------- the sky pad- const floor: Rect = {- // The navigation grid starts at this corner. Desks stand on a 0.85 m raster from their studio's centre, so- // the place beside a chair would fall exactly on a cell boundary for every other cluster width; an eighth- // of a cell keeps all of them clear of one.- minX: planMinX - FLOOR_EDGE + RAIL_CLEARANCE - GRID_NUDGE, maxX: planMaxX + FLOOR_EDGE - RAIL_CLEARANCE,- minZ: topZ - FLOOR_EDGE + RAIL_CLEARANCE, maxZ: bottomZ + FLOOR_EDGE - RAIL_CLEARANCE,- };- const bounds: Rect = { minX: planMinX - FLOOR_EDGE, maxX: planMaxX + FLOOR_EDGE, minZ: topZ - FLOOR_EDGE, maxZ: bottomZ + FLOOR_EDGE };- // The main boulevard runs on through the east windows as a bridge to the landing platform.- const skyPad = skyPadFor(bounds, floor, plazaZ);-- // ------------------------------------------------------------- checkpoints- const elevator = furniture.find((f) => f.id === "elevator")!;- // The spawn point's ring surrounds the terminal; "walk there" and newcomers stand south of it, facing the screen.- const arrival: Point = { x: plaza.x, z: plaza.z + SPAWN.approach };- // Every stop is the place in front of the thing the person uses there.- const checkpoints: Checkpoint[] = [- { id: "spawn", room: "floor", x: plaza.x, z: plaza.z, radius: SPAWN.reach, approach: arrival },- // The reception desk is the one directory and help station.- { id: "manage", room: "reception", x: deskAt.x, z: deskAt.z + 1.7, radius: 1.2 },- // In front of the team board.- { id: "team", room: "team", x: 0.9, z: topZ + 1.6, radius: 1.1 },- // In front of the dressing mirror.- { id: "wardrobe", room: "wardrobe", x: dressAt.x, z: dressAt.z, radius: 1.5 },- // Across the executive desk, behind the guest chairs.- { id: "lead", room: "lead", x: lcx, z: leadDeskZ + 2.4, radius: 1.3 },- // At the coffee bar.- { id: "break", room: "break", x: barX, z: bz0 + 2.0, radius: 1.6 },- // The elevator's doors face east into the lobby; its checkpoint is the floor in front of them.- { id: "elevator", room: "reception", x: elevator.x + 0.95, z: elevator.z, radius: 1.0 },- // Out on the sky pad, beside the courier's hatch.- { id: "ship", room: "floor", x: skyPad.board.x, z: skyPad.board.z, radius: 1.6 },- ];-- // --------------------------------------------------------------- obstacles- const walls = uniqueWalls(rooms);- const benchDesks = departments.flatMap((d) => d.desks);- const obstacles: Rect[] = [- ...walls.map(wallRect),- ...[...leadDesks, ...benchDesks].map(deskRect),- ...leadDesks.map(executiveChairRect),- // Bench desk chairs and the meeting chairs: nobody walks through a chair.- ...benchDesks.map((d) => chairRect(seatOf(d))),- ...spots.filter((s) => s.kind === "meeting").map((s) => chairRect(s)),- ...departments.map(studioWallRect),- ...furniture.filter((f) => FURNITURE_SIZE[f.kind].solid).map(footprint),- // Oak planter boxes at the bench ends.- ...departments.flatMap(benchPlanters).map((p) => p.rect),- ...ambience.flatMap(ambienceObstacles),- // The posts of the lobby's name arch are solid too; nobody walks through them.- ...rooms.filter((r) => !r.walled).flatMap(archPosts).map((p) => ({- minX: p.x - ARCH.post / 2, maxX: p.x + ARCH.post / 2, minZ: p.z - ARCH.post / 2, maxZ: p.z + ARCH.post / 2,- })),- // The courier on its pad.- skyPad.shipRect,- ];-- return {- variant: "agents", departments, studios, zones, ambience,- lead: { minX: lead.minX, maxX: lead.maxX, minZ: lead.minZ, maxZ: lead.maxZ, desks: leadDesks },- rooms, walls, furniture, spots, checkpoints, obstacles,- // The person starts in front of the elevator.- spawn: { x: rx0 + 1.4, z: bottomZ - 2.6 },- arrival, floor, bounds, skyPad,- };-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/canvasMaterials.ts b/dodaios/ui/web/frontend/src/components/society/office/canvasMaterials.tsdeleted file mode 100644index 340967536f..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/canvasMaterials.ts+++ /dev/null@@ -1,95 +0,0 @@-/**- * Canvas-drawn textures and the materials that show them, drawn once per key- * and shared by every prop, sign and floor that uses them.- */-import { CanvasTexture, MeshStandardMaterial, SRGBColorSpace, type Texture } from "three";--const textureCache = new Map<string, Texture | null>();--/**- * A canvas-drawn texture, drawn once per key and cached for the session. Only- * for keys from a fixed set (a kind, a palette entry, a locale's own text): a- * key made from something the user names would grow the cache without end,- * and belongs to `ownedCanvasTexture`. Returns null where no 2D canvas exists- * (SSR, tests without canvas); callers fall back to a colour.- */-export function cachedCanvasTexture(- key: string, width: number, height: number, draw: (ctx: CanvasRenderingContext2D, w: number, h: number) => void,-): Texture | null {- if (textureCache.has(key)) return textureCache.get(key) ?? null;- const texture = ownedCanvasTexture(width, height, draw);- textureCache.set(key, texture);- return texture;-}--/**- * A canvas-drawn texture that belongs to its caller, who disposes it when the- * thing it is drawn for goes: for text the user chose (a team's name).- * Returns null where no 2D canvas exists.- */-export function ownedCanvasTexture(- width: number, height: number, draw: (ctx: CanvasRenderingContext2D, w: number, h: number) => void,-): Texture | null {- const canvas = typeof document !== "undefined" ? document.createElement("canvas") : null;- let ctx: CanvasRenderingContext2D | null = null;- try {- ctx = canvas?.getContext("2d") ?? null;- } catch {- // jsdom without the canvas package throws "not implemented": no texture, the colour fallback is correct.- ctx = null;- }- let texture: Texture | null = null;- if (canvas && ctx) {- canvas.width = width;- canvas.height = height;- draw(ctx, width, height);- const made = new CanvasTexture(canvas);- made.colorSpace = SRGBColorSpace;- made.anisotropy = 4;- texture = made;- }- return texture;-}--const fontWaiters = new Set<string>();--/**- * Redraw a cached canvas texture once its web fonts have loaded. Canvas text- * drawn before a face arrives keeps the fallback face for the whole session,- * because each texture is drawn once.- */-export function redrawWhenFontsLoad(- key: string, texture: Texture | null, fonts: readonly string[], draw: (ctx: CanvasRenderingContext2D, w: number, h: number) => void,-): void {- if (!texture || fontWaiters.has(key) || typeof document === "undefined" || !("fonts" in document)) return;- if (fonts.every((font) => document.fonts.check(font))) return;- fontWaiters.add(key);- Promise.all(fonts.map((font) => document.fonts.load(font))).then(() => {- const canvas = texture.image as HTMLCanvasElement | undefined;- const ctx = canvas?.getContext?.("2d");- if (!canvas || !ctx) return;- draw(ctx, canvas.width, canvas.height);- texture.needsUpdate = true;- }, () => {- // A face that fails to load leaves the fallback face already drawn, which stays legible.- });-}--const materialCache = new Map<string, MeshStandardMaterial>();--/** A material showing a cached canvas texture; `glow` > 0 makes it self-lit like a screen. */-export function canvasMaterial(- key: string, width: number, height: number, draw: (ctx: CanvasRenderingContext2D, w: number, h: number) => void,- { glow = 0, fallback = "#ffffff", roughness = 0.6 }: { glow?: number; fallback?: string; roughness?: number } = {},-): MeshStandardMaterial {- let material = materialCache.get(key);- if (!material) {- const map = cachedCanvasTexture(key, width, height, draw);- material = new MeshStandardMaterial({- color: map ? "#ffffff" : fallback, map, roughness,- emissive: glow > 0 ? "#ffffff" : "#000000", emissiveMap: glow > 0 ? map : null, emissiveIntensity: glow,- });- materialCache.set(key, material);- }- return material;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/cityPlan.test.ts b/dodaios/ui/web/frontend/src/components/society/office/cityPlan.test.tsdeleted file mode 100644index 6b6560be05..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/cityPlan.test.ts+++ /dev/null@@ -1,117 +0,0 @@-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/dodaios/ui/web/frontend/src/components/society/office/cityPlan.ts b/dodaios/ui/web/frontend/src/components/society/office/cityPlan.tsdeleted file mode 100644index b1c1327e01..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/cityPlan.ts+++ /dev/null@@ -1,274 +0,0 @@-/**- * 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/dodaios/ui/web/frontend/src/components/society/office/cityShaders.ts b/dodaios/ui/web/frontend/src/components/society/office/cityShaders.tsdeleted file mode 100644index e624cc19da..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/cityShaders.ts+++ /dev/null@@ -1,681 +0,0 @@-/**- * 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.- // A star is a small dot inside some of the cells of a grid over the sky, never the whole cell.- vec2 sky = vec2(atan(dir.z, dir.x) * 220.0, dir.y * 220.0);- vec2 cellS = floor(sky);- vec2 inCell = fract(sky) - 0.5 - (vec2(hash12(cellS + 3.1), hash12(cellS + 7.7)) - 0.5) * 0.6;- float dot_ = 1.0 - smoothstep(0.04, 0.12, length(inCell));- float star = step(0.9965, hash12(cellS)) * dot_ * smoothstep(0.02, 0.2, dir.y) * (0.4 + 0.6 * hash12(cellS + 1.3));- col += vec3(star) * 0.9;- 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 });-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/codingAmbience.test.ts b/dodaios/ui/web/frontend/src/components/society/office/codingAmbience.test.tsdeleted file mode 100644index 325de46d94..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/codingAmbience.test.ts+++ /dev/null@@ -1,64 +0,0 @@-import { describe, expect, it } from "vitest";--import { codingAmbience } from "./codingAmbience";-import { buildOfficeLayout, type OfficeAgentInput, type Rect } from "./officeLayout";--const agent = (id: string, provider: string): OfficeAgentInput => ({- agentId: id, name: id, tier: "specialist", providerLabel: provider, state: "working", createdMs: 0,-});--const overlaps = (a: Rect, b: Rect) => a.minX < b.maxX && a.maxX > b.minX && a.minZ < b.maxZ && a.maxZ > b.minZ;--describe("coding floor ambience", () => {- for (const count of [0, 12, 40]) {- const layout = buildOfficeLayout(Array.from({ length: count }, (_, i) => agent(`a${i}`, `P${i % 5}`)), { variant: "coding" });- const items = codingAmbience(layout);-- it(`stands clear of every neighbourhood and room (${count} agents)`, () => {- for (const kind of ["tree", "booth", "trough", "grove"] as const) expect(items.some((i) => i.kind === kind), kind).toBe(true);- for (const item of items) {- for (const area of [...layout.departments, ...layout.rooms]) expect(overlaps(item, area), item.id).toBe(false);- expect(item.minX, item.id).toBeGreaterThan(layout.bounds.minX + 0.2);- expect(item.maxX, item.id).toBeLessThan(layout.bounds.maxX - 0.2);- }- });-- it(`is solid in the layout and leaves every window spot free (${count} agents)`, () => {- for (const item of items) {- expect(layout.obstacles.some((o) => o.minX === item.minX && o.maxZ === item.maxZ), item.id).toBe(true);- }- for (const spot of layout.spots.filter((s) => s.kind === "window")) {- expect(items.some((i) => spot.x >= i.minX - 0.3 && spot.x <= i.maxX + 0.3 && spot.z >= i.minZ - 0.3 && spot.z <= i.maxZ + 0.3), spot.id).toBe(false);- }- });- }-- it("plants a grove on the concourse in every row, clear of the town square round the spawn terminal", () => {- const layout = buildOfficeLayout(Array.from({ length: 30 }, (_, i) => agent(`a${i}`, `P${i % 6}`)), { variant: "coding" });- const groves = codingAmbience(layout).filter((i) => i.kind === "grove");- const rows = new Set(layout.departments.map((d) => d.minZ));- expect(groves).toHaveLength(rows.size);- const terminal = layout.furniture.find((f) => f.kind === "spawnTerminal")!;- for (const grove of groves) {- const cx = (grove.minX + grove.maxX) / 2, cz = (grove.minZ + grove.maxZ) / 2;- expect(Math.hypot(cx - terminal.x, cz - terminal.z), grove.id).toBeGreaterThan(4);- }- });-- it("gives every phone booth the colour of the neighbourhood beside it", () => {- const layout = buildOfficeLayout(Array.from({ length: 30 }, (_, i) => agent(`a${i}`, `P${i % 6}`)), { variant: "coding" });- for (const booth of codingAmbience(layout).filter((i) => i.kind === "booth")) {- const index = Number(booth.id.split("-")[1]);- expect(booth.tint, booth.id).toBe(layout.departments[index].tint);- }- });-- it("adds nothing to the agents office and keeps ids unique", () => {- const agents = buildOfficeLayout([]);- for (const item of codingAmbience(agents)) {- expect(agents.obstacles.some((o) => o.minX === item.minX && o.maxZ === item.maxZ), item.id).toBe(false);- }- const items = codingAmbience(buildOfficeLayout([], { variant: "coding" }));- expect(new Set(items.map((i) => i.id)).size).toBe(items.length);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/codingAmbience.ts b/dodaios/ui/web/frontend/src/components/society/office/codingAmbience.tsdeleted file mode 100644index 5cbfe7f281..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/codingAmbience.ts+++ /dev/null@@ -1,124 +0,0 @@-/**- * The coding floor's open-plan dressing as data: tree planters closing every- * cross aisle at the windows; beside each outer neighbourhood a phone booth- * and a planter trough along the glass, either side of its window spot; and- * down the concourse, the floor's main street, a grove — a tall tree in a- * round planter ringed by a bench — in the middle of every row of- * neighbourhoods.- *- * Pure and shared: the layout adds every item to its obstacles, the renderer- * builds each piece inside the same box. The window pieces stand in the- * 1.6 m strip between the neighbourhoods and the glass; the groves stand on- * the concourse's centre line, clear of the cross aisles and the town square.- */-import type { Rect } from "./officeLayout";--export type AmbienceKind = "tree" | "booth" | "trough" | "grove";--export interface AmbienceItem extends Rect {- id: string;- kind: AmbienceKind;- /** The side the piece's front looks at: a booth's door faces into the office. */- facing: "east" | "west";- /** Height of the piece in metres (a tree's crown top). */- h: number;- /** The neighbourhood a booth belongs to (its tint index): the booth wears that team's colour. */- tint?: number;-}--/** A tree planter's square footprint, and how far its centre stands out from the neighbourhood column. */-export const TREE_BOX = 0.84;-const TREE_OUT = 0.8;-/** Troughs: depth, and the band they stand in, measured out from the neighbourhood column. */-const TROUGH_DEPTH = 0.32;-const TROUGH_OUT = 1.04;-/** A phone booth: depth across the strip, length along it, and its gap to the neighbourhood column. */-export const BOOTH = { d: 1.0, len: 1.15, out: 0.28, h: 2.25 } as const;-/** Half the gap left round a neighbourhood's window spot, and the margin at its ends. */-const WINDOW_GAP = 0.85;-const END_MARGIN = 0.35;-const MIN_RUN = 1.2;-/** A grove's round footprint (its square box) on the concourse. */-export const GROVE_BOX = 2.1;--export const TROUGH_H = 0.46;-export const TREE_H = 2.35;-export const GROVE_H = 4.4;--/** Where the aisles are: the neighbourhood rows and the room strips north and south of them. */-export interface AmbienceFrame {- departments: readonly (Rect & { tint?: number })[];- rooms: readonly Rect[];-}--/** Every ambience piece of a coding floor, in a stable order. */-export function codingAmbience({ departments, rooms }: AmbienceFrame): AmbienceItem[] {- if (departments.length === 0) return [];- const colMinX = Math.min(...departments.map((d) => d.minX));- const colMaxX = Math.max(...departments.map((d) => d.maxX));- const firstZ = Math.min(...departments.map((d) => d.minZ));- const lastZ = Math.max(...departments.map((d) => d.maxZ));- const north = rooms.filter((r) => r.maxZ <= firstZ + 1e-6).map((r) => r.maxZ);- const south = rooms.filter((r) => r.minZ >= lastZ - 1e-6).map((r) => r.minZ);- const items: AmbienceItem[] = [];-- // Cross aisles: in front of the north rooms, between neighbourhood rows, in front of the south strip.- const rowStarts = [...new Set(departments.map((d) => d.minZ))].sort((a, b) => a - b);- const aisles: number[] = [];- if (north.length > 0) aisles.push((Math.max(...north) + firstZ) / 2);- for (let i = 1; i < rowStarts.length; i += 1) {- const above = Math.max(...departments.filter((d) => d.minZ === rowStarts[i - 1]).map((d) => d.maxZ));- aisles.push((above + rowStarts[i]) / 2);- }- if (south.length > 0) aisles.push((lastZ + Math.min(...south)) / 2);- aisles.forEach((z, i) => {- for (const [side, x] of [["west", colMinX - TREE_OUT], ["east", colMaxX + TREE_OUT]] as const) {- items.push({- id: `tree-${side}-${i}`, kind: "tree", facing: side === "west" ? "east" : "west", h: TREE_H,- minX: x - TREE_BOX / 2, maxX: x + TREE_BOX / 2, minZ: z - TREE_BOX / 2, maxZ: z + TREE_BOX / 2,- });- }- });-- // Beside each outer neighbourhood: a phone booth in the run north of its window spot, a trough in the run south of it.- departments.forEach((dept, index) => {- const zc = (dept.minZ + dept.maxZ) / 2;- const runs = [[dept.minZ + END_MARGIN, zc - WINDOW_GAP], [zc + WINDOW_GAP, dept.maxZ - END_MARGIN]] as const;- for (const side of ["west", "east"] as const) {- const outer = side === "west" ? dept.minX <= colMinX + 1e-6 : dept.maxX >= colMaxX - 1e-6;- if (!outer) continue;- const facing = side === "west" ? "east" : "west";- runs.forEach(([z0, z1], run) => {- if (z1 - z0 < MIN_RUN) return;- if (run === 0) {- const [minX, maxX] = side === "west"- ? [colMinX - BOOTH.out - BOOTH.d, colMinX - BOOTH.out]- : [colMaxX + BOOTH.out, colMaxX + BOOTH.out + BOOTH.d];- items.push({ id: `booth-${index}-${side}`, kind: "booth", facing, h: BOOTH.h, tint: dept.tint ?? index,- minX, maxX, minZ: z0, maxZ: z0 + BOOTH.len });- return;- }- const [minX, maxX] = side === "west"- ? [colMinX - TROUGH_OUT - TROUGH_DEPTH, colMinX - TROUGH_OUT]- : [colMaxX + TROUGH_OUT, colMaxX + TROUGH_OUT + TROUGH_DEPTH];- items.push({ id: `trough-${index}-${side}`, kind: "trough", facing, h: TROUGH_H, minX, maxX, minZ: z0, maxZ: z1 });- });- }- });-- // The main street: a grove in the middle of every row, on the concourse's centre line.- const west = departments.filter((d) => d.minX <= colMinX + 1e-6);- const east = departments.filter((d) => d.maxX >= colMaxX - 1e-6 && d.minX > colMinX + 1e-6);- if (west.length > 0 && east.length > 0) {- const cx = (Math.max(...west.map((d) => d.maxX)) + Math.min(...east.map((d) => d.minX))) / 2;- rowStarts.forEach((start, i) => {- const row = departments.filter((d) => d.minZ === start);- const z = (start + Math.max(...row.map((d) => d.maxZ))) / 2;- items.push({- id: `grove-${i}`, kind: "grove", facing: "east", h: GROVE_H,- minX: cx - GROVE_BOX / 2, maxX: cx + GROVE_BOX / 2, minZ: z - GROVE_BOX / 2, maxZ: z + GROVE_BOX / 2,- });- });- }- return items;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/codingFloorLook.test.ts b/dodaios/ui/web/frontend/src/components/society/office/codingFloorLook.test.tsdeleted file mode 100644index b560a2670d..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/codingFloorLook.test.ts+++ /dev/null@@ -1,22 +0,0 @@-import { describe, expect, it } from "vitest";-import { Color } from "three";--import { CODING_SCENE, CODING_TEAMS, codingTeam } from "./officePalette";--describe("coding floor look", () => {- it("gives the six neighbourhoods a floor can hold six different team colours, cycled for any index", () => {- expect(new Set(CODING_TEAMS.map((t) => t.accent)).size).toBe(CODING_TEAMS.length);- expect(CODING_TEAMS.length).toBeGreaterThanOrEqual(6);- expect(codingTeam(CODING_TEAMS.length)).toBe(codingTeam(0));- expect(codingTeam(-1)).toBe(codingTeam(CODING_TEAMS.length - 1));- });-- it("keeps team colours apart from the busy lights' status colours", () => {- for (const team of CODING_TEAMS) {- for (const status of [CODING_SCENE.busy.working, CODING_SCENE.busy.waiting, CODING_SCENE.busy.error]) {- const a = new Color(team.accent), b = new Color(status);- expect(Math.hypot(a.r - b.r, a.g - b.g, a.b - b.b), `${team.accent} vs ${status}`).toBeGreaterThan(0.2);- }- }- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/courierAudio.ts b/dodaios/ui/web/frontend/src/components/society/office/courierAudio.tsdeleted file mode 100644index baa4479584..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/courierAudio.ts+++ /dev/null@@ -1,183 +0,0 @@-/**- * The courier's engine sound, synthesised (no audio files): a low hum and a- * filtered rush that rise with the throttle, a hiss for the boost, a thud on- * impact. It is placed in space at the ship and heard from the camera, so it- * pans with the view; its pitch shifts with the speed between the two- * (Doppler); in the cockpit a low-pass makes it the muffled inside of the hull.- *- * The audio context starts on boarding (a key press or a click, so the- * browser allows it) and is closed again on leaving the ship.- */-const SPEED_OF_SOUND = 343;--export interface EngineFrame {- throttle: number;- boost: boolean;- /** Ship and listener positions and velocities, world metres and metres per second. */- ship: { x: number; y: number; z: number };- shipVelocity: { x: number; y: number; z: number };- listener: { x: number; y: number; z: number };- listenerVelocity: { x: number; y: number; z: number };- /** The listener's forward and up, for the panning. */- forward: { x: number; y: number; z: number };- up: { x: number; y: number; z: number };- inside: boolean;- volume: number;-}--/** The pitch factor heard for a source moving relative to a listener (classic Doppler, clamped). */-export function dopplerFactor(frame: Pick<EngineFrame, "ship" | "shipVelocity" | "listener" | "listenerVelocity">): number {- const dx = frame.ship.x - frame.listener.x, dy = frame.ship.y - frame.listener.y, dz = frame.ship.z - frame.listener.z;- const d = Math.hypot(dx, dy, dz);- if (d < 1e-3) return 1;- const ux = dx / d, uy = dy / d, uz = dz / d;- // Speeds along the line from listener to source; positive = moving away from the other.- const source = frame.shipVelocity.x * ux + frame.shipVelocity.y * uy + frame.shipVelocity.z * uz;- const listener = frame.listenerVelocity.x * ux + frame.listenerVelocity.y * uy + frame.listenerVelocity.z * uz;- const factor = (SPEED_OF_SOUND + listener) / (SPEED_OF_SOUND + source);- return Math.min(1.6, Math.max(0.6, factor));-}--export class CourierEngineSound {- private ctx: AudioContext;- private master!: GainNode;- private panner!: PannerNode;- private muffle!: BiquadFilterNode;- private hum!: OscillatorNode;- private hum2!: OscillatorNode;- private humGain!: GainNode;- private rushFilter!: BiquadFilterNode;- private rushGain!: GainNode;- private hissGain!: GainNode;-- constructor() {- const Ctx = window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;- const ctx = new Ctx();- this.ctx = ctx;- try {- this.build(ctx);- } catch (error) {- // Half a graph is no use: close the context so it does not linger, and let the caller go on in silence.- void ctx.close().catch((closeError) => console.warn("courier sound context did not close", closeError));- throw error;- }- }-- private build(ctx: AudioContext): void {- this.master = ctx.createGain();- this.master.gain.value = 0;- this.muffle = ctx.createBiquadFilter();- this.muffle.type = "lowpass";- this.muffle.frequency.value = 18000;- this.panner = ctx.createPanner();- this.panner.panningModel = "HRTF";- this.panner.distanceModel = "inverse";- this.panner.refDistance = 12;- this.panner.rolloffFactor = 0.8;- this.panner.connect(this.muffle).connect(this.master).connect(ctx.destination);-- // The hum: two detuned oscillators, a saw and a square an octave up.- this.humGain = ctx.createGain();- this.humGain.gain.value = 0;- const humFilter = ctx.createBiquadFilter();- humFilter.type = "lowpass";- humFilter.frequency.value = 900;- this.hum = ctx.createOscillator();- this.hum.type = "sawtooth";- this.hum.frequency.value = 48;- this.hum2 = ctx.createOscillator();- this.hum2.type = "square";- this.hum2.frequency.value = 97;- this.hum.connect(humFilter);- this.hum2.connect(humFilter);- humFilter.connect(this.humGain).connect(this.panner);-- // The rush and the boost's hiss: one looping noise buffer, two filters.- const noise = ctx.createBufferSource();- const buffer = ctx.createBuffer(1, ctx.sampleRate * 2, ctx.sampleRate);- const data = buffer.getChannelData(0);- for (let i = 0; i < data.length; i += 1) data[i] = Math.random() * 2 - 1;- noise.buffer = buffer;- noise.loop = true;- this.rushFilter = ctx.createBiquadFilter();- this.rushFilter.type = "bandpass";- this.rushFilter.Q.value = 0.7;- this.rushGain = ctx.createGain();- this.rushGain.gain.value = 0;- noise.connect(this.rushFilter).connect(this.rushGain).connect(this.panner);- const hissFilter = ctx.createBiquadFilter();- hissFilter.type = "highpass";- hissFilter.frequency.value = 3500;- this.hissGain = ctx.createGain();- this.hissGain.gain.value = 0;- noise.connect(hissFilter).connect(this.hissGain).connect(this.panner);-- this.hum.start();- this.hum2.start();- noise.start();- }-- update(frame: EngineFrame): void {- const t = this.ctx.currentTime, glide = 0.08;- const doppler = dopplerFactor(frame);- const th = frame.throttle;- this.master.gain.setTargetAtTime(frame.volume * 0.5, t, 0.3);- this.hum.frequency.setTargetAtTime((44 + th * 40) * doppler, t, glide);- this.hum2.frequency.setTargetAtTime((89 + th * 82) * doppler, t, glide);- this.humGain.gain.setTargetAtTime(0.18 + th * 0.22, t, glide);- this.rushFilter.frequency.setTargetAtTime((300 + th * 1400) * doppler, t, glide);- this.rushGain.gain.setTargetAtTime(0.05 + th * 0.35, t, glide);- this.hissGain.gain.setTargetAtTime(frame.boost ? 0.16 : 0, t, 0.15);- this.muffle.frequency.setTargetAtTime(frame.inside ? 700 : 18000, t, 0.2);- setPosition(this.panner, frame.ship, t);- const l = this.ctx.listener;- if (l.positionX) {- l.positionX.setTargetAtTime(frame.listener.x, t, 0.03);- l.positionY.setTargetAtTime(frame.listener.y, t, 0.03);- l.positionZ.setTargetAtTime(frame.listener.z, t, 0.03);- l.forwardX.setTargetAtTime(frame.forward.x, t, 0.03);- l.forwardY.setTargetAtTime(frame.forward.y, t, 0.03);- l.forwardZ.setTargetAtTime(frame.forward.z, t, 0.03);- l.upX.setTargetAtTime(frame.up.x, t, 0.03);- l.upY.setTargetAtTime(frame.up.y, t, 0.03);- l.upZ.setTargetAtTime(frame.up.z, t, 0.03);- } else {- // Older engines: the deprecated setters.- l.setPosition(frame.listener.x, frame.listener.y, frame.listener.z);- l.setOrientation(frame.forward.x, frame.forward.y, frame.forward.z, frame.up.x, frame.up.y, frame.up.z);- }- }-- /** A thud for an impact of this speed (m/s); the master gain already carries the pilot's volume. */- impact(speed: number): void {- const t = this.ctx.currentTime;- const osc = this.ctx.createOscillator();- const gain = this.ctx.createGain();- osc.type = "triangle";- osc.frequency.setValueAtTime(90, t);- osc.frequency.exponentialRampToValueAtTime(30, t + 0.4);- gain.gain.setValueAtTime(Math.min(0.8, speed / 40), t);- gain.gain.exponentialRampToValueAtTime(0.001, t + 0.5);- osc.connect(gain).connect(this.muffle);- osc.start(t);- osc.stop(t + 0.55);- }-- resume(): void {- if (this.ctx.state === "suspended") void this.ctx.resume().catch((error) => console.warn("courier sound could not start", error));- }-- close(): void {- void this.ctx.close().catch((error) => console.warn("courier sound did not close cleanly", error));- }-}--function setPosition(panner: PannerNode, p: { x: number; y: number; z: number }, t: number) {- if (panner.positionX) {- panner.positionX.setTargetAtTime(p.x, t, 0.03);- panner.positionY.setTargetAtTime(p.y, t, 0.03);- panner.positionZ.setTargetAtTime(p.z, t, 0.03);- } else {- panner.setPosition(p.x, p.y, p.z);- }-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/courierControls.ts b/dodaios/ui/web/frontend/src/components/society/office/courierControls.tsdeleted file mode 100644index 72e879c3a8..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/courierControls.ts+++ /dev/null@@ -1,178 +0,0 @@-/**- * The courier's controls: the actions a pilot has, their default keys, the- * pilot's own rebinding (kept in this browser), and how held keys and a- * gamepad become one FlightInput. Pure and tested.- */-import { Quaternion, Vector3 } from "three";-import type { FlightInput } from "./courierFlight";--export const FLIGHT_ACTIONS = [- "throttleUp", "throttleDown", "pitchUp", "pitchDown", "yawLeft", "yawRight", "rollLeft", "rollRight",- "liftUp", "liftDown", "boost", "brake", "assist", "camera", "land", "exit", "help",-] as const;-export type FlightAction = (typeof FLIGHT_ACTIONS)[number];--/** Continuous actions are read while held; the rest fire once per press. */-export const PRESS_ACTIONS: ReadonlySet<FlightAction> = new Set(["assist", "camera", "land", "exit", "help"]);--export type FlightBindings = Record<FlightAction, string[]>;--export const DEFAULT_BINDINGS: FlightBindings = {- throttleUp: ["KeyW"], throttleDown: ["KeyS"],- pitchUp: ["ArrowUp"], pitchDown: ["ArrowDown"],- yawLeft: ["KeyA"], yawRight: ["KeyD"],- rollLeft: ["KeyQ", "ArrowLeft"], rollRight: ["KeyE", "ArrowRight"],- liftUp: ["Space"], liftDown: ["KeyC", "ControlLeft"],- boost: ["ShiftLeft", "ShiftRight"], brake: ["KeyX"],- assist: ["KeyT"], camera: ["KeyV"], land: ["KeyL"], exit: ["KeyF"], help: ["KeyH"],-};--/** Versioned: the first defaults had the arrows the other way round, and a saved copy of them must not survive. */-const STORAGE_KEY = "dodaios.verse.courier.bindings.v2";--/** The pilot's bindings: the defaults with whatever this browser remembers laid over them. */-export function loadBindings(storage: Pick<Storage, "getItem"> | null = safeStorage()): FlightBindings {- const out: FlightBindings = { ...DEFAULT_BINDINGS };- try {- const raw = storage?.getItem(STORAGE_KEY);- if (!raw) return out;- const saved = JSON.parse(raw) as Partial<Record<string, unknown>>;- for (const action of FLIGHT_ACTIONS) {- const keys = saved[action];- if (Array.isArray(keys) && keys.every((k) => typeof k === "string")) out[action] = keys as string[];- }- } catch (error) {- // A corrupt entry falls back to the defaults; the pilot can rebind again.- console.warn("courier bindings unreadable, using the defaults", error);- }- return out;-}--export function saveBindings(bindings: FlightBindings, storage: Pick<Storage, "setItem"> | null = safeStorage()): void {- try {- storage?.setItem(STORAGE_KEY, JSON.stringify(bindings));- } catch (error) {- // Private windows and blocked storage keep the binding for this visit only.- console.warn("courier bindings not saved", error);- }-}--function safeStorage(): Storage | null {- try {- return typeof window !== "undefined" ? window.localStorage : null;- } catch {- return null; // Storage access itself can throw where site data is blocked; then nothing is remembered.- }-}--/** Bind `code` to `action` alone: it leaves every other action it was on, and replaces the action's keys. */-export function rebind(bindings: FlightBindings, action: FlightAction, code: string): FlightBindings {- const out = {} as FlightBindings;- for (const a of FLIGHT_ACTIONS) out[a] = bindings[a].filter((k) => k !== code);- out[action] = [code];- return out;-}--/** A key code as a pilot reads it ("KeyW" → "W", "ArrowUp" → "↑", "ShiftLeft" → "Shift"). */-export function keyLabel(code: string): string {- if (code.startsWith("Key")) return code.slice(3);- if (code.startsWith("Digit")) return code.slice(5);- const named: Record<string, string> = {- ArrowUp: "↑", ArrowDown: "↓", ArrowLeft: "←", ArrowRight: "→", Space: "Space",- ShiftLeft: "Shift", ShiftRight: "Shift", ControlLeft: "Ctrl", ControlRight: "Ctrl", AltLeft: "Alt", AltRight: "Alt",- };- return named[code] ?? code;-}--/** The subset of a Gamepad this module reads (standard mapping). */-export interface PadState { axes: readonly number[]; buttons: readonly { value: number; pressed: boolean }[] }--const DEAD_ZONE = 0.15;-function stick(v: number | undefined): number {- const x = v ?? 0;- return Math.abs(x) < DEAD_ZONE ? 0 : (x - Math.sign(x) * DEAD_ZONE) / (1 - DEAD_ZONE);-}--/**- * One FlightInput from the held keys and an optional gamepad: left stick pitch and yaw, right stick roll and- * lift, the triggers the throttle, A boost, B brake. Keys and pad add up and are clamped.- */-export function flightInput(held: ReadonlySet<string>, bindings: FlightBindings, pad: PadState | null, invertPitch: boolean): FlightInput {- const on = (action: FlightAction) => (bindings[action].some((k) => held.has(k)) ? 1 : 0);- const axis = (plus: FlightAction, minus: FlightAction) => on(plus) - on(minus);- const b = (i: number) => pad?.buttons[i]?.value ?? 0;- const clamp = (v: number) => Math.max(-1, Math.min(1, v));- // A stick pushed forward (negative y) dives, as in every flight game.- const pitch = clamp(axis("pitchUp", "pitchDown") + stick(pad?.axes[1]));- return {- throttle: clamp(axis("throttleUp", "throttleDown") + b(7) - b(6)),- pitch: invertPitch ? -pitch : pitch,- yaw: clamp(axis("yawRight", "yawLeft") + stick(pad?.axes[0])),- roll: clamp(axis("rollRight", "rollLeft") + stick(pad?.axes[2])),- lift: clamp(axis("liftUp", "liftDown") - stick(pad?.axes[3])),- boost: on("boost") === 1 || (pad?.buttons[0]?.pressed ?? false),- brake: on("brake") === 1 || (pad?.buttons[1]?.pressed ?? false),- };-}--/** Gamepad buttons that fire a press action: X lands, Y switches the camera, Back the assist, Start leaves the ship. */-export const PAD_PRESSES: readonly [number, FlightAction][] = [[2, "land"], [3, "camera"], [8, "assist"], [9, "exit"]];--/**- * Mouse aim. With the mouse captured, moving it moves where the pilot aims (a direction in the world, shown as a- * reticle), and the ship keeps turning towards that aim by itself until its nose is on it, whether or not the- * mouse is still moving. Yaw 0 looks along -z and grows towards -x; pitch is up from the horizon.- */-export interface MouseAim { yaw: number; pitch: number }--/** Radians of aim per pixel of mouse movement, and the steepest aim up or down. */-export const AIM_PER_PIXEL = 0.0024;-const AIM_PITCH_LIMIT = 1.4;-/** How hard the ship steers towards the aim: stick per radian of error. */-const AIM_GAIN = 2.6;--export function aimFromForward(forward: Vector3): MouseAim {- return { yaw: Math.atan2(-forward.x, -forward.z), pitch: Math.asin(Math.max(-1, Math.min(1, forward.y))) };-}--export function aimDirection(aim: MouseAim, out = new Vector3()): Vector3 {- const c = Math.cos(aim.pitch);- return out.set(-Math.sin(aim.yaw) * c, Math.sin(aim.pitch), -Math.cos(aim.yaw) * c);-}--/** Move the aim by a mouse movement (pixels, browser axes: +y is down): up aims higher, right aims right. */-export function moveAim(aim: MouseAim, dx: number, dy: number, invertPitch: boolean): MouseAim {- aim.yaw -= dx * AIM_PER_PIXEL;- aim.pitch = Math.max(-AIM_PITCH_LIMIT, Math.min(AIM_PITCH_LIMIT, aim.pitch + (invertPitch ? dy : -dy) * AIM_PER_PIXEL));- return aim;-}--/** Turn rate of the aim with the cursor at the edge of the view, and the still zone around its middle. */-const CURSOR_TURN_RATE = 1.8;-const CURSOR_DEAD_ZONE = 0.08;--/**- * Cursor steering, for when the view cannot capture the mouse: the cursor's place in the view (-1..1 from the middle,- * +y up) turns the aim at a rate that grows towards the edge, and keeps turning while the cursor rests there.- */-export function cursorTurn(aim: MouseAim, x: number, y: number, dt: number): MouseAim {- const shape = (v: number) => {- const m = Math.max(0, Math.min(1, (Math.abs(v) - CURSOR_DEAD_ZONE) / (1 - CURSOR_DEAD_ZONE)));- return Math.sign(v) * m * m;- };- aim.yaw -= shape(x) * CURSOR_TURN_RATE * dt;- aim.pitch = Math.max(-AIM_PITCH_LIMIT, Math.min(AIM_PITCH_LIMIT, aim.pitch + shape(y) * CURSOR_TURN_RATE * dt));- return aim;-}--const _local = new Vector3();-const _inverse = new Quaternion();--/** The pitch and yaw that turn a ship of orientation q towards direction dir, added to the input. */-export function steerTowards(input: FlightInput, q: Quaternion, dir: Vector3): FlightInput {- const local = _local.copy(dir).applyQuaternion(_inverse.copy(q).invert());- const clamp = (v: number) => Math.max(-1, Math.min(1, v));- input.yaw = clamp(input.yaw + Math.atan2(local.x, -local.z) * AIM_GAIN);- input.pitch = clamp(input.pitch + Math.atan2(local.y, Math.hypot(local.x, local.z)) * AIM_GAIN);- return input;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/courierFlight.test.ts b/dodaios/ui/web/frontend/src/components/society/office/courierFlight.test.tsdeleted file mode 100644index da1ea70cfb..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/courierFlight.test.ts+++ /dev/null@@ -1,259 +0,0 @@-import { describe, expect, it } from "vitest";-import { Vector3 } from "three";-import { GROUND_Y, planCity } from "./cityPlan";-import { aimDirection, aimFromForward, cursorTurn, DEFAULT_BINDINGS, flightInput, keyLabel, loadBindings, moveAim, rebind, saveBindings, steerTowards } from "./courierControls";-import { engageAutopilot, FLIGHT, forwardOf, NO_INPUT, parkedState, stepFlight, type FlightInput, type FlightState } from "./courierFlight";-import { buildCourierWorld, rayDistance, sphereContact } from "./courierWorld";-import { buildOfficeLayout } from "./officeLayout";-import { buildNavGrid, findPath, isWalkable, randomWalkablePoint } from "./officeNav";-import { COURIER, onSkyPad } from "./skyPad";--const staff = Array.from({ length: 8 }, (_, i) => ({ agentId: `a${i}`, name: `Agent ${i}`, tier: "specialist" as const, providerLabel: "x", state: "idle" as const, createdMs: i }));-const layout = buildOfficeLayout(staff);-const pad = layout.skyPad!;-const world = buildCourierWorld(planCity(layout.bounds), layout.bounds, pad);-const home = pad.ship;--function fly(s: FlightState, input: Partial<FlightInput>, seconds: number, assist: "arcade" | "simulation" = "arcade") {- for (let t = 0; t < seconds; t += 1 / 60) stepFlight(s, { ...NO_INPUT, ...input }, 1 / 60, assist, world, home);- return s;-}--describe("the sky pad", () => {- it("stands out of the agents floor's east side on the boulevard's line, outside the slab", () => {- expect(pad.pad.x - pad.pad.r).toBeGreaterThan(layout.bounds.maxX);- expect(pad.gap.minZ).toBeGreaterThan(layout.bounds.minZ);- expect(pad.gap.maxZ).toBeLessThan(layout.bounds.maxZ);- // The courier fits on the deck.- expect(Math.hypot(COURIER.span / 2, COURIER.length / 2)).toBeLessThan(pad.pad.r);- });-- it("is walkable from the floor to the hatch, and its courier is solid", () => {- const grid = buildNavGrid(layout);- expect(isWalkable(grid, pad.board)).toBe(true);- expect(onSkyPad(pad, { x: pad.pad.x, z: pad.pad.z })).toBe(true);- expect(isWalkable(grid, { x: pad.pad.x, z: pad.pad.z })).toBe(false);- // Off the rim and beside the bridge is air.- expect(isWalkable(grid, { x: pad.pad.x + pad.pad.r + 1, z: pad.pad.z })).toBe(false);- expect(isWalkable(grid, { x: (layout.bounds.maxX + pad.bridge.maxX) / 2, z: pad.gap.maxZ + 2 })).toBe(false);- const path = findPath(grid, layout.spawn, pad.board);- expect(path).not.toBeNull();- expect(path!.length).toBeGreaterThan(1);- });-- it("never sends an idle wanderer out onto the pad", () => {- const grid = buildNavGrid(layout);- let seed = 7;- const rng = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);- for (let i = 0; i < 300; i += 1) {- const p = randomWalkablePoint(grid, rng)!;- expect(p.x).toBeLessThanOrEqual(layout.floor.maxX);- }- });-- it("offers the courier as a checkpoint beside its hatch, nowhere else", () => {- const ship = layout.checkpoints.filter((c) => c.id === "ship");- expect(ship).toHaveLength(1);- expect(ship[0].x).toBeCloseTo(pad.board.x);- expect(buildOfficeLayout([]).skyPad).toBeDefined();- expect(buildOfficeLayout(staff, { variant: "coding" }).skyPad).toBeUndefined();- });-});--describe("the courier's world", () => {- it("is solid where the city is and free in the plaza's air", () => {- expect(sphereContact(world, pad.pad.x, 40, pad.pad.z, 2)).toBeNull();- expect(sphereContact(world, pad.pad.x, GROUND_Y + 1, pad.pad.z, 2)).not.toBeNull();- // Inside the office: pushed out.- const c = (layout.bounds.minX + layout.bounds.maxX) / 2;- expect(sphereContact(world, c, 1.5, (layout.bounds.minZ + layout.bounds.maxZ) / 2, 2)).not.toBeNull();- });-- it("measures how far a ray runs before it meets the city", () => {- const down = rayDistance(world, { x: pad.pad.x, y: 50, z: pad.pad.z }, { x: 0, y: -1, z: 0 }, 1000);- expect(down).toBeCloseTo(50, 0);- });-});--describe("the courier's flight", () => {- it("stands on the pad until it is told to lift off, then climbs", () => {- const s = parkedState(home);- fly(s, {}, 1);- expect(s.landed).toBe(true);- expect(s.p.y).toBeCloseTo(COURIER.standHeight);- fly(s, { lift: 1 }, 2);- expect(s.landed).toBe(false);- expect(s.p.y).toBeGreaterThan(COURIER.standHeight + 5);- });-- it("in arcade, climbs and dives steeply and its lift goes straight up or down", () => {- const s = parkedState(home);- fly(s, { lift: 1 }, 2);- fly(s, { throttle: 1 }, 2);- // Full stick back for a second: the nose comes far up, and stays there when the stick is let go.- fly(s, { pitch: 1 }, 0.8);- const climb = forwardOf(s.q).y;- expect(climb).toBeGreaterThan(0.6);- fly(s, {}, 1);- expect(forwardOf(s.q).y).toBeGreaterThan(climb - 0.1);- // From level flight the sink key sinks fast, and a dive goes down steeply.- const level = parkedState(home);- fly(level, { lift: 1 }, 2);- fly(level, { throttle: 1 }, 2);- const y = level.p.y;- fly(level, { lift: -1 }, 1);- expect(level.p.y).toBeLessThan(y - 10);- expect(level.v.y).toBeLessThan(-FLIGHT.lift * 0.5);- fly(level, { pitch: -1 }, 0.8);- expect(forwardOf(level.q).y).toBeLessThan(-0.6);- });-- it("in arcade, flies where its nose points at the throttle's speed and levels its wings", () => {- const s = parkedState(home);- fly(s, { lift: 1 }, 3);- fly(s, { throttle: 1 }, 4);- fly(s, {}, 4);- const nose = forwardOf(s.q);- expect(s.v.length()).toBeGreaterThan(FLIGHT.cruise * 0.8);- expect(s.v.clone().normalize().dot(nose)).toBeGreaterThan(0.95);- // Wings level: the right wing's height is near zero.- expect(Math.abs(new Vector3(1, 0, 0).applyQuaternion(s.q).y)).toBeLessThan(0.1);- });-- it("in simulation, keeps drifting the old way after a turn", () => {- const s = parkedState(home);- fly(s, { lift: 1 }, 0.6, "simulation");- fly(s, { lift: -1 }, 0.6, "simulation");- fly(s, { throttle: 1 }, 3, "simulation");- fly(s, { throttle: -1 }, 2, "simulation");- const before = s.v.clone().normalize();- fly(s, { yaw: 1 }, 1.2, "simulation");- const nose = forwardOf(s.q);- // The nose turned, the velocity mostly did not.- expect(before.dot(nose)).toBeLessThan(0.9);- expect(s.v.clone().normalize().dot(before)).toBeGreaterThan(0.95);- });-- it("boosts past cruise speed and spends its charge doing so", () => {- const s = parkedState(home);- fly(s, { lift: 1 }, 3);- fly(s, { throttle: 1, boost: true }, 3);- expect(s.v.length()).toBeGreaterThan(FLIGHT.cruise * 1.2);- expect(s.charge).toBeLessThan(0.6);- });-- it("never passes through a tower, even at full boost, and flashes its shield", () => {- const s = parkedState(home);- const tower = planCity(layout.bounds).towers.find((t) => t.h > 120 && Math.hypot(t.x - home.x, t.z - home.z) > 150)!;- // Aim at the tower from 120 m out at its mid height.- const at = new Vector3(tower.x, GROUND_Y + tower.h / 2, tower.z);- s.landed = false;- s.p.set(tower.x + 120, at.y, tower.z);- s.q.setFromAxisAngle(new Vector3(0, 1, 0), Math.PI / 2);- s.throttle = 1;- let crossed = false, flashed = false;- for (let i = 0; i < 400; i += 1) {- stepFlight(s, { ...NO_INPUT, throttle: 1, boost: true }, 1 / 60, "simulation", world, home);- if (s.p.x < tower.x) crossed = true;- if (s.shield > 0.2) flashed = true;- }- expect(crossed).toBe(false);- expect(flashed).toBe(true);- });-- it("lands itself on the pad from out over the city, gear down", () => {- const s = parkedState(home);- s.landed = false; s.gear = 0;- s.p.set(home.x + 200, 30, home.z - 150);- s.q.setFromAxisAngle(new Vector3(0, 1, 0), 2.1);- engageAutopilot(s);- for (let i = 0; i < 60 * 90 && !s.landed; i += 1) stepFlight(s, NO_INPUT, 1 / 60, "arcade", world, home);- expect(s.landed).toBe(true);- expect(s.p.distanceTo(new Vector3(home.x, COURIER.standHeight, home.z))).toBeLessThan(0.01);- expect(s.gear).toBeCloseTo(1, 1);- });-- it("lands itself from deep in the city, under the pad and beside the tower too", () => {- for (const [dx, y, dz] of [[0, -60, 0], [-30, -120, 0], [180, -200, 90]] as const) {- const s = parkedState(home);- s.landed = false; s.gear = 0;- s.p.set(home.x + dx, y, home.z + dz);- engageAutopilot(s);- for (let i = 0; i < 60 * 150 && !s.landed; i += 1) stepFlight(s, NO_INPUT, 1 / 60, "arcade", world, home);- expect(s.landed, `from ${dx},${y},${dz}`).toBe(true);- }- });-- it("lets an impact's shake and flash fade while it lands itself and while it stands", () => {- const s = parkedState(home);- s.impact = 40; s.shield = 1;- fly(s, {}, 2);- expect(s.impact).toBe(0);- expect(s.shield).toBe(0);- });-- it("hands the controls back the moment the pilot touches them", () => {- const s = parkedState(home);- s.landed = false; s.p.set(home.x + 100, 40, home.z);- engageAutopilot(s);- stepFlight(s, { ...NO_INPUT, yaw: 1 }, 1 / 60, "arcade", world, home);- expect(s.autopilot).toBeNull();- });-});--describe("the courier's controls", () => {- it("reads held keys and a gamepad into one input", () => {- const input = flightInput(new Set(["KeyW", "KeyA"]), DEFAULT_BINDINGS, { axes: [0, 0, 0.9, 0], buttons: [{ value: 1, pressed: true }] }, false);- expect(input.throttle).toBe(1);- expect(input.yaw).toBe(-1);- expect(input.roll).toBeGreaterThan(0.8);- expect(input.boost).toBe(true);- // A resting stick inside the dead zone is nothing.- expect(flightInput(new Set(), DEFAULT_BINDINGS, { axes: [0.1, -0.1, 0, 0], buttons: [] }, false).yaw).toBe(0);- });-- it("aims with the mouse: the ship turns to the aim and keeps flying there after the mouse stops", () => {- const s = parkedState(home);- fly(s, { lift: 1 }, 2);- fly(s, { throttle: 1 }, 2);- const aim = aimFromForward(forwardOf(s.q));- // One short flick of the mouse up and to the right, then nothing more.- moveAim(aim, 260, -180, false);- const target = aimDirection(aim);- for (let i = 0; i < 60 * 3; i += 1) stepFlight(s, steerTowards({ ...NO_INPUT }, s.q, target), 1 / 60, "arcade", world, home);- // The nose came round onto the aim by itself: up and to the right.- expect(forwardOf(s.q).angleTo(target)).toBeLessThan(0.12);- expect(forwardOf(s.q).y).toBeGreaterThan(0.3);- // And the velocity followed it.- expect(s.v.clone().normalize().angleTo(target)).toBeLessThan(0.25);- // Inverted pitch aims the other way.- expect(moveAim({ yaw: 0, pitch: 0 }, 0, -100, true).pitch).toBeLessThan(0);- });-- it("steers with the cursor when the mouse cannot be captured: a resting cursor off the middle keeps turning", () => {- // In the still zone nothing turns.- expect(cursorTurn({ yaw: 0, pitch: 0 }, 0.05, -0.05, 1)).toEqual({ yaw: 0, pitch: 0 });- // Right of the middle turns right (yaw falls), above it pitches up, and each frame adds the same again.- const aim = { yaw: 0, pitch: 0 };- for (let i = 0; i < 30; i += 1) cursorTurn(aim, 0.6, 0.4, 1 / 60);- const half = { ...aim };- for (let i = 0; i < 30; i += 1) cursorTurn(aim, 0.6, 0.4, 1 / 60);- expect(half.yaw).toBeLessThan(0);- expect(half.pitch).toBeGreaterThan(0);- expect(aim.yaw).toBeCloseTo(half.yaw * 2, 6);- // Further out turns faster.- expect(Math.abs(cursorTurn({ yaw: 0, pitch: 0 }, 1, 0, 1).yaw)).toBeGreaterThan(Math.abs(cursorTurn({ yaw: 0, pitch: 0 }, 0.5, 0, 1).yaw));- });-- it("rebinds a key to one action and remembers it", () => {- const next = rebind(DEFAULT_BINDINGS, "boost", "KeyW");- expect(next.boost).toEqual(["KeyW"]);- expect(next.throttleUp).toEqual([]);- const store = new Map<string, string>();- saveBindings(next, { setItem: (k, v) => store.set(k, v) });- expect(loadBindings({ getItem: (k) => store.get(k) ?? null }).boost).toEqual(["KeyW"]);- expect(loadBindings({ getItem: () => "{broken" }).boost).toEqual(DEFAULT_BINDINGS.boost);- expect(keyLabel("KeyW")).toBe("W");- expect(keyLabel("ArrowUp")).toBe("↑");- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/courierFlight.ts b/dodaios/ui/web/frontend/src/components/society/office/courierFlight.tsdeleted file mode 100644index fb4d381456..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/courierFlight.ts+++ /dev/null@@ -1,282 +0,0 @@-/**- * The courier's flight: a small rigid-body model with thrust, lift, pitch, yaw- * and roll, two assist modes, boost and brake, collisions with the city, and an- * autopilot that lands it on the sky pad. Pure and tested; the scene drives it- * once per frame (SkyCourier.tsx).- *- * Frame: the ship's nose is its local -z, its top +y, its right +x (as the- * exported model). Speeds are metres per second at the Verse's scale.- *- * - Arcade assist (the default): made for fun. The ship flies where it points,- * turns fast, climbs and dives as steeply as the pilot likes, and its lift- * thrusters push straight up or down whatever its attitude. It banks into- * turns and levels its wings (never its nose) when the stick is let go.- * - Simulation: Newtonian. Thrust accelerates along the nose, the ship keeps- * its momentum and drifts; only light rotational dampers help.- */-import { Quaternion, Vector3 } from "three";-import { sphereContact, type CourierWorld } from "./courierWorld";-import { COURIER } from "./skyPad";--export type FlightAssist = "arcade" | "simulation";--export interface FlightInput {- /** -1..1: the throttle lever moves at its rate while held. */- throttle: number;- pitch: number;- yaw: number;- roll: number;- /** -1..1: vertical thrusters, up and down. */- lift: number;- boost: boolean;- brake: boolean;-}--export const NO_INPUT: FlightInput = { throttle: 0, pitch: 0, yaw: 0, roll: 0, lift: 0, boost: false, brake: false };--export type AutopilotPhase = "approach" | "hover" | "descend";--export interface FlightState {- p: Vector3;- v: Vector3;- q: Quaternion;- /** Body rates in radians per second: x pitch, y yaw, z roll. */- w: Vector3;- /** 0..1, the throttle lever. */- throttle: number;- /** 0 retracted .. 1 down. */- gear: number;- /** 0..1 boost charge, spent while boosting and recharged after. */- charge: number;- /** 0..1 shield flash after an impact, fading. */- shield: number;- /** Speed of the last impact (m/s), for the sound and the camera's shake; fades. */- impact: number;- landed: boolean;- autopilot: AutopilotPhase | null;- /** The autopilot's watch: the closest it came to its target, and how long it has gone without getting closer. */- apBest: number;- apStuck: number;-}--export const FLIGHT = {- cruise: 85,- boost: 170,- /** Thrust along the nose (m/s²) in simulation, and the boost's factor on it. */- thrust: 24,- boostFactor: 2.4,- /** Vertical thrust: arcade climbs and sinks at up to this speed (m/s); simulation accelerates with it. */- lift: 30,- /** Body rate at full stick (rad/s): pitch, yaw, roll. */- rates: [1.9, 1.3, 2.8] as const,- /** How fast arcade pulls the velocity onto the nose (1/s), and the simulation's linear drag. */- grip: 2.6,- drag: 0.025,- /** The throttle lever's travel per second at full input. */- leverRate: 1.1,- /** Boost charge spent and regained per second. */- boostDrain: 0.22,- boostRecharge: 0.12,- /** Below this height over the deck the gear comes down. */- gearHeight: 14,- /** The autopilot's hover height above the pad, the speed it approaches with and how fast it sinks. */- hover: 16,- approach: 45,- sink: 3.2,- /** Over every roof of the city (the tallest far ones stay below +45 m) and over the office: the approach's height. */- safeHeight: 60,-} as const;--/** Collision spheres along the keel (local z, metres) and their radius. */-export const KEEL = { offsets: [-6.2, -2.1, 2.1, 6.2], radius: 1.7 } as const;--const _f = new Vector3(), _u = new Vector3(), _r = new Vector3(), _t = new Vector3(), _a = new Vector3(), _q = new Quaternion(), _s = new Vector3();--/** A ship standing on the pad, nose along `heading` (0 = -z, turning towards -x as it grows). */-export function parkedState(pad: { x: number; z: number; heading: number }): FlightState {- return {- p: new Vector3(pad.x, COURIER.standHeight, pad.z),- v: new Vector3(), q: new Quaternion().setFromAxisAngle(new Vector3(0, 1, 0), pad.heading), w: new Vector3(),- throttle: 0, gear: 1, charge: 1, shield: 0, impact: 0, landed: true, autopilot: null, apBest: Infinity, apStuck: 0,- };-}--export function forwardOf(q: Quaternion, out = new Vector3()): Vector3 {- return out.set(0, 0, -1).applyQuaternion(q);-}--function axes(q: Quaternion) {- forwardOf(q, _f);- _u.set(0, 1, 0).applyQuaternion(q);- _r.set(1, 0, 0).applyQuaternion(q);-}--/** Advance the flight by dt seconds (callers pass at most 0.1 s). */-export function stepFlight(s: FlightState, raw: FlightInput, dt: number, assist: FlightAssist, world: CourierWorld,- pad: { x: number; z: number; heading: number }): FlightState {- let input = raw;- // The shield's flash and the impact fade in every state: flying, landing itself or standing on the pad.- s.shield = Math.max(0, s.shield - dt * 1.6);- s.impact = Math.max(0, s.impact - dt * 30);- if (s.autopilot) {- // Any stick or lever input hands the ship back to the pilot.- if (raw.throttle || raw.pitch || raw.yaw || raw.roll || raw.lift || raw.boost) s.autopilot = null;- else return autopilot(s, dt, world, pad);- }- if (s.landed) {- // Standing on the pad: only a lift or the throttle takes off.- if (input.lift > 0.1 || input.throttle > 0.1) { s.landed = false; s.v.set(0, 4, 0); }- else { s.v.set(0, 0, 0); s.w.set(0, 0, 0); s.throttle = 0; return s; }- }- s.throttle = Math.min(1, Math.max(0, s.throttle + input.throttle * FLIGHT.leverRate * dt));- if (input.brake) s.throttle = Math.max(0, s.throttle - 1.5 * dt);- const boosting = input.boost && s.charge > 0.02;- s.charge = Math.min(1, Math.max(0, s.charge + (boosting ? -FLIGHT.boostDrain : FLIGHT.boostRecharge) * dt));- axes(s.q);-- // Rotation: body rates follow the stick (arcade snaps, simulation accelerates and is damped).- const target = _t.set(input.pitch * FLIGHT.rates[0], -input.yaw * FLIGHT.rates[1], -input.roll * FLIGHT.rates[2]);- if (assist === "arcade") {- // Bank into a turn, and level the wings when the stick is let go (the right wing's height is the bank).- const bank = Math.asin(Math.max(-1, Math.min(1, _r.y)));- const wanted = -input.yaw * 0.5;- if (!input.roll) target.z += (wanted - bank) * 2.2;- s.w.lerp(target, 1 - Math.exp(-10 * dt));- } else {- s.w.addScaledVector(_a.copy(target).sub(s.w), 1 - Math.exp(-3 * dt));- }- const turn = _q.setFromAxisAngle(_s.set(s.w.x, s.w.y, s.w.z).normalize(), s.w.length() * dt);- if (s.w.lengthSq() > 1e-10) s.q.multiply(turn).normalize();- axes(s.q);-- // Translation.- const top = boosting ? FLIGHT.boost : FLIGHT.cruise;- if (assist === "arcade") {- // Lift thrusters push along the world's up, so Space always climbs and the sink key always sinks.- const want = _t.copy(_f).multiplyScalar(s.throttle * top);- want.y += input.lift * FLIGHT.lift;- s.v.lerp(want, 1 - Math.exp(-FLIGHT.grip * (boosting ? 1.4 : 1) * dt));- } else {- s.v.addScaledVector(_f, s.throttle * FLIGHT.thrust * (boosting ? FLIGHT.boostFactor : 1) * dt);- s.v.addScaledVector(_u, input.lift * FLIGHT.lift * dt);- s.v.multiplyScalar(Math.exp(-FLIGHT.drag * dt));- if (s.v.length() > FLIGHT.boost * 1.1) s.v.setLength(FLIGHT.boost * 1.1);- }- if (input.brake) s.v.multiplyScalar(Math.exp(-2.2 * dt));- move(s, dt, world);- steerHome(s, dt, world);- s.gear += ((heightOverDeck(s, pad) < FLIGHT.gearHeight ? 1 : 0) - s.gear) * Math.min(1, dt * 1.5);- return s;-}--/** Height of the ship's middle over the pad's deck while above it; Infinity elsewhere. */-export function heightOverDeck(s: FlightState, pad: { x: number; z: number }): number {- return Math.hypot(s.p.x - pad.x, s.p.z - pad.z) < 30 ? s.p.y - COURIER.standHeight : Infinity;-}--/** Move by v·dt in sub-steps no longer than 1.5 m, pushing out of anything solid and bouncing off it. */-function move(s: FlightState, dt: number, world: CourierWorld) {- const steps = Math.max(1, Math.ceil((s.v.length() * dt) / 1.5));- const h = dt / steps;- for (let i = 0; i < steps; i += 1) {- s.p.addScaledVector(s.v, h);- for (const offset of KEEL.offsets) {- _s.set(0, 0, offset).applyQuaternion(s.q).add(s.p);- const hit = sphereContact(world, _s.x, _s.y, _s.z, KEEL.radius);- if (!hit) continue;- s.p.x += hit.nx * hit.depth; s.p.y += hit.ny * hit.depth; s.p.z += hit.nz * hit.depth;- const into = s.v.x * hit.nx + s.v.y * hit.ny + s.v.z * hit.nz;- if (into < 0) {- // Bounce off with a little give, and lose speed along the surface too.- s.v.x -= 1.35 * into * hit.nx; s.v.y -= 1.35 * into * hit.ny; s.v.z -= 1.35 * into * hit.nz;- s.v.multiplyScalar(0.8);- s.shield = Math.min(1, s.shield + Math.min(1, -into / 25) + 0.15);- s.impact = Math.max(s.impact, -into);- }- }- }-}--/** Beyond the city's edge or above its ceiling the ship is turned back gently. */-function steerHome(s: FlightState, dt: number, world: CourierWorld) {- const dx = s.p.x - world.centre.x, dz = s.p.z - world.centre.z, d = Math.hypot(dx, dz);- if (d > world.border) s.v.addScaledVector(_t.set(-dx / d, 0, -dz / d), (d - world.border) * 0.8 * dt);- if (s.p.y > world.ceiling) s.v.y -= (s.p.y - world.ceiling) * 0.8 * dt;-}--/** Start the autopilot that brings the ship home to the pad. */-export function engageAutopilot(s: FlightState): void {- if (s.landed) return;- s.autopilot = "approach";- s.apBest = Infinity;- s.apStuck = 0;-}--/**- * The landing: climb to the safe height first, cross over to the pad there, come down to a hover point over it,- * turn to the pad's heading and sink onto the deck with the gear down. Collisions still count on the way. A watch- * notices when the ship stops getting closer (under the pad, against the tower) and sidesteps outwards before it- * climbs on.- */-function autopilot(s: FlightState, dt: number, world: CourierWorld, pad: { x: number; z: number; heading: number }): FlightState {- const hover = _a.set(pad.x, COURIER.standHeight + FLIGHT.hover, pad.z);- const to = _t.copy(hover).sub(s.p);- const distance = to.length();- const flat = Math.hypot(to.x, to.z);- if (s.autopilot === "approach") {- if (distance < s.apBest - 0.5) { s.apBest = distance; s.apStuck = 0; } else s.apStuck += dt;- const want = _r;- if (s.apStuck > 4) {- // Stuck: out and away from the pad's middle (out from under it, off the tower's wall), then on again.- const out = _u.set(s.p.x - pad.x, 0, s.p.z - pad.z);- if (out.lengthSq() < 1) out.set(1, 0, 0);- want.copy(out.normalize()).multiplyScalar(18);- if (s.apStuck > 7) { s.apStuck = 0; s.apBest = distance; }- } else if (flat > 25 && s.p.y < FLIGHT.safeHeight - 3) {- // Climb first, barely moving sideways, so nothing of the city stands between the ship and the pad.- want.set(to.x, 0, to.z).normalize().multiplyScalar(3).add(_u.set(0, 22, 0));- } else if (flat > 25) {- // Across at the safe height.- want.set(to.x, 0, to.z).normalize().multiplyScalar(Math.min(FLIGHT.approach, flat * 0.7 + 2));- want.y = (FLIGHT.safeHeight - s.p.y) * 1.2;- } else {- want.copy(to).normalize().multiplyScalar(Math.min(FLIGHT.approach, distance * 0.7 + 2));- }- s.v.lerp(want, 1 - Math.exp(-1.5 * dt));- if (distance < 3 && s.v.length() < 4) s.autopilot = "hover";- } else {- s.v.lerp(_t.set(hover.x - s.p.x, 0, hover.z - s.p.z).multiplyScalar(1.5), 1 - Math.exp(-3 * dt));- if (s.autopilot === "hover") {- s.v.y += (hover.y - s.p.y) * 2 * dt - s.v.y * 2 * dt;- if (alignedTo(s, pad.heading) && flat < 1) s.autopilot = "descend";- } else {- const above = s.p.y - COURIER.standHeight;- s.v.y = -Math.min(FLIGHT.sink, Math.max(0.4, above * 0.6));- if (above < 0.05) {- s.p.set(pad.x, COURIER.standHeight, pad.z);- s.q.setFromAxisAngle(_s.set(0, 1, 0), pad.heading);- s.v.set(0, 0, 0); s.w.set(0, 0, 0);- s.landed = true; s.autopilot = null; s.throttle = 0; s.gear = 1;- return s;- }- }- }- // Turn to fly level towards the target (or to the pad's heading once there), wings level.- const heading = s.autopilot === "approach" && flat > 8 ? Math.atan2(-(hover.x - s.p.x), -(hover.z - s.p.z)) : pad.heading;- s.q.slerp(_q.setFromAxisAngle(_s.set(0, 1, 0), heading), 1 - Math.exp(-1.6 * dt));- s.w.set(0, 0, 0);- s.throttle += (Math.min(1, s.v.length() / FLIGHT.cruise) - s.throttle) * Math.min(1, dt * 2);- move(s, dt, world);- s.gear += ((heightOverDeck(s, pad) < FLIGHT.gearHeight ? 1 : 0) - s.gear) * Math.min(1, dt * 1.5);- return s;-}--function alignedTo(s: FlightState, heading: number): boolean {- const target = _q.setFromAxisAngle(_s.set(0, 1, 0), heading);- return s.q.angleTo(target) < 0.05;-}--/** Ground speed for the HUD (m/s). */-export function speedOf(s: FlightState): number {- return s.v.length();-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/courierHud.css b/dodaios/ui/web/frontend/src/components/society/office/courierHud.cssdeleted file mode 100644index 3215f5452f..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/courierHud.css+++ /dev/null@@ -1,37 +0,0 @@-/* The courier's flight HUD: theme tokens only, so light and dark mode both read. */-.courier-hud { position:absolute; z-index:40; left:50%; bottom:16px; transform:translateX(-50%); display:flex; flex-wrap:wrap; align-items:center; gap:10px 16px; padding:10px 14px; max-width:calc(100% - 28px); font-size:12px; }-.courier-speed { position:relative; display:flex; align-items:baseline; gap:4px; min-width:92px; }-.courier-speed strong { font-size:28px; font-weight:700; font-variant-numeric:tabular-nums; line-height:1; }-.courier-speed span { color:hsl(var(--muted-foreground)); }-.courier-speed-arc { position:absolute; left:0; right:0; bottom:-5px; height:3px; border-radius:2px; background:linear-gradient(90deg, hsl(var(--primary)) calc(var(--share) * 100%), hsl(var(--border)) 0); }-.courier-readouts { display:flex; flex-direction:column; gap:4px; min-width:150px; }-.courier-readouts strong { font-variant-numeric:tabular-nums; }-.courier-meter { display:grid; grid-template-columns:62px 1fr; align-items:center; gap:6px; color:hsl(var(--muted-foreground)); }-.courier-meter i { display:block; height:5px; border-radius:3px; background:hsl(var(--secondary)); overflow:hidden; }-.courier-meter b { display:block; height:100%; background:hsl(var(--primary)); transition:width .12s linear; }-.courier-actions { display:flex; flex-wrap:wrap; gap:6px; align-items:center; }-.courier-status { color:hsl(var(--muted-foreground)); }-.courier-primary { background:hsl(var(--primary)); color:hsl(var(--primary-foreground)); border-color:transparent; }-.courier-hud .office-hint { flex-basis:100%; }-.courier-help { position:absolute; z-index:40; right:14px; bottom:16px; width:min(300px, calc(100% - 28px)); max-height:calc(100% - 120px); overflow:auto; padding:12px 14px; font-size:12px; }-.courier-help dl { display:flex; flex-direction:column; gap:4px; margin:8px 0; }-.courier-help dl > div { display:flex; justify-content:space-between; gap:12px; }-.courier-help dt { color:hsl(var(--muted-foreground)); }-.courier-help dd { margin:0; }-.courier-help kbd { font:inherit; font-size:11px; padding:1px 6px; border:1px solid hsl(var(--border)); border-radius:5px; background:hsl(var(--background)); }-.courier-settings { position:absolute; z-index:50; left:50%; top:50%; transform:translate(-50%, -50%); width:min(420px, calc(100% - 28px)); max-height:calc(100% - 40px); overflow:auto; display:flex; flex-direction:column; gap:10px; padding:14px 16px; font-size:13px; }-.courier-settings-head { display:flex; justify-content:space-between; align-items:center; }-.courier-settings-row { display:flex; flex-wrap:wrap; align-items:center; gap:8px; }-.courier-settings-row input[type="range"] { flex:1; accent-color:hsl(var(--primary)); }-.courier-settings-row input[type="checkbox"] { accent-color:hsl(var(--primary)); }-.courier-bindings { display:grid; grid-template-columns:1fr; gap:4px; }-.courier-binding { display:flex; justify-content:space-between; align-items:center; gap:10px; }-.courier-binding span { color:hsl(var(--muted-foreground)); }-@media (max-width:600px) { .courier-hud { bottom:10px; gap:8px; } .courier-help { display:none; } }-/* Mouse aim: a ring where the pilot aims, a small dot where the nose points (both placed by the scene). */-.courier-aim, .courier-nose { position:absolute; z-index:39; pointer-events:none; opacity:0; transform:translate(-50%, -50%); }-.courier-aim { width:34px; height:34px; border-radius:50%; border:2px solid hsl(var(--primary) / .9); box-shadow:0 0 0 1px hsl(var(--background) / .6); }-.courier-aim::before, .courier-aim::after { content:""; position:absolute; left:50%; top:50%; background:hsl(var(--primary) / .9); transform:translate(-50%, -50%); }-.courier-aim::before { width:2px; height:8px; }-.courier-aim::after { width:8px; height:2px; }-.courier-nose { width:10px; height:10px; border-radius:50%; background:hsl(var(--foreground) / .85); box-shadow:0 0 0 2px hsl(var(--background) / .6); }diff --git a/dodaios/ui/web/frontend/src/components/society/office/courierStore.ts b/dodaios/ui/web/frontend/src/components/society/office/courierStore.tsdeleted file mode 100644index e2819b9c7f..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/courierStore.ts+++ /dev/null@@ -1,117 +0,0 @@-/**- * The courier's session: whether the person is flying it, the pilot's choices- * (camera, assist, pitch, sound, key bindings) and what the HUD shows. The- * choices are per viewer and kept in this browser; the flight itself lives in- * the scene (SkyCourier.tsx) and publishes a telemetry snapshot a few times a- * second for the HUD.- */-import { create } from "zustand";-import { loadBindings, saveBindings, type FlightBindings } from "./courierControls";-import type { AutopilotPhase, FlightAssist } from "./courierFlight";--export type CourierView = "chase" | "cockpit";--export interface CourierTelemetry {- speed: number;- throttle: number;- charge: number;- /** Metres over the pad's deck while above it, else over the street level. */- altitude: number;- overPad: boolean;- landed: boolean;- autopilot: AutopilotPhase | null;- /** Near enough the pad for the landing assist. */- canLand: boolean;-}--const PREFS_KEY = "dodaios.verse.courier.prefs";--interface CourierPrefs { view: CourierView; assist: FlightAssist; invertPitch: boolean; volume: number }--const DEFAULT_PREFS: CourierPrefs = { view: "chase", assist: "arcade", invertPitch: false, volume: 0.6 };--function loadPrefs(): CourierPrefs {- try {- const raw = typeof window !== "undefined" ? window.localStorage.getItem(PREFS_KEY) : null;- if (!raw) return DEFAULT_PREFS;- const saved = JSON.parse(raw) as Partial<CourierPrefs>;- return {- view: saved.view === "cockpit" ? "cockpit" : "chase",- assist: saved.assist === "simulation" ? "simulation" : "arcade",- invertPitch: saved.invertPitch === true,- volume: typeof saved.volume === "number" ? Math.min(1, Math.max(0, saved.volume)) : DEFAULT_PREFS.volume,- };- } catch (error) {- console.warn("courier preferences unreadable, using the defaults", error);- return DEFAULT_PREFS;- }-}--function savePrefs(prefs: CourierPrefs) {- try {- window.localStorage.setItem(PREFS_KEY, JSON.stringify(prefs));- } catch (error) {- // Blocked storage keeps the choice for this visit only.- console.warn("courier preferences not saved", error);- }-}--interface CourierState extends CourierPrefs {- flying: boolean;- /** The ship stands loaded on its pad; boarding waits for it. */- ready: boolean;- bindings: FlightBindings;- helpOpen: boolean;- settingsOpen: boolean;- /** The mouse is captured for steering. */- mouseLocked: boolean;- /** The view refused to capture the mouse, so the visible cursor steers instead: its offset from the middle turns the aim. */- cursorAim: boolean;- telemetry: CourierTelemetry;- /** Bumped when the pilot asks for the landing assist, or to step out, from the HUD (the keys act in the scene). */- landRequest: number;- exitRequest: number;- board: () => void;- disembark: () => void;- setPrefs: (patch: Partial<CourierPrefs>) => void;- setBindings: (bindings: FlightBindings) => void;- set: (patch: Partial<Pick<CourierState, "helpOpen" | "settingsOpen" | "telemetry" | "mouseLocked" | "cursorAim">>) => void;- requestLanding: () => void;- requestExit: () => void;- setReady: (ready: boolean) => void;-}--const IDLE: CourierTelemetry = { speed: 0, throttle: 0, charge: 1, altitude: 0, overPad: true, landed: true, autopilot: null, canLand: false };--export const useCourier = create<CourierState>((set, get) => ({- ...loadPrefs(),- flying: false,- ready: false,- bindings: loadBindings(),- helpOpen: false,- settingsOpen: false,- mouseLocked: false,- cursorAim: false,- telemetry: IDLE,- landRequest: 0,- exitRequest: 0,- board: () => {- if (!get().ready) return;- courierSession.flying = true;- set({ flying: true, telemetry: IDLE });- },- disembark: () => { courierSession.flying = false; set({ flying: false, settingsOpen: false, helpOpen: false, telemetry: IDLE }); },- setPrefs: (patch) => {- set(patch);- const { view, assist, invertPitch, volume } = get();- savePrefs({ view, assist, invertPitch, volume });- },- setBindings: (bindings) => { saveBindings(bindings); set({ bindings }); },- set: (patch) => set(patch),- requestLanding: () => set((s) => ({ landRequest: s.landRequest + 1 })),- requestExit: () => set((s) => ({ exitRequest: s.exitRequest + 1 })),- setReady: (ready) => set({ ready }),-}));--/** Read every frame by the camera rig and the character: no subscription, no render. */-export const courierSession = { flying: false };diff --git a/dodaios/ui/web/frontend/src/components/society/office/courierWorld.ts b/dodaios/ui/web/frontend/src/components/society/office/courierWorld.tsdeleted file mode 100644index 2a63fd8720..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/courierWorld.ts+++ /dev/null@@ -1,165 +0,0 @@-/**- * What the courier can hit while it flies: every tower of the city, the- * Dodaios tower itself and the floor on top of it, the sky pad and its- * bridge, the street level, the singularity's core, and a soft border round- * the city. Pure and tested.- *- * The ship is a row of spheres along its keel (courierFlight.ts); a collider- * pushes each sphere out along the nearest surface normal. Towers are looked- * up in a coarse spatial hash, so a step costs a handful of box tests.- */-import { GROUND_Y, SINGULARITY, type CityPlan } from "./cityPlan";-import type { Rect } from "./officeLayout";-import type { SkyPad } from "./skyPad";-import { SKY_PAD } from "./skyPad";--export interface Box3D { minX: number; maxX: number; minY: number; maxY: number; minZ: number; maxZ: number }--export interface CourierWorld {- boxes: Box3D[];- /** Cell size of the spatial hash and the boxes in each cell (indices into `boxes`), keyed by `cellKey`. */- cell: number;- hash: Map<number, number[]>;- /** Per box, the query that last looked at it: a box in several cells is tested once per query, with no set. */- stamp: Int32Array;- query: number;- /** Spheres that cannot be entered (the singularity's core). */- spheres: { x: number; y: number; z: number; r: number }[];- ground: number;- /** The city's middle and the radius and height the ship is turned back at. */- centre: { x: number; z: number };- border: number;- ceiling: number;-}--export interface Contact { nx: number; ny: number; nz: number; depth: number }--/** The floor and its window walls stand this high over the slab; the ship cannot fly through the office. */-const OFFICE_HEIGHT = 4.2;-const HASH_CELL = 40;--/** One number per hash cell (the city spans far less than ±50 000 cells). */-function cellKey(i: number, j: number): number {- return (i + 50_000) * 100_000 + (j + 50_000);-}--function addBox(world: CourierWorld, box: Box3D) {- const index = world.boxes.push(box) - 1;- for (let i = Math.floor(box.minX / world.cell); i <= Math.floor(box.maxX / world.cell); i += 1) {- for (let j = Math.floor(box.minZ / world.cell); j <= Math.floor(box.maxZ / world.cell); j += 1) {- const key = cellKey(i, j);- const list = world.hash.get(key);- if (list) list.push(index); else world.hash.set(key, [index]);- }- }-}--export function buildCourierWorld(plan: CityPlan, bounds: Rect, skyPad?: SkyPad): CourierWorld {- const world: CourierWorld = {- boxes: [], cell: HASH_CELL, hash: new Map(), stamp: new Int32Array(0), query: 0, spheres: [], ground: GROUND_Y,- centre: plan.centre, border: 760, ceiling: 420,- };- for (const t of plan.towers) {- // Prisms and spires are boxed by their full footprint whatever their turn; a tower is never thinner than that.- const half = Math.max(t.w, t.d) / 2;- addBox(world, { minX: t.x - half, maxX: t.x + half, minY: GROUND_Y, maxY: GROUND_Y + t.h, minZ: t.z - half, maxZ: t.z + half });- }- // The Dodaios tower and the floor on it, office and window walls included.- addBox(world, { ...bounds, minY: GROUND_Y, maxY: OFFICE_HEIGHT });- if (skyPad) {- const { pad, bridge } = skyPad;- addBox(world, { minX: bounds.maxX, maxX: bridge.maxX, minY: -SKY_PAD.thickness, maxY: 0, minZ: skyPad.gap.minZ, maxZ: skyPad.gap.maxZ });- // The pad's deck as the box inside its disc (the ship lands on its middle; the rim is open air).- const inner = pad.r * Math.SQRT1_2;- addBox(world, { minX: pad.x - inner, maxX: pad.x + inner, minY: -SKY_PAD.thickness, maxY: 0, minZ: pad.z - inner, maxZ: pad.z + inner });- }- world.spheres.push({ ...plan.singularity, r: SINGULARITY.core * 1.15 });- world.stamp = new Int32Array(world.boxes.length);- return world;-}--/** The one contact `sphereContact` hands out; callers read it before the next query. */-const CONTACT: Contact = { nx: 0, ny: 0, nz: 0, depth: 0 };--/**- * The deepest contact of a sphere with the world, or null when it is free. Runs a few dozen times a frame in- * flight, so it allocates nothing: the result is a shared object, valid until the next call.- */-export function sphereContact(world: CourierWorld, x: number, y: number, z: number, r: number): Contact | null {- let found = false;- const consider = (nx: number, ny: number, nz: number, depth: number) => {- if (depth > 0 && (!found || depth > CONTACT.depth)) { CONTACT.nx = nx; CONTACT.ny = ny; CONTACT.nz = nz; CONTACT.depth = depth; found = true; }- };- // Street level.- consider(0, 1, 0, world.ground + r - y);- const query = ++world.query;- for (let i = Math.floor((x - r) / world.cell); i <= Math.floor((x + r) / world.cell); i += 1) {- for (let j = Math.floor((z - r) / world.cell); j <= Math.floor((z + r) / world.cell); j += 1) {- const list = world.hash.get(cellKey(i, j));- if (!list) continue;- for (const index of list) {- if (world.stamp[index] === query) continue;- world.stamp[index] = query;- const b = world.boxes[index];- const px = Math.max(b.minX, Math.min(x, b.maxX)), py = Math.max(b.minY, Math.min(y, b.maxY)), pz = Math.max(b.minZ, Math.min(z, b.maxZ));- const dx = x - px, dy = y - py, dz = z - pz;- const d = Math.hypot(dx, dy, dz);- if (d > 1e-6) {- if (d < r) consider(dx / d, dy / d, dz / d, r - d);- continue;- }- // The centre is inside the box: out through the nearest face.- let nx = -1, ny = 0, nz = 0, gap = x - b.minX;- if (b.maxX - x < gap) { nx = 1; ny = 0; nz = 0; gap = b.maxX - x; }- if (y - b.minY < gap) { nx = 0; ny = -1; nz = 0; gap = y - b.minY; }- if (b.maxY - y < gap) { nx = 0; ny = 1; nz = 0; gap = b.maxY - y; }- if (z - b.minZ < gap) { nx = 0; ny = 0; nz = -1; gap = z - b.minZ; }- if (b.maxZ - z < gap) { nx = 0; ny = 0; nz = 1; gap = b.maxZ - z; }- consider(nx, ny, nz, gap + r);- }- }- }- for (const s of world.spheres) {- const dx = x - s.x, dy = y - s.y, dz = z - s.z, d = Math.hypot(dx, dy, dz) || 1e-6;- consider(dx / d, dy / d, dz / d, s.r + r - d);- }- return found ? CONTACT : null;-}--/** How far along a ray (origin, unit direction) the first box lies, up to `max`; `max` when nothing is hit. */-export function rayDistance(world: CourierWorld, o: { x: number; y: number; z: number }, d: { x: number; y: number; z: number }, max: number): number {- let best = max;- if (d.y < -1e-6) best = Math.min(best, (world.ground - o.y) / d.y);- const query = ++world.query;- const steps = Math.ceil(max / world.cell) + 1;- for (let s = 0; s <= steps; s += 1) {- const t = Math.min(max, s * world.cell);- const cx = Math.floor((o.x + d.x * t) / world.cell), cz = Math.floor((o.z + d.z * t) / world.cell);- for (let i = cx - 1; i <= cx + 1; i += 1) {- for (let j = cz - 1; j <= cz + 1; j += 1) {- for (const index of world.hash.get(cellKey(i, j)) ?? []) {- if (world.stamp[index] === query) continue;- world.stamp[index] = query;- const hit = rayBox(world.boxes[index], o, d);- if (hit !== null && hit < best) best = hit;- }- }- }- }- return Math.max(0, best);-}--function rayBox(b: Box3D, o: { x: number; y: number; z: number }, d: { x: number; y: number; z: number }): number | null {- let t0 = 0, t1 = Infinity;- for (const [origin, dir, lo, hi] of [[o.x, d.x, b.minX, b.maxX], [o.y, d.y, b.minY, b.maxY], [o.z, d.z, b.minZ, b.maxZ]] as const) {- if (Math.abs(dir) < 1e-9) {- if (origin < lo || origin > hi) return null;- } else {- let a = (lo - origin) / dir, c = (hi - origin) / dir;- if (a > c) [a, c] = [c, a];- t0 = Math.max(t0, a); t1 = Math.min(t1, c);- if (t0 > t1) return null;- }- }- return t0;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/deskBusyLights.test.ts b/dodaios/ui/web/frontend/src/components/society/office/deskBusyLights.test.tsdeleted file mode 100644index 51613aa4e5..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/deskBusyLights.test.ts+++ /dev/null@@ -1,21 +0,0 @@-import { describe, expect, it } from "vitest";-import { Color } from "three";--import { busyColour } from "./DeskBusyLights";-import { CODING_SCENE } from "./officePalette";--describe("desk busy lights", () => {- it("shows the pane's state: green at work, grey idle, red failed", () => {- const out = new Color();- expect(busyColour("working", 0, out).getHexString()).toBe(new Color(CODING_SCENE.busy.working).getHexString());- expect(busyColour("idle", 3, out).getHexString()).toBe(new Color(CODING_SCENE.busy.idle).getHexString());- const failed = busyColour("error", 0, out);- expect(failed.r).toBeGreaterThan(failed.g * 2);- });-- it("blinks while the pane waits for the person, lit at the still frame", () => {- const on = busyColour("waiting", 0.1, new Color());- const off = busyColour("waiting", 0.7, new Color());- expect(on.r).toBeGreaterThan(off.r * 3);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/deskKit.test.ts b/dodaios/ui/web/frontend/src/components/society/office/deskKit.test.tsdeleted file mode 100644index 8ed7e3afd3..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/deskKit.test.ts+++ /dev/null@@ -1,169 +0,0 @@-import { describe, expect, it } from "vitest";-import { dressDesk, dressOfficeDesk, kitPlacements, LEAD_CHAIR_COLOUR, leadMark, leadMarkPlacements, oakPlanterPlacements, officeKitPlacements, planterPlacements } from "./deskKit";-import { allDesks, benchPlanters, buildOfficeLayout, chairRect, deskRect, seatOf, type Rect } from "./officeLayout";-import { DEPARTMENT_ZONES } from "./officePalette";--const overlaps = (a: Rect, b: Rect) => a.minX < b.maxX && b.minX < a.maxX && a.minZ < b.maxZ && b.minZ < a.maxZ;--/** A hex colour in CIE L*a*b* (D65). */-function lab(hex: string): [number, number, number] {- const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255)- .map((v) => (v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4));- const f = (t: number) => (t > 0.008856 ? Math.cbrt(t) : 7.787 * t + 16 / 116);- const x = f((r * 0.4124 + g * 0.3576 + b * 0.1805) / 0.95047);- const y = f(r * 0.2126 + g * 0.7152 + b * 0.0722);- const z = f((r * 0.0193 + g * 0.1192 + b * 0.9505) / 1.08883);- return [116 * y - 16, 500 * (x - y), 200 * (y - z)];-}--/** How far apart two colours look (CIE76); about 2 is just noticeable, 30 is unmistakable. */-function deltaE(a: string, b: string): number {- const [l1, a1, b1] = lab(a), [l2, a2, b2] = lab(b);- return Math.hypot(l1 - l2, a1 - a2, b1 - b2);-}--const roster = (n: number) => Array.from({ length: n }, (_, i) => ({- agentId: `a${i}`, name: `A${i}`, tier: "specialist" as const, providerLabel: `ws${i % 3}`, state: "working" as const, createdMs: i,-}));--describe("desk dressing", () => {- it("dresses a desk the same way every time, from its id alone", () => {- for (const id of ["dept-0:0:north:0", "dept-2:1:south:3", "x"]) {- expect(dressDesk(id, true)).toEqual(dressDesk(id, true));- expect(kitPlacements(dressDesk(id, false))).toEqual(kitPlacements(dressDesk(id, false)));- }- });-- it("varies from desk to desk", () => {- const kits = Array.from({ length: 32 }, (_, i) => dressDesk(`dept-0:${i >> 3}:north:${i & 7}`, true));- expect(new Set(kits.map((k) => k.mat)).size).toBeGreaterThan(2);- expect(new Set(kits.map((k) => k.side)).size).toBeGreaterThan(1);- expect(new Set(kits.map((k) => k.corner)).size).toBeGreaterThan(2);- });-- it("keeps a desk's mat, plant and lamp when an agent sits down; only personal things are added", () => {- for (let i = 0; i < 40; i += 1) {- const id = `dept-1:0:south:${i}`;- const empty = dressDesk(id, false), taken = dressDesk(id, true);- expect(empty.mat).toBe(taken.mat);- expect(empty.notebook).toBeNull();- expect(empty.headphones).toBeNull();- expect(empty.notes).toBe(0);- expect(empty.side === "laptop").toBe(false);- if (empty.corner === "succulent") expect(taken.corner).toBe("succulent");- if (empty.side === "lamp") expect(taken.side).toBe("lamp");- }- });-- it("never reaches into the monitor, so the live terminal screen stays clear", () => {- for (let i = 0; i < 60; i += 1) {- for (const part of kitPlacements(dressDesk(`d:${i}`, true))) {- const [x, y, z] = part.p;- // The screen: |x| ≤ 0.36, 0.965–1.395 m high, at z ≈ -0.21; nothing in front of it above the desk.- if (Math.abs(x) < 0.4 && z > -0.3 && z < 0.2) expect(y, part.part).toBeLessThan(0.96);- }- }- });-- it("seeds each planter by its key", () => {- const rect = { minX: 0, maxX: 0.36, minZ: 0, maxZ: 1.56 };- expect(planterPlacements(rect, "k")).toEqual(planterPlacements(rect, "k"));- expect(planterPlacements(rect, "k")).not.toEqual(planterPlacements(rect, "other"));- });-- it.each(["coding", "agents"] as const)("stands the %s floor's bench planters clear of every desk and chair", (variant) => {- const layout = buildOfficeLayout(roster(20), { variant });- const desks = allDesks(layout);- const planters = layout.departments.flatMap(benchPlanters);- expect(planters.length).toBe(layout.departments.reduce((n, d) => n + new Set(d.desks.map((k) => k.id.split(":").at(-3))).size * 2, 0));- for (const { rect } of planters) {- for (const desk of desks) {- expect(overlaps(rect, deskRect(desk))).toBe(false);- expect(overlaps(rect, chairRect(seatOf(desk)))).toBe(false);- }- expect(layout.obstacles).toContainEqual(rect);- }- });-});--describe("agents floor office kit", () => {- it("dresses a desk the same way every time, from its id alone", () => {- for (const id of ["dept-0:0:north:0", "dept-3:1:south:2", "y"]) {- expect(officeKitPlacements(dressOfficeDesk(id, true))).toEqual(officeKitPlacements(dressOfficeDesk(id, true)));- }- });-- it("varies from desk to desk", () => {- const kits = Array.from({ length: 32 }, (_, i) => dressOfficeDesk(`dept-1:${i >> 3}:south:${i & 7}`, true));- expect(new Set(kits.map((k) => k.corner)).size).toBeGreaterThan(2);- expect(new Set(kits.map((k) => k.side)).size).toBeGreaterThan(2);- expect(new Set(kits.map((k) => k.front)).size).toBeGreaterThan(1);- });-- it("keeps an empty desk's tray, plant and lamp when an agent sits down", () => {- for (let i = 0; i < 40; i += 1) {- const id = `dept-2:0:north:${i}`;- const empty = dressOfficeDesk(id, false), taken = dressOfficeDesk(id, true);- expect(empty.front).toBeNull();- expect(empty.photo || empty.phone || empty.cup || empty.pinned).toBe(false);- if (empty.corner !== null) expect(taken.corner).toBe(empty.corner);- if (empty.side !== null) expect(taken.side).toBe(empty.side);- if (empty.penCup) expect(taken.penCup).toBe(true);- expect(taken.phone && taken.side === "dock").toBe(false);- }- });-- it("marks a team lead's place with a red chair and the team's colour, from parts the kit already draws and one plain box", () => {- const mark = leadMark("#8aa391");- const all = leadMarkPlacements("#8aa391");- expect(all).toHaveLength(mark.chair.length + mark.mat.length + mark.stand.length);- expect([...new Set(all.map((p) => p.part))].sort()).toEqual(["brassTrim", "felt", "oakSlat", "paper"]);- // The chair is one deep red in every studio, so it never blends into chairs that already wear the team's colour;- // mat and name plate wear the team's colour. The name line is paper, oak and bronze are their own.- for (const part of mark.chair.filter((p) => p.part === "felt")) expect(part.c).toBe(LEAD_CHAIR_COLOUR);- for (const part of [...mark.mat, ...mark.stand].filter((p) => p.part === "felt")) expect(part.c).toBe("#8aa391");- // It keeps a clear distance (CIE76) from every studio's seat fabric, wall panel and rug and from the dark mesh back.- for (const zone of DEPARTMENT_ZONES) {- for (const colour of [zone.seat, zone.panel, zone.rug]) expect(deltaE(LEAD_CHAIR_COLOUR, colour)).toBeGreaterThan(30);- }- expect(deltaE(LEAD_CHAIR_COLOUR, "#1c1f24")).toBeGreaterThan(30);- expect(leadMark("#c2a24c").mat[0].c).toBe("#c2a24c");- // A shell of three panels with a cap each and a seat pad; one mat; a base, a plate, a name line and a top edge.- expect(mark.chair.map((p) => p.part).sort()).toEqual(["brassTrim", "brassTrim", "brassTrim", "felt", "felt", "felt", "felt"]);- expect(mark.mat.map((p) => p.part)).toEqual(["felt"]);- expect(mark.stand.map((p) => p.part).sort()).toEqual(["brassTrim", "felt", "oakSlat", "paper"]);- // The stand keeps clear of the takeaway cup (0.64, 0.07) and of the mouse (0.33, 0.22).- for (const part of mark.stand) {- expect(Math.hypot(part.p[0] - 0.64, part.p[2] - 0.07), part.part).toBeGreaterThan(0.15);- expect(part.p[0] - 0.33, part.part).toBeGreaterThan(0.2);- }- });-- it("never reaches into the monitor, and keeps clear of the desk's mug", () => {- for (let i = 0; i < 80; i += 1) {- for (const part of officeKitPlacements(dressOfficeDesk(`o:${i}`, true))) {- const [x, y, z] = part.p;- if (Math.abs(x) < 0.4 && z > -0.3 && z < 0.2) expect(y, part.part).toBeLessThan(0.96);- // The screen itself: nothing above the desk inside its width, in front of the felt panel.- if (Math.abs(x) < 0.37 && z > -0.39) expect(y, part.part).toBeLessThan(0.96);- // DeskInstances' mug at (-0.52, 0.02).- expect(Math.hypot(x + 0.52, z - 0.02), part.part).toBeGreaterThan(0.07);- // Everything stays on the desk top.- expect(Math.abs(x), part.part).toBeLessThan(0.75);- expect(Math.abs(z), part.part).toBeLessThan(0.4);- }- }- });-- it("seeds each oak planter by its key and keeps its plants over the box", () => {- const rect = { minX: 0, maxX: 0.36, minZ: 0, maxZ: 1.56 };- expect(oakPlanterPlacements(rect, "k")).toEqual(oakPlanterPlacements(rect, "k"));- expect(oakPlanterPlacements(rect, "k")).not.toEqual(oakPlanterPlacements(rect, "other"));- for (const part of oakPlanterPlacements(rect, "k")) {- expect(part.p[0]).toBeGreaterThan(rect.minX - 0.15);- expect(part.p[0]).toBeLessThan(rect.maxX + 0.15);- expect(part.p[2]).toBeGreaterThan(rect.minZ - 0.15);- expect(part.p[2]).toBeLessThan(rect.maxZ + 0.15);- }- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/deskKit.ts b/dodaios/ui/web/frontend/src/components/society/office/deskKit.tsdeleted file mode 100644index 9a4fc78ea0..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/deskKit.ts+++ /dev/null@@ -1,666 +0,0 @@-/**- * What sits on (and under) every workstation, and the planter boxes at the- * ends of each bench. The coding floor carries a developer's kit (laptops,- * headphones, a walnut planter); the agents floor, where agents do office- * work, an office kit (letter trays, documents, a tablet, a phone dock, pen- * cups, a framed photo, takeaway coffee, a pale-oak planter). Pure: it says- * which parts go where; `DeskDressing.tsx` draws them, one instanced mesh- * per part.- *- * A desk's kit is seeded by its id, so the same desk always carries the same- * things and nothing jumps when the roster refetches. A desk nobody sits at- * is a clean hot desk (mat, maybe a plant or a lamp); an occupied one is- * lived in (a laptop on a stand, a notebook, headphones on a hook, sticky- * notes on the felt screen).- *- * Desk-local space matches `DeskInstances`: origin under the desk centre, the- * seated agent at +z looking north (-z) at its monitor, the top at 0.77 m.- * Nothing here reaches the monitor (|x| ≤ 0.36, above 0.96 m), so the live- * terminal screens stay readable and clickable.- */-import { hashString } from "./toyFigureModel";-import type { Rect } from "./officeLayout";--export type Vec3 = [number, number, number];--/** Every part type drawn; each is one instanced mesh across the whole floor. */-export type DressingPart =- | "mat" | "standPlate" | "standLeg" | "laptopBase" | "laptopLid" | "laptopScreen"- | "lampBase" | "lampArm" | "lampShade" | "lampBulb"- | "pot" | "soil" | "succulent" | "book" | "bottle" | "bottleCap"- | "notebook" | "notebookBand" | "pen" | "hook" | "headband" | "earCup" | "note"- | "tray" | "snake" | "puck"- | "planterBody" | "planterPlinth" | "planterRail" | "planterSoil" | "foliage" | "blade"- // The agents floor's office kit and its oak planters.- | "letterTray" | "trayPost" | "paper" | "page" | "folder"- | "tabletBody" | "tabletScreen" | "tabletStand" | "phoneBody" | "phoneScreen" | "dock"- | "penCup" | "pencil" | "frame" | "photo" | "cup" | "cupLid" | "cupSleeve"- | "oakPlanter" | "oakSlat" | "brassTrim"- // A plain box in a team's colour: what marks a team lead's place.- | "felt";--/**- * One part in place. `r` is an Euler rotation applied in YXZ order (a yaw,- * then a tilt), `s` the scale (the size, for the unit box and cylinder), `c`- * the instance colour of a tinted part.- */-export interface Placement { part: DressingPart; p: Vec3; r?: Vec3; s?: Vec3; c?: string }--export const DRESSING_COLOURS = {- mat: ["#2e3136", "#454a52", "#7f9a86", "#c98f6f", "#d9d0c1", "#3d4b63"],- lamp: ["#1f2226", "#f1efe9", "#7f9a86", "#c96f4a"],- pot: ["#c56f4f", "#eeeae3", "#34373d", "#9fb4a0"],- leaf: ["#5f8f5a", "#78a86a", "#8fb89a", "#4d7a52"],- book: ["#c8553d", "#e9b44c", "#4f7cac", "#5e9c76", "#8d6cab", "#e7e2d8", "#2f3a4f"],- bottle: ["#c9ced6", "#8fae96", "#e27d60", "#34507a", "#f3f1ec"],- notebook: ["#1f2226", "#b08a5f", "#34507a", "#8a3b34", "#5e7d63"],- headphones: ["#1f2226", "#eeeae3", "#7f9a86", "#c9b79c"],- note: ["#f7d65a", "#f29fb5", "#9fe0c3", "#9cc8f2"],- foliage: ["#4f8f52", "#2f6b3f", "#77ad64", "#3e7d4a", "#5f9a58"],- blade: ["#2f6b3f", "#3f7d45", "#5a8f4c"],-} as const;--/** The things one desk carries; every field is decided by the desk id alone (and whether someone sits there). */-export interface DeskKit {- /** Desk mat colour index. */- mat: number;- /** Back-left corner. */- corner: "succulent" | "books" | "bottle" | null;- /** Back-right, beside the monitor. */- side: "laptop" | "lamp" | null;- /** Colour index per part, and small turns so no two desks are laid out alike. */- cornerColour: number;- sideColour: number;- notebook: number | null;- headphones: number | null;- /** Sticky notes on the felt screen, 0–3. */- notes: number;- /** Seeded jitter in [-1, 1) for yaw and placement. */- jitter: [number, number, number];-}--/** A small deterministic generator (mulberry32) seeded from a string. */-export function seeded(key: string): () => number {- let state = hashString(key);- return () => {- state = (state + 0x6d2b79f5) >>> 0;- let t = state;- t = Math.imul(t ^ (t >>> 15), t | 1);- t ^= t + Math.imul(t ^ (t >>> 7), t | 61);- return ((t ^ (t >>> 14)) >>> 0) / 0x1_0000_0000;- };-}--const pick = (n: number, r: number) => Math.min(n - 1, Math.floor(r * n));--/**- * The kit of one desk. Every random draw is taken in the same order whether- * or not the desk is occupied, so a desk that gains an agent keeps its mat,- * plant and lamp and only gains the personal things.- */-export function dressDesk(deskId: string, occupied: boolean): DeskKit {- const rand = seeded(`desk-dressing:${deskId}`);- const mat = pick(DRESSING_COLOURS.mat.length, rand());- const cornerRoll = rand(), sideRoll = rand();- const cornerColour = Math.floor(rand() * 64), sideColour = Math.floor(rand() * 64);- const notebookRoll = rand(), notebookColour = pick(DRESSING_COLOURS.notebook.length, rand());- const headRoll = rand(), headColour = pick(DRESSING_COLOURS.headphones.length, rand());- const notes = pick(4, rand());- const jitter: [number, number, number] = [rand() * 2 - 1, rand() * 2 - 1, rand() * 2 - 1];- if (!occupied) {- return {- mat, corner: cornerRoll < 0.45 ? "succulent" : null, side: sideRoll < 0.35 ? "lamp" : null,- cornerColour, sideColour, notebook: null, headphones: null, notes: 0, jitter,- };- }- return {- mat,- corner: cornerRoll < 0.45 ? "succulent" : cornerRoll < 0.7 ? "books" : cornerRoll < 0.92 ? "bottle" : null,- side: sideRoll < 0.35 ? "lamp" : sideRoll < 0.88 ? "laptop" : null,- cornerColour, sideColour,- notebook: notebookRoll < 0.6 ? notebookColour : null,- headphones: headRoll < 0.5 ? headColour : null,- notes, jitter,- };-}--/** Places a sub-assembly's parts: rotate by `yaw` about the assembly origin, then move it to (x, z). */-function assembly(x: number, z: number, yaw: number, parts: Placement[]): Placement[] {- const cos = Math.cos(yaw), sin = Math.sin(yaw);- return parts.map((part) => {- const [px, py, pz] = part.p;- const [rx, ry, rz] = part.r ?? [0, 0, 0];- return { ...part, p: [x + px * cos + pz * sin, py, z - px * sin + pz * cos], r: [rx, ry + yaw, rz] };- });-}--const TOP = 0.77;-const at = <T>(list: readonly T[], i: number): T => list[((i % list.length) + list.length) % list.length];--/** A laptop open on an aluminium stand, its front at +z. */-function laptop(): Placement[] {- const tilt = 0.3, lid = -0.25;- return [- { part: "standPlate", p: [0, 0.815, 0], r: [tilt, 0, 0], s: [0.24, 0.008, 0.22] },- { part: "standLeg", p: [0, 0.807, -0.1], s: [0.2, 0.075, 0.012] },- { part: "laptopBase", p: [0, 0.826, 0.002], r: [tilt, 0, 0] },- { part: "laptopLid", p: [0, 0.954, -0.125], r: [lid, 0, 0] },- { part: "laptopScreen", p: [0, 0.9552, -0.1206], r: [lid, 0, 0] },- ];-}--/** A balanced-arm desk lamp; its head reaches out along +z. */-function lamp(colour: string): Placement[] {- return [- { part: "lampBase", p: [0, TOP + 0.0075, 0], s: [0.06, 0.015, 0.06], c: colour },- { part: "lampArm", p: [0, 0.9225, -0.03], r: [-0.215, 0, 0], s: [0.008, 0.2815, 0.008], c: colour },- { part: "lampArm", p: [0, 1.04, 0.07], r: [1.723, 0, 0], s: [0.008, 0.263, 0.008], c: colour },- { part: "lampShade", p: [0, 0.995, 0.2], s: [0.055, 0.07, 0.055], c: colour },- { part: "lampBulb", p: [0, 0.957, 0.2], s: [0.042, 0.004, 0.042] },- ];-}--/** A succulent in a small ceramic pot: a rosette of fleshy leaves round a heart. */-function succulent(colour: number, turn: number): Placement[] {- const potH = 0.07;- const leaf = (i: number) => at(DRESSING_COLOURS.leaf, colour + i);- const ring = Array.from({ length: 5 }, (_, i): Placement => {- const a = turn + (i * 2 * Math.PI) / 5;- return { part: "succulent", p: [Math.sin(a) * 0.03, TOP + potH + 0.012, Math.cos(a) * 0.03], r: [0, a, 0], s: [0.022, 0.014, 0.034], c: leaf(i % 2) };- });- return [- { part: "pot", p: [0, TOP + potH / 2, 0], s: [0.048, potH, 0.048], c: at(DRESSING_COLOURS.pot, colour) },- { part: "soil", p: [0, TOP + potH + 0.001, 0], s: [0.043, 0.004, 0.043] },- ...ring,- { part: "succulent", p: [0, TOP + potH + 0.024, 0], s: [0.02, 0.022, 0.02], c: leaf(2) },- ];-}--/** Two or three hardbacks stacked flat, each a little askew. */-function books(colour: number, jitter: number): Placement[] {- const count = 2 + (colour % 2);- const sizes: Vec3[] = [[0.2, 0.032, 0.26], [0.18, 0.026, 0.235], [0.16, 0.022, 0.21]];- let y = TOP;- return sizes.slice(0, count).map((s, i) => {- const placed: Placement = { part: "book", p: [0, y + s[1] / 2, 0], r: [0, (i - 1) * 0.18 + jitter * 0.1, 0], s, c: at(DRESSING_COLOURS.book, colour + i * 3) };- y += s[1];- return placed;- });-}--function bottle(colour: number): Placement[] {- return [- { part: "bottle", p: [0, TOP + 0.11, 0], s: [0.034, 0.22, 0.034], c: at(DRESSING_COLOURS.bottle, colour) },- { part: "bottleCap", p: [0, TOP + 0.235, 0], s: [0.027, 0.03, 0.027] },- ];-}--/** A closed notebook with an elastic band, a pen lying on it. */-function notebook(colour: number): Placement[] {- return [- { part: "notebook", p: [0, TOP + 0.007, 0], s: [0.15, 0.014, 0.21], c: at(DRESSING_COLOURS.notebook, colour) },- { part: "notebookBand", p: [0.055, TOP + 0.0075, 0], s: [0.008, 0.0155, 0.212] },- { part: "pen", p: [-0.01, TOP + 0.019, 0.01], r: [Math.PI / 2, 0.35, 0], s: [0.005, 0.14, 0.005] },- ];-}--/** Over-ear headphones hanging from a hook under the desk's front edge; the band parallel to the edge. */-function headphones(colour: string): Placement[] {- const z = 0.43, top = 0.708, radius = 0.08;- return [- { part: "hook", p: [0, 0.726, 0.42], s: [0.026, 0.012, 0.06] },- { part: "hook", p: [0, 0.713, 0.449], s: [0.026, 0.03, 0.008] },- { part: "headband", p: [0, top - radius, z], c: colour },- ...[-1, 1].map((side): Placement => ({- part: "earCup", p: [side * (radius + 0.004), top - radius - 0.035, z], r: [0, 0, Math.PI / 2], s: [0.046, 0.034, 0.046], c: colour,- })),- ];-}--/** Every part of one desk's kit, in desk-local space. */-export function kitPlacements(kit: DeskKit): Placement[] {- const [j0, j1, j2] = kit.jitter;- const out: Placement[] = [- // Felt desk mat under the keyboard and mouse.- { part: "mat", p: [0.06, TOP + 0.002, 0.22], c: DRESSING_COLOURS.mat[kit.mat] },- // Cable tray under the back of the desk and the snake that feeds it from a floor box.- { part: "tray", p: [0, 0.64, -0.3], s: [1.2, 0.05, 0.14] },- { part: "snake", p: [-0.25, 0.3075, -0.34], s: [0.022, 0.615, 0.022] },- { part: "puck", p: [-0.25, 0.012, -0.34], s: [0.13, 0.024, 0.13] },- ];- if (kit.side === "laptop") out.push(...assembly(0.56 + j0 * 0.02, -0.1, -0.45 + j1 * 0.08, laptop()));- if (kit.side === "lamp") out.push(...assembly(0.62, -0.27, -1.0 + j1 * 0.15, lamp(at(DRESSING_COLOURS.lamp, kit.sideColour))));- const cornerX = -0.6 + j2 * 0.03, cornerZ = -0.24;- if (kit.corner === "succulent") out.push(...assembly(cornerX, cornerZ, 0, succulent(kit.cornerColour, j0 * Math.PI)));- if (kit.corner === "books") out.push(...assembly(cornerX + 0.02, cornerZ + 0.02, 0.2 + j0 * 0.2, books(kit.cornerColour, j1)));- if (kit.corner === "bottle") out.push(...assembly(cornerX - 0.02, cornerZ + 0.02, 0, bottle(kit.cornerColour)));- if (kit.notebook !== null) out.push(...assembly(-0.48, 0.26, 0.12 + j2 * 0.22, notebook(kit.notebook)));- if (kit.headphones !== null) out.push(...assembly(-0.52, 0, 0, headphones(DRESSING_COLOURS.headphones[kit.headphones])));- for (let i = 0; i < kit.notes; i += 1) {- // Pinned to the felt screen left of the monitor, a hair in front of its face.- out.push({- part: "note", p: [-0.44 - i * 0.085, 1.02 + ((i * 37 + Math.round(j1 * 10)) % 5) * 0.012, -0.3935],- r: [0, 0, (i % 2 === 0 ? 1 : -1) * 0.08 + j0 * 0.05], c: at(DRESSING_COLOURS.note, kit.cornerColour + i),- });- }- return out;-}--/** Planter box: height, rail width, and how far the soil sits below the rim. */-export const PLANTER_H = 0.46;-const RAIL = 0.035;--/**- * A low walnut planter box on a recessed black plinth, oak-rimmed, full of- * mixed foliage and tall snake-plant blades, filling `rect` (world space, long- * side along z). Seeded by `key`.- */-export function planterPlacements(rect: Rect, key: string): Placement[] {- const rand = seeded(`planter:${key}`);- const cx = (rect.minX + rect.maxX) / 2, cz = (rect.minZ + rect.maxZ) / 2;- const w = rect.maxX - rect.minX, d = rect.maxZ - rect.minZ;- const plinth = 0.05;- const out: Placement[] = [- { part: "planterPlinth", p: [cx, plinth / 2, cz], s: [w - 0.06, plinth, d - 0.06] },- { part: "planterBody", p: [cx, plinth + (PLANTER_H - plinth) / 2, cz], s: [w, PLANTER_H - plinth, d] },- { part: "planterSoil", p: [cx, PLANTER_H - 0.03, cz], s: [w - RAIL * 2, 0.01, d - RAIL * 2] },- { part: "planterRail", p: [rect.minX + RAIL / 2, PLANTER_H + 0.01, cz], s: [RAIL, 0.02, d + 0.01] },- { part: "planterRail", p: [rect.maxX - RAIL / 2, PLANTER_H + 0.01, cz], s: [RAIL, 0.02, d + 0.01] },- { part: "planterRail", p: [cx, PLANTER_H + 0.01, rect.minZ + RAIL / 2], s: [w - RAIL * 2, 0.02, RAIL] },- { part: "planterRail", p: [cx, PLANTER_H + 0.01, rect.maxZ - RAIL / 2], s: [w - RAIL * 2, 0.02, RAIL] },- ];- // Foliage in two staggered rows of mixed sizes, so it reads as plants, not a clipped hedge.- const clusters = Math.max(4, Math.round(d / 0.16));- for (let i = 0; i < clusters; i += 1) {- const z = rect.minZ + RAIL + 0.08 + (i + 0.5) * ((d - RAIL * 2 - 0.16) / clusters);- const size = 0.06 + rand() * rand() * 0.16;- out.push({- part: "foliage", p: [cx + (i % 2 === 0 ? -1 : 1) * w * 0.14 + (rand() - 0.5) * 0.04, PLANTER_H + size * 0.5, z],- r: [0, rand() * Math.PI, 0], s: [size * 1.1, size * (0.7 + rand() * 0.6), size], c: at(DRESSING_COLOURS.foliage, Math.floor(rand() * 16)),- });- }- // Snake-plant blades rising out of the foliage, in a few tufts.- const tufts = 2 + Math.floor(rand() * 2);- for (let t = 0; t < tufts; t += 1) {- const tz = rect.minZ + 0.2 + ((t + 0.5) / tufts) * (d - 0.4);- const blades = 3 + Math.floor(rand() * 3);- for (let i = 0; i < blades; i += 1) {- const h = 0.3 + rand() * 0.28;- out.push({- part: "blade", p: [cx + (rand() - 0.5) * 0.08, PLANTER_H + h / 2 - 0.02, tz + (rand() - 0.5) * 0.1],- r: [(rand() - 0.5) * 0.35, rand() * Math.PI, (rand() - 0.5) * 0.35], s: [0.032, h, 0.012], c: at(DRESSING_COLOURS.blade, Math.floor(rand() * 8)),- });- }- }- return out;-}--// ----------------------------------------------------------------------------// The agents floor: an office kit on every bench desk and pale-oak planters.-// Desk-local space is the same as above, but that floor's `DeskInstances`-// desk already carries a mug at (-0.52, 0.02) and a pedestal under the right-// side, so the kit keeps clear of the mug.-// -----------------------------------------------------------------------------/** Scandinavian oak, sage, linen and brass: the agents floor's own palette. */-export const OFFICE_KIT_COLOURS = {- tray: ["#c7a064", "#d8c7a6", "#8fa58f", "#2c2e33", "#ece6da"],- paper: ["#f6f3ec", "#fbfaf6", "#efe8d9"],- folder: ["#dcc497", "#9db09a", "#c98f6f", "#6f86a6", "#e6dccb"],- lamp: ["#b8914f", "#ebe6da", "#8fa58f", "#2b2d31", "#c98f6f"],- pot: ["#ece6da", "#b8836a", "#8fa58f", "#d8cbb4", "#3a3d42"],- leaf: ["#6f9a64", "#86ad73", "#5b8757", "#9dbb86"],- penCup: ["#b8914f", "#2b2d31", "#ebe6da", "#8fa58f", "#b8836a"],- pencil: ["#e9b44c", "#c8553d", "#4f7cac", "#2b2d31", "#5e9c76", "#ebe6da"],- frame: ["#c9a46a", "#d8c7a6", "#2b2d31", "#efe9de", "#8a6a4a"],- /** Multiplies the one photo texture: warm, cool, faded and true prints. */- photo: ["#ffffff", "#ffe6c8", "#dde8ff", "#efe2f5", "#e8f0dc"],- cup: ["#f3efe7", "#c9a27a", "#e7ddd0", "#2f3136"],- lid: ["#f6f3ec", "#2b2d31"],- foliage: ["#6f9a64", "#557f52", "#8cb07a", "#7a9f6e", "#a3bf8e"],- frond: ["#6c9a5e", "#86ad73", "#5a8a55", "#9cc08a"],-} as const;--/** The things one agents-floor desk carries; decided by the desk id alone (and whether someone sits there). */-export interface OfficeKit {- /** Back-left corner. */- corner: "tray" | "plant" | "books" | null;- /** Back-right, beside the monitor. */- side: "lamp" | "tablet" | "dock" | null;- /** Front-left, beside the keyboard (the mug stays behind it). */- front: "notebook" | "documents" | null;- photo: boolean;- penCup: boolean;- /** A phone lying face up at the front right (never together with the dock, which holds it). */- phone: boolean;- cup: boolean;- /** A printed page pinned to the felt screen, right of the monitor. */- pinned: boolean;- /** Sticky notes on the felt screen, 0–2. */- notes: number;- /** Colour seed shared by the kit's parts. */- colour: number;- /** Seeded jitter in [-1, 1) for yaw and placement. */- jitter: [number, number, number];-}--/**- * The office kit of one desk. As with `dressDesk`, every draw is taken in the- * same order either way and the empty desk's choices are prefixes of the- * occupied desk's thresholds, so an agent sitting down only adds things.- */-export function dressOfficeDesk(deskId: string, occupied: boolean): OfficeKit {- const rand = seeded(`office-desk:${deskId}`);- const cornerRoll = rand(), sideRoll = rand(), frontRoll = rand();- const photoRoll = rand(), penRoll = rand(), phoneRoll = rand(), cupRoll = rand(), pinRoll = rand();- const notes = pick(3, rand());- const colour = Math.floor(rand() * 64);- const jitter: [number, number, number] = [rand() * 2 - 1, rand() * 2 - 1, rand() * 2 - 1];- const corner = cornerRoll < 0.4 ? "tray" : cornerRoll < 0.72 ? "plant" : occupied && cornerRoll < 0.9 ? "books" : null;- const side = sideRoll < 0.32 ? "lamp" : occupied && sideRoll < 0.64 ? "tablet" : occupied && sideRoll < 0.86 ? "dock" : null;- if (!occupied) {- return { corner, side, front: null, photo: false, penCup: penRoll < 0.3, phone: false, cup: false, pinned: false, notes: 0, colour, jitter };- }- return {- corner, side,- front: frontRoll < 0.45 ? "notebook" : frontRoll < 0.85 ? "documents" : null,- photo: photoRoll < 0.55,- penCup: penRoll < 0.65,- phone: side !== "dock" && phoneRoll < 0.5,- cup: cupRoll < 0.45,- pinned: pinRoll < 0.5,- notes, colour, jitter,- };-}--/** A sheet's printed face, laid flat on top of a stack (or a folder) at height `y`. */-const printedFace = (x: number, y: number, z: number, yaw: number, w = 0.19, d = 0.26): Placement =>- ({ part: "page", p: [x, y, z], r: [-Math.PI / 2, yaw, 0], s: [w, d, 1] });--/** A one- or two-tier letter tray, open towards the seat (+z), paper in each tier. */-function letterTray(colour: string, paper: string, tiers: number, jitter: number): Placement[] {- const w = 0.24, d = 0.3, gap = 0.075, wall = 0.008;- const out: Placement[] = [];- for (let t = 0; t < tiers; t += 1) {- const y0 = TOP + t * gap;- const stack = 0.008 + ((t * 5 + Math.round(jitter * 7) + 7) % 4) * 0.006;- const yaw = jitter * 0.05 * (t === 0 ? 1 : -1);- out.push(- { part: "letterTray", p: [0, y0 + 0.004, 0], s: [w, 0.008, d], c: colour },- ...[-1, 1].map((side): Placement => ({ part: "letterTray", p: [side * (w / 2 - wall / 2), y0 + 0.02, 0], s: [wall, 0.032, d], c: colour })),- { part: "letterTray", p: [0, y0 + 0.02, -d / 2 + wall / 2], s: [w, 0.032, wall], c: colour },- { part: "paper", p: [0, y0 + 0.008 + stack / 2, 0.012], r: [0, yaw, 0], s: [0.205, stack, 0.28], c: paper },- printedFace(0, y0 + 0.0085 + stack, 0.012, yaw, 0.2, 0.275),- );- }- if (tiers > 1) {- for (const sx of [-1, 1]) {- for (const sz of [-1, 1]) {- out.push({ part: "trayPost", p: [sx * (w / 2 - 0.012), TOP + 0.008 + gap / 2, sz * (d / 2 - 0.03)], s: [0.006, gap, 0.006] });- }- }- }- return out;-}--/** A manila folder with a few sheets in it and one loose page on top, a little askew. */-function documents(folder: string, paper: string, jitter: number): Placement[] {- return [- { part: "folder", p: [0, TOP + 0.003, 0], s: [0.22, 0.006, 0.29], c: folder },- { part: "paper", p: [0.006, TOP + 0.009, -0.004], r: [0, 0.04, 0], s: [0.2, 0.006, 0.27], c: paper },- { part: "paper", p: [0.03, TOP + 0.0131, 0.012], r: [0, -0.16 + jitter * 0.08, 0], s: [0.2, 0.0022, 0.27], c: paper },- printedFace(0.03, TOP + 0.0145, 0.012, -0.16 + jitter * 0.08),- ];-}--/** A tablet leaning back in a brass stand, its calendar facing +z. */-function tablet(): Placement[] {- const tilt = -0.35, half = 0.085, foot = TOP + 0.014;- const up = Math.cos(tilt) * half, back = Math.sin(tilt) * half;- return [- { part: "tabletStand", p: [0, TOP + 0.004, -0.02], s: [0.13, 0.008, 0.11] },- { part: "tabletStand", p: [0, TOP + 0.014, 0.008], s: [0.13, 0.014, 0.01] },- { part: "tabletStand", p: [0, TOP + 0.045, -0.052], r: [0.5, 0, 0], s: [0.05, 0.08, 0.008] },- { part: "tabletBody", p: [0, foot + up, back], r: [tilt, 0, 0] },- { part: "tabletScreen", p: [0, foot + up - Math.sin(tilt) * 0.0045, back + Math.cos(tilt) * 0.0045], r: [tilt, 0, 0] },- ];-}--/** A phone standing in a charging dock, its screen facing +z. */-function phoneDock(): Placement[] {- const tilt = -0.3, half = 0.075, foot = TOP + 0.012;- const up = Math.cos(tilt) * half, back = Math.sin(tilt) * half;- return [- { part: "dock", p: [0, TOP + 0.006, -0.005], s: [0.085, 0.012, 0.075] },- { part: "dock", p: [0, TOP + 0.04, -0.034], r: [0.3, 0, 0], s: [0.06, 0.07, 0.01] },- { part: "phoneBody", p: [0, foot + up, back], r: [tilt, 0, 0] },- { part: "phoneScreen", p: [0, foot + up - Math.sin(tilt) * 0.0045, back + Math.cos(tilt) * 0.0045], r: [tilt, 0, 0] },- ];-}--/** A phone lying face up. */-function phoneFlat(): Placement[] {- return [- { part: "phoneBody", p: [0, TOP + 0.004, 0], r: [-Math.PI / 2, 0, 0] },- { part: "phoneScreen", p: [0, TOP + 0.0085, 0], r: [-Math.PI / 2, 0, 0] },- ];-}--/** A pen cup with a few pencils leaning out of it. */-function penCup(colour: number): Placement[] {- const leans: Vec3[] = [[0.16, 0, 0.08], [-0.1, 0, -0.14], [0.02, 0, 0.2]];- return [- { part: "penCup", p: [0, TOP + 0.045, 0], s: [0.032, 0.09, 0.032], c: at(OFFICE_KIT_COLOURS.penCup, colour) },- ...leans.map(([rx, , rz], i): Placement => ({- part: "pencil", p: [-rz * 0.03, TOP + 0.1, rx * 0.03], r: [rx, 0, rz], s: [0.0045, 0.15, 0.0045], c: at(OFFICE_KIT_COLOURS.pencil, colour + i * 2),- })),- ];-}--/** A small framed photo leaning back on its strut, facing +z. */-function photoFrame(frame: string, print: string): Placement[] {- const tilt = -0.2, half = 0.07;- const up = Math.cos(tilt) * half, back = Math.sin(tilt) * half;- return [- { part: "frame", p: [0, TOP + up, back], r: [tilt, 0, 0], s: [0.11, 0.14, 0.012], c: frame },- { part: "photo", p: [0, TOP + up - Math.sin(tilt) * 0.0065, back + Math.cos(tilt) * 0.0065], r: [tilt, 0, 0], s: [0.086, 0.114, 1], c: print },- { part: "frame", p: [0, TOP + 0.048, -0.045], r: [0.38, 0, 0], s: [0.02, 0.1, 0.006], c: frame },- ];-}--/** A takeaway coffee cup: tapered body, kraft sleeve, lid. */-function takeawayCup(colour: number): Placement[] {- return [- { part: "cup", p: [0, TOP + 0.055, 0], s: [0.042, 0.11, 0.042], c: at(OFFICE_KIT_COLOURS.cup, colour) },- { part: "cupSleeve", p: [0, TOP + 0.06, 0], s: [0.0445, 0.042, 0.0445] },- { part: "cupLid", p: [0, TOP + 0.115, 0], s: [0.0445, 0.012, 0.0445], c: at(OFFICE_KIT_COLOURS.lid, colour) },- ];-}--/** A leafy plant in a ceramic pot, a few leaves trailing over the rim. */-function leafyPlant(colour: number, turn: number): Placement[] {- const potH = 0.09;- const leaf = (i: number) => at(OFFICE_KIT_COLOURS.leaf, colour + i);- const crown = Array.from({ length: 4 }, (_, i): Placement => {- const a = turn + (i * 2 * Math.PI) / 4;- const size = 0.034 + (i % 2) * 0.01;- return { part: "foliage", p: [Math.sin(a) * 0.03, TOP + potH + 0.035 + (i % 2) * 0.02, Math.cos(a) * 0.03], r: [0, a, 0], s: [size, size * 0.85, size], c: leaf(i) };- });- const trail = Array.from({ length: 3 }, (_, i): Placement => ({- part: "succulent", p: [Math.sin(turn) * 0.056, TOP + potH - 0.012 - i * 0.03, Math.cos(turn) * 0.056 + (i - 1) * 0.008],- r: [0.4, turn + i, 0.3], s: [0.018, 0.008, 0.024], c: leaf(i + 1),- }));- return [- { part: "pot", p: [0, TOP + potH / 2, 0], s: [0.055, potH, 0.055], c: at(OFFICE_KIT_COLOURS.pot, colour) },- { part: "soil", p: [0, TOP + potH + 0.001, 0], s: [0.05, 0.004, 0.05] },- ...crown,- { part: "foliage", p: [0, TOP + potH + 0.07, 0], s: [0.03, 0.032, 0.03], c: leaf(2) },- ...trail,- ];-}--/** Every part of one agents-floor desk's kit, in desk-local space. */-export function officeKitPlacements(kit: OfficeKit): Placement[] {- const [j0, j1, j2] = kit.jitter;- const c = kit.colour;- const paper = at(OFFICE_KIT_COLOURS.paper, c);- const out: Placement[] = [];- const cornerX = -0.6 + j2 * 0.02, cornerZ = -0.225;- if (kit.corner === "tray") out.push(...assembly(cornerX, cornerZ, j0 * 0.06, letterTray(at(OFFICE_KIT_COLOURS.tray, c), paper, 1 + (c % 2), j1)));- if (kit.corner === "plant") out.push(...assembly(cornerX + 0.02, cornerZ - 0.02, 0, leafyPlant(c, j0 * Math.PI)));- if (kit.corner === "books") out.push(...assembly(cornerX + 0.02, cornerZ + 0.02, 0.2 + j0 * 0.2, books(c, j1)));- if (kit.photo) out.push(...assembly(-0.39, -0.29, 0.22 + j1 * 0.12, photoFrame(at(OFFICE_KIT_COLOURS.frame, c + 1), at(OFFICE_KIT_COLOURS.photo, c + 3))));- if (kit.side === "lamp") out.push(...assembly(0.62, -0.27, -1.0 + j1 * 0.15, lamp(at(OFFICE_KIT_COLOURS.lamp, c))));- if (kit.side === "tablet") out.push(...assembly(0.56 + j0 * 0.015, -0.15, -0.6 + j1 * 0.08, tablet()));- if (kit.side === "dock") out.push(...assembly(0.6, -0.24, -0.45 + j1 * 0.1, phoneDock()));- if (kit.penCup) out.push(...assembly(kit.side === "dock" ? 0.47 : 0.43, -0.31, j2, penCup(c + 1)));- if (kit.front === "notebook") out.push(...assembly(-0.47, 0.25, 0.12 + j2 * 0.2, notebook(c)));- if (kit.front === "documents") out.push(...assembly(-0.47, 0.25, 0.1 + j2 * 0.12, documents(at(OFFICE_KIT_COLOURS.folder, c + 2), paper, j0)));- if (kit.phone) out.push(...assembly(0.53, 0.27, -0.25 + j0 * 0.3, phoneFlat()));- if (kit.cup) out.push(...assembly(0.64, 0.07 + j1 * 0.02, 0, takeawayCup(c + 2)));- if (kit.pinned) {- // A printed page pinned to the felt screen right of the monitor, a hair in front of its face.- out.push({ part: "page", p: [0.5 + j0 * 0.03, 1.02, -0.3935], r: [0, 0, j1 * 0.06], s: [0.1, 0.135, 1] });- }- for (let i = 0; i < kit.notes; i += 1) {- out.push({- part: "note", p: [-0.46 - i * 0.085, 1.03 + ((i * 37 + Math.round(j1 * 10)) % 5) * 0.012, -0.3935],- r: [0, 0, (i % 2 === 0 ? 1 : -1) * 0.08 + j0 * 0.05], c: at(DRESSING_COLOURS.note, c + i),- });- }- return out;-}--/**- * Where `DeskInstances` stands the task chair behind a desk, and the chair's backrest as `OfficeChairs` builds it:- * a reclined cone segment half a metre high whose middle is 0.86 m up, 0.55 m from an axis in front of the seat.- */-const LEAD_CHAIR = { z: 0.62, axisZ: -0.288, radius: 0.55, midY: 0.86, recline: 0.197, seatTop: 0.522 } as const;-/** The name stand's plate leans back this far from upright, so it faces a camera looking down at forty degrees. */-const STAND_TILT = -0.7;-/** The stand is turned towards the view from the south-east. */-const STAND_YAW = 0.66;-/**- * The lead's chair wears one deep red in every studio. In the team's own colour it vanished among the studio's- * chairs, which already wear that colour; this red keeps its distance from every studio's seat fabric, wall panel- * and rug and from the chairs' dark mesh (deskKit.test.ts measures it).- */-export const LEAD_CHAIR_COLOUR = "#a3202f";--/**- * What marks a team lead's place, in desk-local space:- * - `chair`: a deep red shell on the back of the task chair (three panels round its curve) with a bronze cap along- * its top edge, and a pad on the seat in the same red. The chair is what the camera sees first, and it stays when the lead is away.- * - `mat`: a chair mat in the team's colour on the floor under the chair, which is what reads from the overview.- * - `stand`: a tent card on the desk's front right corner: an oak base and a plate in the team's colour leaning- * back towards the camera, with a pale name line and a bronze top edge.- * Made of parts the desk kit already draws, plus one plain coloured box; everything stays inside the desk and the- * strip its chair rolls on.- */-export function leadMark(colour: string): { chair: Placement[]; mat: Placement[]; stand: Placement[] } {- const { recline } = LEAD_CHAIR;- const r = LEAD_CHAIR.radius + 0.03;- const chair: Placement[] = [];- for (const [theta, h] of [[0, 0.44], [-0.29, 0.4], [0.29, 0.4]] as const) {- const x = Math.sin(theta) * r, z = LEAD_CHAIR.z + LEAD_CHAIR.axisZ + Math.cos(theta) * r;- const y = LEAD_CHAIR.midY - (theta === 0 ? 0 : 0.012);- chair.push({ part: "felt", p: [x, y, z], r: [recline, theta, 0], s: [0.172, h, 0.02], c: LEAD_CHAIR_COLOUR });- // The cap sits on the panel's top edge, in the panel's own lean.- const up = h / 2 + 0.011;- chair.push({- part: "brassTrim", r: [recline, theta, 0], s: [0.176, 0.022, 0.034],- p: [x + up * Math.sin(recline) * Math.sin(theta), y + up * Math.cos(recline), z + up * Math.sin(recline) * Math.cos(theta)],- });- }- // The pad rests in the seat's dish and stands a few millimetres proud of its rim.- chair.push({ part: "felt", p: [0, LEAD_CHAIR.seatTop + 0.007, LEAD_CHAIR.z - 0.02], s: [0.36, 0.018, 0.34], c: LEAD_CHAIR_COLOUR });-- // Above the studio's rug (its field lies at 7 mm), below the light pools (12 mm).- const mat: Placement[] = [{ part: "felt", p: [0, 0.009, 0.725], s: [1.15, 0.003, 0.95], c: colour }];-- const half = 0.065, foot = TOP + 0.014;- const up = Math.cos(STAND_TILT) * half, back = Math.sin(STAND_TILT) * half;- // The plate's outward normal, for what lies on its face.- const ny = -Math.sin(STAND_TILT), nz = Math.cos(STAND_TILT);- const stand = assembly(0.66, 0.325, STAND_YAW, [- { part: "oakSlat", p: [0, TOP + 0.007, -0.04], s: [0.17, 0.014, 0.1] },- { part: "felt", p: [0, foot + up, back], r: [STAND_TILT, 0, 0], s: [0.16, half * 2, 0.006], c: colour },- { part: "paper", p: [0, foot + up + ny * 0.0045, back + nz * 0.0045], r: [STAND_TILT, 0, 0], s: [0.11, 0.024, 0.003], c: "#f6f3ec" },- { part: "brassTrim", p: [0, foot + up * 2, back * 2], r: [STAND_TILT, 0, 0], s: [0.164, 0.008, 0.012] },- ]);- return { chair, mat, stand };-}--/** Every part of a team lead's mark; see `leadMark`. */-export function leadMarkPlacements(colour: string): Placement[] {- const { chair, mat, stand } = leadMark(colour);- return [...chair, ...mat, ...stand];-}--/** The agents floor's planter: taller than the coding floor's box, so it also screens the bench end. */-export const OAK_PLANTER_H = 0.52;--/**- * A pale-oak planter on short feet, clad in vertical slats and rimmed in- * brass, full of sage-green foliage and arching fronds, filling `rect` (world- * space, long side along z). Seeded by `key`.- */-export function oakPlanterPlacements(rect: Rect, key: string): Placement[] {- const rand = seeded(`oak-planter:${key}`);- const cx = (rect.minX + rect.maxX) / 2, cz = (rect.minZ + rect.maxZ) / 2;- const w = rect.maxX - rect.minX, d = rect.maxZ - rect.minZ;- const H = OAK_PLANTER_H, feet = 0.06, slat = 0.03, pitch = 0.055, trim = 0.022;- const inW = w - 0.02, inD = d - 0.02;- const out: Placement[] = [- { part: "oakPlanter", p: [cx, feet + (H - feet) / 2, cz], s: [inW - 0.012, H - feet, inD - 0.012] },- { part: "planterSoil", p: [cx, H - 0.035, cz], s: [inW - trim * 2, 0.01, inD - trim * 2] },- ];- for (const sx of [-1, 1]) {- for (const sz of [-1, 1]) out.push({ part: "oakSlat", p: [cx + sx * (inW / 2 - 0.04), feet / 2, cz + sz * (inD / 2 - 0.05)], s: [0.04, feet, 0.04] });- }- // Slats: along both long sides, then the two short ends.- const along = Math.floor(inD / pitch);- for (let i = 0; i < along; i += 1) {- const z = cz - ((along - 1) * pitch) / 2 + i * pitch;- for (const sx of [-1, 1]) out.push({ part: "oakSlat", p: [cx + sx * (inW / 2 - 0.006), feet + (H - feet) / 2, z], s: [0.012, H - feet, slat] });- }- const across = Math.max(2, Math.floor(inW / pitch));- for (let i = 0; i < across; i += 1) {- const x = cx - ((across - 1) * pitch) / 2 + i * pitch;- for (const sz of [-1, 1]) out.push({ part: "oakSlat", p: [x, feet + (H - feet) / 2, cz + sz * (inD / 2 - 0.006)], s: [slat, H - feet, 0.012] });- }- // Brass rim, flush over the slats.- out.push(- { part: "brassTrim", p: [cx - inW / 2 + trim / 2, H + 0.006, cz], s: [trim, 0.012, inD + 0.004] },- { part: "brassTrim", p: [cx + inW / 2 - trim / 2, H + 0.006, cz], s: [trim, 0.012, inD + 0.004] },- { part: "brassTrim", p: [cx, H + 0.006, cz - inD / 2 + trim / 2], s: [inW - trim * 2, 0.012, trim] },- { part: "brassTrim", p: [cx, H + 0.006, cz + inD / 2 - trim / 2], s: [inW - trim * 2, 0.012, trim] },- );- // Soft mounds of foliage in two staggered rows.- const clusters = Math.max(4, Math.round(inD / 0.15));- for (let i = 0; i < clusters; i += 1) {- const z = rect.minZ + 0.1 + (i + 0.5) * ((d - 0.2) / clusters);- const size = 0.07 + rand() * rand() * 0.12;- out.push({- part: "foliage", p: [cx + (i % 2 === 0 ? -1 : 1) * w * 0.12 + (rand() - 0.5) * 0.04, H + size * 0.45, z],- r: [0, rand() * Math.PI, 0], s: [size * 1.15, size * (0.65 + rand() * 0.4), size], c: at(OFFICE_KIT_COLOURS.foliage, Math.floor(rand() * 16)),- });- }- // Arching fronds fanning out of a few crowns, like ferns and soft grasses.- const crowns = 3 + Math.floor(rand() * 2);- for (let t = 0; t < crowns; t += 1) {- const tz = rect.minZ + 0.18 + ((t + 0.5) / crowns) * (d - 0.36);- const fronds = 5 + Math.floor(rand() * 3);- for (let i = 0; i < fronds; i += 1) {- const h = 0.2 + rand() * 0.2;- const yaw = (i / fronds) * Math.PI * 2 + rand() * 0.5, lean = 0.45 + rand() * 0.45;- // Tilt outwards about the frond's own base, then lift it so the base sits in the soil.- const reach = Math.sin(lean) * h * 0.5;- out.push({- part: "blade", p: [cx + Math.sin(yaw) * reach, H - 0.02 + Math.cos(lean) * h * 0.5, tz + Math.cos(yaw) * reach],- r: [lean, yaw, 0], s: [0.03, h, 0.01], c: at(OFFICE_KIT_COLOURS.frond, Math.floor(rand() * 8)),- });- }- }- return out;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/dogLife.test.ts b/dodaios/ui/web/frontend/src/components/society/office/dogLife.test.tsdeleted file mode 100644index cd0dea0992..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/dogLife.test.ts+++ /dev/null@@ -1,132 +0,0 @@-import { beforeEach, describe, expect, it } from "vitest";-import { createRng } from "./officeBehavior";-import {- DOG_FOLLOW_MS, DOG_FOLLOW_NEAR, followPoint, insideRoom, nextDogStep, pickOtherBasket, useOfficeDog, type DogActivity,-} from "./dogLife";-import { buildOfficeLayout, type OfficeAgentInput } from "./officeLayout";-import { buildNavGrid, findPath } from "./officeNav";--const lead: OfficeAgentInput = { agentId: "l", name: "L", tier: "lead", providerLabel: "", state: "idle", createdMs: 1 };--describe("the office dog's day", () => {- it("always finds its way back to a basket, and sometimes moves to another one", () => {- const rng = createRng("dog-test");- let moves = 0;- for (let run = 0; run < 60; run += 1) {- let activity: DogActivity = "sleep";- let roamsLeft = 0;- for (let step = 0; step < 40 && !(step > 0 && activity === "sleep"); step += 1) {- const next = nextDogStep(activity, roamsLeft, rng, 3);- activity = next.activity;- roamsLeft = next.roamsLeft;- if (activity === "move") moves += 1;- }- expect(activity).toBe("sleep");- }- expect(moves).toBeGreaterThan(0);- });-- it("never moves house when there is only one basket", () => {- const rng = createRng("one-basket");- for (let i = 0; i < 100; i += 1) expect(nextDogStep("sleep", 0, rng, 1).activity).not.toBe("move");- });-- it("picks a different basket to move to", () => {- const rng = createRng("pick");- for (let i = 0; i < 50; i += 1) {- const next = pickOtherBasket(1, 3, rng);- expect(next).not.toBe(1);- expect(next).toBeGreaterThanOrEqual(0);- expect(next).toBeLessThan(3);- }- expect(pickOtherBasket(0, 1, rng)).toBe(0);- });-- it("follows the person after being petted, then goes home", () => {- const rng = createRng("dog-pet");- expect(nextDogStep("petted", 0, rng)).toMatchObject({ activity: "follow", durationMs: DOG_FOLLOW_MS });- expect(nextDogStep("follow", 0, rng).activity).toBe("home");- });-- it("carries the treat home after the trick and falls asleep after chewing", () => {- const rng = createRng("dog-treat");- expect(nextDogStep("trick", 0, rng).activity).toBe("home");- expect(nextDogStep("chew", 0, rng).activity).toBe("sleep");- });-- it("follows from a little behind the person, never on top of them", () => {- const p = followPoint({ x: 0, z: 0, heading: 0 }, { x: 0, z: -3 });- expect(p.z).toBeLessThan(0);- expect(Math.hypot(p.x, p.z)).toBeGreaterThan(DOG_FOLLOW_NEAR * 0.8);- });-- it("knows when the person has left its room", () => {- const room = { minX: 0, maxX: 5, minZ: 0, maxZ: 4 };- expect(insideRoom(room, { x: 2, z: 2 })).toBe(true);- expect(insideRoom(room, { x: 2, z: 4.2 })).toBe(true);- expect(insideRoom(room, { x: 2, z: 6 })).toBe(false);- });-});--describe("petting and the treat", () => {- beforeEach(() => useOfficeDog.setState({ near: false, nearJar: false, hasBone: false, pending: null }));-- it("pets once per press", () => {- const before = useOfficeDog.getState().petSeq;- useOfficeDog.setState({ near: true, pending: "pet" });- expect(useOfficeDog.getState().interact()).toBe(true);- expect(useOfficeDog.getState().petSeq).toBe(before + 1);- expect(useOfficeDog.getState().pending).toBeNull();- });-- it("takes a bone at the jar and gives it to the dog instead of petting", () => {- const { petSeq, treatSeq } = useOfficeDog.getState();- useOfficeDog.setState({ nearJar: true });- expect(useOfficeDog.getState().interact()).toBe(true);- expect(useOfficeDog.getState().hasBone).toBe(true);- useOfficeDog.setState({ nearJar: false, near: true });- useOfficeDog.getState().interact();- expect(useOfficeDog.getState()).toMatchObject({ hasBone: false, treatSeq: treatSeq + 1, petSeq });- });-- it("does nothing when neither the dog nor the jar is in reach", () => {- expect(useOfficeDog.getState().interact()).toBe(false);- });-});--describe("the dog on the floor plan", () => {- const layout = buildOfficeLayout([lead]);- const grid = buildNavGrid(layout);- const beds = layout.furniture.filter((f) => f.kind === "dogBed");-- it("has a basket in the lead office, the team room and the break room", () => {- expect(beds.map((b) => b.room).sort()).toEqual(["break", "lead", "team"]);- const room = layout.rooms.find((r) => r.kind === "lead")!;- const leadBed = beds.find((b) => b.room === "lead")!;- expect(leadBed.x).toBeGreaterThan(room.maxX - 1);- expect(leadBed.z).toBeLessThan(room.minZ + 1.5);- });-- it("can walk from every basket to every other one", () => {- for (const a of beds) {- for (const b of beds) {- if (a === b) continue;- const path = findPath(grid, a, b);- expect(path, `${a.id} -> ${b.id}`).not.toBeNull();- const last = path![path!.length - 1];- expect(Math.hypot(last.x - b.x, last.z - b.z)).toBeLessThan(0.01);- }- }- });-- it("keeps the treat jar in the break room, reachable from the elevator", () => {- const jar = layout.furniture.find((f) => f.kind === "treatJar")!;- expect(jar.room).toBe("break");- expect(findPath(grid, layout.spawn, { x: jar.x, z: jar.z + 0.6 })).not.toBeNull();- });-- it("has no dog on the coding floor", () => {- const coding = buildOfficeLayout([lead], { variant: "coding" });- expect(coding.furniture.some((f) => f.kind === "dogBed" || f.kind === "treatJar")).toBe(false);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/dogLife.ts b/dodaios/ui/web/frontend/src/components/society/office/dogLife.tsdeleted file mode 100644index 04c962f392..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/dogLife.ts+++ /dev/null@@ -1,155 +0,0 @@-/**- * The office dog: a black-and-tan rottweiler with a day of its own. It has a- * basket in several rooms (lead office, team room, break room) and lives in- * the room of its current basket: it sleeps, gets up, roams that room,- * sniffs, sits and lies down, and goes back to bed. Now and then it walks —- * never jumps — over to another basket and settles in there.- *- * The person can pet it (E nearby, or a click): it sits, wags, shows hearts- * and follows the person around inside its room for a while. Easter egg: a- * treat jar in the break room hands out a bone; give it to the dog and it- * begs, catches it, spins twice in the air and carries the bone to its basket- * to chew on it.- *- * Pure schedule + a small store; OfficeDog.tsx moves and animates the figure.- * Like the agents' idle life, all of it is client-side and costs nothing.- */-import { create } from "zustand";-import type { Point, Rect } from "./officeLayout";--export type DogActivity =- | "sleep" | "stretch" | "roam" | "sniff" | "sit" | "lie" | "home" | "move"- | "petted" | "follow" | "trick" | "chew";--/** The body pose an activity shows; walking poses come from movement, not from here. */-export type DogPose = "sleep" | "stand" | "sit" | "lie" | "sniff" | "beg";--export const DOG_POSE: Record<DogActivity, DogPose> = {- sleep: "sleep", stretch: "stand", roam: "stand", sniff: "sniff", sit: "sit", lie: "lie", home: "stand", move: "stand",- petted: "sit", follow: "stand", trick: "beg", chew: "lie",-};--/** Petting reach, metres from the person to the dog. */-export const DOG_PET_RANGE = 1.4;-/** Reach to take a bone from the treat jar. */-export const TREAT_JAR_RANGE = 1.3;-/** How long the dog enjoys being petted, and then follows the person. */-export const DOG_PETTED_MS = 3200;-export const DOG_FOLLOW_MS = 30000;-/** The treat trick (beg, catch, two spins) and the chewing afterwards. */-export const DOG_TRICK_MS = 3600;-export const DOG_CHEW_MS = 18000;-/** Following: trot after the person beyond this distance, stop inside the lower one. */-export const DOG_FOLLOW_FAR = 1.7;-export const DOG_FOLLOW_NEAR = 1.15;-export const DOG_WALK_SPEED = 1.5;-export const DOG_RUN_SPEED = 3.6;-/** Chance that waking up sends the dog over to another basket instead of roaming. */-export const DOG_MOVE_CHANCE = 0.35;--export interface DogStep { activity: DogActivity; durationMs: number }--function between(rng: () => number, min: number, max: number): number {- return min + rng() * (max - min);-}--/**- * What the dog does after `current` ends. `roamsLeft` counts the outings- * before it heads home; `baskets` is how many baskets it could move between.- * The schedule always ends up back in a basket.- */-export function nextDogStep(current: DogActivity, roamsLeft: number, rng: () => number, baskets = 1): DogStep & { roamsLeft: number } {- switch (current) {- case "sleep":- if (baskets > 1 && rng() < DOG_MOVE_CHANCE) return { activity: "move", durationMs: Infinity, roamsLeft: 0 };- return { activity: "stretch", durationMs: 1500, roamsLeft: 2 + Math.floor(rng() * 3) };- case "stretch":- return { activity: "roam", durationMs: Infinity, roamsLeft };- case "roam": {- // Arrived somewhere: have a look around.- const r = rng();- if (r < 0.45) return { activity: "sniff", durationMs: between(rng, 2000, 4000), roamsLeft };- if (r < 0.8) return { activity: "sit", durationMs: between(rng, 4000, 8000), roamsLeft };- return { activity: "lie", durationMs: between(rng, 6000, 12000), roamsLeft };- }- case "sniff":- case "sit":- case "lie":- return roamsLeft > 1- ? { activity: "roam", durationMs: Infinity, roamsLeft: roamsLeft - 1 }- : { activity: "home", durationMs: Infinity, roamsLeft: 0 };- case "petted":- return { activity: "follow", durationMs: DOG_FOLLOW_MS, roamsLeft: 0 };- case "follow":- return { activity: "home", durationMs: Infinity, roamsLeft: 0 };- case "trick":- // Off to the basket with the bone, then chew there.- return { activity: "home", durationMs: Infinity, roamsLeft: 0 };- case "chew":- return { activity: "sleep", durationMs: between(rng, 20000, 40000), roamsLeft: 0 };- case "home":- case "move":- return { activity: "sleep", durationMs: between(rng, 20000, 50000), roamsLeft: 0 };- }-}--/** Another basket to move to (never the current one), or the current one when it is the only one. */-export function pickOtherBasket(current: number, count: number, rng: () => number): number {- if (count <= 1) return current;- const offset = 1 + Math.floor(rng() * (count - 1));- return (current + offset) % count;-}--/** Is `p` inside `room`, allowing a margin (a doorway step still counts as inside)? */-export function insideRoom(room: Rect, p: Point, margin = 0.3): boolean {- return p.x >= room.minX - margin && p.x <= room.maxX + margin && p.z >= room.minZ - margin && p.z <= room.maxZ + margin;-}--/** Where to stand while following: a little behind the person, on the side the dog comes from. */-export function followPoint(person: { x: number; z: number; heading: number }, dog: Point): Point {- const bx = person.x - Math.sin(person.heading) * DOG_FOLLOW_NEAR;- const bz = person.z - Math.cos(person.heading) * DOG_FOLLOW_NEAR;- // Blend towards the dog's own side so it does not cut across the person's feet.- const dx = dog.x - person.x, dz = dog.z - person.z;- const d = Math.hypot(dx, dz) || 1;- return { x: (bx + person.x + (dx / d) * DOG_FOLLOW_NEAR) / 2, z: (bz + person.z + (dz / d) * DOG_FOLLOW_NEAR) / 2 };-}--interface OfficeDogState {- /** The person stands within petting reach. */- near: boolean;- /** The person stands at the treat jar. */- nearJar: boolean;- /** The person carries a bone from the treat jar. */- hasBone: boolean;- /** Bumped on every pet / every bone given; the dog reacts to each new value once. */- petSeq: number;- treatSeq: number;- /** Clicked from afar: pet the dog / take a bone once the walk there brings the person within reach. */- pending: "pet" | "jar" | null;- set: (patch: Partial<Pick<OfficeDogState, "near" | "nearJar" | "pending">>) => void;- pet: () => void;- takeBone: () => void;- giveTreat: () => void;- /** E next to the dog: give the bone when carrying one, else pet it. Next to the jar: take a bone. */- interact: () => boolean;-}--export const useOfficeDog = create<OfficeDogState>((set, get) => ({- near: false,- nearJar: false,- hasBone: false,- petSeq: 0,- treatSeq: 0,- pending: null,- set: (patch) => set((s) => (Object.entries(patch).every(([k, v]) => s[k as keyof typeof patch] === v) ? s : patch)),- pet: () => set((s) => ({ petSeq: s.petSeq + 1, pending: null })),- takeBone: () => set({ hasBone: true, pending: null }),- giveTreat: () => set((s) => (s.hasBone ? { hasBone: false, treatSeq: s.treatSeq + 1, pending: null } : s)),- interact: () => {- const s = get();- if (s.near) { if (s.hasBone) s.giveTreat(); else s.pet(); return true; }- if (s.nearJar && !s.hasBone) { s.takeBone(); return true; }- return false;- },-}));diff --git a/dodaios/ui/web/frontend/src/components/society/office/dogProps.tsx b/dodaios/ui/web/frontend/src/components/society/office/dogProps.tsxdeleted file mode 100644index 4de639755d..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/dogProps.tsx+++ /dev/null@@ -1,49 +0,0 @@-/**- * Small props of the office dog: the treat bone (carried by the person and by- * the dog) and the treat jar in the break room that hands the bones out.- * Built like every office prop: centred on the origin, front towards +z,- * inside its FURNITURE_SIZE footprint.- */-import { CylinderGeometry, MeshStandardMaterial, SphereGeometry } from "three";-import { Box } from "./OfficeFurniture";--const M = {- bone: new MeshStandardMaterial({ color: "#f3ead7", roughness: 0.7 }),- wood: new MeshStandardMaterial({ color: "#6d4a33", roughness: 0.7 }),- woodDark: new MeshStandardMaterial({ color: "#4a3122", roughness: 0.7 }),- brass: new MeshStandardMaterial({ color: "#d8ae52", roughness: 0.3, metalness: 0.75 }),- glass: new MeshStandardMaterial({ color: "#dff1ff", roughness: 0.05, transparent: true, opacity: 0.28, depthWrite: false }),- label: new MeshStandardMaterial({ color: "#8f2f3a", roughness: 0.8 }),-};-const G = { cyl: new CylinderGeometry(1, 1, 1, 14), sphere: new SphereGeometry(1, 14, 10) };--/** A cartoon bone along local x, about 0.2 m long at scale 1. */-export function TreatBone({ scale = 1 }: { scale?: number }) {- return (- <group scale={scale}>- <mesh geometry={G.cyl} material={M.bone} rotation={[0, 0, Math.PI / 2]} scale={[0.022, 0.16, 0.022]} castShadow />- {[-0.08, 0.08].flatMap((x) => [-0.022, 0.022].map((z) => (- <mesh key={`${x}${z}`} geometry={G.sphere} material={M.bone} position={[x, 0, z]} scale={0.032} castShadow />- )))}- </group>- );-}--/** A wooden stand with a glass jar of bones on top and a bone plaque on the front. */-export function TreatJar() {- return (- <group>- <Box size={[0.46, 0.78, 0.46]} position={[0, 0.39, 0]} material={M.wood} />- <Box size={[0.5, 0.04, 0.5]} position={[0, 0.8, 0]} material={M.woodDark} />- <Box size={[0.3, 0.12, 0.012]} position={[0, 0.55, 0.236]} material={M.label} cast={false} />- <group position={[0, 0.55, 0.246]} rotation={[Math.PI / 2, 0, 0]}><TreatBone scale={0.7} /></group>- {/* The jar: bones inside, a brass lid with a knob. */}- {[[-0.05, 0.88, 0.02, 0.5], [0.05, 0.9, -0.03, -0.6], [0, 0.97, 0.03, 1.2]].map(([x, y, z, r], i) => (- <group key={i} position={[x, y, z]} rotation={[0, r, 0.4]}><TreatBone scale={0.6} /></group>- ))}- <mesh geometry={G.cyl} material={M.glass} position={[0, 0.96, 0]} scale={[0.16, 0.28, 0.16]} />- <mesh geometry={G.cyl} material={M.brass} position={[0, 1.115, 0]} scale={[0.165, 0.03, 0.165]} castShadow />- <mesh geometry={G.sphere} material={M.brass} position={[0, 1.15, 0]} scale={0.03} />- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/elevatorCall.test.ts b/dodaios/ui/web/frontend/src/components/society/office/elevatorCall.test.tsdeleted file mode 100644index 5933151e63..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/elevatorCall.test.ts+++ /dev/null@@ -1,42 +0,0 @@-import { describe, expect, it } from "vitest";-import { atElevator, CALL_BUTTON_LOCAL, callButtonPose } from "./elevatorCall";-import { buildOfficeLayout } from "./officeLayout";--describe("callButtonPose", () => {- it("keeps the local offset for an unrotated prop", () => {- const pose = callButtonPose({ x: 2, z: 3, rotationY: 0 });- expect(pose.x).toBeCloseTo(2 + CALL_BUTTON_LOCAL.x);- expect(pose.z).toBeCloseTo(3 + CALL_BUTTON_LOCAL.z);- expect(pose.y).toBe(CALL_BUTTON_LOCAL.y);- });-- it("turns the offset with the prop (doors facing +x)", () => {- const pose = callButtonPose({ x: 0, z: 0, rotationY: Math.PI / 2 });- // Local +z (out of the doors) becomes world +x; local +x (right of the doors) becomes world -z.- expect(pose.x).toBeCloseTo(CALL_BUTTON_LOCAL.z);- expect(pose.z).toBeCloseTo(-CALL_BUTTON_LOCAL.x);- expect(pose.rotationY).toBeCloseTo(Math.PI / 2);- });-- it("sits within reach of the elevator checkpoint on both floors", () => {- for (const variant of ["agents", "coding"] as const) {- const layout = buildOfficeLayout([], { variant });- const shaft = layout.furniture.find((f) => f.kind === "elevator");- const cp = layout.checkpoints.find((c) => c.id === "elevator");- expect(shaft && cp).toBeTruthy();- const pose = callButtonPose(shaft!);- expect(Math.hypot(pose.x - cp!.x, pose.z - cp!.z)).toBeLessThan(2.2);- }- });-});--describe("atElevator", () => {- const cp = { x: 0, z: 0, radius: 1.2 };- it("is true inside the checkpoint radius only", () => {- expect(atElevator({ x: 0.5, z: 0.5 }, cp)).toBe(true);- expect(atElevator({ x: 3, z: 0 }, cp)).toBe(false);- });- it("is false on a plan without an elevator", () => {- expect(atElevator({ x: 0, z: 0 }, undefined)).toBe(false);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/elevatorCall.ts b/dodaios/ui/web/frontend/src/components/society/office/elevatorCall.tsdeleted file mode 100644index 887ef73bdc..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/elevatorCall.ts+++ /dev/null@@ -1,29 +0,0 @@-/**- * The elevator's call button: where it sits on the shaft and who may press it.- *- * Riding takes a deliberate press of the button beside the doors, the way a- * real elevator works: the person walks up to the elevator and clicks the- * button (or presses E there). A click from across the floor only walks the- * character over; it never rides from afar.- */-import type { Checkpoint, Furniture, Point } from "./officeLayout";--/** The button plate in the elevator prop's own frame: right of the doors, at hand height, just proud of the shaft face. */-export const CALL_BUTTON_LOCAL = { x: 0.9, y: 1.15, z: 0.13 } as const;--/** How long the lit button shows before the doors start to close. */-export const CALL_PRESS_MS = 650;--export interface CallButtonPose { x: number; y: number; z: number; rotationY: number }--/** World pose of the call button for the elevator prop `item` (rotation about +y, as the prop is drawn). */-export function callButtonPose(item: Pick<Furniture, "x" | "z" | "rotationY">): CallButtonPose {- const { x: lx, y, z: lz } = CALL_BUTTON_LOCAL;- const cos = Math.cos(item.rotationY), sin = Math.sin(item.rotationY);- return { x: item.x + lx * cos + lz * sin, y, z: item.z - lx * sin + lz * cos, rotationY: item.rotationY };-}--/** Is the character standing at the elevator, close enough to press its button? */-export function atElevator(body: Point, checkpoint: Pick<Checkpoint, "x" | "z" | "radius"> | undefined): boolean {- return !!checkpoint && Math.hypot(body.x - checkpoint.x, body.z - checkpoint.z) <= checkpoint.radius;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/gigiErrands.feed.test.tsx b/dodaios/ui/web/frontend/src/components/society/office/gigiErrands.feed.test.tsxdeleted file mode 100644index babda477fe..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/gigiErrands.feed.test.tsx+++ /dev/null@@ -1,25 +0,0 @@-import { afterEach, describe, expect, it } from "vitest";-import { act, renderHook } from "@testing-library/react";-import { useEventStore } from "@/store/events";-import type { SocietyAgent } from "../data";-import { useErrandFeed, useGigiErrands } from "./gigiErrands";--const agents = new Map([- ["jarvis", { agentId: "jarvis", name: "Jarvis", tier: "lead" } as SocietyAgent],- ["nora", { agentId: "nora", name: "Nora", tier: "specialist" } as SocietyAgent],-]);--afterEach(() => useGigiErrands.getState().reset());--describe("useErrandFeed", () => {- it("queues Gigi's errand when the lead hands an agent a task", () => {- renderHook(() => useErrandFeed(agents, true));- act(() => {- useEventStore.getState().pushEvent({- id: "e-1", name: "SocietyMessageSent", layer: "society", ts: Date.now(),- payload: { event_id: "a1", msg_type: "ASSIGN", from_agent: "jarvis", to_agent: "nora", room_id: "", text: "Do it" },- });- });- expect(useGigiErrands.getState().current).toMatchObject({ id: "a1", to: "nora", toName: "Nora", phase: "fly" });- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/gigiErrands.test.ts b/dodaios/ui/web/frontend/src/components/society/office/gigiErrands.test.tsdeleted file mode 100644index b24bce5dff..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/gigiErrands.test.ts+++ /dev/null@@ -1,71 +0,0 @@-import { afterEach, describe, expect, it } from "vitest";-import { deliverySpot, errandFrom, ERRAND_STALE_MS, MAX_QUEUED, useGigiErrands, type Errand } from "./gigiErrands";--const agents = new Map([- ["jarvis", { tier: "lead" as const, name: "Jarvis" }],- ["nora", { tier: "specialist" as const, name: "Nora" }],- ["max", { tier: "specialist" as const, name: "Max" }],-]);--const assign = (patch: Record<string, unknown> = {}) => ({- event_id: "e1", msg_type: "ASSIGN", from_agent: "jarvis", to_agent: "nora", room_id: "", text: "Check the inbox", ...patch,-});--function errand(id: string, queuedMs = Date.now()): Errand {- return { id, to: "nora", toName: "Nora", text: id, msgType: "ASSIGN", queuedMs };-}--afterEach(() => useGigiErrands.getState().reset());--describe("errandFrom", () => {- it("turns the lead's task for an agent into an errand", () => {- expect(errandFrom(assign(), agents, 5)).toEqual({ id: "e1", to: "nora", toName: "Nora", text: "Check the inbox", msgType: "ASSIGN", queuedMs: 5 });- });-- it("ignores lines that are not the lead handing something to a present agent", () => {- expect(errandFrom(assign({ from_agent: "max" }), agents, 0)).toBeNull();- expect(errandFrom(assign({ to_agent: "ghost" }), agents, 0)).toBeNull();- expect(errandFrom(assign({ to_agent: "jarvis" }), agents, 0)).toBeNull();- expect(errandFrom(assign({ room_id: "r1" }), agents, 0)).toBeNull();- expect(errandFrom(assign({ msg_type: "ANSWER" }), agents, 0)).toBeNull();- expect(errandFrom(null, agents, 0)).toBeNull();- });-});--describe("deliverySpot", () => {- it("hovers next to the recipient on the side Gigi comes from", () => {- expect(deliverySpot({ x: 0, z: 0 }, { x: 10, z: 0 }, 1)).toEqual({ x: 1, z: 0 });- expect(deliverySpot({ x: 2, z: 2 }, { x: 2, z: 2 }, 1)).toEqual({ x: 3, z: 2 });- });-});--describe("errand queue", () => {- it("flies, delivers, then takes the next errand", () => {- const store = useGigiErrands.getState();- store.enqueue(errand("a"));- store.enqueue(errand("b"));- store.enqueue(errand("a"));- expect(useGigiErrands.getState().current).toMatchObject({ id: "a", phase: "fly" });- expect(useGigiErrands.getState().queue.map((e) => e.id)).toEqual(["b"]);- store.arrive("a");- expect(useGigiErrands.getState().current).toMatchObject({ id: "a", phase: "deliver" });- store.finish("a");- expect(useGigiErrands.getState().current).toMatchObject({ id: "b", phase: "fly" });- store.finish("b");- expect(useGigiErrands.getState().current).toBeNull();- });-- it("caps the queue and skips errands whose moment has passed", () => {- const store = useGigiErrands.getState();- store.enqueue(errand("now"));- store.enqueue(errand("old", Date.now() - ERRAND_STALE_MS - 1));- for (let i = 0; i < MAX_QUEUED + 2; i += 1) store.enqueue(errand(`q${i}`));- expect(useGigiErrands.getState().queue).toHaveLength(MAX_QUEUED);- store.reset();- store.enqueue(errand("first"));- store.enqueue(errand("stale", Date.now() - ERRAND_STALE_MS - 1));- store.enqueue(errand("fresh"));- store.finish("first");- expect(useGigiErrands.getState().current?.id).toBe("fresh");- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/gigiErrands.ts b/dodaios/ui/web/frontend/src/components/society/office/gigiErrands.tsdeleted file mode 100644index 0f9cf7f0f1..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/gigiErrands.ts+++ /dev/null@@ -1,130 +0,0 @@-/**- * Gigi's errands: when Jarvis (the lead) hands an agent a task, Gigi flies- * over to that agent's figure, delivers the message in a speech bubble, and- * flies back to its day.- *- * The source is the board's own `SocietyMessageSent` event (msg_type ASSIGN,- * or a direct line from the lead), which the WebSocket already forwards; the- * errand is pure choreography on top of it — it never starts, stops or- * changes work. Errands queue, so three tasks in a row are three flights.- */-import { useEffect, useRef } from "react";-import { create } from "zustand";-import { useEventStore } from "@/store/events";-import type { SocietyAgent } from "../data";-import type { Point } from "./officeLayout";--/** The board types that count as the lead sending an agent something. */-const ERRAND_TYPES = new Set(["ASSIGN", "SAY", "QUERY"]);-const MESSAGE_EVENT = "SocietyMessageSent";-/** How long Gigi hovers next to the agent while the message is read out. */-export const DELIVER_MS = 5_000;-/** An errand still waiting after this long is stale: the moment has passed. */-export const ERRAND_STALE_MS = 60_000;-/** Queue cap — a burst of delegations never becomes minutes of flying. */-export const MAX_QUEUED = 4;-/** Gigi stops this far from the agent, on the side it comes from (metres). */-export const DELIVERY_GAP_M = 0.95;-/** Gigi's errand speed: brisk, faster than anyone walks (m/s). */-export const ERRAND_SPEED = 3.4;-/** Newest events inspected per update, same bound as the island's feed. */-const MAX_CATCHUP = 64;--export interface Errand {- id: string;- /** Recipient agent id. */- to: string;- /** Recipient's name, for Gigi's "on my way to …" bubble. */- toName: string;- /** Bubble-sized preview of what was handed over. */- text: string;- msgType: string;- queuedMs: number;-}--export type ErrandPhase = "fly" | "deliver";--interface ErrandState {- queue: Errand[];- current: (Errand & { phase: ErrandPhase; untilMs: number }) | null;- enqueue: (errand: Errand) => void;- arrive: (id: string) => void;- /** Ends the current errand and starts the next one that is still fresh. */- finish: (id: string) => void;- reset: () => void;-}--function nextFresh(queue: Errand[], now: number): { current: ErrandState["current"]; queue: Errand[] } {- const fresh = queue.filter((e) => now - e.queuedMs < ERRAND_STALE_MS);- const [head, ...rest] = fresh;- return { current: head ? { ...head, phase: "fly", untilMs: 0 } : null, queue: rest };-}--export const useGigiErrands = create<ErrandState>((set) => ({- queue: [],- current: null,- enqueue: (errand) => set((s) => {- if (s.current?.id === errand.id || s.queue.some((e) => e.id === errand.id)) return s;- if (!s.current) return { current: { ...errand, phase: "fly", untilMs: 0 } };- return { queue: [...s.queue, errand].slice(-MAX_QUEUED) };- }),- arrive: (id) => set((s) => (s.current?.id === id && s.current.phase === "fly"- ? { current: { ...s.current, phase: "deliver", untilMs: Date.now() + DELIVER_MS } } : s)),- finish: (id) => set((s) => (s.current?.id === id ? nextFresh(s.queue, Date.now()) : s)),- reset: () => set({ queue: [], current: null }),-}));--/**- * The errand a board event describes, or null: only the lead sending a live- * agent (never itself) a task or a direct line counts.- */-export function errandFrom(payload: unknown, agents: ReadonlyMap<string, Pick<SocietyAgent, "tier" | "name">>, now: number): Errand | null {- if (!payload || typeof payload !== "object") return null;- const p = payload as Record<string, unknown>;- const from = typeof p.from_agent === "string" ? p.from_agent : "";- const to = typeof p.to_agent === "string" ? p.to_agent : "";- const msgType = typeof p.msg_type === "string" ? p.msg_type : "";- if (!ERRAND_TYPES.has(msgType) || !to || to === from || p.room_id) return null;- if (agents.get(from)?.tier !== "lead" || !agents.has(to)) return null;- const id = typeof p.event_id === "string" && p.event_id ? p.event_id : `${from}>${to}:${now}`;- return { id, to, toName: agents.get(to)?.name ?? "", text: typeof p.text === "string" ? p.text : "", msgType, queuedMs: now };-}--/** Where Gigi hovers to deliver: next to the recipient, on the side Gigi comes from. */-export function deliverySpot(recipient: Point, from: Point, gap = DELIVERY_GAP_M): Point {- const dx = from.x - recipient.x, dz = from.z - recipient.z;- const d = Math.hypot(dx, dz);- if (d < 1e-6) return { x: recipient.x + gap, z: recipient.z };- return { x: recipient.x + (dx / d) * gap, z: recipient.z + (dz / d) * gap };-}--/**- * Queue an errand for every board line the lead sends while the office is- * awake. Drains the event log from a cursor (like the island's feed), so a- * burst of delegations is never half-lost; asleep, it forgets everything.- */-export function useErrandFeed(agents: ReadonlyMap<string, SocietyAgent>, enabled: boolean): void {- const roster = useRef(agents);- roster.current = agents;- useEffect(() => {- if (!enabled) { useGigiErrands.getState().reset(); return; }- let cursor: string | null = useEventStore.getState().events[0]?.id ?? null;- return useEventStore.subscribe((state) => {- const log = state.events;- const top = log[0];- if (!top || top.id === cursor) return;- const fresh = [];- for (let i = 0; i < log.length && i < MAX_CATCHUP; i += 1) {- if (log[i].id === cursor) break;- fresh.push(log[i]);- }- cursor = top.id;- const now = Date.now();- for (let i = fresh.length - 1; i >= 0; i -= 1) {- if (fresh[i].name !== MESSAGE_EVENT) continue;- const errand = errandFrom(fresh[i].payload, roster.current, now);- if (errand) useGigiErrands.getState().enqueue(errand);- }- });- }, [enabled]);-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/gigiFlight.test.ts b/dodaios/ui/web/frontend/src/components/society/office/gigiFlight.test.tsdeleted file mode 100644index 9761d9bbd5..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/gigiFlight.test.ts+++ /dev/null@@ -1,264 +0,0 @@-import { describe, expect, it } from "vitest";-import {- createGigiFlight, createGigiPose, followAnchor, GIGI_FOLLOW_BACK_M, GIGI_FOLLOW_HOVER_M, GIGI_FOLLOW_SIDE_M,- GIGI_HOVER_M, GIGI_MAX_LEAN, GIGI_MAX_Y, GIGI_MIN_Y, GIGI_SLEEP_HOVER_M, stepGigiFlight, type GigiFlightMode,-} from "./gigiFlight";--const MODES: GigiFlightMode[] = ["idle", "work", "talk", "wave", "sleep", "follow"];-const DT = 1 / 60;--describe("a pet on the floor (ground mode)", () => {- it("starts grounded and clears a previous flyer's height and bank immediately", () => {- expect(createGigiFlight(2, -3, 0.7, true).base).toBe(0);- expect(createGigiPose(true).y).toBe(0);- const state = createGigiFlight(2, -3);- state.pitch = 0.2;- state.roll = -0.3;- state.vBase = 0.4;- const pose = stepGigiFlight(state, {- targetX: 2, targetZ: -3, moving: false, mode: "idle", speaking: false, t: 0, dt: DT, ground: true,- });- expect(pose.y).toBe(0);- expect(pose.pitch).toBe(0);- expect(pose.roll).toBe(0);- expect(state.vBase).toBe(0);- });-- it("lands on the floor, never leans or banks, and hops only while standing happy", () => {- const state = createGigiFlight(0, 0);- const pose = createGigiPose();- let maxStandingY = 0;- for (let t = 0; t < 20; t += DT) {- const moving = t > 10;- stepGigiFlight(state, {- targetX: moving ? (t - 10) * 1.2 : 0, targetZ: 0, moving, mode: "follow", speaking: !moving, t, dt: DT, ground: true,- }, pose);- expect(pose.y).toBeGreaterThanOrEqual(0);- if (t > 4) {- expect(pose.pitch).toBeCloseTo(0, 6);- expect(pose.roll).toBeCloseTo(0, 6);- }- if (t > 6 && !moving) maxStandingY = Math.max(maxStandingY, pose.y);- if (t > 12) expect(pose.y).toBeLessThan(0.02);- }- expect(maxStandingY).toBeGreaterThan(0.02);- expect(maxStandingY).toBeLessThan(0.1);- });-- it("falls in right behind the person instead of beside the shoulder", () => {- const air = followAnchor(0, 0, 0, 1);- const floor = followAnchor(0, 0, 0, 1, undefined, true);- expect(air.z).toBeCloseTo(-GIGI_FOLLOW_BACK_M);- expect(floor.z).toBeLessThan(air.z);- expect(Math.abs(floor.x)).toBeLessThan(Math.abs(air.x));- expect(Math.abs(air.x)).toBeCloseTo(GIGI_FOLLOW_SIDE_M);- });-});--describe("gigi flight", () => {- it("stays between 0.6 and 1.5 m in every mode, speaking or not, at any frame rate", () => {- for (const mode of MODES) {- for (const speaking of [false, true]) {- for (const dt of [1 / 144, 1 / 30, 0.25]) {- const state = createGigiFlight(0, 0);- const pose = createGigiPose();- for (let t = 0; t < 20; t += dt) {- stepGigiFlight(state, { targetX: Math.sin(t) * 2, targetZ: 0, moving: t % 6 < 3, mode, speaking, t, dt }, pose);- expect(pose.y).toBeGreaterThanOrEqual(GIGI_MIN_Y);- expect(pose.y).toBeLessThanOrEqual(GIGI_MAX_Y);- expect(pose.glow).toBeGreaterThanOrEqual(0);- expect(pose.glow).toBeLessThanOrEqual(1);- expect(Number.isFinite(pose.x + pose.z + pose.yaw + pose.pitch + pose.roll + pose.scale)).toBe(true);- }- }- }- }- });-- it("hovers at chest height, and sinks lower to sleep", () => {- const awake = createGigiFlight(0, 0);- const asleep = createGigiFlight(0, 0);- const sumAwake = { y: 0 }, sumAsleep = { y: 0 };- let n = 0;- for (let t = 0; t < 30; t += DT) {- const a = stepGigiFlight(awake, { targetX: 0, targetZ: 0, moving: false, mode: "idle", speaking: false, t, dt: DT });- const s = stepGigiFlight(asleep, { targetX: 0, targetZ: 0, moving: false, mode: "sleep", speaking: false, t, dt: DT });- if (t > 10) { sumAwake.y += a.y; sumAsleep.y += s.y; n++; }- }- expect(sumAwake.y / n).toBeCloseTo(GIGI_HOVER_M, 1);- expect(sumAsleep.y / n).toBeCloseTo(GIGI_SLEEP_HOVER_M, 1);- });-- it("converges to a moved target without shooting more than 0.15 m past it", () => {- for (const dt of [1 / 144, DT, 1 / 20]) {- // A jump of 3 m (below the snap threshold) along +x.- const state = createGigiFlight(0, 0);- let maxPast = 0;- for (let t = 0; t < 6; t += dt) {- const pose = stepGigiFlight(state, { targetX: 3, targetZ: 0, moving: t < 2, mode: "work", speaking: false, t, dt });- maxPast = Math.max(maxPast, pose.x - 3);- }- expect(maxPast).toBeLessThanOrEqual(0.15);- expect(Math.abs(state.x - 3)).toBeLessThan(0.01);-- // A walker going along an L-shaped path at walking pace, then stopping.- const walk = createGigiFlight(0, 0);- let pastX = 0, pastZ = 0;- for (let t = 0; t < 10; t += dt) {- const s = Math.min(t * 1.35, 6);- const tx = Math.min(s, 3), tz = Math.max(0, s - 3);- const pose = stepGigiFlight(walk, { targetX: tx, targetZ: tz, moving: s < 6, mode: "work", speaking: false, t, dt });- pastX = Math.max(pastX, pose.x - 3);- pastZ = Math.max(pastZ, pose.z - 3);- }- expect(pastX).toBeLessThanOrEqual(0.15);- expect(pastZ).toBeLessThanOrEqual(0.15);- expect(Math.hypot(walk.x - 3, walk.z - 3)).toBeLessThan(0.01);- }- });-- it("snaps when the walker was re-placed far away", () => {- const state = createGigiFlight(0, 0);- stepGigiFlight(state, { targetX: 10, targetZ: -4, moving: false, mode: "idle", speaking: false, t: 0, dt: DT });- expect(state.x).toBe(10);- expect(state.z).toBe(-4);- });-- it("faces the travel direction, leans forward and never over 15°", () => {- for (const [dx, dz] of [[1, 0], [0, 1], [-1, 0], [0.6, -0.8]] as const) {- const state = createGigiFlight(0, 0);- let pose = createGigiPose();- for (let t = 0; t < 3; t += DT) {- pose = stepGigiFlight(state, { targetX: dx * 1.35 * t, targetZ: dz * 1.35 * t, moving: true, mode: "idle", speaking: false, t, dt: DT }, pose);- expect(pose.pitch).toBeLessThanOrEqual(GIGI_MAX_LEAN + 1e-9);- }- const expected = Math.atan2(dx, dz);- expect(Math.abs(Math.atan2(Math.sin(pose.yaw - expected), Math.cos(pose.yaw - expected)))).toBeLessThan(0.05);- expect(pose.pitch).toBeGreaterThan(0.1);- }- });-- it("banks into turns", () => {- const state = createGigiFlight(0, 0);- let minRoll = 0, maxRoll = 0;- // Circle counter-clockwise seen from above in x/z: yaw keeps increasing.- for (let t = 0; t < 4; t += DT) {- const a = t * 0.9;- const pose = stepGigiFlight(state, { targetX: Math.sin(a) * 1.5, targetZ: Math.cos(a) * 1.5 - 1.5, moving: true, mode: "idle", speaking: false, t, dt: DT });- minRoll = Math.min(minRoll, pose.roll); maxRoll = Math.max(maxRoll, pose.roll);- }- expect(minRoll).toBeLessThan(-0.02);- expect(maxRoll).toBeLessThan(0.02);- });-- it("glows brighter when talking or speaking than when idle", () => {- const glowAfter = (mode: GigiFlightMode, speaking: boolean) => {- const state = createGigiFlight(0, 0);- let sum = 0, n = 0;- for (let t = 0; t < 8; t += DT) {- const pose = stepGigiFlight(state, { targetX: 0, targetZ: 0, moving: false, mode, speaking, t, dt: DT });- if (t > 4) { sum += pose.glow; n++; }- }- return sum / n;- };- expect(glowAfter("talk", false)).toBeGreaterThan(glowAfter("idle", false) + 0.2);- expect(glowAfter("idle", true)).toBeGreaterThan(glowAfter("idle", false) + 0.2);- expect(glowAfter("sleep", false)).toBeLessThan(glowAfter("idle", false));- });-- it("reduced motion hovers statically on the target", () => {- const state = createGigiFlight(0, 0);- const pose = createGigiPose();- for (let t = 0; t < 3; t += DT) {- stepGigiFlight(state, { targetX: 1, targetZ: 2, moving: false, mode: "wave", speaking: true, t, dt: DT, heading: 1, reduced: true }, pose);- expect(pose.x).toBe(1);- expect(pose.z).toBe(2);- expect(pose.y).toBe(GIGI_HOVER_M);- expect(pose.yaw).toBeCloseTo(1);- expect(pose.pitch).toBe(0);- }- });-- it("is deterministic and writes into the given pose", () => {- const run = () => {- const state = createGigiFlight(0.5, -1, 0.3);- const pose = createGigiPose();- const trace: number[] = [];- for (let i = 0; i < 600; i++) {- const t = i * DT;- const mode = MODES[Math.floor(t / 2) % MODES.length]!;- const returned = stepGigiFlight(state, { targetX: Math.cos(t) * 2, targetZ: Math.sin(t * 0.7), moving: i % 200 < 120, mode, speaking: i % 150 > 100, t, dt: DT }, pose);- expect(returned).toBe(pose);- trace.push(pose.x, pose.y, pose.z, pose.yaw, pose.pitch, pose.roll, pose.scale, pose.glow);- }- return trace;- };- expect(run()).toEqual(run());- });-});--describe("gigi follow mode", () => {- it("anchors behind and beside the walker, on the side it keeps to", () => {- // Facing +z: behind is -z, the walker's right is -x.- const right = followAnchor(0, 0, 0, 1);- expect(right.z).toBeCloseTo(-GIGI_FOLLOW_BACK_M);- expect(right.x).toBeCloseTo(-GIGI_FOLLOW_SIDE_M);- expect(right.side).toBe(1);- const left = followAnchor(0, 0, 0, -1);- expect(left.x).toBeCloseTo(GIGI_FOLLOW_SIDE_M);- // Facing +x: behind is -x.- const east = followAnchor(2, 3, Math.PI / 2, 1);- expect(east.x).toBeCloseTo(2 - GIGI_FOLLOW_BACK_M);- });-- it("switches shoulders when its side is blocked, and falls back to right above the walker", () => {- const noWest = (x: number) => x > -0.1;- const flipped = followAnchor(0, 0, 0, 1, noWest);- expect(flipped.side).toBe(-1);- expect(flipped.x).toBeGreaterThan(0);- const behindOnly = followAnchor(0, 0, 0, 1, (x) => Math.abs(x) < 0.1);- expect(behindOnly.x).toBeCloseTo(0);- expect(behindOnly.z).toBeLessThan(0);- const boxedIn = followAnchor(1, 1, 0, 1, (x, z) => x === 1 && z === 1);- expect(boxedIn).toEqual({ x: 1, z: 1, side: 1 });- });-- it("rejects an anchor with a wall between it and the walker", () => {- // A thin wall at x = -0.3: the anchor at x = -0.6 is clear, the midpoint is not.- const wall = (x: number) => Math.abs(x + 0.3) > 0.05;- const anchor = followAnchor(0, 0, 0, 1, wall);- expect(anchor.side).toBe(-1);- });-- it("trails a walking person smoothly at shoulder height and never settles inside a wall", () => {- const state = createGigiFlight(0, 0);- const pose = createGigiPose();- const clear = (x: number) => x < 3;- let side: 1 | -1 = 1;- let previous = { x: 0, z: 0 };- let heights = 0, n = 0;- for (let t = 0; t < 12; t += DT) {- // Walk east at 2 m/s towards a wall at x = 3, then stand still.- const px = Math.min(2.8, t * 2), heading = Math.PI / 2;- const anchor = followAnchor(px, 0, heading, side, clear);- side = anchor.side;- stepGigiFlight(state, { targetX: anchor.x, targetZ: anchor.z, moving: px < 2.8, mode: "follow", speaking: false, t, dt: DT, heading, clear }, pose);- expect(clear(state.x)).toBe(true);- // No teleports: one frame never moves Gigi more than a sprint would.- expect(Math.hypot(state.x - previous.x, state.z - previous.z)).toBeLessThan(0.2);- previous = { x: state.x, z: state.z };- if (t > 8) { heights += pose.y; n++; }- }- expect(heights / n).toBeCloseTo(GIGI_FOLLOW_HOVER_M, 1);- // Resting behind the walker, not on it.- expect(Math.hypot(state.x - 2.8, state.z)).toBeGreaterThan(0.4);- });-- it("snaps along when the person is placed elsewhere (an elevator ride)", () => {- const state = createGigiFlight(0, 0);- const anchor = followAnchor(40, 10, 0, 1);- stepGigiFlight(state, { targetX: anchor.x, targetZ: anchor.z, moving: false, mode: "follow", speaking: false, t: 0, dt: DT });- expect(state.x).toBeCloseTo(anchor.x);- expect(state.z).toBeCloseTo(anchor.z);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/gigiFlight.ts b/dodaios/ui/web/frontend/src/components/society/office/gigiFlight.tsdeleted file mode 100644index ad90423c0c..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/gigiFlight.ts+++ /dev/null@@ -1,313 +0,0 @@-/**- * Flight of Gigi, the lead agent's mascot, over the office floor. The lead is- * not drawn as a figure: Gigi hovers at chest/head height of the toy figures- * and follows the walker's ground position (x, z). In "follow" mode it trails- * the person's own character instead, hovering behind-beside its shoulder- * (`followAnchor`): always on the coding floor, and on the agents floor- * whenever no errand or summons takes it away. When the person's pet is one- * that walks (`ground`), the same model keeps it on the floor right behind them.- *- * Pure and deterministic: the same state and inputs give the same pose. With- * an `out` object a step allocates nothing, so it can run every frame.- */--export type GigiFlightMode = "idle" | "work" | "talk" | "wave" | "sleep" | "follow";--export interface GigiFlightInput {- /** The walker's ground position; Gigi hovers above it. */- targetX: number;- targetZ: number;- /** True while the walker travels along a path. */- moving: boolean;- mode: GigiFlightMode;- /** The assistant is talking right now (voice output). */- speaking: boolean;- /** Seconds on a monotonic clock; drives bob, drift and hops. */- t: number;- /** Seconds since the last step. Clamped internally to 0.1 s. */- dt: number;- /** Facing to settle on while hovering in place (rotation about +y, 0 = +z). */- heading?: number;- /** Reduced motion: static hover, no bob, drift, hops or spins. */- reduced?: boolean;- /** Is a point free airspace (not inside a wall or solid prop)? Gigi never settles where it is not. */- clear?: (x: number, z: number) => boolean;- /**- * The companion is a pet that walks, hops or crawls (the person's pet from- * My Pets): it keeps to the floor, so no hover height, bob, drift or lean;- * it still turns, hops for joy and settles where it is clear.- */- ground?: boolean;-}--export interface GigiFlightPose {- /** Body centre in world space. */- x: number;- y: number;- z: number;- /** Rotation about +y; 0 faces +z (the model's front). Includes happy spins. */- yaw: number;- /** Rotation about local x; positive tips the front down (leaning into travel). */- pitch: number;- /** Rotation about local z; banks into turns. */- roll: number;- /** Uniform scale multiplier around 1 (breathing, speaking pulse). */- scale: number;- /** Glow intensity, 0..1. */- glow: number;- /** Horizontal speed in m/s. */- speed: number;-}--export interface GigiFlightState {- x: number;- z: number;- vx: number;- vz: number;- /** Base hover height before bob/hops, spring-smoothed across modes. */- base: number;- vBase: number;- /** Smoothed facing without the spin offset. */- yaw: number;- pitch: number;- roll: number;- /** Extra yaw of a running happy spin, in [0, 2π); 0 = no spin. */- spin: number;- /** 0..1 blends so mode changes glide instead of jumping. */- idleBlend: number;- workBlend: number;- sleepBlend: number;- happyBlend: number;- glow: number;- scale: number;-}--/** Chest/head height of the 1.3 m toy figures. */-export const GIGI_HOVER_M = 1.15;-export const GIGI_SLEEP_HOVER_M = 0.8;-export const GIGI_MIN_Y = 0.6;-export const GIGI_MAX_Y = 1.5;-/** Maximum forward lean (~15°). */-export const GIGI_MAX_LEAN = (15 * Math.PI) / 180;-/** Following the person: just above shoulder height of the 1.3 m figure. */-export const GIGI_FOLLOW_HOVER_M = 1.3;-/** The follow anchor sits this far behind and beside the person. */-export const GIGI_FOLLOW_BACK_M = 0.45;-export const GIGI_FOLLOW_SIDE_M = 0.6;-/** A pet on the floor follows right behind the person, a little to one side. */-export const GROUND_FOLLOW_BACK_M = 0.75;-export const GROUND_FOLLOW_SIDE_M = 0.3;-/** Happy hops of a pet on the floor (speaking, waving), metres. */-const GROUND_HOP_M = 0.06;-/** In follow mode Gigi trails the anchor by at most this much (a sprint stretches the spring). */-const FOLLOW_MAX_LAG_M = 1.1;-const MAX_BANK = 0.35;-/** Spring stiffness of horizontal follow; steady lag at walking pace is 2v/ω ≈ 0.4 m. */-const FOLLOW_OMEGA = 6.5;-const HEIGHT_OMEGA = 3.5;-/** Farther than this and the walker was placed, not walked: re-place Gigi too. */-const SNAP_DISTANCE_M = 4;-/** Gigi never trails the walker by more than this (keeps it off walls at corners). */-const MAX_LAG_M = 0.6;-const LEAN_FULL_SPEED = 1.6;-const SPIN_SECONDS = 0.9;-const SPIN_PERIOD = 4.5;-const TAU = Math.PI * 2;--function wrap(angle: number): number {- let a = angle % TAU;- if (a <= -Math.PI) a += TAU;- else if (a > Math.PI) a -= TAU;- return a;-}--function clamp(value: number, min: number, max: number): number {- return value < min ? min : value > max ? max : value;-}--/** Frame-rate independent exponential approach factor. */-function approach(rate: number, dt: number): number {- return 1 - Math.exp(-rate * dt);-}--export function createGigiFlight(x: number, z: number, heading = 0, ground = false): GigiFlightState {- return {- x, z, vx: 0, vz: 0, base: ground ? 0 : GIGI_HOVER_M, vBase: 0, yaw: heading, pitch: 0, roll: 0, spin: 0,- idleBlend: 1, workBlend: 0, sleepBlend: 0, happyBlend: 0, glow: 0.35, scale: 1,- };-}--export function createGigiPose(ground = false): GigiFlightPose {- return { x: 0, y: ground ? 0 : GIGI_HOVER_M, z: 0, yaw: 0, pitch: 0, roll: 0, scale: 1, glow: 0.35, speed: 0 };-}--/**- * Exact critically damped spring step (no overshoot from rest, stable at any dt).- * Writes the new position to `result[0]` and velocity to `result[1]`.- */-function springStep(position: number, velocity: number, target: number, omega: number, dt: number, result: [number, number]): void {- const offset = position - target;- const decay = Math.exp(-omega * dt);- const temp = (velocity + omega * offset) * dt;- result[0] = target + (offset + temp) * decay;- result[1] = (velocity - omega * temp) * decay;-}--const scratch: [number, number] = [0, 0];--export function stepGigiFlight(state: GigiFlightState, input: GigiFlightInput, out?: GigiFlightPose): GigiFlightPose {- const pose = out ?? createGigiPose();- const dt = Number.isFinite(input.dt) ? clamp(input.dt, 0, 0.1) : 0;- const t = Number.isFinite(input.t) ? input.t : 0;- const reduced = input.reduced === true;- const { targetX, targetZ, mode } = input;- const happy = mode === "talk" || mode === "wave" || input.speaking;- const moving = input.moving;- const ground = input.ground === true;-- // ---- Horizontal follow ------------------------------------------------- const px = state.x, pz = state.z;- const gap = Math.hypot(targetX - state.x, targetZ - state.z);- if (reduced || gap > SNAP_DISTANCE_M || !Number.isFinite(gap)) {- state.x = Number.isFinite(targetX) ? targetX : state.x;- state.z = Number.isFinite(targetZ) ? targetZ : state.z;- state.vx = 0; state.vz = 0;- } else if (dt > 0) {- springStep(state.x, state.vx, targetX, FOLLOW_OMEGA, dt, scratch);- state.x = scratch[0]; state.vx = scratch[1];- springStep(state.z, state.vz, targetZ, FOLLOW_OMEGA, dt, scratch);- state.z = scratch[0]; state.vz = scratch[1];- const lag = Math.hypot(state.x - targetX, state.z - targetZ);- const maxLag = mode === "follow" ? FOLLOW_MAX_LAG_M : MAX_LAG_M;- if (lag > maxLag) {- const k = maxLag / lag;- state.x = targetX + (state.x - targetX) * k;- state.z = targetZ + (state.z - targetZ) * k;- }- }- // Never settle inside a wall: pull back along the lag towards the (clear) target.- if (input.clear && !input.clear(state.x, state.z)) {- for (const k of [0.5, 0.25, 0]) {- const x = targetX + (state.x - targetX) * k, z = targetZ + (state.z - targetZ) * k;- if (k === 0 || input.clear(x, z)) { state.x = x; state.z = z; break; }- }- }- const speed = dt > 0 ? Math.hypot(state.x - px, state.z - pz) / dt : 0;-- // ---- Mode blends --------------------------------------------------------- const blend = approach(3, dt);- const hovering = mode === "idle" || mode === "follow";- state.idleBlend += ((!moving && hovering && !input.speaking ? 1 : 0) - state.idleBlend) * blend;- state.workBlend += ((mode === "work" && !input.speaking ? 1 : 0) - state.workBlend) * blend;- state.sleepBlend += ((mode === "sleep" && !input.speaking ? 1 : 0) - state.sleepBlend) * blend;- state.happyBlend += ((happy ? 1 : 0) - state.happyBlend) * blend;-- // ---- Height -------------------------------------------------------------- const baseTarget = ground ? 0- : mode === "sleep" && !input.speaking ? GIGI_SLEEP_HOVER_M : mode === "follow" ? GIGI_FOLLOW_HOVER_M : GIGI_HOVER_M;- // Ground pets start on the floor, also when replacing a hovering companion.- if (ground || reduced) { state.base = baseTarget; state.vBase = 0; }- else if (dt > 0) {- springStep(state.base, state.vBase, baseTarget, HEIGHT_OMEGA, dt, scratch);- state.base = scratch[0]; state.vBase = scratch[1];- }- let y = state.base;- let driftX = 0, driftZ = 0, wiggle = 0;- if (ground) {- // On the floor: only hops for joy, and only while standing (a walk has its own gait).- if (!reduced && !moving) y += Math.abs(Math.sin(t * Math.PI * 1.5)) * GROUND_HOP_M * state.happyBlend;- y = Math.max(0, y);- } else if (!reduced) {- const calm = 1 - state.sleepBlend;- // Gentle hover bob, ~0.06 m at 0.5 Hz; quieter while busy.- y += Math.sin(t * Math.PI) * 0.06 * calm * (1 - 0.6 * state.workBlend);- // Busy: small quick bobs as if typing along.- y += Math.sin(t * TAU * 2.4) * 0.018 * state.workBlend;- // Sleep: slow breathing.- y += Math.sin(t * TAU * 0.2) * 0.03 * state.sleepBlend;- // Happy hops.- y += Math.abs(Math.sin(t * Math.PI * 1.5)) * 0.07 * state.happyBlend;- // Idle: a slow figure-8 drift around the anchor.- const w = t * 0.45;- driftX = Math.sin(w) * 0.1 * state.idleBlend;- driftZ = Math.sin(2 * w) * 0.05 * state.idleBlend;- wiggle = Math.sin(t * 3.2) * 0.22 * state.happyBlend * (mode === "wave" ? 0 : 1);- }- if (!ground) y = clamp(y, GIGI_MIN_Y, GIGI_MAX_Y);-- // ---- Facing, lean and bank ---------------------------------------------- const previousYaw = state.yaw;- if (moving && speed > 0.15 && !reduced) {- const travel = Math.atan2(state.x - px, state.z - pz);- state.yaw = wrap(state.yaw + wrap(travel - state.yaw) * approach(8, dt));- } else if (input.heading !== undefined && Number.isFinite(input.heading)) {- state.yaw = reduced ? wrap(input.heading) : wrap(state.yaw + wrap(input.heading - state.yaw) * approach(5, dt));- }- const yawRate = dt > 0 ? wrap(state.yaw - previousYaw) / dt : 0;- const leanTarget = reduced || ground ? 0 : GIGI_MAX_LEAN * clamp(speed / LEAN_FULL_SPEED, 0, 1);- // Turning towards +x (yaw increasing) tips the top towards +x: negative roll.- const bankTarget = reduced || ground ? 0 : clamp(-yawRate * clamp(speed, 0, 2) * 0.12, -MAX_BANK, MAX_BANK);- // A freshly selected ground pet must not inherit a flyer's fading lean:- // tilting a raised torso shifts its projection away from the floor marker.- state.pitch = ground ? 0 : state.pitch + (leanTarget - state.pitch) * approach(6, dt);- state.roll = ground ? 0 : state.roll + (bankTarget - state.roll) * approach(6, dt);-- // ---- Happy spin (wave): one full turn every few seconds, always finished ----- if (reduced) state.spin = 0;- else if (state.spin > 0 || (mode === "wave" && !moving && t % SPIN_PERIOD < SPIN_SECONDS * 0.5)) {- state.spin += (dt * TAU) / SPIN_SECONDS;- if (state.spin >= TAU) state.spin = 0;- }-- // ---- Glow and scale ------------------------------------------------------ let glowTarget = 0.35 + 0.15 * state.workBlend - 0.2 * state.sleepBlend + 0.4 * state.happyBlend;- let scaleTarget = 1;- if (!reduced) {- glowTarget += Math.sin(t * TAU * 2.4) * 0.06 * state.workBlend + Math.sin(t * TAU * 0.2) * 0.08 * state.sleepBlend;- scaleTarget += Math.sin(t * TAU * 0.2) * 0.03 * state.sleepBlend;- if (input.speaking) { glowTarget += 0.1 + Math.sin(t * 9) * 0.1; scaleTarget += 0.03 + Math.sin(t * 9) * 0.02; }- } else if (input.speaking) glowTarget += 0.1;- state.glow += (clamp(glowTarget, 0, 1) - state.glow) * (reduced ? 1 : approach(10, dt));- state.scale += (scaleTarget - state.scale) * (reduced ? 1 : approach(10, dt));-- pose.x = state.x + driftX;- pose.y = y;- pose.z = state.z + driftZ;- pose.yaw = wrap(state.yaw + state.spin + wiggle);- pose.pitch = state.pitch;- pose.roll = state.roll;- pose.scale = state.scale;- pose.glow = clamp(state.glow, 0, 1);- pose.speed = speed;- return pose;-}--export interface FollowAnchor { x: number; z: number; /** +1 or -1: which shoulder Gigi keeps to; carry it into the next call. */ side: 1 | -1 }--/**- * Where Gigi hovers while following a walker at (x, z) facing `heading`- * (0 = +z): behind and beside its shoulder, on the side it already keeps to- * unless that side is blocked (then the other side, then straight behind,- * then right above the walker). `clear` tests free airspace; a candidate- * counts only when the midpoint to it is clear too, so no wall sits between.- */-export function followAnchor(x: number, z: number, heading: number, side: 1 | -1, clear?: (x: number, z: number) => boolean,- ground = false): FollowAnchor {- const fx = Math.sin(heading), fz = Math.cos(heading);- // The walker's right hand (heading 0 faces +z, so its right is -x).- const rx = -fz, rz = fx;- // A flyer hovers behind-beside the shoulder; a pet on the floor walks right behind the feet.- const back = ground ? GROUND_FOLLOW_BACK_M : GIGI_FOLLOW_BACK_M;- const lateral = ground ? GROUND_FOLLOW_SIDE_M : GIGI_FOLLOW_SIDE_M;- const candidates: [number, number, 1 | -1][] = [- [back, lateral * side, side],- [back, -lateral * side, side === 1 ? -1 : 1],- [back + 0.2, 0, side],- [0.25, 0, side],- ];- for (const [back, lateral, keep] of candidates) {- const ax = x - fx * back + rx * lateral, az = z - fz * back + rz * lateral;- if (!clear || (clear(ax, az) && clear((x + ax) / 2, (z + az) / 2))) return { x: ax, z: az, side: keep };- }- return { x, z, side };-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/hallFloorLayout.test.ts b/dodaios/ui/web/frontend/src/components/society/office/hallFloorLayout.test.tsdeleted file mode 100644index 822e4eab9f..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/hallFloorLayout.test.ts+++ /dev/null@@ -1,106 +0,0 @@-import { describe, expect, it } from "vitest";-import { REWARD_IDS } from "../progression/levelCatalog";-import { arrivalPose } from "./officeFloors";-import { buildHallLayout, LEVEL_HALL } from "./hallFloorLayout";-import { buildOfficeLayout, FURNITURE_SIZE, footprint } from "./officeLayout";-import { buildNavGrid, findPath, isWalkable } from "./officeNav";-import { floorForKey, PANEL_FLOORS } from "./ElevatorPanel";-import { callDirection } from "./ElevatorCallButton";-import { floorLevel, OFFICE_FLOORS } from "./officeStore";--describe("Level Hall floor", () => {- const layout = buildHallLayout();- const hall = layout.rooms.find((r) => r.kind === "levels")!;- const grid = buildNavGrid(layout);-- it("is a floor of its own: the hall behind a door, a foyer with the elevator, nobody's desk", () => {- expect(layout.variant).toBe("hall");- expect(layout.rooms.map((r) => r.kind)).toEqual(["levels"]);- expect(layout.departments).toEqual([]);- expect(layout.lead.desks).toEqual([]);- expect(layout.checkpoints.map((c) => c.id)).toEqual(["studio", "levels", "elevator"]);- expect(hall.walled).toBe(true);- expect(hall.maxX - hall.minX).toBeCloseTo(LEVEL_HALL.width, 9);- expect(hall.maxZ - hall.minZ).toBeCloseTo(LEVEL_HALL.depth, 9);- expect(hall.doors).toEqual([{ side: "south", at: 0, width: LEVEL_HALL.door }]);- // The same plan every time.- expect(buildHallLayout()).toEqual(layout);- // Nothing of it is left on the agents floor.- const below = buildOfficeLayout([]);- expect(below.rooms.some((r) => r.kind === "levels")).toBe(false);- expect(below.checkpoints.some((c) => c.id === "studio" || c.id === "levels")).toBe(false);- });-- it("keeps the hall's fittings: rank wall, dais, a display case per reward up the runner, the guide", () => {- const pedestals = layout.furniture.filter((f) => f.kind === "rewardPedestal");- expect(pedestals.map((p) => p.id)).toEqual(REWARD_IDS.map((_, n) => `level-pedestal-${n}`));- const cx = (hall.minX + hall.maxX) / 2;- pedestals.forEach((p, n) => {- const box = footprint(p);- expect(box.minX > hall.minX && box.maxX < hall.maxX && box.minZ > hall.minZ && box.maxZ < hall.maxZ, p.id).toBe(true);- expect(Math.sign(p.x - cx)).toBe(n % 2 === 0 ? -1 : 1);- if (n >= 2) {- expect(p.z).toBeLessThan(pedestals[n - 2].z);- // Room to walk between two cases on the same side.- expect(pedestals[n - 2].z - p.z).toBeGreaterThan(FURNITURE_SIZE.rewardPedestal.d + 0.9);- }- });- const stage = layout.furniture.find((f) => f.kind === "studioStage")!;- const studio = layout.checkpoints.find((c) => c.id === "studio")!;- expect([studio.x, studio.z]).toEqual([stage.x, stage.z]);- expect(stage.z).toBeLessThan(Math.min(...pedestals.map((p) => p.z)));- expect(layout.furniture.find((f) => f.kind === "levelWall")!.z).toBeLessThan(stage.z);- const guide = layout.furniture.find((f) => f.kind === "levelGuide")!;- const levels = layout.checkpoints.find((c) => c.id === "levels")!;- expect(guide.z).toBeGreaterThan(Math.max(...pedestals.map((p) => p.z)));- expect(levels.z).toBeLessThan(guide.z);- for (const item of layout.furniture.filter((f) => f.room === "levels")) {- expect(item.x > hall.minX && item.x < hall.maxX && item.z > hall.minZ && item.z < hall.maxZ, item.id).toBe(true);- }- expect(new Set(layout.furniture.map((f) => f.id)).size).toBe(layout.furniture.length);- });-- it("lets the person step out of the elevator and walk to both stations through the door", () => {- const elevator = layout.furniture.find((f) => f.kind === "elevator")!;- const stop = layout.checkpoints.find((c) => c.id === "elevator")!;- expect(stop.z).toBeCloseTo(elevator.z, 9);- expect(stop.x).toBeGreaterThan(elevator.x);- expect(stop.z).toBeGreaterThan(hall.maxZ);- // Arriving by elevator: at its stop, facing away from the doors (east).- const pose = arrivalPose(layout, "elevator");- expect([pose.x, pose.z]).toEqual([stop.x, stop.z]);- expect(pose.heading).toBeCloseTo(Math.PI / 2, 9);- expect(isWalkable(grid, pose)).toBe(true);- expect(isWalkable(grid, layout.spawn)).toBe(true);- // The doorway is open, the wall beside it is not.- expect(isWalkable(grid, { x: 0, z: hall.maxZ })).toBe(true);- expect(isWalkable(grid, { x: hall.minX + 1.5, z: hall.maxZ })).toBe(false);- const studio = layout.checkpoints.find((c) => c.id === "studio")!;- const levels = layout.checkpoints.find((c) => c.id === "levels")!;- for (const target of [studio.approach!, { x: levels.x, z: levels.z }]) {- expect(isWalkable(grid, target)).toBe(true);- const path = findPath(grid, pose, target)!;- expect(path).not.toBeNull();- // The only way in is the door.- const crossing = [pose, ...path].findIndex((p) => p.z < hall.maxZ);- expect(crossing).toBeGreaterThan(0);- }- for (const cp of layout.checkpoints) {- const solid = layout.furniture.filter((f) => FURNITURE_SIZE[f.kind].solid).map(footprint);- const at = cp.approach ?? cp;- expect(solid.some((o) => at.x >= o.minX && at.x <= o.maxX && at.z >= o.minZ && at.z <= o.maxZ), cp.id).toBe(false);- }- });-- it("is the top floor of the elevator: listed, numbered, reachable by its key", () => {- expect(OFFICE_FLOORS).toEqual(["agents", "coding", "arcade", "hall"]);- expect(floorLevel("hall")).toBe(3);- expect(PANEL_FLOORS[0]).toBe("hall");- expect(floorForKey("3")).toBe("hall");- expect(floorForKey("0")).toBe("agents");- expect(floorForKey("4")).toBeNull();- expect(callDirection("hall")).toBe("down");- expect(callDirection("arcade")).toBe("both");- expect(callDirection("agents")).toBe("up");- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/hallFloorLayout.ts b/dodaios/ui/web/frontend/src/components/society/office/hallFloorLayout.tsdeleted file mode 100644index fedeee5e50..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/hallFloorLayout.ts+++ /dev/null@@ -1,103 +0,0 @@-/**- * The Level Hall's own floor, on top of the building: a small foyer with the- * elevator, and behind its door the hall of honour.- *- * ┌──────── Level Hall ────────┐- * │ rank wall · studio dais │ north- * │ display cases either side │- * │ of the runner │- * │ service guide │- * ├────────── door ────────────┤- * │ elevator foyer │ south- * └────────────────────────────┘- *- * The hall's fittings, north to south: the rank wall on the north wall with- * the studio's round dais in front of it (its checkpoint is the dais itself),- * the runner down the middle with a display case per reward on either side —- * the lowest unlock at the south end, the highest by the dais, so walking up- * the runner is climbing the ranks — and at the runner's start the- * double-sided service guide with its checkpoint on the runner side. Plants- * frame the dais, olive trees the guide.- *- * Takes no input: the hall is the same for everyone; what it shows comes from- * the level state at render time.- */-import { REWARD_IDS } from "../progression/levelCatalog";-import {- FLOOR_EDGE, footprint, FURNITURE_SIZE, RAIL_CLEARANCE, wallRect, wallsOf,- type Checkpoint, type Furniture, type FurnitureKind, type OfficeLayout, type Rect, type Room, type Spot,-} from "./officeLayout";--/** The hall's width and depth, the foyer's depth, where the dais stands, and how far the runner stays from each end of the hall. */-export const LEVEL_HALL = { width: 9.2, depth: 34, foyer: 6.4, door: 2.4, stageZ: 4.5, stageR: 1.6, roadNorth: 8.2, roadSouth: 6.4, guideZ: 3.3 } as const;-/** The display cases stand this far either side of the hall's centre line, the runner between them. */-export const PEDESTAL_OFFSET_X = 1.8;--/** Build the Level Hall's floor. */-export function buildHallLayout(): OfficeLayout {- const minX = -LEVEL_HALL.width / 2, maxX = LEVEL_HALL.width / 2;- const total = LEVEL_HALL.depth + LEVEL_HALL.foyer;- const topZ = -total / 2, bottomZ = total / 2;- const hall: Room = { id: "levels", kind: "levels", walled: true, minX, maxX, minZ: topZ, maxZ: topZ + LEVEL_HALL.depth,- doors: [{ side: "south", at: 0, width: LEVEL_HALL.door }] };- const cx = 0;- const piece = (id: string, kind: FurnitureKind, x: number, z: number, rotationY = 0, size?: { w: number; d: number }): Furniture =>- ({ id, kind, x, z, rotationY, room: "levels", ...(size ? { size } : {}) });- const stageZ = hall.minZ + LEVEL_HALL.stageZ;- const roadMinZ = hall.minZ + LEVEL_HALL.roadNorth, roadMaxZ = hall.maxZ - LEVEL_HALL.roadSouth;- const guideZ = hall.maxZ - LEVEL_HALL.guideZ;- // Case n (0 = the lowest unlock) stands on the west side when n is even, the east side when odd, rising northwards.- const rows = Math.ceil(REWARD_IDS.length / 2);- const pitch = rows > 1 ? (roadMaxZ - roadMinZ - 1.2) / (rows - 1) : 0;- const pedestals = REWARD_IDS.map((_, n) => piece(`level-pedestal-${n}`, "rewardPedestal",- cx + (n % 2 === 0 ? -PEDESTAL_OFFSET_X : PEDESTAL_OFFSET_X), roadMaxZ - 0.6 - Math.floor(n / 2) * pitch, n % 2 === 0 ? Math.PI / 2 : -Math.PI / 2));- // The foyer: the elevator on the west edge like on every floor (doors facing east), its mat, an olive tree in each south corner.- const elevator: Furniture = { id: "elevator", kind: "elevator", x: minX + 0.25, z: bottomZ - 2.6, rotationY: Math.PI / 2, room: "floor" };- const furniture: Furniture[] = [- piece("level-wall", "levelWall", cx, hall.minZ + 0.08 + FURNITURE_SIZE.levelWall.d / 2),- piece("level-stage", "studioStage", cx, stageZ),- piece("level-road", "levelRoad", cx, (roadMinZ + roadMaxZ) / 2, 0, { w: 2.2, d: roadMaxZ - roadMinZ }),- ...pedestals,- // The guide faces up the runner; its back shows the same screen to whoever comes in through the door.- piece("level-guide", "levelGuide", cx, guideZ, Math.PI),- piece("level-plant-nw", "designerPlant", hall.minX + 0.6, hall.minZ + 0.7),- piece("level-plant-ne", "designerPlant", hall.maxX - 0.6, hall.minZ + 0.7),- piece("level-olive-sw", "oliveTree", hall.minX + 0.85, hall.maxZ - 0.85),- piece("level-olive-se", "oliveTree", hall.maxX - 0.85, hall.maxZ - 0.85),- elevator,- { id: "foyer-mat", kind: "entranceMat", x: minX + 1.3, z: elevator.z, rotationY: 0, room: "floor", size: { w: 1.1, d: 1.9 } },- { id: "foyer-olive", kind: "oliveTree", x: maxX - 0.8, z: bottomZ - 0.8, rotationY: 0, room: "floor" },- ];- const spots: Spot[] = [];- const elevatorStop: Checkpoint = { id: "elevator", room: "floor", x: elevator.x + 0.95, z: elevator.z, radius: 1.0 };- const checkpoints: Checkpoint[] = [- { id: "studio", room: "levels", x: cx, z: stageZ, radius: LEVEL_HALL.stageR, approach: { x: cx, z: stageZ + 0.6 } },- { id: "levels", room: "levels", x: cx, z: guideZ - 1.45, radius: 1.1 },- elevatorStop,- ];- const walls = wallsOf(hall);- const obstacles: Rect[] = [- ...walls.map(wallRect),- ...furniture.filter((f) => FURNITURE_SIZE[f.kind].solid).map(footprint),- ];- const start = { x: elevator.x + 1.15, z: elevator.z };- return {- variant: "hall",- departments: [],- // Nobody leads up here; the rect is the foyer so it stays a real place on the floor.- lead: { minX, maxX, minZ: hall.maxZ, maxZ: bottomZ, desks: [] },- rooms: [hall],- walls,- furniture,- spots,- checkpoints,- obstacles,- spawn: start,- arrival: start,- floor: {- minX: minX - FLOOR_EDGE + RAIL_CLEARANCE, maxX: maxX + FLOOR_EDGE - RAIL_CLEARANCE,- minZ: topZ - FLOOR_EDGE + RAIL_CLEARANCE, maxZ: bottomZ + FLOOR_EDGE - RAIL_CLEARANCE,- },- bounds: { minX: minX - FLOOR_EDGE, maxX: maxX + FLOOR_EDGE, minZ: topZ - FLOOR_EDGE, maxZ: bottomZ + FLOOR_EDGE },- };-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/leadMark.test.tsx b/dodaios/ui/web/frontend/src/components/society/office/leadMark.test.tsxdeleted file mode 100644index 824c898272..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/leadMark.test.tsx+++ /dev/null@@ -1,237 +0,0 @@-/**- * A team lead's place must be found on screen, not only in the plan. These- * tests put the mark (chair shell, chair mat, name stand) through the real- * cameras: the default follow view and the campus overview, in a 1600 x 900- * window, and check how many pixels each piece covers and that nothing on the- * floor stands between it and the camera.- */-import { describe, expect, it } from "vitest";-import { Box3, Matrix4, PerspectiveCamera, Vector3 } from "three";-import { pendantHousings } from "./AgentsFloorAmbience";-import { placementMatrix } from "./DeskDressing";-import { leadMark, type Placement } from "./deskKit";-import { TASK_CHAIR_PARTS } from "./OfficeChairs";-import { campusOverview, CAMERA_FOV, FOLLOW_DISTANCE_M, HOME_PITCH_RAD, HOME_YAW_RAD, type CameraPose } from "./officeCamera";-import { buildOfficeLayout, leadDesks, standOf, type DeskSlot, type OfficeAgentInput, type OfficeLayout, type OfficeTeamInput } from "./officeLayout";--const VIEW = { w: 1600, h: 900 } as const;-/** The height the follow view looks at (OfficeCameraRig's target height). */-const TARGET_HEIGHT = 0.8;--const staff = (count: number): OfficeAgentInput[] => Array.from({ length: count }, (_, i) => ({- agentId: `a${i + 1}`, name: `Agent ${i + 1}`, tier: "specialist", providerLabel: "Codex", state: "idle", createdMs: i,-}));-const teamsOf = (count: number, size: number): OfficeTeamInput[] => Array.from({ length: count }, (_, t) => ({- id: `team-${t}`, name: `Team ${t}`, createdMs: t, members: Array.from({ length: size }, (_, i) => `a${1 + t * size + i}`),- // Not the earliest arrival: the lead had to be seated at the head desk.- leadId: `a${2 + t * size}`,-}));--/** The view that follows the person standing at `at`, as the camera rig sets it. */-function followPose(at: { x: number; z: number }, distance = FOLLOW_DISTANCE_M): CameraPose {- const horizontal = Math.cos(HOME_PITCH_RAD) * distance;- return {- target: [at.x, TARGET_HEIGHT, at.z],- position: [at.x + Math.sin(HOME_YAW_RAD) * horizontal, Math.sin(HOME_PITCH_RAD) * distance + TARGET_HEIGHT, at.z + Math.cos(HOME_YAW_RAD) * horizontal],- };-}--function cameraOf(pose: CameraPose): PerspectiveCamera {- const camera = new PerspectiveCamera(CAMERA_FOV, VIEW.w / VIEW.h, 0.2, 800);- camera.position.set(...pose.position);- camera.lookAt(...pose.target);- camera.updateMatrixWorld(true);- camera.updateProjectionMatrix();- return camera;-}--const pixel = (camera: PerspectiveCamera, point: Vector3): { x: number; y: number } => {- const ndc = point.clone().project(camera);- return { x: ((ndc.x + 1) / 2) * VIEW.w, y: ((1 - ndc.y) / 2) * VIEW.h };-};-const apart = (a: { x: number; y: number }, b: { x: number; y: number }) => Math.hypot(a.x - b.x, a.y - b.y);--/** A desk's own space in the world, as DeskDressing and DeskInstances place it. */-const deskWorld = (desk: DeskSlot) => new Matrix4().makeRotationY(desk.facing === "north" ? 0 : Math.PI).setPosition(desk.x, 0, desk.z);-const worldOf = (desk: DeskSlot, part: Placement) => deskWorld(desk).multiply(placementMatrix(part));--/** A point of a part's unit box (each side from -0.5 to 0.5) in the world. */-const corner = (matrix: Matrix4, x: number, y: number, z: number) => new Vector3(x, y, z).applyMatrix4(matrix);--/** On-screen length of a plate's two sides, measured across the middle of the face that looks along its local `normal`. */-function faceSides(camera: PerspectiveCamera, matrix: Matrix4, normal: "y" | "z"): [number, number] {- const p = (u: number, v: number) => pixel(camera, normal === "z" ? corner(matrix, u, v, 0.5) : corner(matrix, u, 0.5, v));- return [apart(p(-0.5, 0), p(0.5, 0)), apart(p(0, -0.5), p(0, 0.5))];-}--/** Points spread over a plate's visible face, a little inside its edges. */-function faceSamples(matrix: Matrix4, normal: "y" | "z", n = 5): Vector3[] {- const out: Vector3[] = [];- for (let i = 0; i < n; i += 1) {- for (let j = 0; j < n; j += 1) {- const u = -0.42 + (0.84 * i) / (n - 1), v = -0.42 + (0.84 * j) / (n - 1);- out.push(normal === "z" ? corner(matrix, u, v, 0.52) : corner(matrix, u, 0.52, v));- }- }- return out;-}--/** Does the straight line from `from` to `to` pass through `box`? */-function crosses(from: Vector3, to: Vector3, box: Box3): boolean {- let near = 0, far = 1;- for (const axis of ["x", "y", "z"] as const) {- const d = to[axis] - from[axis];- if (Math.abs(d) < 1e-9) {- if (from[axis] < box.min[axis] || from[axis] > box.max[axis]) return false;- continue;- }- const a = (box.min[axis] - from[axis]) / d, b = (box.max[axis] - from[axis]) / d;- near = Math.max(near, Math.min(a, b));- far = Math.min(far, Math.max(a, b));- if (near > far) return false;- }- return true;-}--const boxAt = (desk: DeskSlot, centre: [number, number, number], size: [number, number, number]): Box3 => {- const turn = desk.facing === "north" ? 1 : -1;- return new Box3().setFromCenterAndSize(new Vector3(desk.x + turn * centre[0], centre[1], desk.z + turn * centre[2]), new Vector3(...size));-};--/**- * What can stand in the way on the floor: every desk's monitor and felt screen, every chair's back and whoever sits- * on it (as boxes a little larger than the things), and the pendant lights. `own` is the lead's desk, whose own- * chair back the shell lies on: `withOwnChair` leaves that one out.- */-function occluders(layout: OfficeLayout, own: DeskSlot, withOwnChair: boolean): Box3[] {- const out: Box3[] = [];- for (const desk of layout.departments.flatMap((d) => d.desks)) {- out.push(boxAt(desk, [0, 1.18, -0.224], [0.74, 0.45, 0.04]));- out.push(boxAt(desk, [0, 0.95, -0.41], [1.46, 0.36, 0.04]));- // A seated figure: from the seat to the top of the head.- out.push(boxAt(desk, [0, 0.98, 0.6], [0.5, 0.96, 0.36]));- if (desk.id !== own.id || withOwnChair) out.push(boxAt(desk, [0, 0.86, 0.87], [0.5, 0.52, 0.1]));- }- for (const p of pendantHousings(layout.departments)) {- out.push(new Box3().setFromCenterAndSize(new Vector3(p.x, p.y, p.z), new Vector3(p.length, p.h + 0.03, p.w + 0.02)));- }- return out;-}--/** The share of `points` the camera sees with nothing in `boxes` in front of them. */-function seen(camera: PerspectiveCamera, points: Vector3[], boxes: Box3[]): number {- const clear = points.filter((point) => !boxes.some((box) => crosses(point, camera.position, box)));- return clear.length / points.length;-}--const felt = (parts: Placement[]) => parts.filter((p) => p.part === "felt");--describe("a team lead's place", () => {- const layout = buildOfficeLayout(staff(15), { teams: teamsOf(3, 4) });- const leads = leadDesks(layout);- const mark = leadMark("#8aa391");- const shell = felt(mark.chair).slice(0, 3), plate = felt(mark.stand)[0], mat = mark.mat[0];-- it("is marked at every team's head desk, which faces north: its chair's back looks at the south-east camera", () => {- expect(leads).toHaveLength(3);- for (const { desk } of leads) expect(desk.facing).toBe("north");- });-- it("hugs the real chair: the shell lies on the backrest, the pad on the seat, the mat under it", () => {- const back = new Box3(), seat = new Box3();- TASK_CHAIR_PARTS.forEach((part, i) => {- part.geometry.computeBoundingBox();- if (part.finish === "mesh") back.union(part.geometry.boundingBox!);- if (part.finish === "fabric" && i === 2) seat.union(part.geometry.boundingBox!);- });- // DeskInstances stands the chair 0.62 m behind the desk's centre.- const chairZ = 0.62;- const shellBox = new Box3();- for (const part of shell) {- const m = placementMatrix(part);- for (const x of [-0.5, 0.5]) for (const y of [-0.5, 0.5]) for (const z of [-0.5, 0.5]) shellBox.expandByPoint(corner(m, x, y, z));- }- // Behind the mesh (never in front of it, where the sitter is), by a few centimetres at most; inside its height; as wide as it.- expect(shellBox.max.z - (back.max.z + chairZ)).toBeGreaterThan(0.015);- expect(shellBox.max.z - (back.max.z + chairZ)).toBeLessThan(0.07);- expect(shellBox.min.z).toBeGreaterThan(back.min.z + chairZ);- expect(shellBox.min.y).toBeGreaterThan(back.min.y);- expect(shellBox.max.y).toBeLessThan(back.max.y + 0.01);- expect(Math.abs(shellBox.max.x - back.max.x)).toBeLessThan(0.05);- expect(Math.abs(shellBox.min.x - back.min.x)).toBeLessThan(0.05);- const pad = felt(mark.chair)[3];- // The pad rests in the seat's dish and stands a few millimetres proud of its rim.- expect(pad.p[1] - pad.s![1] / 2).toBeLessThan(seat.max.y);- expect(pad.p[1] + pad.s![1] / 2).toBeGreaterThan(seat.max.y + 0.002);- expect(pad.p[1] + pad.s![1] / 2).toBeLessThan(seat.max.y + 0.012);- expect(pad.s![0]).toBeLessThan(seat.max.x - seat.min.x);- // The mat is flat, above the rug's field (7 mm) and under the light pools (12 mm).- expect(mat.p[1] - mat.s![1] / 2).toBeGreaterThan(0.007);- expect(mat.p[1] + mat.s![1] / 2).toBeLessThan(0.012);- });-- it("reads in the default follow view: chair shell and name plate cover more than ten pixels each way, with nothing in front", () => {- for (const { desk, dept } of leads) {- const centre = { x: (dept.minX + dept.maxX) / 2, z: (dept.minZ + dept.maxZ) / 2 };- // Standing beside the lead, in the middle of its studio, and in its doorway.- for (const person of [standOf(desk), centre, { x: centre.x, z: dept.maxZ - 0.5 }]) {- const camera = cameraOf(followPose(person));- const at = `${desk.id} from ${person.x.toFixed(1)},${person.z.toFixed(1)}`;-- // The chair's shell as one shape: its box on screen.- const pixels = shell.flatMap((part) => {- const m = worldOf(desk, part);- return [-0.5, 0.5].flatMap((x) => [-0.5, 0.5].flatMap((y) => [-0.5, 0.5].map((z) => pixel(camera, corner(m, x, y, z)))));- });- const w = Math.max(...pixels.map((p) => p.x)) - Math.min(...pixels.map((p) => p.x));- const h = Math.max(...pixels.map((p) => p.y)) - Math.min(...pixels.map((p) => p.y));- expect(Math.min(w, h), `shell ${at}`).toBeGreaterThan(24);- for (const p of pixels) {- expect(p.x > 0 && p.x < VIEW.w && p.y > 0 && p.y < VIEW.h, `shell on screen ${at}`).toBe(true);- }- const blockers = occluders(layout, desk, false);- // Its rear face looks away from the desk (local +z).- for (const part of shell) expect(seen(camera, faceSamples(worldOf(desk, part), "z"), blockers), `shell seen ${at}`).toBe(1);-- // The name plate on the desk: both of its sides, and all of its face.- const plateWorld = worldOf(desk, plate);- const [pw, ph] = faceSides(camera, plateWorld, "z");- expect(Math.min(pw, ph), `plate ${at}`).toBeGreaterThanOrEqual(10);- expect(seen(camera, faceSamples(plateWorld, "z"), occluders(layout, desk, true)), `plate seen ${at}`).toBe(1);- }- }- });-- it("reads from the overview: the chair mat is a patch of the team's colour ten pixels across, most of it in the open", () => {- const camera = cameraOf(campusOverview(layout.bounds, VIEW.w / VIEW.h));- for (const { desk } of leads) {- const matWorld = worldOf(desk, mat);- const [mw, md] = faceSides(camera, matWorld, "y");- expect(Math.min(mw, md), desk.id).toBeGreaterThanOrEqual(10);- // The chair and whoever sits on it stand on the mat; the rest of it lies open.- expect(seen(camera, faceSamples(matWorld, "y", 7), occluders(layout, desk, true)), desk.id).toBeGreaterThan(0.55);- // The shell is still there as a second patch above it.- for (const part of shell) expect(seen(camera, faceSamples(worldOf(desk, part), "z"), occluders(layout, desk, false)), desk.id).toBe(1);- }- });-- it("stays inside the desk top and the strip the chair rolls on", () => {- const TOP = 0.77;- for (const part of mark.stand) {- const m = placementMatrix(part);- for (const x of [-0.5, 0.5]) for (const y of [-0.5, 0.5]) for (const z of [-0.5, 0.5]) {- const p = corner(m, x, y, z);- // On the desk top (1.5 m x 0.8 m), right of the keyboard and the mouse, lower than the monitor's lower edge.- expect(p.x, part.part).toBeGreaterThan(0.4);- expect(p.x, part.part).toBeLessThan(0.75);- expect(p.z, part.part).toBeGreaterThan(0.15);- expect(p.z, part.part).toBeLessThan(0.4);- expect(p.y, part.part).toBeGreaterThanOrEqual(TOP - 1e-9);- expect(p.y, part.part).toBeLessThan(0.96);- }- }- // The mat: narrower than the desk pitch (1.7 m), and it ends well inside the bench's own depth (2.1 m from its middle).- expect(mat.s![0]).toBeLessThan(1.5);- expect(0.45 + mat.p[2] + mat.s![2] / 2).toBeLessThan(2.1);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/leadSeat.test.ts b/dodaios/ui/web/frontend/src/components/society/office/leadSeat.test.tsdeleted file mode 100644index 38cafdc391..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/leadSeat.test.ts+++ /dev/null@@ -1,60 +0,0 @@-import { describe, expect, it } from "vitest";-import { buildOfficeLayout, seatOf, type OfficeAgentInput } from "./officeLayout";-import { buildNavGrid, findPath, isWalkable } from "./officeNav";-import { chairInReach, SEAT_REACH, seatDesks } from "./leadSeat";--const lead: OfficeAgentInput = { agentId: "lead", name: "Lead", tier: "lead", providerLabel: "", state: "idle", createdMs: 1 };-const staff: OfficeAgentInput = { agentId: "s1", name: "S1", tier: "specialist", providerLabel: "codex", state: "idle", createdMs: 2 };--describe("the lead's executive chair", () => {- const layout = buildOfficeLayout([lead, staff]);- const grid = buildNavGrid(layout);- const desk = layout.lead.desks[0];- const seat = seatOf(desk);-- it("is solid: nobody walks through it", () => {- expect(isWalkable(grid, seat)).toBe(false);- });-- it("can still be reached to sit down, ending exactly on the seat", () => {- const path = findPath(grid, layout.spawn, seat);- expect(path).not.toBeNull();- const last = path![path!.length - 1];- expect(Math.hypot(last.x - seat.x, last.z - seat.z)).toBeLessThan(0.01);- });-- it("is within reach only from close by, and bench desks are never sittable", () => {- expect(chairInReach(layout.lead.desks, { x: seat.x + 0.7, z: seat.z })?.id).toBe(desk.id);- expect(chairInReach(layout.lead.desks, { x: seat.x + SEAT_REACH + 0.2, z: seat.z })).toBeNull();- const bench = layout.departments.flatMap((d) => d.desks)[0];- expect(chairInReach([bench], seatOf(bench))).toBeNull();- });-- it("puts the sleeping dog in the lead office", () => {- expect(layout.furniture.some((f) => f.kind === "dogBed" && f.room === "lead")).toBe(true);- });-});--describe("Mission Control's boss chair", () => {- const layout = buildOfficeLayout([staff], { variant: "coding" });- const grid = buildNavGrid(layout);- const desk = layout.command!;- const seat = seatOf(desk);-- it("is a seat on the coding floor only, facing the monitors (south)", () => {- expect(desk.id).toBe("command");- expect(buildOfficeLayout([lead, staff]).command).toBeUndefined();- expect(seatDesks(layout)).toEqual([desk]);- // The person sits north of the desk, between it and the wall, looking south at the monitors.- expect(seat.z).toBeLessThan(desk.z);- expect(seat.facing).toBe(0);- });-- it("is solid, yet reachable to sit down, and within reach only from close by", () => {- expect(isWalkable(grid, seat)).toBe(false);- const path = findPath(grid, layout.spawn, seat);- expect(path).not.toBeNull();- expect(chairInReach(seatDesks(layout), { x: seat.x + 0.7, z: seat.z })?.id).toBe("command");- expect(chairInReach(seatDesks(layout), { x: seat.x + SEAT_REACH + 0.2, z: seat.z })).toBeNull();- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/leadSeat.ts b/dodaios/ui/web/frontend/src/components/society/office/leadSeat.tsdeleted file mode 100644index 5e4cd64e0e..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/leadSeat.ts+++ /dev/null@@ -1,53 +0,0 @@-/**- * The person's character can take an executive chair: the lead's downstairs,- * Mission Control's upstairs. Walk up and press E (or click the chair), sit,- * then click the monitors (the lead agent, or the Mission Control panel).- * Seated at Mission Control the view turns first person onto its monitors.- * Any movement stands the character up again.- *- * Kept apart from the general office store: only executive chairs are- * sittable, and each chair's prompt lives in the scene next to it.- */-import { create } from "zustand";-import { seatOf, type DeskSlot, type OfficeLayout, type Point } from "./officeLayout";--/** How close the character must stand to the chair to sit down with E, in metres. */-export const SEAT_REACH = 1.1;--interface LeadSeatState {- /** Desk id whose chair the character sits on, or null. */- seated: string | null;- /** Desk id whose chair is within reach (the E prompt), or null. */- near: string | null;- /** Desk id the character is walking to in order to sit (the chair was clicked from afar). */- pending: string | null;- /** One-shot: the character just stood up and must step out of the chair's footprint. */- standUp: boolean;- set: (patch: Partial<Pick<LeadSeatState, "seated" | "near" | "pending" | "standUp">>) => void;-}--export const useLeadSeat = create<LeadSeatState>((set) => ({- seated: null,- near: null,- pending: null,- standUp: false,- set: (patch) => set((s) => (Object.entries(patch).every(([k, v]) => s[k as keyof typeof patch] === v) ? s : patch)),-}));--/** Every desk whose chair the person can take on this floor: the lead desks, and Mission Control's. */-export function seatDesks(layout: Pick<OfficeLayout, "lead" | "command">): DeskSlot[] {- return layout.command ? [...layout.lead.desks, layout.command] : layout.lead.desks;-}--/** The executive chair within reach of `at`, if any (sittable desks carry a size; bench desks never do). */-export function chairInReach(desks: readonly DeskSlot[], at: Point): DeskSlot | null {- let best: DeskSlot | null = null;- let bestDistance = SEAT_REACH;- for (const desk of desks) {- if (!desk.size) continue;- const seat = seatOf(desk);- const d = Math.hypot(seat.x - at.x, seat.z - at.z);- if (d <= bestDistance) { best = desk; bestDistance = d; }- }- return best;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/liveMonitors.test.ts b/dodaios/ui/web/frontend/src/components/society/office/liveMonitors.test.tsdeleted file mode 100644index 771f1c51f7..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/liveMonitors.test.ts+++ /dev/null@@ -1,28 +0,0 @@-import { describe, expect, it } from "vitest";-import { pickRealChats } from "./LiveMonitors";-import { screenFillDistance } from "./OfficeCameraRig";--describe("real chat monitors", () => {- it("runs the real chat only on the nearest few seated agents", () => {- const picked = pickRealChats([- { id: "a", distance: 3 }, { id: "b", distance: 9 }, { id: "c", distance: 5 }, { id: "d", distance: 7 }, { id: "far", distance: 30 },- ], new Set());- expect([...picked].sort()).toEqual(["a", "c", "d"]);- });- it("keeps a running chat until it is clearly out of range (no flicker at the edge)", () => {- expect(pickRealChats([{ id: "a", distance: 12 }], new Set()).has("a")).toBe(false);- expect(pickRealChats([{ id: "a", distance: 12 }], new Set(["a"])).has("a")).toBe(true);- expect(pickRealChats([{ id: "a", distance: 15 }], new Set(["a"])).has("a")).toBe(false);- });-});--describe("monitor dive", () => {- it("stands back far enough for the whole screen to fit, wider views closer", () => {- const wide = screenFillDistance(35, 2.2);- const narrow = screenFillDistance(35, 0.8);- expect(narrow).toBeGreaterThan(wide);- // At 35° the 0.38 m screen height needs about 0.6 m.- expect(wide).toBeGreaterThan(0.55);- expect(wide).toBeLessThan(0.7);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/mapHooks.ts b/dodaios/ui/web/frontend/src/components/society/office/mapHooks.tsdeleted file mode 100644index 241188e63e..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/mapHooks.ts+++ /dev/null@@ -1,141 +0,0 @@-/**- * Small hooks shared by the minimap, the compass bar and the full map:- * theme and pixel-ratio change signals, element size, and a throttled- * requestAnimationFrame loop.- */-import { useEffect, useRef, useState, type RefObject } from "react";-import type { MinimapAgentState } from "./minimap";--/** What the maps need to know about an agent; `SocietyAgent` satisfies it. */-export interface OfficeMapAgent {- agentId: string;- name: string;- state: MinimapAgentState;- palette?: { primary?: string } | null;-}--/** Token colour of an agent: its palette's primary colour, or a neutral slate. */-export function agentColour(agent: OfficeMapAgent): string {- const primary = agent.palette?.primary?.trim();- return primary ? primary : "#7c8aa5";-}--function pixelRatio(): number {- return typeof window !== "undefined" && window.devicePixelRatio > 0 ? window.devicePixelRatio : 1;-}--/** Bumps whenever light/dark mode may have changed: OS preference, or the app's class/data-theme on <html>. */-export function useThemeVersion(): number {- const [version, setVersion] = useState(0);- useEffect(() => {- const bump = () => setVersion((v) => v + 1);- const media = typeof window.matchMedia === "function" ? window.matchMedia("(prefers-color-scheme: dark)") : null;- media?.addEventListener?.("change", bump);- const observer = typeof MutationObserver === "function" ? new MutationObserver(bump) : null;- observer?.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "data-theme", "style"] });- return () => {- media?.removeEventListener?.("change", bump);- observer?.disconnect();- };- }, []);- return version;-}--/** The device pixel ratio, refreshed when the window moves to another screen or zooms. */-export function usePixelRatio(): number {- const [dpr, setDpr] = useState(pixelRatio);- useEffect(() => {- const check = () => setDpr((prev) => (prev === pixelRatio() ? prev : pixelRatio()));- window.addEventListener("resize", check);- return () => window.removeEventListener("resize", check);- }, []);- return dpr;-}--/** CSS size of an element, rounded to whole pixels; {0, 0} until measured. */-export function useElementSize(ref: RefObject<HTMLElement>, enabled = true): { width: number; height: number } {- const [size, setSize] = useState({ width: 0, height: 0 });- useEffect(() => {- const el = ref.current;- if (!enabled || !el) return;- const measure = () => {- const rect = el.getBoundingClientRect();- const next = { width: Math.round(rect.width), height: Math.round(rect.height) };- setSize((prev) => (prev.width === next.width && prev.height === next.height ? prev : next));- };- measure();- if (typeof ResizeObserver !== "function") {- window.addEventListener("resize", measure);- return () => window.removeEventListener("resize", measure);- }- const observer = new ResizeObserver(measure);- observer.observe(el);- return () => observer.disconnect();- }, [ref, enabled]);- return size;-}--/**- * Calls `draw(now)` at most once per `frameMs` from requestAnimationFrame while- * `enabled`. The latest `draw` is read through a ref, so a re-render never- * restarts the loop.- *- * Deliberately NOT gated on `document.hidden`: the desktop WebView reports an- * on-screen window as hidden for minutes at a time (see useCanvasAwake), which- * froze the minimap and compass. requestAnimationFrame already stops by itself- * for a window that is really hidden.- */-export function useThrottledFrames(draw: (now: number) => void, frameMs: number, enabled: boolean): void {- const drawRef = useRef(draw);- drawRef.current = draw;- useEffect(() => {- if (!enabled || typeof requestAnimationFrame !== "function") return;- let last = 0;- const tick = (now: number) => {- raf = requestAnimationFrame(tick);- if (now - last < frameMs) return;- last = now;- drawRef.current(now);- };- let raf = requestAnimationFrame(tick);- return () => cancelAnimationFrame(raf);- }, [frameMs, enabled]);-}--/** A theme token (raw "H S% L%") as a CSS colour, or the fallback when the token is missing. */-export function tokenColour(style: CSSStyleDeclaration | null, name: string, fallback: string, alpha?: number): string {- const raw = style?.getPropertyValue(name).trim() ?? "";- if (!raw) return fallback;- return alpha === undefined ? `hsl(${raw})` : `hsl(${raw} / ${alpha})`;-}--/** An offscreen canvas of `cssW × cssH` CSS px at `ratio`, or null without a 2D canvas (headless test DOM). */-export function offscreenLayer(cssW: number, cssH: number, ratio: number): { canvas: HTMLCanvasElement; ctx: CanvasRenderingContext2D; ratio: number } | null {- if (typeof document === "undefined" || cssW <= 0 || cssH <= 0) return null;- // Keep a layer under ~4k px per side even on very dense screens.- const k = Math.max(0.5, Math.min(ratio, 4096 / Math.max(cssW, cssH)));- const canvas = document.createElement("canvas");- canvas.width = Math.max(1, Math.round(cssW * k));- canvas.height = Math.max(1, Math.round(cssH * k));- let ctx: CanvasRenderingContext2D | null = null;- try {- ctx = canvas.getContext("2d");- } catch {- // jsdom without the canvas package throws "not implemented": no picture, the chrome still renders.- ctx = null;- }- if (!ctx) return null;- ctx.setTransform(k, 0, 0, k, 0, 0);- return { canvas, ctx, ratio: k };-}--/** The 2D context of a visible canvas, or null (headless test DOM). */-export function context2d(canvas: HTMLCanvasElement | null): CanvasRenderingContext2D | null {- if (!canvas) return null;- try {- return canvas.getContext("2d");- } catch {- // jsdom without the canvas package: nothing to paint on.- return null;- }-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/memoryBubble.test.ts b/dodaios/ui/web/frontend/src/components/society/office/memoryBubble.test.tsdeleted file mode 100644index dbb6af4ae3..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/memoryBubble.test.ts+++ /dev/null@@ -1,27 +0,0 @@-import { describe, expect, it } from "vitest";-import { memoryLine, type MemoryLabels } from "./memoryBubble";--const LABELS: MemoryLabels = {- updating: "Updating memory", updatingFile: "Updating memory · {0}",- saved: "Memory saved", savedFile: "Saved to {0}",- failed: "Memory not saved", failedFile: "Couldn't save {0}",-};--describe("memoryLine", () => {- it("names the file being written", () => {- expect(memoryLine({ phase: "pending", files: ["MEMORY.md"], atMs: 0 }, LABELS)).toEqual({ phase: "pending", text: "Updating memory · MEMORY.md" });- });-- it("names every file of concurrent writes", () => {- expect(memoryLine({ phase: "saved", files: ["USER.md", "SOUL.md"], atMs: 0 }, LABELS).text).toBe("Saved to USER.md, SOUL.md");- });-- it("falls back to a plain line while the file is not known", () => {- expect(memoryLine({ phase: "pending", files: [], atMs: 0 }, LABELS).text).toBe("Updating memory");- expect(memoryLine({ phase: "failed", files: [], atMs: 0 }, LABELS).text).toBe("Memory not saved");- });-- it("states a failure as a failure", () => {- expect(memoryLine({ phase: "failed", files: ["SOUL.md"], atMs: 0 }, LABELS)).toEqual({ phase: "failed", text: "Couldn't save SOUL.md" });- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/memoryBubble.ts b/dodaios/ui/web/frontend/src/components/society/office/memoryBubble.tsdeleted file mode 100644index f02fe58e80..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/memoryBubble.ts+++ /dev/null@@ -1,24 +0,0 @@-/**- * The memory line in the lead pet's thought bubble: "Updating memory ·- * MEMORY.md" while a write is pending, "Saved to MEMORY.md" only after the- * backend confirmed the file on disk, "Couldn't save MEMORY.md" when it- * failed. Pure, tested in `memoryBubble.test.ts`; the receipts themselves- * live in `store/memoryWrites.ts`.- */-import type { MemoryNote, MemoryWritePhase } from "@/store/memoryWrites";--export interface MemoryLabels {- updating: string; updatingFile: string;- saved: string; savedFile: string;- failed: string; failedFile: string;-}--export interface MemoryLine { phase: MemoryWritePhase; text: string }--export function memoryLine(note: MemoryNote, labels: MemoryLabels): MemoryLine {- const files = note.files.join(", ");- const [plain, named] = note.phase === "pending"- ? [labels.updating, labels.updatingFile]- : note.phase === "saved" ? [labels.saved, labels.savedFile] : [labels.failed, labels.failedFile];- return { phase: note.phase, text: files ? named.replace("{0}", files) : plain };-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/minimap.test.ts b/dodaios/ui/web/frontend/src/components/society/office/minimap.test.tsdeleted file mode 100644index 43c93ac6f4..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/minimap.test.ts+++ /dev/null@@ -1,368 +0,0 @@-import { describe, expect, it } from "vitest";-import { buildOfficeLayout, type OfficeAgentInput } from "./officeLayout";-import {- MAP_PAINT, STATE_RING, ZOOM_DEFAULT_M, ZOOM_MAX_M, ZOOM_MIN_M, bearingOf, centredTransform, clampToEdge, clampToRect,- clampZoom, columnLabel, compassPosition, compassTicks, drawAgentToken, drawEdgeArrow, drawFloorArt, drawMapLabel, drawPlayerArrow,- fitSheet, fitTransform, minimapCentre, gridLabel, initialOf, inkOn, mapGrid, mapToWorld, pickNearest, placeAt, relativeBearing, shade,- worldToMap, yawToBearing, zoomStep,-} from "./minimap";--const agent = (id: string, provider: string, extra: Partial<OfficeAgentInput> = {}): OfficeAgentInput => ({- agentId: id, name: id, tier: "specialist", providerLabel: provider, state: "idle", createdMs: Number(id.replace(/\D/g, "")) || 0, ...extra,-});--/** A 2D context stand-in that records every call and property write, in order. */-function recorder(): { ctx: CanvasRenderingContext2D; log: string[] } {- const log: string[] = [];- const state: Record<string, unknown> = {};- const ctx = new Proxy(state, {- get(target, prop: string) {- if (prop in target) return target[prop];- if (prop === "createRadialGradient" || prop === "createLinearGradient") return undefined;- return (...args: unknown[]) => { log.push(`${prop}(${args.map((a) => (typeof a === "number" ? a.toFixed(1) : String(a))).join(",")})`); };- },- set(target, prop: string, value) {- target[prop] = value;- log.push(`${prop}=${String(value)}`);- return true;- },- });- return { ctx: ctx as unknown as CanvasRenderingContext2D, log };-}--describe("map transforms", () => {- const bounds = { minX: -10, maxX: 10, minZ: -20, maxZ: 20 };-- it("fits a rect keeping the aspect and centring it inside the padding", () => {- const t = fitTransform(bounds, 220, 300, 10);- expect(t.scale).toBeCloseTo(7); // (300 - 20) / 40- const nw = worldToMap(t, { x: -10, z: -20 });- const se = worldToMap(t, { x: 10, z: 20 });- expect(nw.y).toBeCloseTo(10);- expect(se.y).toBeCloseTo(290);- expect(nw.x + se.x).toBeCloseTo(220);- });-- it("centres the player and shows the zoom's metres across the shorter side", () => {- const t = centredTransform({ x: 12, z: -4 }, 26, 200, 200);- expect(worldToMap(t, { x: 12, z: -4 })).toEqual({ x: 100, y: 100 });- expect(t.scale).toBeCloseTo(200 / 26);- // 13 m east of the player is the right edge; north (−z) is up.- expect(worldToMap(t, { x: 25, z: -4 }).x).toBeCloseTo(200);- expect(worldToMap(t, { x: 12, z: -5 }).y).toBeLessThan(100);- });-- it("round-trips between world and map", () => {- const t = centredTransform({ x: 3, z: 7 }, 40, 200, 160);- for (const p of [{ x: 3.5, z: -7.25 }, { x: -10, z: 20 }, { x: 0, z: 0 }]) {- const back = mapToWorld(t, worldToMap(t, p));- expect(back.x).toBeCloseTo(p.x);- expect(back.z).toBeCloseTo(p.z);- }- });-- it("clamps a click on the railing onto the walkable floor", () => {- expect(clampToRect({ x: 50, z: -50 }, bounds)).toEqual({ x: 10, z: -20 });- });-- it("zooms within 16–60 m", () => {- expect(clampZoom(5)).toBe(ZOOM_MIN_M);- expect(clampZoom(500)).toBe(ZOOM_MAX_M);- expect(clampZoom(Number.NaN)).toBe(ZOOM_DEFAULT_M);- expect(zoomStep(26, 1)).toBeLessThan(26);- expect(zoomStep(26, -1)).toBeGreaterThan(26);- expect(zoomStep(ZOOM_MIN_M, 1)).toBe(ZOOM_MIN_M);- expect(zoomStep(ZOOM_MAX_M, -1)).toBe(ZOOM_MAX_M);- });-});--describe("edge clamping of off-screen agents", () => {- it("leaves a point inside the inset area alone", () => {- const m = clampToEdge({ x: 120, y: 80 }, 200, 200, 12);- expect(m).toMatchObject({ x: 120, y: 80, clamped: false });- });-- it("pulls a point far east onto the right edge, arrow pointing right", () => {- const m = clampToEdge({ x: 900, y: 100 }, 200, 200, 12);- expect(m.clamped).toBe(true);- expect(m.x).toBeCloseTo(188);- expect(m.y).toBeCloseTo(100);- expect(m.angle).toBeCloseTo(0);- });-- it("keeps the direction for a diagonal point and hits the nearer edge", () => {- // Far south-west, steeper than 45°: the bottom edge is reached first.- const m = clampToEdge({ x: 100 - 300, y: 100 + 600 }, 200, 200, 10);- expect(m.clamped).toBe(true);- expect(m.y).toBeCloseTo(190);- expect(m.x).toBeCloseTo(100 - 45);- expect(m.angle).toBeCloseTo(Math.atan2(600, -300));- // Straight north: top edge, arrow pointing up.- const up = clampToEdge({ x: 100, y: -500 }, 200, 200, 10);- expect(up.y).toBeCloseTo(10);- expect(up.angle).toBeCloseTo(-Math.PI / 2);- });-});--describe("compass", () => {- it("measures bearings clockwise from north (−z)", () => {- expect(bearingOf(0, -1)).toBeCloseTo(0);- expect(bearingOf(1, 0)).toBeCloseTo(90);- expect(bearingOf(0, 1)).toBeCloseTo(180);- expect(bearingOf(-1, 0)).toBeCloseTo(270);- expect(bearingOf(-1, -1)).toBeCloseTo(315);- });-- it("reads yaw 0 as facing south and yaw π as facing north", () => {- expect(yawToBearing(0)).toBeCloseTo(180);- expect(yawToBearing(Math.PI) % 360).toBeCloseTo(0);- expect(yawToBearing(Math.PI / 2)).toBeCloseTo(90);- });-- it("wraps relative bearings around north", () => {- expect(relativeBearing(10, 350)).toBeCloseTo(20);- expect(relativeBearing(350, 10)).toBeCloseTo(-20);- expect(relativeBearing(180, 0)).toBeCloseTo(-180);- expect(relativeBearing(90, 90)).toBeCloseTo(0);- });-- it("lays out ticks every 15° with the winds on the 45s, across north", () => {- const ticks = compassTicks(350, 90, 15);- expect(ticks.map((t) => t.deg)).toEqual([315, 330, 345, 0, 15, 30]);- expect(ticks.find((t) => t.deg === 0)?.point).toBe("n");- expect(ticks.find((t) => t.deg === 315)?.point).toBe("nw");- expect(ticks.find((t) => t.deg === 330)?.point).toBeUndefined();- const north = ticks.find((t) => t.deg === 0)!;- expect(north.at).toBeCloseTo(0.5 + 10 / 90);- for (const t of ticks) {- expect(t.at).toBeGreaterThanOrEqual(0);- expect(t.at).toBeLessThanOrEqual(1);- }- });-- it("places pips by bearing and hides those outside the span", () => {- expect(compassPosition(0, 0, 150)).toBeCloseTo(0.5);- expect(compassPosition(5, 355, 150)).toBeCloseTo(0.5 + 10 / 150);- expect(compassPosition(180, 0, 150)).toBeNull();- });-});--describe("full-map grid", () => {- const bounds = { minX: -20, maxX: 20, minZ: -30, maxZ: 31 };-- it("uses square cells: 8 lettered columns and as many rows as the depth needs", () => {- const grid = mapGrid(bounds, 8);- expect(grid.cell).toBeCloseTo(5);- expect(grid.columns).toBe(8);- expect(grid.rows).toBe(13); // 61 m / 5 m → 12.2 → 13- });-- it("labels columns A… and rows 1…", () => {- expect([0, 1, 7, 25, 26, 27].map(columnLabel)).toEqual(["A", "B", "H", "Z", "AA", "AB"]);- const grid = mapGrid(bounds, 8);- expect(gridLabel(grid, { x: -19.9, z: -29.9 })).toBe("A1");- expect(gridLabel(grid, { x: 0.1, z: 0.1 })).toBe("E7");- expect(gridLabel(grid, { x: 19.99, z: 30.9 })).toBe("H13");- // Points off the grid clamp onto its edge cells.- expect(gridLabel(grid, { x: 999, z: -999 })).toBe("H1");- });-});--describe("hit testing", () => {- const items = [{ id: "a", x: 100, y: 100 }, { id: "b", x: 104, y: 100 }, { id: "c", x: 150, y: 150 }];-- it("picks the closest marker within the radius", () => {- expect(pickNearest(items, { x: 103, y: 100 }, 10)?.id).toBe("b");- expect(pickNearest(items, { x: 101, y: 101 }, 10)?.id).toBe("a");- expect(pickNearest(items, { x: 150, y: 157 }, 8)?.id).toBe("c");- expect(pickNearest(items, { x: 150, y: 170 }, 8)).toBeNull();- });-- it("hits an off-screen agent at its clamped edge position", () => {- const t = centredTransform({ x: 0, z: 0 }, 20, 200, 200);- const far = worldToMap(t, { x: 80, z: 0 });- const edge = clampToEdge(far, 200, 200, 12);- expect(pickNearest([{ id: "far", x: edge.x, y: edge.y }], { x: 186, y: 101 }, 10)?.id).toBe("far");- });-- it("names the place under a point: checkpoint, then room, then studio, then the campus zone", () => {- const layout = buildOfficeLayout([agent("a1", "codex"), agent("a2", "gemini")], {- teams: [{ id: "t1", name: "Core", members: ["a1"], createdMs: 1 }],- });- const manage = layout.checkpoints.find((c) => c.id === "manage")!;- expect(placeAt(layout, manage)).toEqual({ kind: "checkpoint", id: "manage" });- const lead = layout.rooms.find((r) => r.kind === "lead")!;- expect(placeAt(layout, { x: lead.minX + 0.3, z: lead.minZ + 0.3 })).toEqual({ kind: "room", id: "lead" });- // The pool studio has no name of its own; a team's studio carries the team's.- const [pool, core] = layout.departments;- expect(placeAt(layout, { x: pool.minX + 0.2, z: pool.minZ + 0.2 })).toEqual({ kind: "department", label: "" });- expect(placeAt(layout, { x: core.minX + 0.2, z: core.minZ + 0.2 })).toEqual({ kind: "department", label: "Core" });- // Between the studios: the most specific zone wins where they overlap.- const zone = (kind: string) => layout.zones!.find((z) => z.kind === kind)!;- const mid = (kind: string) => ({ x: (zone(kind).minX + zone(kind).maxX) / 2, z: (zone(kind).minZ + zone(kind).maxZ) / 2 });- const atrium = zone("atrium");- expect(placeAt(layout, { x: atrium.minX + 0.5, z: atrium.minZ + 0.5 })).toEqual({ kind: "zone", id: "atrium" });- expect(placeAt(layout, { x: zone("plaza").minX + 0.5, z: atrium.minZ + 0.5 })).toEqual({ kind: "zone", id: "plaza" });- expect(placeAt(layout, { x: 0, z: zone("boulevard").minZ + 0.5 })).toEqual({ kind: "zone", id: "boulevard" });- for (const kind of ["plot", "garden", "booths", "library", "cafe"] as const) expect(placeAt(layout, mid(kind)), kind).toEqual({ kind: "zone", id: kind });- expect(placeAt(layout, { x: layout.bounds.minX + 0.01, z: 0 })).toBeNull();- // The coding floor has no zones: open floor stays nameless.- const coding = buildOfficeLayout([], { variant: "coding" });- expect(placeAt(coding, coding.arrival)).toEqual({ kind: "checkpoint", id: "launch" });- expect(placeAt(coding, { x: 0, z: coding.arrival.z + 1.4 })).toBeNull();- });-});--describe("the minimap's framing", () => {- const bounds = { minX: -26, maxX: 26, minZ: -23.5, maxZ: 23.5 };-- it("follows the person in the middle of the floor and stays on the floor at its edges", () => {- // In the open: centred on the person.- expect(minimapCentre({ x: 3, z: -2 }, bounds, 26)).toEqual({ x: 3, z: -2 });- // At the elevator by the south window: the card stops a step past the edge instead of showing half a card of night.- const south = minimapCentre({ x: -9, z: 20.9 }, bounds, 26);- expect(south.x).toBe(-9);- expect(south.z).toBeCloseTo(23.5 + 1.5 - 13, 9);- // In a corner both axes hold.- expect(minimapCentre({ x: 25, z: -23 }, bounds, 26)).toEqual({ x: 26 + 1.5 - 13, z: -23.5 - 1.5 + 13 });- // The person is still on the card.- const t = centredTransform(south, 26, 200, 200);- const me = worldToMap(t, { x: -9, z: 20.9 });- expect(me.y).toBeGreaterThan(100);- expect(me.y).toBeLessThan(200);- });-- it("centres a floor that is narrower than the view", () => {- const hall = { minX: -6.2, maxX: 6.2, minZ: -21.8, maxZ: 21.8 };- const centre = minimapCentre({ x: -3.4, z: 17 }, hall, 26);- expect(centre.x).toBeCloseTo(0, 9);- expect(centre.z).toBeCloseTo(21.8 + 1.5 - 13, 9);- // Zoomed out past the whole floor, the floor sits in the middle whatever the person does.- expect(minimapCentre({ x: 20, z: 20 }, bounds, 90)).toEqual({ x: 0, z: 0 });- });-});--describe("the full map's sheet", () => {- it("takes the plan's shape, so no band of the sheet stays empty", () => {- const pad = 30, head = 46;- // A nearly square plan in a wide space: full height, only as wide as the plan needs.- const square = fitSheet({ minX: 0, maxX: 52, minZ: 0, maxZ: 47 }, 1400, 800, pad, head);- expect(square.height).toBe(800);- expect((square.width - pad * 2) / (square.height - head - pad * 2)).toBeCloseTo(52 / 47, 1);- expect(square.width).toBeLessThan(1000);- // A plan taller than wide gets a narrow sheet; a wide plan is held by the width instead.- const tall = fitSheet({ minX: 0, maxX: 52, minZ: 0, maxZ: 81 }, 1400, 800, pad, head);- expect(tall.width).toBeLessThan(square.width);- const wide = fitSheet({ minX: 0, maxX: 120, minZ: 0, maxZ: 30 }, 900, 800, pad, head);- expect(wide.width).toBe(900);- expect(wide.height).toBeLessThan(800);- expect((wide.width - pad * 2) / (wide.height - head - pad * 2)).toBeCloseTo(4, 1);- // Never wider than the cap, never taller than the space.- expect(fitSheet({ minX: 0, maxX: 100, minZ: 0, maxZ: 40 }, 3000, 900, pad, head).width).toBe(1200);- });-- it("keeps a long name over its own place: smaller first, then cut", () => {- const calls: string[] = [];- let font = "";- const ctx = {- set font(value: string) { font = value; },- get font() { return font; },- // Seven pixels a letter at 12 px, scaling with the size.- measureText: (text: string) => ({ width: text.length * 7 * (Number(/([0-9.]+)px/.exec(font)?.[1] ?? 12) / 12) }),- strokeText: (text: string) => { calls.push(text); },- fillText: (text: string) => { calls.push(text); },- } as unknown as CanvasRenderingContext2D;- drawMapLabel(ctx, "CORE", 0, 0, 12, 800, 80);- expect(calls.at(-1)).toBe("CORE");- expect(font).toContain("12px");- drawMapLabel(ctx, "PLATFORM TEAM", 0, 0, 12, 800, 80);- expect(calls.at(-1)).toBe("PLATFORM TEAM");- expect(font).not.toContain(" 12px");- drawMapLabel(ctx, "THE VERY LONG NAME OF A TEAM", 0, 0, 12, 800, 80);- expect(calls.at(-1)!.endsWith("…")).toBe(true);- expect(calls.at(-1)!.length).toBeLessThan(20);- });-});--describe("colour helpers", () => {- it("shades hex colours and passes anything else through", () => {- expect(shade("#808080", -1)).toBe("#000000");- expect(shade("#808080", 1)).toBe("#ffffff");- expect(shade("#fff", -0.5)).toBe("#808080");- expect(shade("hsl(1 2% 3%)", -0.3)).toBe("hsl(1 2% 3%)");- });-- it("picks readable ink and initials", () => {- expect(inkOn("#ffffff")).not.toBe("#ffffff");- expect(inkOn("#1b1f2a")).toBe("#ffffff");- expect(initialOf(" ada")).toBe("A");- expect(initialOf("")).toBe("?");- });-});--describe("drawing", () => {- const layout = buildOfficeLayout([agent("a1", "codex"), agent("a2", "codex", { state: "working" }), agent("l", "", { tier: "lead" })]);-- it("paints the floor art with every wall segment", () => {- const { ctx, log } = recorder();- const t = fitTransform(layout.bounds, 220, 300);- drawFloorArt(ctx, layout, t, layout.bounds);- expect(log[0]).toBe("globalAlpha=1");- expect(log).toContain(`fillStyle=${MAP_PAINT.space}`);- expect(log).toContain(`fillStyle=${MAP_PAINT.floor}`);- expect(log).toContain(`strokeStyle=${MAP_PAINT.wall}`);- // Walls are the only straight segments started with moveTo after the planks; at least one per wall.- expect(log.filter((l) => l.startsWith("moveTo")).length).toBeGreaterThanOrEqual(layout.walls.length);- expect(log[log.length - 1]).not.toMatch(/^globalAlpha=0/);- });-- it("paints the campus: paved boulevards, planted ground, the free plot, the atrium, trees and every studio's name wall", () => {- const { ctx, log } = recorder();- drawFloorArt(ctx, layout, fitTransform(layout.bounds, 420, 360), layout.bounds);- for (const colour of [MAP_PAINT.paving, MAP_PAINT.moss, MAP_PAINT.felt, MAP_PAINT.tile, MAP_PAINT.plot, MAP_PAINT.atrium, MAP_PAINT.olive,- MAP_PAINT.tree, MAP_PAINT.bench, MAP_PAINT.screen, MAP_PAINT.oak, MAP_PAINT.sofa, MAP_PAINT.counter]) {- expect(log, colour).toContain(`fillStyle=${colour}`);- }- // The plot is outlined dashed, in the bronze of the atrium's ring.- expect(log).toContain(`strokeStyle=${MAP_PAINT.inlay}`);- expect(log.some((l) => l.startsWith("setLineDash(") && l !== "setLineDash()")).toBe(true);- // A round mark per tree and per standing table, besides the atrium's disc.- const round = layout.ambience!.filter((i) => i.kind === "olive" || i.kind === "tree" || i.kind === "hightable").length;- expect(log.filter((l) => l.startsWith("arc(")).length).toBeGreaterThanOrEqual(round + 1);- // The coding floor paints none of it.- const above = recorder();- const coding = buildOfficeLayout([agent("p1", "Website")], { variant: "coding" });- drawFloorArt(above.ctx, coding, fitTransform(coding.bounds, 220, 300), coding.bounds);- for (const colour of [MAP_PAINT.paving, MAP_PAINT.moss, MAP_PAINT.plot, MAP_PAINT.olive]) expect(above.log).not.toContain(`fillStyle=${colour}`);- });-- it("rings tokens by state, dashes the paused one and prints the initial", () => {- const { ctx, log } = recorder();- const base = { x: 50, y: 50, colour: "#336699", selected: false };- drawAgentToken(ctx, { ...base, id: "w", name: "Wes", state: "working" }, 6, null);- drawAgentToken(ctx, { ...base, id: "q", name: "quinn", state: "waiting", selected: true }, 6, 0.5);- drawAgentToken(ctx, { ...base, id: "p", name: "Pia", state: "paused" }, 6, null);- expect(log).toContain(`strokeStyle=${STATE_RING.working}`);- expect(log).toContain(`strokeStyle=${STATE_RING.waiting}`);- expect(log.some((l) => l.startsWith("setLineDash(2,2"))).toBe(true);- expect(log.some((l) => l.startsWith("fillText(W,"))).toBe(true);- expect(log.some((l) => l.startsWith("fillText(Q,"))).toBe(true);- // The selected token gets a halo ring with a pulse-dependent alpha.- expect(log).toContain("strokeStyle=rgba(255,255,255,0.450)");- });-- it("points the player arrow and the edge arrow the right way", () => {- const { ctx, log } = recorder();- // Heading π looks north: the arrow tip lies above the player.- drawPlayerArrow(ctx, 100, 100, Math.PI, 9);- const tip = log.find((l) => l.startsWith("moveTo"))!;- const [, y] = tip.slice("moveTo(".length, -1).split(",").map(Number);- expect(y).toBeLessThan(100);-- const edge = recorder();- drawEdgeArrow(edge.ctx, 188, 100, 0, { colour: "#336699", state: "idle", selected: false });- const edgeTip = edge.log.find((l) => l.startsWith("moveTo"))!;- const [ex] = edgeTip.slice("moveTo(".length, -1).split(",").map(Number);- expect(ex).toBeGreaterThan(188);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/minimap.ts b/dodaios/ui/web/frontend/src/components/society/office/minimap.tsdeleted file mode 100644index 4407e5320b..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/minimap.ts+++ /dev/null@@ -1,916 +0,0 @@-/**- * The office maps as pure math and drawing code: the player-centred minimap,- * the compass bar and the full map share one world → map transform and one- * painted art style (a game-style map: warm floor, coloured rooms with soft- * outlines, carpets, tiny desks, crisp walls, gold checkpoint icons).- *- * Map space is CSS pixels on a canvas: +x right (east), +y down (south), so- * every map is north-up. World north is −z. Compass bearings are degrees- * clockwise from north (east = 90). Nothing here touches the DOM, so the- * transforms, clamping, bearings, grid labels and hit-testing are unit-tested- * and the drawing takes any 2D context (an offscreen layer or a test recorder).- */-import type { SkyPad } from "./skyPad";-import { CHECKPOINT_GOLD, DEPARTMENT_TINTS, ROOM_FLOOR_COLOURS } from "./officePalette";-import {- FURNITURE_SIZE, allDesks, deskRect, footprint, roomAt,- type CampusZoneKind, type CheckpointKind, type FurnitureKind, type OfficeLayout, type Point, type Rect, type RoomKind,-} from "./officeLayout";--export type MinimapAgentState = "idle" | "working" | "waiting" | "paused";--export interface MapTransform {- /** Map pixels per metre. */- scale: number;- /** Map position of the world origin. */- offsetX: number;- offsetY: number;- width: number;- height: number;-}--export interface MapPoint { x: number; y: number }--// ---------------------------------------------------------------- transforms--/** Fit `bounds` into a widthPx × heightPx map with `padding` on every side, keeping the aspect and centring. */-export function fitTransform(bounds: Rect, widthPx: number, heightPx: number, padding = 6): MapTransform {- const bw = Math.max(1e-6, bounds.maxX - bounds.minX);- const bh = Math.max(1e-6, bounds.maxZ - bounds.minZ);- const innerW = Math.max(1, widthPx - padding * 2);- const innerH = Math.max(1, heightPx - padding * 2);- const scale = Math.min(innerW / bw, innerH / bh);- const offsetX = (widthPx - bw * scale) / 2 - bounds.minX * scale;- const offsetY = (heightPx - bh * scale) / 2 - bounds.minZ * scale;- return { scale, offsetX, offsetY, width: widthPx, height: heightPx };-}--/** A north-up map `metresAcross` wide (along its shorter side) with `centre` in the middle of the canvas. */-export function centredTransform(centre: Point, metresAcross: number, widthPx: number, heightPx: number): MapTransform {- const scale = Math.min(widthPx, heightPx) / Math.max(1e-6, metresAcross);- return { scale, offsetX: widthPx / 2 - centre.x * scale, offsetY: heightPx / 2 - centre.z * scale, width: widthPx, height: heightPx };-}--/**- * Where the minimap looks: at the person, but never further than `margin` metres past the floor's edge — standing- * at a window or by the elevator, the card shows the floor behind the person instead of half a card of night.- * A floor narrower than the view on an axis is simply centred on it.- */-export function minimapCentre(at: Point, bounds: Rect, metresAcross: number, margin = 1.5): Point {- const half = metresAcross / 2;- const hold = (value: number, min: number, max: number) => {- const low = min - margin + half, high = max + margin - half;- return low > high ? (min + max) / 2 : Math.min(high, Math.max(low, value));- };- return { x: hold(at.x, bounds.minX, bounds.maxX), z: hold(at.z, bounds.minZ, bounds.maxZ) };-}--export function worldToMap(t: MapTransform, p: Point): MapPoint {- return { x: t.offsetX + p.x * t.scale, y: t.offsetY + p.z * t.scale };-}--export function mapToWorld(t: MapTransform, p: MapPoint): Point {- return { x: (p.x - t.offsetX) / t.scale, z: (p.y - t.offsetY) / t.scale };-}--/**- * The size of the full map's sheet for a plan: as tall as the space allows, as wide as the plan's shape asks —- * or, where that is too wide, the full width and less height. The sheet then holds the plan with `pad` px round- * it and nothing else, whatever the floor's proportions. `chromeH` is the sheet's header.- */-export function fitSheet(plan: Rect, availW: number, availH: number, pad: number, chromeH: number, maxW = 1200): { width: number; height: number } {- const aspect = Math.max(1e-6, plan.maxX - plan.minX) / Math.max(1e-6, plan.maxZ - plan.minZ);- const widest = Math.max(1, Math.min(availW, maxW));- let bodyH = Math.max(pad * 2 + 1, availH - chromeH);- let width = (bodyH - pad * 2) * aspect + pad * 2;- if (width > widest) {- width = widest;- bodyH = (width - pad * 2) / aspect + pad * 2;- }- return { width: Math.round(width), height: Math.round(bodyH + chromeH) };-}--/** Clamp a world point onto the walkable floor (a click on the railing still means "over there"). */-export function clampToRect(p: Point, r: Rect): Point {- return { x: Math.min(r.maxX, Math.max(r.minX, p.x)), z: Math.min(r.maxZ, Math.max(r.minZ, p.z)) };-}--// ---------------------------------------------------------------------- zoom--/** Minimap zoom: metres across the card. The widest step shows the agents floor's campus from window to window. */-export const ZOOM_MIN_M = 16;-export const ZOOM_MAX_M = 90;-export const ZOOM_DEFAULT_M = 26;--export function clampZoom(metres: number): number {- if (!Number.isFinite(metres)) return ZOOM_DEFAULT_M;- return Math.min(ZOOM_MAX_M, Math.max(ZOOM_MIN_M, metres));-}--/** One zoom step: `direction` > 0 zooms in (fewer metres), < 0 zooms out. */-export function zoomStep(metres: number, direction: number): number {- if (direction === 0) return clampZoom(metres);- return clampZoom(Math.round(metres * (direction > 0 ? 1 / 1.25 : 1.25)));-}--// ------------------------------------------------------------- edge clamping--export interface EdgeMarker extends MapPoint {- /** True when the point lay outside the inset area and was pulled onto its edge. */- clamped: boolean;- /** Direction from the map centre to the real point, radians, canvas convention (0 = right, π/2 = down). */- angle: number;-}--/**- * Keep a marker inside a width × height map with `inset` px of margin. A point- * outside is pulled towards the centre onto the inset edge (like an off-screen- * teammate on a game minimap), keeping its direction.- */-export function clampToEdge(p: MapPoint, width: number, height: number, inset: number): EdgeMarker {- const cx = width / 2;- const cy = height / 2;- const dx = p.x - cx;- const dy = p.y - cy;- const angle = Math.atan2(dy, dx);- const hw = Math.max(0, cx - inset);- const hh = Math.max(0, cy - inset);- if (Math.abs(dx) <= hw && Math.abs(dy) <= hh) return { x: p.x, y: p.y, clamped: false, angle };- const k = Math.min(Math.abs(dx) > 1e-9 ? hw / Math.abs(dx) : Infinity, Math.abs(dy) > 1e-9 ? hh / Math.abs(dy) : Infinity);- return { x: cx + dx * k, y: cy + dy * k, clamped: true, angle };-}--// ------------------------------------------------------------------- compass--function wrap360(deg: number): number {- const d = deg % 360;- return d < 0 ? d + 360 : d;-}--/** Compass bearing (degrees clockwise from north, [0, 360)) of a world direction; north is −z. */-export function bearingOf(dx: number, dz: number): number {- if (Math.abs(dx) < 1e-12 && Math.abs(dz) < 1e-12) return 0;- return wrap360((Math.atan2(dx, -dz) * 180) / Math.PI);-}--/** Bearing of a yaw/heading (direction = (sin yaw, cos yaw), so yaw 0 looks south = 180°). */-export function yawToBearing(yaw: number): number {- return bearingOf(Math.sin(yaw), Math.cos(yaw));-}--/** Signed angle from `heading` to `bearing`, in [-180, 180): negative = to the left. */-export function relativeBearing(bearing: number, heading: number): number {- return wrap360(bearing - heading + 180) - 180;-}--/** Compass point keys (8 winds) in bearing order; labels come from i18n. */-export const COMPASS_POINTS = ["n", "ne", "e", "se", "s", "sw", "w", "nw"] as const;-export type CompassPoint = (typeof COMPASS_POINTS)[number];--export interface CompassTick {- /** Bearing of the tick, [0, 360). */- deg: number;- /** Horizontal position as a fraction of the bar width, 0 = left edge, 1 = right edge. */- at: number;- /** Set on the eight winds (every 45°). */- point?: CompassPoint;- major: boolean;-}--/** Ticks every `stepDeg` visible on a bar that spans `spanDeg` centred on `heading`. */-export function compassTicks(heading: number, spanDeg: number, stepDeg = 15): CompassTick[] {- const out: CompassTick[] = [];- const half = spanDeg / 2;- const first = Math.ceil((heading - half) / stepDeg) * stepDeg;- for (let raw = first; raw <= heading + half + 1e-9; raw += stepDeg) {- const deg = wrap360(raw);- const rounded = Math.round(deg * 1000) / 1000;- const isWind = Math.abs(rounded % 45) < 1e-6;- out.push({- deg: rounded,- at: (raw - (heading - half)) / spanDeg,- point: isWind ? COMPASS_POINTS[Math.round(rounded / 45) % 8] : undefined,- major: isWind,- });- }- return out;-}--/** Where a bearing sits on the bar (fraction of the width), or null when it lies outside the span. */-export function compassPosition(bearing: number, heading: number, spanDeg: number): number | null {- const rel = relativeBearing(bearing, heading);- if (Math.abs(rel) > spanDeg / 2) return null;- return 0.5 + rel / spanDeg;-}--// ---------------------------------------------------------------------- grid--export interface MapGrid {- columns: number;- rows: number;- /** Cell edge in metres (square cells). */- cell: number;- originX: number;- originZ: number;-}--/** A square grid over `bounds`: `columns` letters across, as many numbered rows as the depth needs. */-export function mapGrid(bounds: Rect, columns = 8): MapGrid {- const width = Math.max(1e-6, bounds.maxX - bounds.minX);- const depth = Math.max(1e-6, bounds.maxZ - bounds.minZ);- const cell = width / Math.max(1, columns);- return { columns: Math.max(1, columns), rows: Math.max(1, Math.ceil(depth / cell - 1e-6)), cell, originX: bounds.minX, originZ: bounds.minZ };-}--/** Column letters A, B, … Z, AA, AB, … */-export function columnLabel(index: number): string {- let n = Math.max(0, Math.floor(index));- let out = "";- do {- out = String.fromCharCode(65 + (n % 26)) + out;- n = Math.floor(n / 26) - 1;- } while (n >= 0);- return out;-}--/** The grid cell of a world point, like "C4", clamped onto the grid. */-export function gridLabel(grid: MapGrid, p: Point): string {- const col = Math.min(grid.columns - 1, Math.max(0, Math.floor((p.x - grid.originX) / grid.cell)));- const row = Math.min(grid.rows - 1, Math.max(0, Math.floor((p.z - grid.originZ) / grid.cell)));- return `${columnLabel(col)}${row + 1}`;-}--// --------------------------------------------------------------- hit testing--/** The item whose map point is closest to `at` within `radiusPx`, or null. */-export function pickNearest<T extends MapPoint>(items: readonly T[], at: MapPoint, radiusPx: number): T | null {- let best: T | null = null;- let bestD = radiusPx * radiusPx;- for (const item of items) {- const d = (item.x - at.x) ** 2 + (item.y - at.y) ** 2;- if (d <= bestD) { best = item; bestD = d; }- }- return best;-}--export type MinimapPlace =- | { kind: "checkpoint"; id: CheckpointKind }- | { kind: "room"; id: RoomKind }- | { kind: "department"; label: string }- | { kind: "zone"; id: CampusZoneKind };--/** Campus zones overlap (the atrium lies on the plaza, the plaza crosses the boulevard): the most specific one names a point. */-const ZONE_PRIORITY: readonly CampusZoneKind[] = ["atrium", "plot", "garden", "booths", "library", "cafe", "plaza", "boulevard"];--/**- * What lies under a world point: a checkpoint (within its radius) beats a room, a room beats a department (on the- * agents floor: a team studio), and a studio beats the campus zone round it.- */-export function placeAt(layout: OfficeLayout, p: Point): MinimapPlace | null {- for (const cp of layout.checkpoints) {- if ((cp.x - p.x) ** 2 + (cp.z - p.z) ** 2 <= cp.radius * cp.radius) return { kind: "checkpoint", id: cp.id };- }- const room = roomAt(layout, p);- if (room) return { kind: "room", id: room.kind };- const within = (r: Rect) => p.x >= r.minX && p.x <= r.maxX && p.z >= r.minZ && p.z <= r.maxZ;- const dept = layout.departments.find(within);- if (dept) return { kind: "department", label: dept.label };- const zones = (layout.zones ?? []).filter(within);- for (const kind of ZONE_PRIORITY) if (zones.some((z) => z.kind === kind)) return { kind: "zone", id: kind };- return null;-}--// -------------------------------------------------------------------- colour--function parseHex(hex: string): [number, number, number] | null {- const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(hex.trim());- if (!m) return null;- const h = m[1].length === 3 ? m[1].split("").map((c) => c + c).join("") : m[1];- return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)];-}--/** Lighten (amount > 0) or darken (< 0) a hex colour by mixing with white or black. Non-hex passes through. */-export function shade(hex: string, amount: number): string {- const rgb = parseHex(hex);- if (!rgb) return hex;- const target = amount >= 0 ? 255 : 0;- const k = Math.min(1, Math.abs(amount));- const out = rgb.map((c) => Math.round(c + (target - c) * k));- return `#${out.map((c) => c.toString(16).padStart(2, "0")).join("")}`;-}--/** Dark or white ink for text on a hex background (white for anything that is not hex). */-export function inkOn(hex: string): string {- const rgb = parseHex(hex);- if (!rgb) return "#ffffff";- const [r, g, b] = rgb.map((c) => {- const s = c / 255;- return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;- });- return 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.45 ? "#1b1f2a" : "#ffffff";-}--/** First letter of a name for a portrait token ("?" when empty). */-export function initialOf(name: string): string {- const ch = name.trim().charAt(0);- return ch ? ch.toLocaleUpperCase() : "?";-}--// ------------------------------------------------------------ painted palette--/**- * The map art's own colours. Like the 3D diorama the painted map looks the- * same in light and dark mode; only the chrome around it reads theme tokens.- */-export const MAP_PAINT = {- space: "#121833",- star: "#e8ecff",- slab: "#474d5c",- slabEdge: "#2c303b",- railing: "#c9ced6",- floor: "#e9d3ad",- plank: "#b98a5e",- deskTop: "#fbf3e2",- deskEdge: "#9c7b58",- monitor: "#2a2d35",- wall: "#2b2f3a",- glass: "#d9f0ff",- furniture: "#8d7a66",- plant: "#5fa35a",- rug: "#d8c8ae",- // Agents floor: the boulevards' limestone, the atrium's disc and bronze ring, planted ground, a free plot, trees and benches.- paving: "#e6dfd1",- atrium: "#f3eee4",- inlay: "#a8865a",- moss: "#c3d0ae",- felt: "#c3cbd3",- tile: "#eadfcd",- plot: "#f1eadc",- olive: "#6f9a5f",- tree: "#4f8a55",- bench: "#c9a878",- // A studio's screens, and the oak and white of built fittings (booths, step seating, kitchen, cabinets, tables).- screen: "#6f675c",- oak: "#d9bf97",- sofa: "#bdb6aa",- counter: "#f6f3ee",- checkpoint: CHECKPOINT_GOLD.face,- checkpointDeep: CHECKPOINT_GOLD.faceDeep,- checkpointIcon: CHECKPOINT_GOLD.icon,- working: "#4ade80",- waiting: "#fbbf24",- idle: "#aab3c2",- paused: "#aab3c2",- tokenRim: "#1b1f2a",- player: "#ffd23f",- playerRim: "#1b1f2a",- label: "#ffffff",- labelHalo: "rgba(20,24,40,0.85)",-} as const;--const FURNITURE_PAINT: Partial<Record<FurnitureKind, string>> = {- couch: "#4a5366", coffeeTable: "#c89f74", meetingTable: "#c89f74", teamBoard: "#f4f4f0", receptionDesk: "#f2eee6",- lockers: "#5fa8a0", mirror: "#d6ecf8", coffeeBar: "#8a6240", waterCooler: "#6fb7ea", arcade: "#6a58b0",- beanbag: "#e27d60", bookshelf: "#8a6240", plant: MAP_PAINT.plant, rug: MAP_PAINT.rug, elevator: "#c9ced6",- breakSofa: "#d8cdb9", breakSofaCorner: "#d8cdb9", breakTable: "#d6b98f", breakRug: "#e2c9a8", breakBookcase: "#a88660",- readingNook: "#93a58a", foosball: "#3f7d4a", breakPlant: MAP_PAINT.plant, arcadeMat: "#2a2548",- leadWall: "#6a4f37", executiveRug: "#48515e", guestChair: "#b98558", chesterfield: "#8e5a3a", loungeTable: "#b08d5c",- executiveBar: "#8b6b4a", globe: "#5f8f96", floorLamp: "#b08d5c", commandWall: "#3a2a20", commandDesk: "#c9b79c",- serverRack: "#23272e", coldAisle: "#b3bac3", nocConsole: "#2b3038", statusWall: "#1a1d22", ups: "#2b3038", fireSuppression: "#c8262b",- teamWall: "#b99a72", credenza: "#b99a72", designerPlant: MAP_PAINT.plant, teamRug: "#e6dccb",- wardrobeWall: "#d2b187", dressingMirror: "#e9edf0", tailorDummy: "#e8dfcf", dressingBench: "#7e9378", coatStand: "#a88660",- roundRug: "#e6ddca",- brandWall: "#d2b286", agentTotem: "#2b2f33", lobbySofa: "#efe9de", lobbyArmchair: "#a8653a", lobbyTable: "#e7ddcc",- sideTable: "#f1eeea", lobbyLamp: "#c7a15e", oliveTree: MAP_PAINT.plant, awardCase: "#d2b286", entranceMat: "#3b3a37", lobbyRug: "#e8dfcf",- spawnPad: "#d8c08c", spawnTerminal: "#2b2f33",- retroCabinet: "#7c5cff", prizeCounter: "#d6457f", tokenMachine: "#e0b23a", clawMachine: "#ff5fa2", airHockey: "#3d8bff",- pinball: "#9b5cff", snackCounter: "#c47a3a",- levelWall: "#1d2b52", studioStage: "#e9c46a", rewardPedestal: "#f0e6cf", levelRoad: "#3a4f8f", levelGuide: "#1d2b52",- studioBoard: "#2a2d33", teamStand: "#d9bf97",-};--export const STATE_RING: Record<MinimapAgentState, string> = {- working: MAP_PAINT.working, waiting: MAP_PAINT.waiting, idle: MAP_PAINT.idle, paused: MAP_PAINT.paused,-};--/** Checkpoint icon per checkpoint kind, for the maps' gold badges. */-export const CHECKPOINT_ICON_KEYS: Record<CheckpointKind, "spawn" | "plus" | "list" | "team" | "shirt" | "star" | "coffee" | "elevator" | "target" | "sparkle" | "trophy" | "ship"> = {- spawn: "spawn", launch: "spawn", create: "plus", manage: "list", team: "team", wardrobe: "shirt", lead: "star", break: "coffee", elevator: "elevator", mission: "target",- studio: "sparkle", levels: "trophy", ship: "ship",-};--/** Stroke-only icons in a 24 × 24 box. */-const ICON_PATHS: Record<(typeof CHECKPOINT_ICON_KEYS)[CheckpointKind], string> = {- spawn: "M12 8.5v7M8.5 12h7M5.2 7.5A8 8 0 0 1 18.8 7.5M18.8 16.5A8 8 0 0 1 5.2 16.5",- plus: "M12 5v14M5 12h14",- list: "M9 6h11M9 12h11M9 18h11M4.5 6h.01M4.5 12h.01M4.5 18h.01",- team: "M9 11a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM3 20c0-3.3 2.7-5.5 6-5.5s6 2.2 6 5.5M16.5 11a2.5 2.5 0 1 0 0-5M18 14.5c2 .6 3.5 2.4 3.5 5",- shirt: "M8 3L3 6l2 4 2.5-1v12h9V9l2.5 1 2-4-5-3c-.5 1.5-2 2.5-4 2.5S8.5 4.5 8 3z",- star: "M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z",- coffee: "M4 9h12v5a5 5 0 0 1-5 5H9a5 5 0 0 1-5-5V9zM16 10h1.5a2.5 2.5 0 0 1 0 5H16M8 3.5c0 1 1 1 1 2M12 3.5c0 1 1 1 1 2",- elevator: "M5 3h14v18H5zM9 10l3-3 3 3M9 14l3 3 3-3",- target: "M12 3a9 9 0 1 1 0 18a9 9 0 1 1 0-18zM12 8a4 4 0 1 1 0 8a4 4 0 1 1 0-8zM12 1v4M12 19v4M1 12h4M19 12h4",- sparkle: "M10 3l1.6 5.4L17 10l-5.4 1.6L10 17l-1.6-5.4L3 10l5.4-1.6zM18 14l.8 2.2L21 17l-2.2.8L18 20l-.8-2.2L15 17l2.2-.8z",- ship: "M12 2.5c3 2.6 4.4 6.4 4.4 10.4v4.6l-4.4 2.5-4.4-2.5v-4.6c0-4 1.4-7.8 4.4-10.4zM7.6 14l-3.1 3v3l3.1-1.5M16.4 14l3.1 3v3l-3.1-1.5M12 9.5h.01",- trophy: "M7 4h10v5a5 5 0 0 1-10 0V4zM7 6H4.5a2.5 2.5 0 0 0 2.6 3.6M17 6h2.5a2.5 2.5 0 0 1-2.6 3.6M12 14v3M8 20h8M9.5 17h5",-};--// ------------------------------------------------------------------ drawing--type Ctx = CanvasRenderingContext2D;--function roundRectPath(ctx: Ctx, x: number, y: number, w: number, h: number, r: number): void {- const rr = Math.max(0, Math.min(r, w / 2, h / 2));- ctx.beginPath();- ctx.moveTo(x + rr, y);- ctx.lineTo(x + w - rr, y);- ctx.arcTo(x + w, y, x + w, y + rr, rr);- ctx.lineTo(x + w, y + h - rr);- ctx.arcTo(x + w, y + h, x + w - rr, y + h, rr);- ctx.lineTo(x + rr, y + h);- ctx.arcTo(x, y + h, x, y + h - rr, rr);- ctx.lineTo(x, y + rr);- ctx.arcTo(x, y, x + rr, y, rr);- ctx.closePath();-}--function rectPath(ctx: Ctx, t: MapTransform, r: Rect, radiusM = 0): { x: number; y: number; w: number; h: number } {- const a = worldToMap(t, { x: r.minX, z: r.minZ });- const w = (r.maxX - r.minX) * t.scale;- const h = (r.maxZ - r.minZ) * t.scale;- roundRectPath(ctx, a.x, a.y, w, h, radiusM * t.scale);- return { x: a.x, y: a.y, w, h };-}--/** Small deterministic pseudo-random sequence (stars must not flicker between rebuilds). */-function seeded(seed: number): () => number {- let s = seed >>> 0;- return () => {- s = (s * 1664525 + 1013904223) >>> 0;- return s / 4294967296;- };-}--/**- * The painted floor: night sky with stars, slab and railing, warm planks,- * department carpets, rooms, furniture, desks and crisp walls. `area` is the- * world rectangle to cover (the layout bounds plus any margin the caller wants).- */-export function drawFloorArt(ctx: Ctx, layout: OfficeLayout, t: MapTransform, area: Rect): void {- ctx.globalAlpha = 1;- ctx.fillStyle = MAP_PAINT.space;- const sky = worldToMap(t, { x: area.minX, z: area.minZ });- ctx.fillRect(sky.x, sky.y, (area.maxX - area.minX) * t.scale, (area.maxZ - area.minZ) * t.scale);-- // Stars: about one per 14 m², deterministic per layout size.- const rand = seeded(Math.round((area.maxX - area.minX) * 131 + (area.maxZ - area.minZ) * 17));- const count = Math.min(900, Math.round(((area.maxX - area.minX) * (area.maxZ - area.minZ)) / 14));- ctx.fillStyle = MAP_PAINT.star;- for (let i = 0; i < count; i += 1) {- const p = worldToMap(t, { x: area.minX + rand() * (area.maxX - area.minX), z: area.minZ + rand() * (area.maxZ - area.minZ) });- ctx.globalAlpha = 0.25 + rand() * 0.55;- const r = 0.4 + rand() * 0.8;- ctx.fillRect(p.x - r / 2, p.y - r / 2, r, r);- }- ctx.globalAlpha = 1;-- // Slab with a soft shadow, then the railing line and the warm plank floor.- ctx.save();- ctx.shadowColor = "rgba(0,0,0,0.45)";- ctx.shadowBlur = Math.max(4, t.scale * 0.8);- ctx.fillStyle = MAP_PAINT.slab;- rectPath(ctx, t, layout.bounds, 0.8);- ctx.fill();- ctx.restore();- ctx.strokeStyle = MAP_PAINT.slabEdge;- ctx.lineWidth = 1.5;- ctx.stroke();- if (layout.skyPad) drawSkyPad(ctx, layout.skyPad, t);-- ctx.fillStyle = MAP_PAINT.floor;- rectPath(ctx, t, layout.floor, 0.4);- ctx.fill();- ctx.strokeStyle = MAP_PAINT.railing;- ctx.lineWidth = 1;- ctx.stroke();-- if (t.scale >= 4) {- // Faint plank seams, every 0.9 m, running east-west.- ctx.save();- rectPath(ctx, t, layout.floor, 0.4);- ctx.clip();- ctx.strokeStyle = MAP_PAINT.plank;- ctx.globalAlpha = 0.14;- ctx.lineWidth = 1;- ctx.beginPath();- const left = worldToMap(t, { x: layout.floor.minX, z: 0 }).x;- const right = worldToMap(t, { x: layout.floor.maxX, z: 0 }).x;- for (let z = layout.floor.minZ; z <= layout.floor.maxZ; z += 0.9) {- const y = Math.round(worldToMap(t, { x: 0, z }).y) + 0.5;- ctx.moveTo(left, y);- ctx.lineTo(right, y);- }- ctx.stroke();- ctx.restore();- ctx.globalAlpha = 1;- }-- // Agents floor: the paved boulevards, planted courts, the free plot and the atrium, under everything built on them.- const zones = layout.zones ?? [];- if (zones.length > 0) {- const paint = (kinds: readonly CampusZoneKind[], colour: string, radiusM: number) => {- ctx.fillStyle = colour;- for (const zone of zones) {- if (!kinds.includes(zone.kind)) continue;- rectPath(ctx, t, zone, radiusM);- ctx.fill();- }- };- paint(["boulevard", "plaza"], MAP_PAINT.paving, 0);- paint(["garden"], MAP_PAINT.moss, 0.6);- paint(["booths"], MAP_PAINT.felt, 0.6);- paint(["cafe"], MAP_PAINT.tile, 0.6);- const plot = zones.find((z) => z.kind === "plot");- if (plot) {- rectPath(ctx, t, plot, 0.3);- ctx.fillStyle = MAP_PAINT.plot;- ctx.fill();- // A dashed outline: marked out, not built yet.- ctx.setLineDash?.([Math.max(2, t.scale * 0.5), Math.max(2, t.scale * 0.35)]);- ctx.strokeStyle = MAP_PAINT.inlay;- ctx.lineWidth = Math.max(1, Math.min(2, t.scale * 0.12));- ctx.stroke();- ctx.setLineDash?.([]);- }- const atrium = zones.find((z) => z.kind === "atrium");- if (atrium) {- const c = worldToMap(t, { x: (atrium.minX + atrium.maxX) / 2, z: (atrium.minZ + atrium.maxZ) / 2 });- ctx.beginPath();- ctx.arc(c.x, c.y, 5 * t.scale, 0, Math.PI * 2);- ctx.fillStyle = MAP_PAINT.atrium;- ctx.fill();- ctx.strokeStyle = MAP_PAINT.inlay;- ctx.lineWidth = Math.max(1, t.scale * 0.14);- ctx.stroke();- }- }-- // Department carpets and rooms: painted areas with soft darker outlines.- ctx.lineWidth = Math.max(1, Math.min(2, t.scale * 0.12));- for (const dept of layout.departments) {- const tint = DEPARTMENT_TINTS[dept.tint % DEPARTMENT_TINTS.length];- rectPath(ctx, t, dept, 0.5);- ctx.globalAlpha = 0.85;- ctx.fillStyle = tint;- ctx.fill();- ctx.globalAlpha = 1;- ctx.strokeStyle = shade(tint, -0.3);- ctx.stroke();- }- for (const room of layout.rooms) {- const base = ROOM_FLOOR_COLOURS[room.kind].base;- rectPath(ctx, t, room, room.walled ? 0.15 : 0.5);- ctx.globalAlpha = 0.92;- ctx.fillStyle = base;- ctx.fill();- ctx.globalAlpha = 1;- ctx.strokeStyle = shade(base, -0.32);- ctx.stroke();- }-- // Furniture: rugs first, then solid pieces; plants and beanbags are round.- for (const pass of ["rug", "solid"] as const) {- for (const item of layout.furniture) {- const isRug = item.kind === "rug" || item.kind === "executiveRug" || item.kind === "teamRug"- || item.kind === "breakRug" || item.kind === "arcadeMat" || item.kind === "lobbyRug"- || item.kind === "entranceMat" || item.kind === "roundRug" || item.kind === "spawnPad";- if ((pass === "rug") !== isRug) continue;- const colour = FURNITURE_PAINT[item.kind] ?? MAP_PAINT.furniture;- const fp = footprint(item);- if (item.kind === "plant" || item.kind === "designerPlant" || item.kind === "breakPlant" || item.kind === "beanbag" || item.kind === "spawnPad") {- const c = worldToMap(t, item);- ctx.beginPath();- ctx.arc(c.x, c.y, Math.max(1.2, (FURNITURE_SIZE[item.kind].w / 2) * t.scale * 0.85), 0, Math.PI * 2);- } else {- rectPath(ctx, t, fp, isRug ? 0.3 : 0.08);- }- ctx.fillStyle = colour;- ctx.fill();- if (!isRug) {- ctx.strokeStyle = shade(colour, -0.35);- ctx.lineWidth = 0.8;- ctx.stroke();- }- }- }-- // Agents floor: trees as round crowns (a large tree's spreads wider), standing tables as discs, everything else- // as a block in its own tone: screens dark and slim, sofas soft, built fittings oak or white.- const BLOCK: Record<string, string> = {- bench: MAP_PAINT.bench, planter: MAP_PAINT.plant, screen: MAP_PAINT.screen, cabinet: MAP_PAINT.counter, sofa: MAP_PAINT.sofa,- booth: MAP_PAINT.oak, steps: MAP_PAINT.oak, counter: MAP_PAINT.counter, island: MAP_PAINT.oak, crate: MAP_PAINT.oak,- };- for (const item of layout.ambience ?? []) {- if (item.kind === "olive" || item.kind === "tree" || item.kind === "hightable") {- const c = worldToMap(t, { x: (item.minX + item.maxX) / 2, z: (item.minZ + item.maxZ) / 2 });- const radiusM = item.kind === "tree" ? 1.25 : item.kind === "olive" ? 0.62 : 0.4;- ctx.beginPath();- ctx.arc(c.x, c.y, Math.max(1.4, radiusM * t.scale), 0, Math.PI * 2);- ctx.fillStyle = item.kind === "tree" ? MAP_PAINT.tree : item.kind === "olive" ? MAP_PAINT.olive : MAP_PAINT.oak;- ctx.globalAlpha = item.kind === "hightable" ? 1 : 0.9;- ctx.fill();- ctx.globalAlpha = 1;- } else {- rectPath(ctx, t, item, 0.08);- ctx.fillStyle = BLOCK[item.kind] ?? MAP_PAINT.furniture;- ctx.fill();- if (item.kind === "booth" || item.kind === "steps" || item.kind === "counter" || item.kind === "island" || item.kind === "sofa") {- ctx.strokeStyle = shade(BLOCK[item.kind], -0.3);- ctx.lineWidth = 0.8;- ctx.stroke();- }- }- }- // Agents floor: every studio's name wall along its north edge, in the studio's colour.- if (layout.studios && layout.studios.length > 0) {- ctx.lineCap = "butt";- ctx.lineWidth = Math.max(1.5, Math.min(4, t.scale * 0.22));- for (const dept of layout.departments) {- const a = worldToMap(t, { x: dept.minX + 0.2, z: dept.minZ + 0.11 });- const b = worldToMap(t, { x: dept.maxX - 0.2, z: dept.minZ + 0.11 });- ctx.strokeStyle = shade(DEPARTMENT_TINTS[dept.tint % DEPARTMENT_TINTS.length], -0.45);- ctx.beginPath();- ctx.moveTo(a.x, a.y);- ctx.lineTo(b.x, b.y);- ctx.stroke();- }- }-- // Desks: tiny light blocks with the monitor on the far side from the chair.- for (const desk of allDesks(layout)) {- const c = worldToMap(t, desk);- const rect = deskRect(desk);- const deskW = (rect.maxX - rect.minX) * t.scale;- const deskD = (rect.maxZ - rect.minZ) * t.scale;- roundRectPath(ctx, c.x - deskW / 2, c.y - deskD / 2, deskW, deskD, Math.min(2, deskD * 0.2));- ctx.fillStyle = MAP_PAINT.deskTop;- ctx.fill();- ctx.strokeStyle = MAP_PAINT.deskEdge;- ctx.lineWidth = 0.8;- ctx.stroke();- if (t.scale >= 5) {- const mh = Math.max(1, deskD * 0.18);- // A north-facing agent looks at a monitor on the desk's north edge.- const my = desk.facing === "north" ? c.y - deskD / 2 + mh * 0.6 : c.y + deskD / 2 - mh * 1.6;- ctx.fillStyle = MAP_PAINT.monitor;- ctx.fillRect(c.x - deskW * 0.28, my, deskW * 0.56, mh);- }- }-- // Walls: crisp dark lines with a thin glass highlight; door gaps are simply not drawn.- const wallW = Math.max(1.5, Math.min(3.5, t.scale * 0.2));- ctx.lineCap = "round";- ctx.beginPath();- for (const w of layout.walls) {- const a = worldToMap(t, { x: w.x1, z: w.z1 });- const b = worldToMap(t, { x: w.x2, z: w.z2 });- ctx.moveTo(a.x, a.y);- ctx.lineTo(b.x, b.y);- }- ctx.strokeStyle = MAP_PAINT.wall;- ctx.lineWidth = wallW;- ctx.stroke();- ctx.strokeStyle = MAP_PAINT.glass;- ctx.globalAlpha = 0.55;- ctx.lineWidth = Math.max(0.5, wallW * 0.3);- ctx.stroke();- ctx.globalAlpha = 1;- ctx.lineCap = "butt";-}--/** A gold checkpoint badge (hexagon) with its white icon, `size` px across. */-export function drawCheckpointBadge(ctx: Ctx, x: number, y: number, size: number, kind: CheckpointKind): void {- const r = size / 2;- ctx.beginPath();- for (let i = 0; i < 6; i += 1) {- const a = (Math.PI / 3) * i;- const px = x + Math.cos(a) * r;- const py = y + Math.sin(a) * r;- if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py);- }- ctx.closePath();- ctx.fillStyle = MAP_PAINT.checkpoint;- ctx.fill();- ctx.strokeStyle = MAP_PAINT.checkpointDeep;- ctx.lineWidth = 1.2;- ctx.stroke();- if (typeof Path2D === "undefined") return;- const path = new Path2D(ICON_PATHS[CHECKPOINT_ICON_KEYS[kind]]);- const k = (size * 0.62) / 24;- ctx.save();- ctx.translate(x - 12 * k, y - 12 * k);- ctx.scale(k, k);- ctx.lineCap = "round";- ctx.lineJoin = "round";- ctx.strokeStyle = MAP_PAINT.checkpointIcon;- ctx.lineWidth = 2.6;- ctx.stroke(path);- ctx.restore();-}--/** Every checkpoint of the layout as a badge. */-export function drawCheckpoints(ctx: Ctx, layout: OfficeLayout, t: MapTransform, size: number): void {- for (const cp of layout.checkpoints) {- const m = worldToMap(t, cp);- drawCheckpointBadge(ctx, m.x, m.y, size, cp.id);- }-}--/** The camera's view as a soft white cone from `origin`, fading out towards `reach` px. */-export function drawViewCone(ctx: Ctx, origin: MapPoint, yaw: number, halfWidth: number, reach: number): void {- const half = Math.max(0.12, Math.min(Math.PI / 2 - 0.05, halfWidth));- // World heading (sin, cos) maps straight onto map (x, y): +x east → right, +z south → down.- const centre = Math.atan2(Math.cos(yaw), Math.sin(yaw));- ctx.save();- const grad = typeof ctx.createRadialGradient === "function" ? ctx.createRadialGradient(origin.x, origin.y, 0, origin.x, origin.y, reach) : null;- if (grad) {- grad.addColorStop(0, "rgba(255,255,255,0.55)");- grad.addColorStop(1, "rgba(255,255,255,0)");- ctx.fillStyle = grad;- } else {- ctx.fillStyle = "rgba(255,255,255,0.3)";- }- ctx.beginPath();- ctx.moveTo(origin.x, origin.y);- ctx.arc(origin.x, origin.y, reach, centre - half, centre + half);- ctx.closePath();- ctx.fill();- ctx.restore();-}--/** The person: a bright arrow pointing along `heading` (same convention as the player body). */-export function drawPlayerArrow(ctx: Ctx, x: number, y: number, heading: number, size = 9): void {- const dx = Math.sin(heading);- const dy = Math.cos(heading);- const len = size;- const wing = size * 0.68;- ctx.save();- ctx.shadowColor = "rgba(0,0,0,0.45)";- ctx.shadowBlur = 3;- ctx.beginPath();- ctx.moveTo(x + dx * len, y + dy * len);- ctx.lineTo(x - dx * len * 0.62 + dy * wing, y - dy * len * 0.62 - dx * wing);- ctx.lineTo(x - dx * len * 0.22, y - dy * len * 0.22);- ctx.lineTo(x - dx * len * 0.62 - dy * wing, y - dy * len * 0.62 + dx * wing);- ctx.closePath();- ctx.fillStyle = MAP_PAINT.player;- ctx.fill();- ctx.restore();- ctx.strokeStyle = MAP_PAINT.playerRim;- ctx.lineWidth = 1.4;- ctx.lineJoin = "round";- ctx.stroke();-}--export interface AgentToken extends MapPoint {- id: string;- name: string;- state: MinimapAgentState;- /** The agent's palette colour (token fill). */- colour: string;- selected: boolean;-}--/**- * A round portrait-like token: the agent's initial on its palette colour- * inside a status ring (working green, waiting amber, idle grey, paused a- * hollow dashed ring). `pulse` in [0, 1) animates the selected agent's halo.- */-export function drawAgentToken(ctx: Ctx, token: AgentToken, radius: number, pulse: number | null): void {- const { x, y } = token;- const r = token.selected ? radius * 1.3 : radius;- if (token.selected) {- const phase = pulse ?? 0.35;- ctx.beginPath();- ctx.arc(x, y, r + 3 + phase * 6, 0, Math.PI * 2);- ctx.strokeStyle = `rgba(255,255,255,${(0.9 * (1 - phase)).toFixed(3)})`;- ctx.lineWidth = 2;- ctx.stroke();- }- // Dark rim for contrast on any floor colour.- ctx.beginPath();- ctx.arc(x, y, r + 2.6, 0, Math.PI * 2);- ctx.fillStyle = MAP_PAINT.tokenRim;- ctx.fill();- const ring = STATE_RING[token.state];- ctx.beginPath();- ctx.arc(x, y, r + 1.4, 0, Math.PI * 2);- if (token.state === "paused") {- ctx.setLineDash?.([2, 2]);- ctx.strokeStyle = ring;- ctx.lineWidth = 1.4;- ctx.stroke();- ctx.setLineDash?.([]);- } else {- ctx.strokeStyle = ring;- ctx.lineWidth = 2.2;- ctx.stroke();- }- ctx.beginPath();- ctx.arc(x, y, r - 0.2, 0, Math.PI * 2);- ctx.globalAlpha = token.state === "paused" ? 0.55 : 1;- ctx.fillStyle = token.colour;- ctx.fill();- ctx.globalAlpha = 1;- ctx.fillStyle = inkOn(token.colour);- ctx.font = `800 ${Math.round(r * 1.25)}px system-ui, -apple-system, "Segoe UI", sans-serif`;- ctx.textAlign = "center";- ctx.textBaseline = "middle";- ctx.fillText(initialOf(token.name), x, y + 0.5);-}--/** An off-screen agent on the card edge: a small arrow in its status colour pointing towards it. */-export function drawEdgeArrow(ctx: Ctx, x: number, y: number, angle: number, token: Pick<AgentToken, "colour" | "state" | "selected">): void {- const size = token.selected ? 8 : 6;- const cos = Math.cos(angle);- const sin = Math.sin(angle);- const pt = (along: number, across: number): MapPoint => ({ x: x + cos * along - sin * across, y: y + sin * along + cos * across });- const tip = pt(size, 0);- const l = pt(-size * 0.7, size * 0.75);- const back = pt(-size * 0.25, 0);- const r = pt(-size * 0.7, -size * 0.75);- ctx.beginPath();- ctx.moveTo(tip.x, tip.y);- ctx.lineTo(l.x, l.y);- ctx.lineTo(back.x, back.y);- ctx.lineTo(r.x, r.y);- ctx.closePath();- ctx.fillStyle = token.colour;- ctx.fill();- ctx.strokeStyle = STATE_RING[token.state];- ctx.lineWidth = token.selected ? 2 : 1.5;- ctx.lineJoin = "round";- ctx.stroke();-}--/**- * A game-map label: white text with a dark halo, centred on (x, y). With `maxWidth` (px) a long name first- * shrinks to three quarters of its size and is then cut with an ellipsis, so it stays over its own place.- */-export function drawMapLabel(ctx: Ctx, text: string, x: number, y: number, px: number, weight = 700, maxWidth?: number): void {- if (!text) return;- const font = (size: number) => `${weight} ${size}px system-ui, -apple-system, "Segoe UI", sans-serif`;- ctx.font = font(px);- if (maxWidth !== undefined && typeof ctx.measureText === "function") {- const widthOf = (value: string) => ctx.measureText(value)?.width ?? 0;- let size = px;- while (size > px * 0.75 && widthOf(text) > maxWidth) {- size -= 0.5;- ctx.font = font(size);- }- px = size;- if (widthOf(text) > maxWidth) {- let cut = text;- while (cut.length > 1 && widthOf(`${cut}…`) > maxWidth) cut = cut.slice(0, -1);- text = `${cut.trimEnd()}…`;- }- }- ctx.textAlign = "center";- ctx.textBaseline = "middle";- ctx.lineJoin = "round";- ctx.strokeStyle = MAP_PAINT.labelHalo;- ctx.lineWidth = Math.max(2.5, px * 0.32);- ctx.strokeText(text, x, y);- ctx.fillStyle = MAP_PAINT.label;- ctx.fillText(text, x, y);-}--/** The sky pad outside the east windows: its bridge, the deck with its gold landing circle, and the courier on it. */-function drawSkyPad(ctx: CanvasRenderingContext2D, pad: SkyPad, t: MapTransform): void {- const deck = worldToMap(t, pad.pad), r = pad.pad.r * t.scale;- ctx.fillStyle = MAP_PAINT.slab;- const a = worldToMap(t, { x: pad.bridge.minX, z: pad.gap.minZ }), b = worldToMap(t, { x: pad.pad.x, z: pad.gap.maxZ });- ctx.fillRect(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.abs(b.x - a.x), Math.abs(b.y - a.y));- ctx.beginPath();- ctx.arc(deck.x, deck.y, r, 0, Math.PI * 2);- ctx.fill();- ctx.strokeStyle = MAP_PAINT.slabEdge;- ctx.lineWidth = 1.5;- ctx.stroke();- ctx.strokeStyle = CHECKPOINT_GOLD.rim;- ctx.lineWidth = Math.max(1, t.scale * 0.25);- ctx.beginPath();- ctx.arc(deck.x, deck.y, r * 0.78, 0, Math.PI * 2);- ctx.stroke();- // The courier: a slim lozenge along its heading (north).- const nose = worldToMap(t, { x: pad.ship.x, z: pad.shipRect.minZ + 0.6 }), tail = worldToMap(t, { x: pad.ship.x, z: pad.shipRect.maxZ - 0.6 });- const half = ((pad.shipRect.maxX - pad.shipRect.minX) / 4) * t.scale;- ctx.fillStyle = "#d7dce4";- ctx.beginPath();- ctx.moveTo(nose.x, nose.y);- ctx.lineTo(nose.x + half, (nose.y + tail.y) / 2);- ctx.lineTo(tail.x, tail.y);- ctx.lineTo(nose.x - half, (nose.y + tail.y) / 2);- ctx.closePath();- ctx.fill();-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/missionControl.css b/dodaios/ui/web/frontend/src/components/society/office/missionControl.cssdeleted file mode 100644index 7aa0f0b1b1..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/missionControl.css+++ /dev/null@@ -1,98 +0,0 @@-/* Coding floor command surfaces: the session command panel and Mission Control.- Theme tokens only, so both read in light and dark mode. */--/* ---- shared ----------------------------------------------------------- */-.office-mc-chips button { padding:4px 10px; border:1px solid hsl(var(--border)); border-radius:999px; background:hsl(var(--background)); color:hsl(var(--foreground)); font-size:11px; font-weight:600; cursor:pointer; }-.office-mc-chips button:hover:not(:disabled) { background:hsl(var(--secondary)); }-.office-mc-chips button:disabled { opacity:.45; cursor:not-allowed; }-.office-mc-chips button[aria-pressed="true"] { border-color:hsl(var(--primary)); background:hsl(var(--primary)); color:hsl(var(--primary-foreground)); text-shadow:none; }-.office-mc-chips button:focus-visible, .office-mc-tabs button:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }-.office-talk-status[data-tone="ok"] { color:hsl(var(--success)); }-.office-talk-status[data-tone="error"] { color:hsl(var(--destructive)); white-space:normal; }-.office-cmd-check { display:inline-flex; align-items:center; gap:6px; flex:none; font-size:11px; color:hsl(var(--muted-foreground)); cursor:pointer; }-.office-cmd-check input { accent-color:hsl(var(--primary)); }--/* ---- Mission Control -------------------------------------------------- */-/* Quiet and typographic: sentence-case headings, hairline dividers, one filled- button per block. No tabs, no pills, no icons for decoration. */-.office-mc { display:flex; flex-direction:column; gap:14px; max-width:520px; }-.office-mc-heading { margin:0 0 10px; font-size:13px; font-weight:600; color:hsl(var(--foreground)); letter-spacing:0; }-.office-mc-more { border-top:1px solid hsl(var(--border)); padding-top:12px; }-.office-mc-more > summary { cursor:pointer; list-style:none; display:flex; align-items:center; justify-content:space-between; margin:0; }-.office-mc-more > summary::-webkit-details-marker { display:none; }-.office-mc-more > summary::after { content:""; width:7px; height:7px; border-right:1.5px solid hsl(var(--muted-foreground)); border-bottom:1.5px solid hsl(var(--muted-foreground)); transform:rotate(45deg); transition:transform .15s; margin-right:3px; }-.office-mc-more[open] > summary { margin-bottom:10px; }-.office-mc-more[open] > summary::after { transform:rotate(-135deg); }-.office-mc-block { display:flex; flex-direction:column; gap:10px; }-.office-mc-note { margin:0; font-size:12px; line-height:1.45; color:hsl(var(--muted-foreground)); }-.office-mc-note[data-tone="ok"] { color:hsl(var(--success)); }-.office-mc-empty { display:flex; flex-direction:column; gap:10px; font-size:12px; color:hsl(var(--muted-foreground)); }-.office-mc-empty p { margin:0; }--/* Agent picker: a two-column list of real marks, the chosen one outlined. */-.office-mc-agents { display:grid; grid-template-columns:repeat(2, minmax(0, 1fr)); gap:6px; }-.office-mc-agents button { display:flex; align-items:center; gap:8px; min-width:0; padding:6px 8px; border:1px solid hsl(var(--border)); border-radius:10px; background:hsl(var(--background)); color:hsl(var(--foreground)); font:inherit; font-size:12px; font-weight:500; text-align:left; cursor:pointer; transition:border-color .12s, background .12s; }-.office-mc-agents button span { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }-.office-mc-agents button:hover:not(:disabled) { background:hsl(var(--secondary)); }-.office-mc-agents button[aria-checked="true"] { border-color:hsl(var(--foreground)); box-shadow:inset 0 0 0 1px hsl(var(--foreground)); }-.office-mc-agents button:disabled { opacity:.5; cursor:not-allowed; }--.office-mc-row { display:flex; align-items:center; justify-content:space-between; gap:10px; font-size:12px; color:hsl(var(--muted-foreground)); }-.office-mc-row .office-mc-select { flex:0 1 60%; width:auto; min-width:0; }-.office-mc-row input { flex:0 1 60%; min-width:0; padding:6px 8px; border:1px solid hsl(var(--border)); border-radius:8px; background:hsl(var(--background)); color:hsl(var(--foreground)); font:inherit; font-size:12px; }-.office-mc-row input::placeholder { color:hsl(var(--muted-foreground)); }-.office-mc-task { width:100%; min-height:44px; resize:vertical; padding:9px 10px; border:1px solid hsl(var(--border)); border-radius:10px; background:hsl(var(--background)); color:hsl(var(--foreground)); font:inherit; font-size:13px; line-height:1.4; }-.office-mc-task::placeholder { color:hsl(var(--muted-foreground)); }--.office-mc-go { display:flex; align-items:center; gap:8px; }-.office-mc-stepper { display:inline-flex; align-items:center; border:1px solid hsl(var(--border)); border-radius:10px; overflow:hidden; flex:none; }-.office-mc-stepper button { display:inline-flex; align-items:center; justify-content:center; width:30px; height:34px; border:0; background:none; color:hsl(var(--foreground)); cursor:pointer; }-.office-mc-stepper button svg { width:14px; height:14px; }-.office-mc-stepper button:hover:not(:disabled) { background:hsl(var(--secondary)); }-.office-mc-stepper button:disabled { opacity:.35; cursor:not-allowed; }-.office-mc-stepper output { min-width:22px; text-align:center; font-size:13px; font-weight:600; font-variant-numeric:tabular-nums; }-.office-mc-primary, .office-mc-secondary { flex:1; height:36px; padding:0 14px; border-radius:10px; font:inherit; font-size:13px; font-weight:600; cursor:pointer; transition:opacity .12s, background .12s; }-.office-mc-primary { border:0; background:hsl(var(--foreground)); color:hsl(var(--background)); text-shadow:none; }-.office-mc-primary:hover:not(:disabled) { opacity:.88; }-.office-mc-secondary { border:1px solid hsl(var(--border)); background:hsl(var(--background)); color:hsl(var(--foreground)); flex:0 1 auto; }-.office-mc-secondary:hover:not(:disabled) { background:hsl(var(--secondary)); }-.office-mc-primary:disabled, .office-mc-secondary:disabled { opacity:.4; cursor:not-allowed; }-.office-mc-link { align-self:flex-start; padding:0; border:0; background:none; color:hsl(var(--muted-foreground)); font:inherit; font-size:12px; text-decoration:underline; text-underline-offset:2px; cursor:pointer; }-.office-mc-link:hover { color:hsl(var(--foreground)); }-.office-mc button:focus-visible, .office-mc select:focus-visible, .office-mc input:focus-visible, .office-mc textarea:focus-visible, .office-mc summary:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }--/* Files: the whole launcher takes a drop; what is held sits under the task as quiet chips. */-.office-mc-dropzone { position:relative; }-.office-mc-drophint { position:absolute; inset:-6px; display:flex; align-items:center; justify-content:center; padding:16px; border:1.5px dashed hsl(var(--ring)); border-radius:12px; background:hsl(var(--background) / .9); color:hsl(var(--foreground)); font-size:13px; font-weight:600; text-align:center; pointer-events:none; }-.office-mc-tools { display:flex; align-items:center; justify-content:space-between; gap:10px; }-.office-mc-attach { display:inline-flex; align-items:center; gap:5px; text-decoration:none; }-.office-mc-attach svg { width:13px; height:13px; }-.office-mc-attach:disabled { opacity:.45; cursor:not-allowed; }-.office-mc-files { list-style:none; margin:0; padding:0; display:flex; flex-wrap:wrap; gap:6px; }-.office-mc-files li { display:inline-flex; align-items:center; gap:2px; max-width:100%; min-width:0; padding:2px 3px 2px 9px; border:1px solid hsl(var(--border)); border-radius:999px; background:hsl(var(--secondary) / .6); color:hsl(var(--foreground)); font-size:11px; }-.office-mc-files span { max-width:220px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }-.office-mc-files button { display:inline-flex; align-items:center; justify-content:center; flex:none; width:18px; height:18px; padding:0; border:0; border-radius:50%; background:none; color:hsl(var(--muted-foreground)); cursor:pointer; }-.office-mc-files button:hover:not(:disabled) { background:hsl(var(--secondary)); color:hsl(var(--foreground)); }-.office-mc-files button:disabled { opacity:.45; cursor:not-allowed; }-.office-mc-files button svg { width:12px; height:12px; }--/* Launch progress: one quiet line per agent with a status dot. */-.office-mc-log { list-style:none; margin:0; padding:0; display:flex; flex-direction:column; gap:5px; font-size:12px; color:hsl(var(--foreground)); }-.office-mc-log li { display:flex; align-items:baseline; gap:8px; line-height:1.4; }-.office-mc-log li i { flex:none; width:7px; height:7px; border-radius:50%; background:hsl(var(--muted-foreground)); transform:translateY(-1px); }-.office-mc-log li[data-tone="busy"] { color:hsl(var(--muted-foreground)); }-.office-mc-log li[data-tone="busy"] i { animation:office-mc-pulse 1.2s ease-in-out infinite; }-.office-mc-log li[data-tone="ok"] i { background:hsl(var(--success)); }-.office-mc-log li[data-tone="warn"] i { background:hsl(var(--warning)); }-.office-mc-log li[data-tone="error"] { color:hsl(var(--destructive)); }-.office-mc-log li[data-tone="error"] i { background:hsl(var(--destructive)); }-@keyframes office-mc-pulse { 50% { opacity:.3; } }-@media (prefers-reduced-motion:reduce) { .office-mc-log li i { animation:none !important; } }--/* Message several: a plain checklist. */-.office-mc-fleet { list-style:none; margin:0; padding:0; max-height:180px; overflow:auto; display:flex; flex-direction:column; }-.office-mc-fleet label { display:flex; align-items:center; gap:9px; padding:6px 2px; border-bottom:1px solid hsl(var(--border) / .6); cursor:pointer; font-size:12px; min-width:0; }-.office-mc-fleet li:last-child label { border-bottom:0; }-.office-mc-fleet input { accent-color:hsl(var(--foreground)); flex:none; }-.office-mc-fleet-name { flex:1; min-width:0; font-weight:500; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }-.office-mc-fleet-state { display:inline-flex; align-items:center; gap:6px; flex:none; color:hsl(var(--muted-foreground)); }diff --git a/dodaios/ui/web/frontend/src/components/society/office/missionControl.test.ts b/dodaios/ui/web/frontend/src/components/society/office/missionControl.test.tsdeleted file mode 100644index e981ca2ddd..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/missionControl.test.ts+++ /dev/null@@ -1,79 +0,0 @@-import { describe, expect, it } from "vitest";-import type { AgentStatus, DropAttachment, IdeProject } from "@/lib/agenticIdeApi";-import type { PaneOccupant } from "./codingFloor";-import { launchableAgents, pickAll, workspaceProjects } from "./MissionControlPanel";-import { folderTarget } from "./NewWorkspaceFields";-import { liveGrid } from "./PaneLiveScreen";-import { briefWithFiles, heldPayload, holdDrop } from "./spawnFiles";--const project = (id: string, path: string, extra: Partial<IdeProject> = {}): IdeProject =>- ({ id, path, name: id, scratch: false, archived: false, exists: true, workspaces: [], ...extra } as IdeProject);--const described = (reference: string): DropAttachment =>- ({ name: reference, reference, kind: "image", detail: "a chart", described_by: "vision", note: "" });--const cli = (name: string, extra: Partial<AgentStatus> = {}): AgentStatus => ({- name, display_name: name, installed: true, version: null, install_command: null, ...extra,-} as AgentStatus);--const occupant = (id: string, state: PaneOccupant["agent"]["state"]): PaneOccupant =>- ({ agent: { agentId: id, state } } as PaneOccupant);--describe("pane live screen", () => {- it("fits the live window's font to the pane's width, within bounds", () => {- // A narrow 40-column TUI in a wide window grows to the cap instead of hugging the left edge.- expect(liveGrid(40, 900, 240).font).toBe(15);- // A wide 200-column terminal shrinks to the floor and is cut on the right.- const wide = liveGrid(200, 500, 240);- expect(wide.font).toBe(10);- expect(wide.cols).toBe(79);- // As many rows as the height holds, never zero.- expect(liveGrid(80, 600, 240).fit).toBe(Math.floor(240 / Math.round(liveGrid(80, 600, 240).font * 1.15)));- expect(liveGrid(80, 0, 0).fit).toBe(1);- });--});--describe("mission control", () => {- it("launches only installed coding CLIs, never a plain shell", () => {- const list = [cli("claude"), cli("codex", { installed: false }), cli("shell", { kind: "shell" }), cli("gemini", { kind: "cli" })];- expect(launchableAgents(list).map((a) => a.name)).toEqual(["claude", "gemini"]);- });-- it("selects everyone on the floor, and clears again once everyone is picked", () => {- const floor = [occupant("a", "working"), occupant("b", "waiting"), occupant("c", "idle")];- expect([...pickAll(floor, new Set(["b"]))]).toEqual(["a", "b", "c"]);- expect([...pickAll(floor, new Set(["a", "b", "c"]))]).toEqual([]);- });-- it("offers a new workspace only in real, reachable, connected folders", () => {- const list = [project("shop", "/w/shop"), project("chats", "/w/c", { scratch: true }),- project("old", "/w/old", { archived: true }), project("usb", "/mnt/usb", { exists: false })];- expect(workspaceProjects(list).map((p) => p.id)).toEqual(["shop"]);- });-- it("recognises a picked folder that is already a connected project", () => {- const list = [project("shop", "C:\\work\\shop")];- expect(folderTarget("c:/work/shop/", list)).toEqual({ path: "C:\\work\\shop", label: "shop", projectId: "shop" });- expect(folderTarget("/home/me/new-app", list)).toEqual({ path: "/home/me/new-app", label: "new-app" });- });-});--describe("spawn point files", () => {- const shot = new File(["png"], "shot.png", { type: "image/png", lastModified: 1 });-- it("holds each dropped file once, paths and bytes alike", () => {- const once = holdDrop([], { paths: ["C:\\docs\\spec.pdf"], files: [shot] });- const twice = holdDrop(once, { paths: ["c:/docs/spec.pdf"], files: [shot] });- expect(twice.map((h) => h.name)).toEqual(["spec.pdf", "shot.png"]);- expect(heldPayload(twice)).toEqual({ paths: ["C:\\docs\\spec.pdf"], files: [shot] });- });-- it("writes in only the files the analysis did not describe, never ending on one", () => {- expect(briefWithFiles("Fix it", ["@a.png"], [described("@a.png")])).toBe("Fix it");- const brief = briefWithFiles("Fix it", ["@a.png", "@big.mov"], [described("@a.png")]);- expect(brief).toContain("@big.mov");- expect(brief).not.toContain("@a.png");- expect(brief.trimEnd().endsWith("@big.mov")).toBe(false);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/missionScreens.css b/dodaios/ui/web/frontend/src/components/society/office/missionScreens.cssdeleted file mode 100644index 00ce91302e..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/missionScreens.css+++ /dev/null@@ -1,22 +0,0 @@-/* Mission Control's live desk monitors: real app sections drawn onto the glass.- The frame is the app's own ground; the IDE monitor takes its colours from the- --pane-* variables the component sets from the pane appearance tables. */-.office-mission-screen { width:100%; height:100%; overflow:hidden; background:hsl(var(--background)); color:hsl(var(--foreground)); border-radius:6px; }-.office-mission-screen > * { height:100%; }--/* The Agentic IDE as the app draws it: the workspace sidebar on the app's own- ground, then the panes side by side, each on the pane ground with its edge. */-.office-ide-monitor { display:flex; height:100%; color:hsl(var(--foreground)); }-.office-ide-side { flex:none; width:220px; padding:10px 8px; overflow:hidden; }-.office-ide-side-title { height:32px; padding:0 8px; font-size:14px; font-weight:600; line-height:32px; }-.office-ide-project { display:flex; align-items:center; gap:8px; margin-top:8px; padding:5px 8px; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; font-size:13px; font-weight:500; }-.office-ide-project svg { flex:none; width:15px; height:15px; color:hsl(var(--muted-foreground)); }-.office-ide-ws { display:flex; align-items:center; gap:8px; margin-top:1px; padding:5px 8px 5px 22px; border-radius:6px; font-size:13px; color:hsl(var(--muted-foreground)); }-.office-ide-ws[data-active] { background:hsl(var(--muted)); color:hsl(var(--foreground)); }-.office-ide-ws i { flex:none; width:6px; height:6px; border-radius:50%; }-.office-ide-ws span { flex:1; min-width:0; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; }-.office-ide-ws b { flex:none; font-size:12px; font-weight:400; color:hsl(var(--muted-foreground)); }-.office-ide-grid { display:grid; flex:1; min-width:0; min-height:0; gap:6px; padding:6px 6px 6px 0; }-.office-ide-tile { display:flex; flex-direction:column; min-width:0; min-height:0; overflow:hidden; border:1px solid var(--pane-rule); border-radius:8px; background:var(--pane-ground); color:var(--pane-ink); }-.office-ide-screen { flex:1 1 auto; min-height:0; margin:0 10px 6px; cursor:inherit; }-.office-ide-empty { margin:auto; font-size:14px; color:hsl(var(--muted-foreground)); }diff --git a/dodaios/ui/web/frontend/src/components/society/office/missionScreens.test.ts b/dodaios/ui/web/frontend/src/components/society/office/missionScreens.test.tsdeleted file mode 100644index 16bdfaee48..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/missionScreens.test.ts+++ /dev/null@@ -1,66 +0,0 @@-import { describe, expect, it } from "vitest";-import type { SocietyAgent } from "../data";-import type { PaneOccupant } from "./codingFloor";-import { deskLive } from "./CommandOffice";-import { ideGrid, idePanes, ideTree, pickShownAgent } from "./MissionScreens";-import { screenFillDistance } from "./OfficeCameraRig";-import { useOfficeStore } from "./officeStore";--const agent = (agentId: string, extra: Partial<SocietyAgent> = {}): SocietyAgent =>- ({ agentId, tier: "specialist", state: "idle", chatSessionId: `chat-${agentId}`, ...extra } as SocietyAgent);--const tile = (key: string, workspace: string, active = false): PaneOccupant =>- ({ pane: { key, workspace_id: workspace, workspace_active: active } } as PaneOccupant);--describe("mission control desk monitors", () => {- it("shows a working agent's chat on the Agents monitor, never the lead's", () => {- const lead = agent("lead", { tier: "lead", state: "working" });- expect(pickShownAgent([lead, agent("a"), agent("b", { state: "working" })])?.agentId).toBe("b");- expect(pickShownAgent([lead, agent("a"), agent("w", { state: "waiting" })])?.agentId).toBe("w");- expect(pickShownAgent([lead, agent("nochat", { chatSessionId: null })])).toBeNull();- });-- it("puts the front workspace's panes on the IDE monitor, in grid order", () => {- const panes = [tile("T1", "back"), tile("T1", "front", true), tile("T2", "front", true), tile("T2", "back")];- const shown = idePanes(panes);- expect(shown.workspace).toBe("front");- expect(shown.tiles.map((t) => t.pane.key)).toEqual(["T1", "T2"]);- // No front workspace: the first one stands in; no panes at all: nothing.- expect(idePanes([tile("T1", "only")]).workspace).toBe("only");- expect(idePanes([]).tiles).toEqual([]);- });-- it("groups the IDE sidebar by project folder, then workspace", () => {- const pane = (workspace: string, folder: string, state: "working" | "idle") =>- ({ pane: { workspace_id: workspace, workspace_name: workspace, folder }, agent: { state } } as PaneOccupant);- const tree = ideTree([pane("a", "/p/jarvis", "idle"), pane("a", "/p/jarvis", "working"), pane("b", "C:\\x\\web", "idle")]);- expect(tree.map((p) => p.name)).toEqual(["jarvis", "web"]);- expect(tree[0].workspaces).toEqual([{ id: "a", name: "a", count: 2, working: true }]);- });-- it("splits the IDE monitor like the IDE grid", () => {- expect(ideGrid(1)).toEqual({ cols: 1, rows: 1 });- expect(ideGrid(2)).toEqual({ cols: 2, rows: 1 });- expect(ideGrid(3)).toEqual({ cols: 3, rows: 1 });- expect(ideGrid(4)).toEqual({ cols: 2, rows: 2 });- expect(ideGrid(6)).toEqual({ cols: 3, rows: 2 });- });-- it("runs the live sections only near the desk, with no flicker at the edge", () => {- expect(deskLive(20, false)).toBe(true);- expect(deskLive(24, false)).toBe(false);- expect(deskLive(24, true)).toBe(true);- expect(deskLive(27, true)).toBe(false);- });-- it("dives into a larger monitor from further back, so it still fills the view", () => {- expect(screenFillDistance(35, 1.6, 0.72, 0.42)).toBeGreaterThan(screenFillDistance(35, 1.6));- });-- it("a monitor click queues the dive and the section it opens", () => {- useOfficeStore.getState().diveToSection("costs", [1, 1.1, 2], 0.4, [0.72, 0.42]);- const { zoom, sectionDive } = useOfficeStore.getState();- expect(zoom).toMatchObject({ target: [1, 1.1, 2], facing: 0.4, size: [0.72, 0.42] });- expect(sectionDive?.section).toBe("costs");- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/monitorMarks.ts b/dodaios/ui/web/frontend/src/components/society/office/monitorMarks.tsdeleted file mode 100644index 73a1a2981b..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/monitorMarks.ts+++ /dev/null@@ -1,77 +0,0 @@-/**- * The CLI marks the desk monitors draw in their title bar, as bitmaps.- *- * A canvas cannot use AgentMark (a DOM component), so the same shipped brand- * file is loaded once per agent and ink, and rendered the way AgentMark shows- * it: an `ink` silhouette tinted with the pane's ink, a `dark` lockup on its- * dark tile, an `any` lockup as it is. Until a mark has loaded — or when an- * agent has none — the monitor draws the terminal glyph instead.- */-import { useEffect, useState } from "react";-import { agentLogoAsset } from "@/components/agentic/AgentMark";--const SIZE = 64;-const marks = new Map<string, HTMLCanvasElement>();-const pending = new Map<string, Promise<HTMLCanvasElement | null>>();-const failedUrls = new Set<string>();--function render(image: HTMLImageElement, ground: "ink" | "dark" | "any", ink: string): HTMLCanvasElement | null {- const canvas = document.createElement("canvas");- canvas.width = SIZE; canvas.height = SIZE;- const ctx = canvas.getContext("2d");- if (!ctx) return null;- if (ground === "dark") {- ctx.fillStyle = "#18181b";- ctx.beginPath(); ctx.roundRect(0, 0, SIZE, SIZE, 12); ctx.fill();- ctx.drawImage(image, 8, 8, SIZE - 16, SIZE - 16);- return canvas;- }- ctx.drawImage(image, 0, 0, SIZE, SIZE);- if (ground === "ink") {- // The silhouette takes the pane's ink, the way AgentMark masks it over the text colour.- ctx.globalCompositeOperation = "source-in";- ctx.fillStyle = ink;- ctx.fillRect(0, 0, SIZE, SIZE);- }- return canvas;-}--function load(agent: string, ink: string): Promise<HTMLCanvasElement | null> {- const asset = agentLogoAsset(agent);- if (!asset || failedUrls.has(asset.url) || typeof document === "undefined") return Promise.resolve(null);- const key = `${agent}|${ink}`;- const known = pending.get(key);- if (known) return known;- const promise = new Promise<HTMLCanvasElement | null>((resolve) => {- const image = new Image(SIZE, SIZE);- image.onload = () => {- const canvas = render(image, asset.ground, ink);- if (canvas) marks.set(key, canvas);- resolve(canvas);- };- image.onerror = () => {- // The monitor keeps its terminal glyph; one line per broken file, never a retry loop.- failedUrls.add(asset.url);- console.warn(`Office monitor: the ${agent} mark could not be loaded from ${asset.url}`);- resolve(null);- };- image.src = asset.url;- });- pending.set(key, promise);- return promise;-}--/** The agent's mark tinted for `ink`, or null until it has loaded (or when there is none). */-export function useAgentMark(agent: string, ink: string): HTMLCanvasElement | null {- const key = `${agent}|${ink}`;- const [mark, setMark] = useState<HTMLCanvasElement | null>(() => marks.get(key) ?? null);- useEffect(() => {- const ready = marks.get(key);- if (ready) { setMark(ready); return; }- let alive = true;- setMark(null);- void load(agent, ink).then((canvas) => { if (alive) setMark(canvas); });- return () => { alive = false; };- }, [agent, ink, key]);- return mark;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/namePlate.test.ts b/dodaios/ui/web/frontend/src/components/society/office/namePlate.test.tsdeleted file mode 100644index e49152e749..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/namePlate.test.ts+++ /dev/null@@ -1,57 +0,0 @@-import { describe, expect, it } from "vitest";-import { PLATE_RANGE, plateDetail, type PlateDetail, type PlateInput } from "./namePlate";--const far: PlateInput = { cameraDistance: 40, personDistance: 30, pointed: false, selected: false };--describe("name plate detail", () => {- it("is a dot from across the floor", () => {- expect(plateDetail("dot", far)).toBe("dot");- expect(plateDetail("full", far)).toBe("dot");- });-- it("opens for the agent that is pointed at or selected, however far away", () => {- expect(plateDetail("dot", { ...far, pointed: true })).toBe("full");- expect(plateDetail("dot", { ...far, selected: true })).toBe("full");- });-- it("opens when the camera comes near", () => {- expect(plateDetail("dot", { ...far, cameraDistance: PLATE_RANGE.camera.open - 0.1 })).toBe("full");- });-- it("opens for the people round the person, even in the overview", () => {- expect(plateDetail("dot", { ...far, personDistance: PLATE_RANGE.person.open - 0.1 })).toBe("full");- });-- it("stays as it is inside the gap, so a plate at the threshold never flickers", () => {- const between = { ...far, cameraDistance: (PLATE_RANGE.camera.open + PLATE_RANGE.camera.close) / 2 };- expect(plateDetail("dot", between)).toBe("dot");- expect(plateDetail("full", between)).toBe("full");- const strolling = { ...far, personDistance: (PLATE_RANGE.person.open + PLATE_RANGE.person.close) / 2 };- expect(plateDetail("dot", strolling)).toBe("dot");- expect(plateDetail("full", strolling)).toBe("full");- });-- it("changes once, not on every step, while someone paces across the threshold", () => {- // An agent wandering between 4.4 m and 5.8 m from the person: inside the gap except at the near end.- const path = [5.8, 5.2, 4.7, 4.4, 4.7, 5.2, 5.8, 5.2, 4.7, 4.4, 4.9, 5.8];- let detail: PlateDetail = "dot";- let changes = 0;- for (const personDistance of path) {- const next = plateDetail(detail, { ...far, personDistance });- if (next !== detail) changes += 1;- detail = next;- }- expect(changes).toBe(1);- expect(detail).toBe("full");- });-- it("closes again only beyond the far edge", () => {- expect(plateDetail("full", { ...far, cameraDistance: PLATE_RANGE.camera.close + 0.1 })).toBe("dot");- expect(plateDetail("full", { ...far, personDistance: PLATE_RANGE.person.close + 0.1 })).toBe("dot");- });-- it("keeps a real gap on both ranges", () => {- expect(PLATE_RANGE.camera.close - PLATE_RANGE.camera.open).toBeGreaterThanOrEqual(1);- expect(PLATE_RANGE.person.close - PLATE_RANGE.person.open).toBeGreaterThanOrEqual(1);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/namePlate.ts b/dodaios/ui/web/frontend/src/components/society/office/namePlate.tsdeleted file mode 100644index 8f60f26094..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/namePlate.ts+++ /dev/null@@ -1,38 +0,0 @@-/**- * How much of a name plate shows. From across the floor an agent is one small- * state dot, so the overview is a calm field of dots and not of labels; the- * whole plate (name, rank, activity) appears when the camera or the person- * comes near, when the pointer or keyboard focus rests on the agent, or when- * it is selected. Pure and tested.- */--export type PlateDetail = "dot" | "full";--/**- * Distances in metres, each as a pair: the plate opens inside the first and- * closes again only beyond the second. The gap keeps a plate from flickering- * while someone stands or strolls right at the threshold.- */-export const PLATE_RANGE = {- /** Camera to agent. The follow view keeps the camera 15 m from the person, so this is a deliberate zoom in. */- camera: { open: 10.5, close: 12.5 },- /** The person's character to agent: the people round you introduce themselves. */- person: { open: 4.6, close: 6 },-} as const;--export interface PlateInput {- /** Camera to the plate. */- cameraDistance: number;- /** The person's character to the agent, on the floor. */- personDistance: number;- /** The pointer or keyboard focus rests on the agent or its plate. */- pointed: boolean;- selected: boolean;-}--export function plateDetail(previous: PlateDetail, input: PlateInput): PlateDetail {- if (input.selected || input.pointed) return "full";- const edge = previous === "full" ? "close" : "open";- const near = input.cameraDistance <= PLATE_RANGE.camera[edge] || input.personDistance <= PLATE_RANGE.person[edge];- return near ? "full" : "dot";-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/office.css b/dodaios/ui/web/frontend/src/components/society/office/office.cssdeleted file mode 100644index cc4308d65a..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/office.css+++ /dev/null@@ -1,130 +0,0 @@-/* HUD over the office canvas: theme tokens, so it follows light and dark mode. */-.office-stage { position:relative; width:100%; min-width:0; height:100%; min-height:0; overflow:hidden; background:#0b1024; }-/* In-world labels (name plates, bubbles) are positioned DOM in here with z-indexes of their own: one stacking- context keeps all of them under every HUD card. */-.office-viewport { position:absolute; inset:0; touch-action:none; isolation:isolate; }-.office-viewport:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:-2px; }-.office-fallback { display:flex; align-items:center; justify-content:center; height:100%; padding:24px; font-size:13px; color:hsl(var(--muted-foreground)); background:hsl(var(--background)); }-.office-hud { position:absolute; z-index:30; }-/* Top left: the floor card, the level card and whatever the floor has to say. It never reaches under the toolbar and the minimap (226 px) on the right. */-.office-hud-left { left:14px; top:14px; display:flex; flex-direction:column; align-items:flex-start; gap:8px; max-width:min(320px, calc(100% - 430px)); }-.office-card { border:1px solid hsl(var(--border)); border-radius:12px; background:hsl(var(--popover) / .92); color:hsl(var(--popover-foreground)); box-shadow:0 4px 18px rgb(0 0 0 / .25); backdrop-filter:blur(6px); }-.office-title { display:flex; flex-direction:column; gap:3px; max-width:100%; padding:8px 12px; font-size:14px; }-.office-title strong { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }-.office-title > span { font-size:11px; color:hsl(var(--muted-foreground)); }-/* Who is doing what, as one quiet line under the floor's name. */-.office-states { display:flex; flex-wrap:wrap; gap:2px 10px; }-.office-states span { display:inline-flex; align-items:center; gap:5px; white-space:nowrap; }-.office-states i { width:7px; height:7px; border-radius:50%; background:hsl(var(--muted-foreground)); }-.office-states [data-tone="working"] i { background:hsl(var(--success)); }-.office-states [data-tone="waiting"] i { background:hsl(var(--warning)); }-.office-states [data-tone="paused"] i { background:transparent; box-shadow:inset 0 0 0 1.5px hsl(var(--muted-foreground)); }-.office-note { margin:0; padding:6px 10px; font-size:11px; color:hsl(var(--muted-foreground)); }--/* The toolbar and what opens from it: a dock left of the minimap (top right, 204 px wide + 8 px gap) that reaches- down to the stage's lower edge, so the places card under the toolbar can never grow out of the stage. The dock- itself takes no pointer; the toolbar and the card do. */-.office-tools-dock { right:226px; top:14px; bottom:16px; z-index:32; display:flex; flex-direction:column; align-items:flex-end; gap:9px; pointer-events:none; }-.office-tools-dock > * { pointer-events:auto; }-.office-tools { flex:none; display:flex; gap:2px; padding:3px; border:1px solid hsl(var(--border)); border-radius:11px; background:hsl(var(--popover) / .92); color:hsl(var(--popover-foreground)); box-shadow:0 4px 18px rgb(0 0 0 / .25); backdrop-filter:blur(6px); }-.office-tool { position:relative; display:inline-flex; align-items:center; justify-content:center; width:30px; height:30px; padding:0; border:0; border-radius:8px; background:none; color:inherit; cursor:pointer; }-.office-tool svg { width:16px; height:16px; }-.office-tool:hover { background:hsl(var(--secondary)); }-.office-tool[aria-pressed="true"], .office-tool[aria-expanded="true"] { background:hsl(var(--secondary)); color:hsl(var(--foreground)); box-shadow:inset 0 0 0 1px hsl(var(--border)); }-.office-tool:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:1px; }-/* Its label, on hover and on keyboard focus (the button carries the same text as its accessible name). */-.office-tool[data-tip]:hover::after, .office-tool[data-tip]:focus-visible::after { content:attr(data-tip); position:absolute; top:calc(100% + 9px); left:50%; transform:translateX(-50%); z-index:2; padding:4px 8px; border-radius:7px; border:1px solid hsl(var(--border)); background:hsl(var(--popover)); color:hsl(var(--popover-foreground)); font-size:11px; font-weight:500; line-height:1.3; white-space:nowrap; pointer-events:none; box-shadow:0 4px 14px rgb(0 0 0 / .22); }-/* The last button's label would leave the toolbar's right edge towards the minimap: keep it inside. */-.office-tools > .office-tool:last-child[data-tip]::after { left:auto; right:0; transform:none; }-/* The places card: an opaque floating surface (never see-through over the scene). It is as tall as its list and- uses the room under the toolbar down to the stage's lower edge (the dock ends there), up to a cap for very tall- stages; only what does not fit scrolls inside it. */-.office-places-card { position:relative; flex:0 1 auto; display:flex; flex-direction:column; min-height:0; width:min(320px, calc(100vw - 28px)); max-height:680px; overflow:hidden; border:1px solid hsl(var(--border)); border-radius:12px; background:hsl(var(--popover)); color:hsl(var(--popover-foreground)); box-shadow:0 10px 30px rgb(0 0 0 / .32); }-.office-places-scroll { flex:1 1 auto; min-height:0; overflow-y:auto; overscroll-behavior:contain; padding:6px; scrollbar-gutter:stable; }-/* More rows below: the lower edge fades, so a cut-off row reads as "scroll" and not as the end. */-.office-places-card[data-more]::after { content:""; position:absolute; left:0; right:0; bottom:0; height:30px; border-radius:0 0 11px 11px; background:linear-gradient(hsl(var(--popover) / 0), hsl(var(--popover))); pointer-events:none; }-/* Narrow: the toolbar sits under the minimap. */-@media (max-width:760px) { .office-tools-dock { right:14px; top:262px; } .office-hud-left { max-width:min(320px, calc(100% - 254px)); } }-/* No minimap (short or very narrow window): the toolbar takes its corner. */-@media (max-height:520px), (max-width:600px) { .office-tools-dock { right:14px; top:14px; } .office-hud-left { max-width:calc(100% - 28px - 190px); } }-/* The IDE side panel: no minimap; the toolbar is a column in the corner, its labels and the places card open to its left. */-.office-stage.office-stage-compact .office-tools-dock { right:8px; top:8px; bottom:8px; flex-direction:row-reverse; align-items:flex-start; }-.office-stage.office-stage-compact .office-tools { flex-direction:column; }-.office-stage.office-stage-compact .office-hud-left { max-width:calc(100% - 62px); }-.office-stage.office-stage-compact .office-tool[data-tip]::after { top:50%; left:auto; right:calc(100% + 9px); transform:translateY(-50%); }-.office-stage.office-stage-compact .office-places-card { width:min(280px, calc(100vw - 80px)); max-height:min(680px, 100%); }--/* Bottom centre: the one prompt, a station's short answer, the first-visit hints. */-.office-hud-bottom { left:50%; bottom:16px; transform:translateX(-50%); display:flex; flex-direction:column; align-items:center; gap:8px; width:max-content; max-width:calc(100% - 28px); pointer-events:none; }-.office-hud-bottom > * { pointer-events:auto; max-width:100%; }-.office-hud-bottom > [role="status"]:empty { display:none; }-.office-prompt { display:inline-flex; align-items:center; gap:8px; padding:6px 13px 6px 6px; border-radius:10px; border:1px solid hsl(var(--border)); background:hsl(var(--popover) / .94); color:hsl(var(--popover-foreground)); font:inherit; font-size:13px; cursor:pointer; box-shadow:0 6px 20px rgb(0 0 0 / .3); backdrop-filter:blur(6px); }-.office-prompt b { font-weight:600; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }-.office-prompt span { color:hsl(var(--muted-foreground)); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }-/* Narrow host: the action is never cut short; it wraps instead (the object's name is not shown there). */-.office-prompt[data-compact] { text-align:left; }-.office-prompt[data-compact] b { white-space:normal; overflow:visible; text-overflow:clip; overflow-wrap:anywhere; }-.office-prompt[data-compact] .office-key { flex:none; }-.office-prompt:hover { background:hsl(var(--popover)); }-.office-prompt:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }-.office-notice { margin:0; padding:6px 12px; font-size:12px; }-.office-hints { display:flex; align-items:center; gap:14px; padding:8px 8px 8px 14px; }-.office-hints ul { display:flex; flex-wrap:wrap; gap:6px 16px; margin:0; padding:0; list-style:none; }-.office-hints li { display:inline-flex; align-items:center; gap:7px; font-size:12px; color:hsl(var(--muted-foreground)); white-space:nowrap; }-.office-hints-dismiss { flex:none; padding:5px 11px; border:1px solid hsl(var(--border)); border-radius:8px; background:hsl(var(--background)); color:hsl(var(--foreground)); font:inherit; font-size:12px; font-weight:500; cursor:pointer; }-.office-hints-dismiss:hover { background:hsl(var(--secondary)); }-.office-hints-dismiss:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }-@media (max-width:700px) { .office-hints { flex-direction:column; align-items:stretch; padding:10px; } }--/* In-world name plates: part of the diorama, so they keep one dark look in both modes.- From afar an agent is only its state dot; the plate fades in over it (see namePlate.ts). Dot and plate share- one grid cell, so nothing moves when one takes over from the other. */-.office-plate-wrap { display:inline-grid; place-items:center; pointer-events:none; }-.office-plate-wrap > * { grid-area:1 / 1; }-.office-plate-dot { position:relative; width:9px; height:9px; border-radius:50%; background:#94a3b8; box-shadow:0 0 0 2px rgb(24 26 32 / .8); pointer-events:auto; cursor:pointer; transition:opacity .18s ease; }-/* A dot is small; its target is not. */-.office-plate-dot::after { content:""; position:absolute; inset:-7px; border-radius:50%; }-.office-plate-wrap[data-state="working"] .office-plate-dot { background:#4ade80; }-.office-plate-wrap[data-state="waiting"] .office-plate-dot { background:#fbbf24; }-.office-plate-wrap[data-state="paused"] .office-plate-dot { background:rgb(24 26 32 / .8); box-shadow:0 0 0 2px rgb(24 26 32 / .8), inset 0 0 0 1.5px #94a3b8; }-.office-plate-wrap .office-plate { transition:opacity .18s ease; }-/* The hidden plate stays in the tab order: keyboard focus on it opens it. */-.office-plate-wrap[data-detail="dot"] .office-plate { opacity:0; pointer-events:none; }-.office-plate-wrap[data-detail="full"] .office-plate { pointer-events:auto; }-.office-plate-wrap[data-detail="full"] .office-plate-dot { opacity:0; pointer-events:none; }-@media (prefers-reduced-motion:reduce) { .office-plate-dot, .office-plate-wrap .office-plate { transition:none; } }-.office-plate { transform-origin:center bottom; display:inline-flex; align-items:center; gap:5px; padding:2px 8px 2px 2px; border:0; border-radius:999px; background:rgb(24 26 32 / .84); color:#f8fafc; cursor:pointer; font-family:inherit; white-space:nowrap; user-select:none; box-shadow:0 2px 8px rgb(0 0 0 / .35); }-.office-plate:hover { background:rgb(36 39 48 / .95); }-.office-plate-name { max-width:16em; overflow:hidden; text-overflow:ellipsis; font-size:12px; font-weight:600; }-.office-plate-badge { display:inline-flex; align-items:center; justify-content:center; width:18px; height:18px; font-size:10px; font-weight:800; color:#fff; clip-path:polygon(25% 3%, 75% 3%, 100% 50%, 75% 97%, 25% 97%, 0 50%); }-.office-plate-state { display:inline-flex; align-items:center; gap:4px; font-size:10px; font-weight:500; color:#cbd5e1; }-.office-plate-state em { font-style:normal; }-.office-plate-state i { width:7px; height:7px; border-radius:50%; background:#94a3b8; }-.office-plate[data-state="working"] .office-plate-state i { background:#4ade80; box-shadow:0 0 6px #4ade80; }-.office-plate[data-state="waiting"] .office-plate-state i { background:#fbbf24; }-.office-plate:focus-visible { outline:2px solid #93c5fd; outline-offset:2px; }-.office-plate[data-selected] { box-shadow:0 0 0 2px #93c5fd, 0 2px 8px rgb(0 0 0 / .35); }-.office-plate-player { cursor:default; background:rgb(58 44 12 / .9); box-shadow:0 0 0 1.5px #f5b83d, 0 2px 8px rgb(0 0 0 / .35); }-/* Coding plates carry the whole title (subject, then result) and the run state. */-.office-plate[data-pane] { align-items:flex-start; gap:6px; padding:4px 10px 4px 4px; border-radius:12px; text-align:left; }-.office-plate[data-pane] .office-plate-badge { flex:none; margin-top:1px; }-/* The coding CLI's mark: ink marks masked in the plate's white, colour lockups on a dark tile. */-.office-plate-logo { display:inline-flex; flex:none; align-items:center; justify-content:center; width:20px; height:20px; margin-top:1px; border-radius:6px; background:rgb(255 255 255 / .08); }-.office-plate-logo[data-ground="dark"] { background:#111318; }-.office-plate-logo i { display:block; width:14px; height:14px; background:#f8fafc; -webkit-mask-repeat:no-repeat; mask-repeat:no-repeat; -webkit-mask-position:center; mask-position:center; -webkit-mask-size:contain; mask-size:contain; }-.office-plate-logo img { display:block; width:14px; height:14px; object-fit:contain; }-.office-plate-text { display:flex; flex-direction:column; align-items:flex-start; gap:1px; min-width:0; line-height:1.25; }-.office-plate[data-pane] .office-plate-name { max-width:13em; }-.office-plate-line { display:inline-flex; align-items:center; gap:6px; max-width:17em; }-.office-plate-result { min-width:0; overflow:hidden; text-overflow:ellipsis; font-size:11px; font-weight:600; color:#e2e8f0; }-.office-plate-line .office-plate-state { flex:none; }-/* max-content: the Html anchor has no width, so an opened plate would otherwise wrap after every word. */-.office-plate[data-pane][data-open] { width:max-content; max-width:min(22em, calc(100vw - 32px)); background:rgb(24 26 32 / .96); }-.office-plate[data-pane][data-open] .office-plate-name,-.office-plate[data-pane][data-open] .office-plate-result { max-width:min(20em, 100%); white-space:normal; overflow:visible; overflow-wrap:anywhere; text-overflow:clip; }-.office-plate[data-pane][data-open] .office-plate-line { max-width:100%; flex-wrap:wrap; }-/* A seat's or the dog's own prompt beside it: the same dark pill with a key cap and a short hint. */-.office-seat-prompt { padding:4px 12px 4px 4px; gap:7px; font-size:12px; font-weight:500; cursor:default; }-.office-seat-prompt kbd { display:inline-flex; align-items:center; justify-content:center; width:20px; height:20px; border-radius:6px; background:#f8fafc; color:#181a20; font-family:inherit; font-size:11px; font-weight:700; }-/* Seated first person at Mission Control: the dots step aside with the plates (officeCameraRig.css hides those). */-.office-viewport[data-first-person] .office-plate-dot { visibility:hidden; }diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeBehavior.test.ts b/dodaios/ui/web/frontend/src/components/society/office/officeBehavior.test.tsdeleted file mode 100644index 1e44ddca1b..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeBehavior.test.ts+++ /dev/null@@ -1,734 +0,0 @@-import { describe, expect, it } from "vitest";-import type { AgentRunState } from "../data";-import { allDesks, buildOfficeLayout, seatOf, standOf, type DeskSlot, type OfficeAgentInput, type Point } from "./officeLayout";-import { BODY_SPACING, paceFor } from "./officeMotion";-import { buildNavGrid, findPath, isWalkable } from "./officeNav";-import {- COMMONS_WEIGHTS, HANDOFF_DWELL_MS, PERSON_SPACE_M, POOL_IDLE_WEIGHTS, TEAM_IDLE_WEIGHTS, TRIP_REACH, createRng, dwellAfter, planFor, planStillValid, shownActivity, SpotBook,- tripReach, type ActivityKind, type Plan, type PlanInput,-} from "./officeBehavior";-import { HUDDLE_SPACE_M, homeStudio, huddlePlaces, leadPlace, mateDesks, studioRect, studioOfTeam, visitSlots } from "./officeTeams";-import { pathLength } from "./officeWalk";-import { campusOf } from "./officeFixtures";--const roster: OfficeAgentInput[] = Array.from({ length: 8 }, (_, i) => ({- agentId: `a${i}`, name: `a${i}`, tier: "specialist", providerLabel: i % 2 ? "Codex" : "Gemini", state: "idle", createdMs: i,-}));-// A floor without team studios (the coding floor): the plain idle day.-const layout = buildOfficeLayout(roster, { variant: "coding" });-const grid = buildNavGrid(layout);-const deskOf = (id: string): DeskSlot => allDesks(layout).find((d) => d.agentId === id)!;--function input(agentId: string, state: AgentRunState, extra: Partial<PlanInput> = {}): PlanInput {- return {- agentId, state, desk: deskOf(agentId), layout, grid, rng: createRng(agentId), book: new SpotBook(),- previous: null, workingColleagues: [], calledTo: null, ...extra,- };-}--describe("createRng", () => {- it("is deterministic per seed and stays in [0, 1)", () => {- const a = createRng("x"), b = createRng("x"), c = createRng("y");- const sa = Array.from({ length: 20 }, a);- expect(Array.from({ length: 20 }, b)).toEqual(sa);- expect(Array.from({ length: 20 }, c)).not.toEqual(sa);- expect(sa.every((v) => v >= 0 && v < 1)).toBe(true);- });-});--describe("SpotBook", () => {- it("gives a spot to one agent at a time and one spot per agent", () => {- const book = new SpotBook();- expect(book.claim("s1", "a")).toBe(true);- expect(book.claim("s1", "b")).toBe(false);- expect(book.holder("s1")).toBe("a");- expect(book.spotOf("a")).toBe("s1");- expect(book.claim("s2", "a")).toBe(true);- expect(book.isFree("s1")).toBe(true);- expect(book.holder("s2")).toBe("a");- book.release("a");- expect(book.isFree("s2")).toBe(true);- expect(book.holder("s2")).toBeNull();- expect(book.spotOf("a")).toBeNull();- });-});--describe("planFor on a floor without studios", () => {- it("seats a working agent at its desk, typing, until the state changes", () => {- const plan = planFor(input("a1", "working"));- const seat = seatOf(deskOf("a1"));- expect(plan).toMatchObject({ kind: "work", target: { x: seat.x, z: seat.z }, facing: seat.facing, pose: "work", dwellMs: Infinity });- });-- it("puts a deskless worker at a window", () => {- const plan = planFor(input("ghost", "working", { desk: null }));- expect(plan.kind).toBe("work");- expect(plan.pose).toBe("work");- expect(plan.spotId).toMatch(/^window-/);- });-- it("stands a waiting agent beside its chair, waving", () => {- const plan = planFor(input("a2", "waiting"));- const stand = standOf(deskOf("a2"));- expect(plan).toMatchObject({ kind: "wait", target: { x: stand.x, z: stand.z }, pose: "wave", dwellMs: Infinity });- });-- it("sends paused agents to sleep, then to the couch, then to their desk", () => {- const book = new SpotBook();- const sleepSpots = layout.spots.filter((s) => s.pose === "sleep").length;- // More seats than paused agents: the couches fill up with whoever is left after the beds.- const couchSeats = Math.min(layout.spots.filter((s) => s.kind === "couch" && s.pose !== "sleep").length, roster.length - sleepSpots);- const plans = roster.map((a) => planFor(input(a.agentId, "paused", { book })));- expect(plans.every((p) => p.kind === "nap" && p.dwellMs === Infinity)).toBe(true);- expect(plans.filter((p) => p.pose === "sleep")).toHaveLength(sleepSpots);- const onCouch = plans.filter((p) => p.spotId && layout.spots.find((s) => s.id === p.spotId)?.kind === "couch" && p.pose === "sit");- expect(onCouch).toHaveLength(couchSeats);- const atDesk = plans.filter((p) => p.spotId === null);- expect(atDesk.length).toBe(roster.length - sleepSpots - couchSeats);- for (const p of atDesk) expect(p.pose).toBe("sit");- const ids = plans.map((p) => p.spotId).filter(Boolean);- expect(new Set(ids).size).toBe(ids.length);- });-- it("answers a call by walking up to the caller and talking", () => {- const caller = layout.checkpoints.find((c) => c.id === "break")!;- const plan = planFor(input("a3", "idle", { calledTo: caller }));- expect(plan.kind).toBe("called");- expect(plan.pose).toBe("talk");- expect(plan.dwellMs).toBe(15000);- expect(isWalkable(grid, plan.target)).toBe(true);- expect(Math.hypot(plan.target.x - caller.x, plan.target.z - caller.z)).toBeLessThan(2);- });-- it("keeps a working agent at its screen even when called", () => {- const caller = layout.checkpoints.find((c) => c.id === "break")!;- expect(planFor(input("a3", "working", { calledTo: caller })).kind).toBe("work");- });-- function idleSequence(seed: string, steps: number, colleagues: PlanInput["workingColleagues"] = []): ActivityKind[] {- const rng = createRng(seed);- const book = new SpotBook();- const kinds: ActivityKind[] = [];- let previous: ActivityKind | null = null;- for (let i = 0; i < steps; i += 1) {- const plan = planFor({ ...input("a4", "idle", { rng, book, previous, workingColleagues: colleagues }) });- kinds.push(plan.kind);- previous = plan.kind;- expect(plan.dwellMs).toBeGreaterThanOrEqual(6000);- expect(plan.dwellMs).toBeLessThanOrEqual(45000);- }- return kinds;- }-- it("gives the same idle life for the same seed and never repeats an activity back to back", () => {- const colleagues = [{ agentId: "a5", desk: deskOf("a5") }];- const first = idleSequence("seed-1", 200, colleagues);- expect(idleSequence("seed-1", 200, colleagues)).toEqual(first);- expect(idleSequence("seed-2", 200, colleagues)).not.toEqual(first);- for (let i = 1; i < first.length; i += 1) {- // A full-spot fallback may land on wander after wander; a chosen activity never repeats.- if (first[i] !== "wander") expect(first[i]).not.toBe(first[i - 1]);- }- expect(new Set(first).size).toBeGreaterThan(6);- // No studios, no team life.- for (const kind of ["huddle", "mate", "studio", "handoff"]) expect(first).not.toContain(kind);- });-- it("looks in on a working colleague from a place of its own beside their chair, without pretending to talk", () => {- const colleague = { agentId: "a5", desk: deskOf("a5") };- const seat = seatOf(colleague.desk);- const book = new SpotBook();- const visits: Plan[] = [];- for (let i = 0; i < 400 && visits.length < 2; i += 1) {- const plan = planFor(input(`a${visits.length === 0 ? 4 : 6}`, "idle", { rng: createRng(`visit-${i}`), book, workingColleagues: [colleague] }));- if (plan.kind === "visit") visits.push(plan); else book.release(`a${visits.length === 0 ? 4 : 6}`);- }- expect(visits).toHaveLength(2);- for (const plan of visits) {- expect(plan).toMatchObject({ with: "a5", pose: "stand" });- expect(plan.spotId).toMatch(/^visit:/);- expect(isWalkable(grid, plan.target)).toBe(true);- // Beside the chair: within reach, outside the body spacing, looking at the colleague.- const gap = Math.hypot(plan.target.x - seat.x, plan.target.z - seat.z);- expect(gap).toBeGreaterThan(BODY_SPACING);- expect(gap).toBeLessThan(1.3);- expect(plan.facing).toBeCloseTo(Math.atan2(seat.x - plan.target.x, seat.z - plan.target.z));- }- // Two visitors never stand on each other.- expect(Math.hypot(visits[0].target.x - visits[1].target.x, visits[0].target.z - visits[1].target.z)).toBeGreaterThanOrEqual(BODY_SPACING);- expect(visits[0].spotId).not.toBe(visits[1].spotId);- });-- it("falls back to wandering when every spot of the chosen kind is taken", () => {- const book = new SpotBook();- for (const spot of layout.spots) book.claim(spot.id, `holder-${spot.id}`);- const office = layout.departments;- for (let i = 0; i < 50; i += 1) {- const plan = planFor(input("a6", "idle", { rng: createRng(`full-${i}`), book, desk: null }));- expect(["wander", "visit"]).toContain(plan.kind);- expect(plan.spotId).toBeNull();- if (plan.kind === "wander") {- expect(plan.facing).toBeNull();- expect(isWalkable(grid, plan.target)).toBe(true);- expect(office.some((d) => plan.target.x >= d.minX - 3.3 && plan.target.x <= d.maxX + 3.3)).toBe(true);- }- }- });-- it("releases an agent's spot when it goes back to work", () => {- const book = new SpotBook();- const idle = planFor(input("a7", "paused", { book }));- expect(idle.spotId).not.toBeNull();- expect(book.holder(idle.spotId!)).toBe("a7");- planFor(input("a7", "working", { book }));- expect(book.isFree(idle.spotId!)).toBe(true);- });-});--describe("SpotBook.retain", () => {- it("keeps claims on surviving spots and drops the rest", () => {- const book = new SpotBook();- book.claim("couch-a1", "a1");- book.claim("window-dept-9", "a2");- book.retain(new Set(["couch-a1"]));- expect(book.holder("couch-a1")).toBe("a1");- expect(book.isFree("window-dept-9")).toBe(true);- // The dropped agent can claim again.- expect(book.claim("couch-a2", "a2")).toBe(true);- });-- it("keeps the places the plan does not list, so a rebuilt floor never hands an occupied one out again", () => {- const book = new SpotBook();- book.claim("fan:studio-team-0:0:1", "a1");- book.claim("visit:6.32,-3.87", "a2");- book.claim("couch-of-the-old-plan", "a3");- book.retain(new Set(["couch-a1"]));- expect(book.holder("fan:studio-team-0:0:1")).toBe("a1");- expect(book.holder("visit:6.32,-3.87")).toBe("a2");- expect(book.isFree("couch-of-the-old-plan")).toBe(true);- // Nobody else is given the place at the board while a1 stands on it.- expect(book.claim("fan:studio-team-0:0:1", "a4")).toBe(false);- });-});--// ----------------------------------------------------------------------------// Team studios: agents belong somewhere.-// -----------------------------------------------------------------------------// 26 agents: teams of 7, 6 and 5, and 8 agents without a team (the pool).-const campus = campusOf(26, [7, 6, 5]);-const cDesk = (id: string): DeskSlot | null => allDesks(campus.layout).find((d) => d.agentId === id) ?? null;--function cInput(agentId: string, state: AgentRunState, extra: Partial<PlanInput> = {}): PlanInput {- return {- agentId, state, desk: cDesk(agentId), layout: campus.layout, grid: campus.grid, rng: createRng(agentId), book: new SpotBook(),- previous: null, workingColleagues: [], calledTo: null, ...extra,- };-}--/** A plan keeps the agent at home when it is in its studio or a few steps round the corner. */-function atHome(agentId: string, plan: Plan): boolean {- const studio = homeStudio(campus.layout, agentId, cDesk(agentId))!;- const rect = studioRect(campus.layout, studio);- const reach = Math.hypot(rect.maxX - rect.minX, rect.maxZ - rect.minZ) / 2 + 3.5;- return Math.hypot(plan.target.x - studio.centre.x, plan.target.z - studio.centre.z) <= reach;-}--function idleDay(agentId: string, steps: number, seed = agentId): Plan[] {- const rng = createRng(seed);- const book = new SpotBook();- const studio = homeStudio(campus.layout, agentId, cDesk(agentId))!;- const mates = mateDesks(campus.layout, studio, agentId).map((d) => ({ agentId: d.agentId as string, desk: d }));- const plans: Plan[] = [];- let previous: ActivityKind | null = null;- let position: Point | null = null;- for (let i = 0; i < steps; i += 1) {- const plan = planFor(cInput(agentId, "idle", { rng, book, previous, position, matesAtDesk: mates }));- plans.push(plan);- previous = plan.kind;- position = plan.target;- }- return plans;-}--describe("the campus", () => {- it("gives every team a studio with a board and places to stand at it, and seats the rest in the pool", () => {- const studios = campus.layout.studios ?? [];- expect(studios.filter((s) => s.teamId !== null).map((s) => s.members.length)).toEqual([7, 6, 5]);- expect(studios.filter((s) => s.teamId === null).flatMap((s) => s.members)).toHaveLength(8);- for (const studio of studios.filter((s) => s.teamId !== null)) {- expect(studio.board).not.toBeNull();- const places = huddlePlaces(campus.layout, campus.grid, studio);- // Room for the whole team at its board, in loose arcs: everybody has more than a metre to themselves.- expect(places.length).toBeGreaterThanOrEqual(studio.members.length);- for (const [i, p] of places.entries()) {- expect(isWalkable(campus.grid, p), p.id).toBe(true);- // Facing the board, from in front of it.- expect(p.facing).toBeCloseTo(Math.atan2(studio.board!.x - p.x, studio.board!.z - p.z));- for (const q of places.slice(i + 1)) expect(Math.hypot(p.x - q.x, p.z - q.z), `${p.id} ${q.id}`).toBeGreaterThanOrEqual(HUDDLE_SPACE_M);- }- }- });-- it("offers a visitor a walkable place of its own at every occupied desk", () => {- for (const desk of allDesks(campus.layout).filter((d) => d.agentId && !d.size)) {- const slots = visitSlots(desk, campus.grid);- expect(slots.length, desk.id).toBeGreaterThanOrEqual(1);- const seat = seatOf(desk);- for (const slot of slots) expect(Math.hypot(slot.x - seat.x, slot.z - seat.z), slot.id).toBeGreaterThan(BODY_SPACING);- }- });-});--describe("idle life with a home", () => {- it("weights a team member four fifths at home and a pool agent far more towards the shared places", () => {- const share = (table: readonly (readonly [string, number])[], keys: string[]) =>- table.filter(([k]) => keys.includes(k)).reduce((s, [, w]) => s + w, 0) / table.reduce((s, [, w]) => s + w, 0);- expect(share(TEAM_IDLE_WEIGHTS, ["desk", "mate", "huddle", "studio", "near"])).toBeCloseTo(0.8, 2);- expect(share(TEAM_IDLE_WEIGHTS, ["commons"])).toBeCloseTo(0.14, 2);- expect(share(POOL_IDLE_WEIGHTS, ["commons"])).toBeCloseTo(0.4, 2);- expect(POOL_IDLE_WEIGHTS.map(([k]) => k)).not.toContain("huddle");- expect(COMMONS_WEIGHTS.every(([, w]) => w > 0)).toBe(true);- });-- it("keeps a team member mostly in and around its own studio", () => {- const plans = idleDay("a1", 400);- const home = plans.filter((p) => atHome("a1", p)).length / plans.length;- expect(home).toBeGreaterThan(0.68);- expect(home).toBeLessThan(0.95);- const kinds = new Set(plans.map((p) => p.kind));- for (const kind of ["desk", "mate", "huddle", "studio"] as const) expect(kinds, kind).toContain(kind);- // It still gets out: a coffee or the couch now and then.- expect(plans.some((p) => !atHome("a1", p))).toBe(true);- });-- it("sends an agent without a team to the shared places far more often", () => {- const member = idleDay("a1", 400).filter((p) => !atHome("a1", p)).length;- const pooled = idleDay("a20", 400).filter((p) => !atHome("a20", p)).length;- expect(homeStudio(campus.layout, "a20", cDesk("a20"))!.teamId).toBeNull();- expect(pooled).toBeGreaterThan(member * 1.5);- expect(idleDay("a20", 400).map((p) => p.kind)).not.toContain("huddle");- });-- it("is the same day for the same agent, and a different one for another", () => {- const day = idleDay("a3", 120).map((p) => [p.kind, p.spotId, p.target.x, p.target.z, p.dwellMs]);- expect(idleDay("a3", 120).map((p) => [p.kind, p.spotId, p.target.x, p.target.z, p.dwellMs])).toEqual(day);- expect(idleDay("a4", 120).map((p) => p.kind)).not.toEqual(day.map((d) => d[0]));- });-- it("never takes the same home activity twice in a row, and every place is real floor or a real seat", () => {- const plans = idleDay("a2", 300);- for (let i = 1; i < plans.length; i += 1) {- if (["desk", "mate", "huddle"].includes(plans[i].kind)) expect(plans[i].kind, `step ${i}`).not.toBe(plans[i - 1].kind);- }- for (const plan of plans) {- if (plan.pose === "stand") expect(isWalkable(campus.grid, plan.target), `${plan.kind} ${plan.spotId}`).toBe(true);- expect(findPath(campus.grid, campus.layout.spawn, plan.target), `${plan.kind} ${plan.spotId}`).not.toBeNull();- }- });-- it("stands at a teammate's desk only while that teammate sits there, and only watches", () => {- const studio = homeStudio(campus.layout, "a1", cDesk("a1"))!;- const mate = mateDesks(campus.layout, studio, "a1")[0];- const seat = seatOf(mate);- for (let i = 0; i < 300; i += 1) {- const plan = planFor(cInput("a1", "idle", { rng: createRng(`mate-${i}`), matesAtDesk: [{ agentId: mate.agentId as string, desk: mate }] }));- if (plan.kind !== "mate") continue;- expect(plan).toMatchObject({ with: mate.agentId, pose: "stand" });- expect(Math.hypot(plan.target.x - seat.x, plan.target.z - seat.z)).toBeLessThan(1.3);- // Nobody at their desk: nobody to look in on.- for (let j = 0; j < 200; j += 1) expect(planFor(cInput("a1", "idle", { rng: createRng(`alone-${j}`), matesAtDesk: [] })).kind).not.toBe("mate");- return;- }- throw new Error("no visit to a teammate in 300 seeds");- });-- it("gives everyone a place of their own, whatever they pick", () => {- const book = new SpotBook();- const taken = new Map<string, string>();- for (let round = 0; round < 6; round += 1) {- for (const agent of campus.roster) {- const plan = planFor(cInput(agent.agentId, "idle", { rng: createRng(`${agent.agentId}:${round}`), book }));- if (plan.spotId) {- for (const [id, spot] of taken) if (id !== agent.agentId) expect(spot, `${agent.agentId} vs ${id}`).not.toBe(plan.spotId);- taken.set(agent.agentId, plan.spotId);- } else taken.delete(agent.agentId);- }- }- });-});--describe("a round of the team", () => {- const team = (campus.layout.studios ?? []).find((s) => s.teamId === "team-0")!;-- it("brings the free members to their own studio board, each on a place of its own, until it ends", () => {- const book = new SpotBook();- const plans = team.members.map((id) => planFor(cInput(id, "idle", { book, round: { speaker: false } })));- const places = huddlePlaces(campus.layout, campus.grid, team);- for (const plan of plans) {- expect(plan).toMatchObject({ kind: "huddle", pose: "stand", dwellMs: Infinity });- const place = places.find((p) => p.id === plan.spotId)!;- expect(place).toBeDefined();- // Facing the board.- expect(plan.facing).toBeCloseTo(place.facing);- expect(Math.hypot(plan.target.x - team.board!.x, plan.target.z - team.board!.z)).toBeLessThan(5);- }- expect(new Set(plans.map((p) => p.spotId)).size).toBe(team.members.length);- });-- it("never pulls a working member away from its screen, nor a waiting or a resting one", () => {- const id = team.members[2];- const seat = seatOf(cDesk(id)!);- expect(planFor(cInput(id, "working", { round: { speaker: false } }))).toMatchObject({ kind: "work", target: { x: seat.x, z: seat.z } });- expect(planFor(cInput(id, "waiting", { round: { speaker: false } })).kind).toBe("wait");- expect(planFor(cInput(id, "paused", { round: { speaker: false } })).kind).toBe("nap");- });-- it("places the member contributing right now at the board, although its run state reads working", () => {- const plan = planFor(cInput(team.members[1], "working", { round: { speaker: true } }));- expect(plan.kind).toBe("huddle");- expect(huddlePlaces(campus.layout, campus.grid, team).map((p) => p.id)).toContain(plan.spotId);- });-- it("fills the arc nearest the board first, so nobody has to squeeze through the people already there", () => {- const book = new SpotBook();- const board = team.board!;- const places = huddlePlaces(campus.layout, campus.grid, team);- const depth = (id: string | null) => { const p = places.find((q) => q.id === id)!; return Math.hypot(p.x - board.x, p.z - board.z); };- const depths = team.members.map((id) => depth(planFor(cInput(id, "idle", { book, round: { speaker: false } })).spotId));- for (let i = 1; i < depths.length; i += 1) expect(depths[i]).toBeGreaterThanOrEqual(depths[i - 1] - 0.01);- expect(depths[0]).toBeLessThan(depths[depths.length - 1]);- });-- it("leaves the person room: nobody takes a place on the person's toes, and whoever stands there moves aside", () => {- const places = huddlePlaces(campus.layout, campus.grid, team);- const person = { x: places[0].x + 0.2, z: places[0].z };- const book = new SpotBook();- const plans = team.members.slice(0, 4).map((id) => planFor(cInput(id, "idle", { book, person, round: { speaker: false } })));- for (const plan of plans) expect(Math.hypot(plan.target.x - person.x, plan.target.z - person.z)).toBeGreaterThanOrEqual(PERSON_SPACE_M);- // An agent already standing where the person walks to gives the place up for another one.- const mover = team.members[5];- const before = planFor(cInput(mover, "idle", { book, round: { speaker: false } }));- const here = { x: before.target.x, z: before.target.z + 0.3 };- const after = planFor(cInput(mover, "idle", { book, person: here, round: { speaker: false } }));- expect(after.kind).toBe("huddle");- expect(after.spotId).not.toBe(before.spotId);- expect(Math.hypot(after.target.x - here.x, after.target.z - here.z)).toBeGreaterThanOrEqual(PERSON_SPACE_M);- // With no other place left it stays rather than leaving the round.- const full = new SpotBook();- for (const p of places) if (p.id !== before.spotId) full.claim(p.id, `holder-${p.id}`);- full.claim(before.spotId!, mover);- expect(planFor(cInput(mover, "idle", { book: full, person: here, round: { speaker: false } })).spotId).toBe(before.spotId);- });-- it("keeps a member on its place when it is planned again mid-round", () => {- const book = new SpotBook();- const id = team.members[0];- const first = planFor(cInput(id, "idle", { book, round: { speaker: false } }));- for (let i = 0; i < 20; i += 1) {- const again = planFor(cInput(id, i % 2 ? "working" : "idle", { book, rng: createRng(`again-${i}`), round: { speaker: true } }));- expect(again.spotId).toBe(first.spotId);- }- });-- it("gathers a member that sits in another studio at the board of the team whose round it is", () => {- const outsider = "a20";- const plan = planFor(cInput(outsider, "idle", { round: { speaker: false, teamId: "team-0" } }));- expect(plan.kind).toBe("huddle");- expect(huddlePlaces(campus.layout, campus.grid, team).map((p) => p.id)).toContain(plan.spotId);- });-- it("goes back to its desk first when the round has ended", () => {- const id = team.members[3];- const seat = seatOf(cDesk(id)!);- for (let i = 0; i < 20; i += 1) {- expect(planFor(cInput(id, "idle", { rng: createRng(`back-${i}`), backToDesk: true }))).toMatchObject({ kind: "desk", target: { x: seat.x, z: seat.z }, pose: "sit" });- }- });-- it("lets the person's call outrank a round", () => {- const caller = campus.layout.checkpoints.find((c) => c.id === "break")!;- expect(planFor(cInput(team.members[0], "idle", { calledTo: caller, round: { speaker: false } })).kind).toBe("called");- });-});--describe("a team with a lead", () => {- // The same campus, and the same with the first team led by its third member.- const led = campusOf(26, [7, 6, 5], [2]);- const team = studioOfTeam(led.layout, "team-0")!;- const plain = studioOfTeam(campus.layout, "team-0")!;- const places = huddlePlaces(led.layout, led.grid, team);- const centre = leadPlace(places, team)!;- const lInput = (agentId: string, state: AgentRunState, extra: Partial<PlanInput> = {}): PlanInput => ({- agentId, state, desk: allDesks(led.layout).find((d) => d.agentId === agentId) ?? null, layout: led.layout, grid: led.grid,- rng: createRng(agentId), book: new SpotBook(), previous: null, workingColleagues: [], calledTo: null, ...extra,- });-- it("knows its lead, and the lead's place is the middle of the front arc", () => {- expect(team.leadId).toBe(led.teams[0].members[2]);- expect(plain.leadId).toBeNull();- expect(centre.id).toBe(`fan:${team.deptId}:0:0`);- const board = team.board!;- const aside = (p: { x: number; z: number }) => Math.abs((p.x - board.x) * Math.cos(board.facing) - (p.z - board.z) * Math.sin(board.facing));- const front = places.filter((p) => p.id.startsWith(`fan:${team.deptId}:0:`));- for (const p of front) expect(aside(centre)).toBeLessThanOrEqual(aside(p) + 1e-6);- // A studio without a lead has no special place.- expect(leadPlace(huddlePlaces(campus.layout, campus.grid, plain), plain)).toBeNull();- });-- it("stands the lead at the centre of the front arc in a round, whenever it comes", () => {- const lead = team.leadId!;- // First to arrive.- expect(planFor(lInput(lead, "idle", { round: { speaker: false } })).spotId).toBe(centre.id);- // Last to arrive: the others left the place free.- const book = new SpotBook();- const others = team.members.filter((id) => id !== lead).map((id) => planFor(lInput(id, "idle", { book, round: { speaker: false } })));- expect(others.map((p) => p.spotId)).not.toContain(centre.id);- expect(new Set(others.map((p) => p.spotId)).size).toBe(others.length);- expect(planFor(lInput(lead, "idle", { book, round: { speaker: false } })).spotId).toBe(centre.id);- // As the speaker, too.- expect(planFor(lInput(lead, "working", { round: { speaker: true } })).spotId).toBe(centre.id);- });-- it("does not move a working lead, and invents nothing for an idle one", () => {- const lead = team.leadId!;- expect(planFor(lInput(lead, "working", { round: { speaker: false } })).kind).toBe("work");- expect(planFor(lInput(lead, "waiting", { round: { speaker: false } })).kind).toBe("wait");- // No round: the lead's idle day is drawn exactly like a member's, place by place.- const rng = () => createRng("same-seed");- const asLead = Array.from({ length: 1 }, () => { const r = rng(); return Array.from({ length: 60 }, () => planFor(lInput(lead, "idle", { rng: r }))); })[0];- const noLead = { ...led.layout, studios: (led.layout.studios ?? []).map((s) => ({ ...s, leadId: null })) };- const r = rng();- const asMember = Array.from({ length: 60 }, () => planFor(lInput(lead, "idle", { rng: r, layout: noLead })));- expect(asLead.map((p) => [p.kind, p.spotId, p.target.x, p.target.z, p.dwellMs])).toEqual(asMember.map((p) => [p.kind, p.spotId, p.target.x, p.target.z, p.dwellMs]));- });-- it("gives the lead's place to a member only when no other is left, and to the lead another when the person stands on it", () => {- const lead = team.leadId!;- const book = new SpotBook();- for (const p of places) if (p.id !== centre.id) book.claim(p.id, `holder-${p.id}`);- expect(planFor(lInput(team.members[0], "idle", { book, round: { speaker: false } })).spotId).toBe(centre.id);- const plan = planFor(lInput(lead, "idle", { person: { x: centre.x, z: centre.z + 0.2 }, round: { speaker: false } }));- expect(plan.kind).toBe("huddle");- expect(plan.spotId).not.toBe(centre.id);- });-- it("plans a team without a lead exactly as before", () => {- // Round by round and seed by seed, the same places as on the campus that never heard of leads.- const withNull = { ...campus.layout, studios: (campus.layout.studios ?? []).map((s) => ({ ...s, leadId: null })) };- for (let seed = 0; seed < 20; seed += 1) {- const a = new SpotBook(), b = new SpotBook();- for (const id of plain.members) {- const first = planFor(cInput(id, "idle", { book: a, rng: createRng(`${id}:${seed}`), round: { speaker: false } }));- const second = planFor(cInput(id, "idle", { book: b, rng: createRng(`${id}:${seed}`), layout: withNull, round: { speaker: false } }));- expect(second).toEqual(first);- }- }- });-});--describe("a message walked over", () => {- const giver = "a8", receiver = "a1";- const receiverDesk = cDesk(receiver)!;-- it("takes the free sender to a place beside the receiver's chair, to talk for a moment", () => {- const seat = seatOf(receiverDesk);- const plan = planFor(cInput(giver, "idle", { handoff: { to: receiver, desk: receiverDesk, seated: true, at: seat } }));- expect(plan).toMatchObject({ kind: "handoff", pose: "talk", with: receiver, dwellMs: HANDOFF_DWELL_MS });- expect(plan.spotId).toMatch(/^visit:/);- expect(isWalkable(campus.grid, plan.target)).toBe(true);- const gap = Math.hypot(plan.target.x - seat.x, plan.target.z - seat.z);- expect(gap).toBeGreaterThan(BODY_SPACING);- expect(gap).toBeLessThan(1.3);- });-- it("walks to where the receiver stands when it is away from its desk", () => {- const at = campus.layout.spots.find((s) => s.kind === "coffee")!;- const plan = planFor(cInput(giver, "idle", { position: campus.layout.spawn, handoff: { to: receiver, desk: receiverDesk, seated: false, at } }));- expect(plan.kind).toBe("handoff");- expect(isWalkable(campus.grid, plan.target)).toBe(true);- const gap = Math.hypot(plan.target.x - at.x, plan.target.z - at.z);- expect(gap).toBeGreaterThan(BODY_SPACING);- expect(gap).toBeLessThan(1.6);- expect(plan.facing).toBeCloseTo(Math.atan2(at.x - plan.target.x, at.z - plan.target.z));- });-- it("never moves a sender that is working, waiting or resting", () => {- const handoff = { to: receiver, desk: receiverDesk, seated: true, at: seatOf(receiverDesk) };- expect(planFor(cInput(giver, "working", { handoff })).kind).toBe("work");- expect(planFor(cInput(giver, "waiting", { handoff })).kind).toBe("wait");- expect(planFor(cInput(giver, "paused", { handoff })).kind).toBe("nap");- });-- it("is skipped when the receiver is nowhere to be found", () => {- expect(planFor(cInput(giver, "idle", { handoff: { to: "gone", desk: null, seated: false, at: null } })).kind).not.toBe("handoff");- });-});--describe("trips on a small roster", () => {- it("reaches less far the fewer agents there are", () => {- expect(tripReach(1)).toBe(TRIP_REACH.fewM);- expect(tripReach(5)).toBe(TRIP_REACH.fewM);- expect(tripReach(60)).toBe(TRIP_REACH.manyM);- expect(tripReach(18)).toBeGreaterThan(TRIP_REACH.fewM);- expect(tripReach(18)).toBeLessThan(TRIP_REACH.manyM);- });-- it("keeps five agents round their studio and the commons near it instead of crossing the campus", () => {- const small = campusOf(5, [3]);- const desks = new Map(allDesks(small.layout).filter((d) => d.agentId).map((d) => [d.agentId as string, d]));- const far: number[] = [];- let trips = 0, longTrips = 0, plans = 0;- for (const agent of small.roster) {- const studio = homeStudio(small.layout, agent.agentId, desks.get(agent.agentId)!)!;- const rng = createRng(agent.agentId);- const book = new SpotBook();- let previous: ActivityKind | null = null;- for (let i = 0; i < 300; i += 1) {- const plan = planFor({- agentId: agent.agentId, state: "idle", desk: desks.get(agent.agentId)!, layout: small.layout, grid: small.grid, rng, book,- previous, workingColleagues: [], calledTo: null,- });- previous = plan.kind;- plans += 1;- const away = Math.hypot(plan.target.x - studio.centre.x, plan.target.z - studio.centre.z);- if (away > 14) { trips += 1; far.push(away); }- if (away > 30) longTrips += 1;- }- }- // The floor is far larger than that: without the bias its windows and far rooms would take a good share.- const spread = Math.max(...small.layout.spots.map((s) => Math.hypot(s.x, s.z)));- expect(spread).toBeGreaterThan(30);- expect(trips).toBeGreaterThan(0);- expect(longTrips / plans).toBeLessThan(0.03);- expect(trips / plans).toBeLessThan(0.3);- });-- it("still lets a full floor range further", () => {- const share = (count: number, sizes: number[]) => {- const floor = campusOf(count, sizes);- const desks = new Map(allDesks(floor.layout).filter((d) => d.agentId).map((d) => [d.agentId as string, d]));- let long = 0, plans = 0;- for (const agent of floor.roster.slice(0, 5)) {- const studio = homeStudio(floor.layout, agent.agentId, desks.get(agent.agentId)!)!;- const rng = createRng(agent.agentId);- const book = new SpotBook();- for (let i = 0; i < 400; i += 1) {- const plan = planFor({ agentId: agent.agentId, state: "idle", desk: desks.get(agent.agentId)!, layout: floor.layout, grid: floor.grid, rng, book, previous: null, workingColleagues: [], calledTo: null });- plans += 1;- if (Math.hypot(plan.target.x - studio.centre.x, plan.target.z - studio.centre.z) > 22) long += 1;- }- }- return long / plans;- };- // The same five agents of the same first team, alone on the floor and among sixty.- expect(share(60, [5, 9, 8, 7, 6, 6])).toBeGreaterThan(share(5, [5]));- });-});--describe("what a name plate says", () => {- it("calls idle life in the studio what it is, and keeps the team board for a real gathering", () => {- // Standing at the board or beside a studio mate on an ordinary idle day says nothing about teamwork.- expect(shownActivity("huddle", false)).toBe("studio");- expect(shownActivity("mate", false)).toBe("studio");- expect(shownActivity("mate", true)).toBe("studio");- // A running round, or a meeting the person called at the board.- expect(shownActivity("huddle", true)).toBe("huddle");- // Everything else is itself.- for (const kind of ["work", "wait", "desk", "coffee", "studio", "wander", "visit", "handoff", "called", "meeting"] as const) {- expect(shownActivity(kind, false)).toBe(kind);- expect(shownActivity(kind, true)).toBe(kind);- }- });-- it("is never the team board for an idle day without a round, whatever the agent picks", () => {- for (const plan of idleDay("a1", 300)) expect(shownActivity(plan.kind, false)).not.toBe("huddle");- });-});--describe("a rebuilt floor plan", () => {- it("keeps a plan whose place is still there and drops one whose spot is gone or built over", () => {- const spot = campus.layout.spots.find((s) => s.kind === "coffee")!;- const atSpot: Plan = { kind: "coffee", target: { x: spot.x, z: spot.z }, facing: spot.facing, pose: "stand", dwellMs: 9000, spotId: spot.id, with: null };- expect(planStillValid(atSpot, campus.layout, campus.grid)).toBe(true);- expect(planStillValid({ ...atSpot, spotId: "coffee-of-another-floor" }, campus.layout, campus.grid)).toBe(false);- expect(planStillValid({ ...atSpot, target: { x: spot.x + 2, z: spot.z } }, campus.layout, campus.grid)).toBe(false);- const desk = cDesk("a1")!;- const stroll: Plan = { kind: "studio", target: campus.layout.spawn, facing: null, pose: "stand", dwellMs: 8000, spotId: null, with: null };- expect(planStillValid(stroll, campus.layout, campus.grid)).toBe(true);- expect(planStillValid({ ...stroll, target: { x: desk.x, z: desk.z } }, campus.layout, campus.grid)).toBe(false);- // A place of our own (at a board, beside a desk) holds while that board or desk still stands there.- const studio = (campus.layout.studios ?? []).find((s) => s.teamId === "team-0")!;- const place = huddlePlaces(campus.layout, campus.grid, studio)[0];- const atBoard: Plan = { kind: "huddle", target: { x: place.x, z: place.z }, facing: place.facing, pose: "stand", dwellMs: Infinity, spotId: place.id, with: null };- expect(planStillValid(atBoard, campus.layout, campus.grid)).toBe(true);- const slot = visitSlots(desk, campus.grid)[0];- const beside: Plan = { kind: "mate", target: { x: slot.x, z: slot.z }, facing: slot.facing, pose: "stand", dwellMs: 9000, spotId: slot.id, with: "a1" };- expect(planStillValid(beside, campus.layout, campus.grid)).toBe(true);- // The same plans on a floor where the team's studio stands elsewhere: the places are gone.- const moved = campusOf(26, [5, 7, 6]);- expect(planStillValid({ ...atBoard, spotId: "fan:studio-gone:0:0" }, moved.layout, moved.grid)).toBe(false);- expect(planStillValid({ ...atBoard, target: { x: place.x + 3, z: place.z } }, campus.layout, campus.grid)).toBe(false);- expect(planStillValid({ ...beside, spotId: "visit:999.00,999.00", target: { x: 999, z: 999 } }, campus.layout, campus.grid)).toBe(false);- // Plans at the agent's own desk are checked by their desk, not here.- expect(planStillValid({ ...stroll, kind: "work", target: { x: desk.x, z: desk.z } }, campus.layout, campus.grid)).toBe(true);- });-});--describe("a floor several times larger", () => {- it("stretches a stay after a long walk and leaves calls and open-ended stays alone", () => {- const plan: Plan = { kind: "coffee", target: { x: 0, z: 0 }, facing: 0, pose: "stand", dwellMs: 10000, spotId: "coffee-1", with: null };- expect(dwellAfter(plan, 3)).toBe(10000);- expect(dwellAfter(plan, 54)).toBeCloseTo(128000, -2);- expect(dwellAfter(plan, 500)).toBe(150000);- expect(dwellAfter({ ...plan, dwellMs: Infinity }, 54)).toBe(Infinity);- expect(dwellAfter({ ...plan, kind: "handoff" }, 54)).toBe(10000);- expect(dwellAfter({ ...plan, kind: "called" }, 54)).toBe(10000);- });-- it("shows people being somewhere: at any moment about one idle agent in six is on the move, the rest are somewhere", () => {- // 60 idle agents over twenty simulated minutes, each living its seeded day on a shared reservation book.- const big = campusOf(60, [10, 9, 8, 7, 6, 6]);- const book = new SpotBook();- const desks = new Map(allDesks(big.layout).filter((d) => d.agentId).map((d) => [d.agentId as string, d]));- const people = big.roster.map((a) => ({- id: a.agentId, rng: createRng(a.agentId), clock: 0, walked: 0, away: 0, at: seatOf(desks.get(a.agentId)!) as Point,- previous: null as ActivityKind | null, seated: true,- }));- const END_S = 20 * 60;- for (;;) {- const person = people.reduce((a, b) => (a.clock <= b.clock ? a : b));- if (person.clock >= END_S) break;- const studio = homeStudio(big.layout, person.id, desks.get(person.id)!)!;- const matesAtDesk = mateDesks(big.layout, studio, person.id)- .filter((d) => people.find((p) => p.id === d.agentId)?.seated).map((d) => ({ agentId: d.agentId as string, desk: d }));- const plan = planFor({- agentId: person.id, state: "idle", desk: desks.get(person.id)!, layout: big.layout, grid: big.grid, rng: person.rng, book,- previous: person.previous, workingColleagues: [], calledTo: null, position: person.at, matesAtDesk,- });- const path = findPath(big.grid, person.at, plan.target);- expect(path, `${person.id} ${plan.kind}`).not.toBeNull();- const metres = pathLength(person.at, path!);- // The pace at the start of the leg is the fastest it gets; the walk is at least this long.- const walkS = metres / paceFor(metres);- const stayS = dwellAfter(plan, metres) / 1000;- person.walked += walkS;- if (Math.hypot(plan.target.x - studio.centre.x, plan.target.z - studio.centre.z) > 14) person.away += stayS;- person.clock += walkS + stayS;- person.at = plan.target;- person.previous = plan.kind;- person.seated = plan.kind === "desk";- }- const total = people.reduce((s, p) => s + p.clock, 0);- const walking = people.reduce((s, p) => s + p.walked, 0) / total;- expect(walking).toBeLessThan(0.22);- expect(walking).toBeGreaterThan(0.05);- // Nobody is a commuter, and the team members' time is spent near home.- for (const p of people) expect(p.walked / p.clock, p.id).toBeLessThan(0.3);- const members = people.filter((p) => homeStudio(big.layout, p.id, desks.get(p.id)!)!.teamId !== null);- const awayShare = (list: typeof people) => list.reduce((s, p) => s + p.away, 0) / list.reduce((s, p) => s + p.clock, 0);- expect(awayShare(members)).toBeLessThan(0.33);- // Agents without a team are out and about clearly more.- expect(awayShare(people.filter((p) => !members.includes(p)))).toBeGreaterThan(awayShare(members) * 1.25);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeBehavior.ts b/dodaios/ui/web/frontend/src/components/society/office/officeBehavior.tsdeleted file mode 100644index 61301399c4..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeBehavior.ts+++ /dev/null@@ -1,613 +0,0 @@-/**- * What each figure on the office map does, decided client-side and- * deterministically from a seeded random stream.- *- * The map is a projection of the roster: it never starts work, and idle life- * (coffee, couch, wandering) costs zero model calls. Working, waiting and- * paused agents mirror their real run state; only idle agents pick hobbies.- *- * On a floor with team studios an agent belongs somewhere: its idle life- * happens mostly in and around its own studio (its desk, the studio board, a- * teammate's desk, a stroll between the benches), and only sometimes at the- * shared places. Two things outrank idle life because they are real: a round- * of its team (it stands at the studio board) and a message it sent a- * colleague (it walks over). A floor without studios keeps the plain idle- * day.- */-import type { AgentRunState } from "../data";-import { seatOf, standOf, type DeskSlot, type OfficeLayout, type Point, type Rect, type Spot, type SpotKind, type Studio } from "./officeLayout";-import { BODY_SPACING, clearOfBodies, WALK_SPEED } from "./officeMotion";-import { isWalkable, nearestWalkable, randomWalkablePoint, type NavGrid } from "./officeNav";-import { homeStudio, huddlePlaces, leadPlace, studioOfTeam, studioRect, visitSlots, type Place } from "./officeTeams";--export type Pose = "sit" | "stand" | "sleep" | "wave" | "talk" | "work";--export type ActivityKind =- | "work" | "wait" | "desk" | "coffee" | "couch" | "nap" | "window" | "shelf" | "arcade"- | "cooler" | "beanbag" | "meeting" | "board" | "wander" | "visit" | "called"- // Team life: at the own studio board, at a teammate's desk, strolling in the own studio, walking a message over.- | "huddle" | "mate" | "studio" | "handoff";--export interface Plan {- kind: ActivityKind;- target: Point;- /** Heading to settle into on arrival; null = keep the walking heading. */- facing: number | null;- pose: Pose;- dwellMs: number;- spotId: string | null;- /** Agent id being visited. */- with: string | null;-}--/** Deterministic PRNG (mulberry32) seeded from a string hash. */-export function createRng(seed: string): () => number {- // FNV-1a over the UTF-16 code units, then one avalanche round.- let h = 0x811c9dc5;- for (let i = 0; i < seed.length; i += 1) {- h ^= seed.charCodeAt(i);- h = Math.imul(h, 0x01000193);- }- h ^= h >>> 16; h = Math.imul(h, 0x85ebca6b); h ^= h >>> 13;- let state = h >>> 0;- return () => {- state = (state + 0x6d2b79f5) >>> 0;- let t = state;- t = Math.imul(t ^ (t >>> 15), t | 1);- t ^= t + Math.imul(t ^ (t >>> 7), t | 61);- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;- };-}--/** Ids of standing places the floor plan does not list: beside a desk (`visit:`) and at a studio board (`fan:`). */-export function isOwnPlace(spotId: string): boolean {- return spotId.startsWith("visit:") || spotId.startsWith("fan:");-}--/** Exclusive claims on hangout spots: one agent per spot, one spot per agent. */-export class SpotBook {- private bySpot = new Map<string, string>();- private byAgent = new Map<string, string>();-- /** Claim a spot for an agent; releases the agent's previous spot. False if another agent holds it. */- claim(spotId: string, agentId: string): boolean {- const holder = this.bySpot.get(spotId);- if (holder !== undefined && holder !== agentId) return false;- this.release(agentId);- this.bySpot.set(spotId, agentId);- this.byAgent.set(agentId, spotId);- return true;- }-- release(agentId: string): void {- const spotId = this.byAgent.get(agentId);- if (spotId === undefined) return;- this.byAgent.delete(agentId);- if (this.bySpot.get(spotId) === agentId) this.bySpot.delete(spotId);- }-- /**- * Keep only claims on spots that still exist (after the floor plan was- * rebuilt). Claims on places the plan does not list (beside a desk, at a- * studio board) are kept: each belongs to a walker that checks its own- * plan against the new floor (`planStillValid`) and lets go when the place- * is gone. Dropping them here would hand an occupied place to the next- * agent that plans.- */- retain(spotIds: ReadonlySet<string>): void {- for (const [spotId, agentId] of [...this.bySpot]) {- if (!spotIds.has(spotId) && !isOwnPlace(spotId)) { this.bySpot.delete(spotId); this.byAgent.delete(agentId); }- }- }-- holder(spotId: string): string | null {- return this.bySpot.get(spotId) ?? null;- }-- /** The spot an agent holds right now, or null. */- spotOf(agentId: string): string | null {- return this.byAgent.get(agentId) ?? null;- }-- isFree(spotId: string): boolean {- return !this.bySpot.has(spotId);- }-}--export interface PlanInput {- agentId: string;- state: AgentRunState;- desk: DeskSlot | null;- layout: OfficeLayout;- grid: NavGrid;- rng: () => number;- book: SpotBook;- previous: ActivityKind | null;- workingColleagues: { agentId: string; desk: DeskSlot }[];- calledTo: Point | null;- /** Where the agent currently is; lets a called agent stop on its own side of the caller. */- position?: Point | null;- /** A team meeting's chair for this agent (a `meeting-*` spot id); it sits there instead of standing by `calledTo`. */- calledSeat?: string | null;- /**- * The agent's team runs a round right now and this agent takes part in it:- * it stands at the studio board. `speaker` = it is the one contributing at- * the moment (the only working member a round ever moves). `teamId` names- * the team when it is not the agent's home studio (an agent in several teams).- */- round?: { speaker: boolean; teamId?: string | null } | null;- /** A real message this agent sent a colleague and has not walked over yet: the receiver, its desk, and whether it sits there. */- handoff?: { to: string; desk: DeskSlot | null; seated: boolean; at: Point | null } | null;- /** Studio mates sitting at their own desk right now: worth walking over to. */- matesAtDesk?: { agentId: string; desk: DeskSlot }[];- /** The round this agent stood in has just ended: it goes back to its desk before anything else. */- backToDesk?: boolean;- /** Where everybody else stands right now; a place beside a desk that somebody already stands at is not offered. */- bodies?: readonly Point[];- /** Where the person's character stands: agents at a board leave it room. */- person?: Point | null;-}--/** Idle activities and their relative weights on a floor without studios. */-const IDLE_WEIGHTS: readonly [ActivityKind, number][] = [- ["couch", 22], ["coffee", 18], ["window", 12], ["cooler", 8], ["arcade", 8], ["shelf", 7], ["beanbag", 8],- ["meeting", 5], ["board", 4], ["wander", 10], ["visit", 6], ["desk", 10],-];--/**- * What an idle agent with a home does next. `desk`, `mate`, `huddle`, `studio`- * and `near` keep it in and around its studio; `commons` is a trip to a shared- * place anywhere on the floor; `wander` a stroll in the neighbourhood;- * `visit` a look at a busy colleague's desk.- */-export type IdleChoice = "desk" | "mate" | "huddle" | "studio" | "near" | "commons" | "wander" | "visit";--/**- * A team member: four in five of its idle choices keep it at home, one in seven is a trip to a shared place.- * A trip earns a long stay (`dwellAfter`), so by the clock it weighs more than by the count; these numbers are- * tuned for the clock, where a member still spends about two thirds of its idle time in and around its studio.- */-export const TEAM_IDLE_WEIGHTS: readonly [IdleChoice, number][] = [- ["desk", 30], ["mate", 14], ["huddle", 12], ["studio", 12], ["near", 12], ["commons", 14], ["wander", 6],-];--/** An agent without a team (the pool studio): its desk is home, but it uses the shared places far more. */-export const POOL_IDLE_WEIGHTS: readonly [IdleChoice, number][] = [- ["desk", 20], ["studio", 10], ["near", 10], ["visit", 8], ["commons", 40], ["wander", 12],-];--/** Which shared place a trip goes to. */-export const COMMONS_WEIGHTS: readonly [SpotKind, number][] = [- ["couch", 22], ["coffee", 18], ["window", 12], ["cooler", 8], ["arcade", 8], ["shelf", 7], ["beanbag", 8], ["meeting", 4], ["board", 3],-];--const SPOT_KIND: Partial<Record<ActivityKind, SpotKind>> = {- couch: "couch", coffee: "coffee", window: "window", cooler: "cooler", arcade: "arcade",- shelf: "shelf", beanbag: "beanbag", meeting: "meeting", board: "board",-};--const HANGOUT_KINDS: ReadonlySet<SpotKind> = new Set(Object.values(SPOT_KIND));--const CALLED_DISTANCE = 1.2;-const CALLED_DWELL_MS = 15000;-/** How long the sender of a message stays with its receiver. */-export const HANDOFF_DWELL_MS = 8000;-/** Places at the board within this much of the nearest free one count as the same row. */-const HUDDLE_ROW_M = 0.45;-/** An agent at a board keeps this far from the person's character, and makes room when the person comes closer than PERSON_CROWD_M. */-export const PERSON_SPACE_M = 1.25;-export const PERSON_CROWD_M = 0.95;-/** A spot this far beyond the studio's own floor still counts as "round the corner". */-const NEAR_MARGIN_M = 3.5;-/** A stroll in the neighbourhood stays within this distance of the studio's centre. */-const STROLL_RADIUS_M = 12;-/**- * How far a trip to a shared place reaches: at this distance from the studio a place is half as likely as one- * next door, at twice the distance a fifth. A handful of agents on a large campus keep to their neighbourhood- * and the commons at its centre; a full floor ranges further.- */-export const TRIP_REACH = { fewM: 10, manyM: 20, few: 6, many: 30 } as const;--/** The reach of a trip on a floor with `population` seated agents. */-export function tripReach(population: number): number {- const t = Math.min(1, Math.max(0, (population - TRIP_REACH.few) / (TRIP_REACH.many - TRIP_REACH.few)));- return TRIP_REACH.fewM + (TRIP_REACH.manyM - TRIP_REACH.fewM) * t;-}--const populationCache = new WeakMap<OfficeLayout, number>();-/** How many agents have a desk on this floor. */-function populationOf(layout: OfficeLayout): number {- let count = populationCache.get(layout);- if (count === undefined) {- count = layout.lead.desks.filter((d) => d.agentId).length + layout.departments.reduce((n, dept) => n + dept.desks.filter((d) => d.agentId).length, 0);- populationCache.set(layout, count);- }- return count;-}--function between(rng: () => number, minMs: number, maxMs: number): number {- return Math.round(minMs + rng() * (maxMs - minMs));-}--function pick<T>(rng: () => number, items: readonly T[]): T {- return items[Math.min(items.length - 1, Math.floor(rng() * items.length))];-}--function weighted<T>(rng: () => number, options: readonly (readonly [T, number])[]): T {- const total = options.reduce((sum, [, w]) => sum + w, 0);- let roll = rng() * total;- for (const [value, w] of options) {- if (roll < w) return value;- roll -= w;- }- return options[options.length - 1][0];-}--function poseOfSpot(spot: Spot): Pose {- return spot.pose;-}--/** Claim a random free spot matching `filter`; null when all are taken. */-function claimSpot(input: PlanInput, filter: (s: Spot) => boolean): Spot | null {- const free = input.layout.spots.filter((s) => filter(s) && input.book.isFree(s.id));- if (free.length === 0) return null;- const spot = pick(input.rng, free);- input.book.claim(spot.id, input.agentId);- return spot;-}--/** The open office between the north and south strips: the departments' bounding box. */-function openOffice(layout: OfficeLayout): Rect {- if (layout.departments.length === 0) return layout.floor;- return {- minX: Math.min(...layout.departments.map((d) => d.minX)),- maxX: Math.max(...layout.departments.map((d) => d.maxX)),- minZ: Math.min(...layout.departments.map((d) => d.minZ)),- maxZ: Math.max(...layout.departments.map((d) => d.maxZ)),- };-}--/** How often a stroll draws again when its place turns out to be somebody's, or a bottleneck. */-const STROLL_DRAWS = 6;-/** The ring of points round a place that must be floor for it to count as open ground. */-const STANDING_ROOM: readonly [number, number][] = [0, 1, 2, 3, 4, 5, 6, 7].map((i) => [Math.sin((i * Math.PI) / 4) * 0.7, Math.cos((i * Math.PI) / 4) * 0.7]);--/**- * A free patch of floor inside `within` to stroll to: open ground, and not where somebody already stands or- * sits. After a few draws it takes what it has (the walk stops beside whoever is there).- */-function strollPoint(input: PlanInput, within?: Rect): Point | null {- let point = randomWalkablePoint(input.grid, input.rng, within);- const bodies = input.bodies ?? [];- // Open ground: floor a body's width to every side, so nobody stops for a rest in a doorway or a gap between planters.- const roomy = (p: Point) => STANDING_ROOM.every(([dx, dz]) => isWalkable(input.grid, { x: p.x + dx, z: p.z + dz }));- for (let i = 1; i < STROLL_DRAWS && point && !(roomy(point) && clearOfBodies(point, bodies, BODY_SPACING * 1.3)); i += 1) {- point = randomWalkablePoint(input.grid, input.rng, within);- }- return point;-}--function wanderPlan(input: PlanInput, pose: Pose, dwellMs: number): Plan {- const target = strollPoint(input, openOffice(input.layout))- ?? randomWalkablePoint(input.grid, input.rng)- ?? input.layout.spawn;- return { kind: "wander", target, facing: null, pose, dwellMs, spotId: null, with: null };-}--function spotPlan(kind: ActivityKind, spot: Spot, pose: Pose, dwellMs: number): Plan {- return { kind, target: { x: spot.x, z: spot.z }, facing: spot.facing, pose, dwellMs, spotId: spot.id, with: null };-}--function placePlan(kind: ActivityKind, place: Place, pose: Pose, dwellMs: number, withId: string | null = null): Plan {- return { kind, target: { x: place.x, z: place.z }, facing: place.facing, pose, dwellMs, spotId: place.id, with: withId };-}--function deskPlan(desk: DeskSlot, dwellMs: number): Plan {- const seat = seatOf(desk);- return { kind: "desk", target: { x: seat.x, z: seat.z }, facing: seat.facing, pose: "sit", dwellMs, spotId: null, with: null };-}--function calledPlan(input: PlanInput, caller: Point): Plan {- const from = input.position;- let angle: number;- if (from && Math.hypot(from.x - caller.x, from.z - caller.z) > 1e-3) angle = Math.atan2(from.x - caller.x, from.z - caller.z);- else angle = input.rng() * Math.PI * 2;- const wanted = { x: caller.x + Math.sin(angle) * CALLED_DISTANCE, z: caller.z + Math.cos(angle) * CALLED_DISTANCE };- const target = nearestWalkable(input.grid, wanted) ?? nearestWalkable(input.grid, caller) ?? wanted;- const facing = Math.atan2(caller.x - target.x, caller.z - target.z);- return { kind: "called", target, facing, pose: "talk", dwellMs: CALLED_DWELL_MS, spotId: null, with: null };-}--/** A free place for a visitor at `desk`, claimed; null when the desk has none left. */-function claimVisitSlot(input: PlanInput, desk: DeskSlot): Place | null {- const free = visitSlots(desk, input.grid).filter((p) => input.book.isFree(p.id) && clearOfBodies(p, input.bodies ?? []));- if (free.length === 0) return null;- const place = pick(input.rng, free);- input.book.claim(place.id, input.agentId);- return place;-}--/**- * Looking in on a colleague at their desk. The visitor stands and watches: no- * talking pose and no bubble, because nothing was said. Talking is kept for- * exchanges that really happened. Null when both places beside the chair are- * taken: nobody queues up behind a visitor.- */-function visitPlan(input: PlanInput, kind: "visit" | "mate", colleague: { agentId: string; desk: DeskSlot }, dwellMs: number): Plan | null {- const place = claimVisitSlot(input, colleague.desk);- return place ? placePlan(kind, place, "stand", dwellMs, colleague.agentId) : null;-}--/**- * A place at the agent's own studio board, the one it already holds first;- * null when the studio has none left. In a gathering (`gathered`: a round of- * the team, not an idle look at the board) a team with a lead keeps the- * centre of the front arc for it: the lead takes that place when it comes,- * and the others leave it free while any other place is.- */-function huddlePlan(input: PlanInput, studio: Studio, held: string | null, pose: Pose, dwellMs: number, gathered = false): Plan | null {- const places = huddlePlaces(input.layout, input.grid, studio);- const centre = gathered ? leadPlace(places, studio) : null;- // The lead takes its place, unless the person is standing on it.- const personThere = !!centre && !!input.person && Math.hypot(centre.x - input.person.x, centre.z - input.person.z) < PERSON_SPACE_M;- if (centre && !personThere && studio.leadId === input.agentId && input.book.claim(centre.id, input.agentId)) return placePlan("huddle", centre, pose, dwellMs);- const unclaimed = places.filter((p) => input.book.isFree(p.id));- const others = centre && studio.leadId !== input.agentId ? unclaimed.filter((p) => p.id !== centre.id) : unclaimed;- const open = others.length > 0 ? others : unclaimed;- // Not on the person's toes: the places round where the person stands are left empty while there are others.- const person = input.person;- const roomy = person ? open.filter((p) => Math.hypot(p.x - person.x, p.z - person.z) >= PERSON_SPACE_M) : open;- const free = roomy.length > 0 ? roomy : open;- if (free.length === 0) return null;- const kept = held ? free.find((p) => p.id === held) : undefined;- // The row nearest the board fills up first, then the ones behind it: whoever comes later never has to squeeze- // through the people already standing there. Within a row the place is the agent's own draw.- const board = studio.board!;- const fromBoard = (p: Place) => Math.hypot(p.x - board.x, p.z - board.z);- const nearest = Math.min(...free.map(fromBoard));- const row = free.filter((p) => fromBoard(p) <= nearest + HUDDLE_ROW_M);- const place = kept ?? pick(input.rng, row);- input.book.claim(place.id, input.agentId);- return placePlan("huddle", place, pose, dwellMs);-}--/** Walking a real message over: beside the receiver's chair when it sits there, else a step from where it stands. */-function handoffPlan(input: PlanInput): Plan | null {- const handoff = input.handoff;- if (!handoff) return null;- if (handoff.desk && handoff.seated) {- const place = claimVisitSlot(input, handoff.desk);- if (place) return placePlan("handoff", place, "talk", HANDOFF_DWELL_MS, handoff.to);- }- const at = handoff.at ?? (handoff.desk ? standOf(handoff.desk) : null);- if (!at) return null;- const from = input.position;- const angle = from && Math.hypot(from.x - at.x, from.z - at.z) > 1e-3 ? Math.atan2(from.x - at.x, from.z - at.z) : input.rng() * Math.PI * 2;- const wanted = { x: at.x + Math.sin(angle) * 0.95, z: at.z + Math.cos(angle) * 0.95 };- const target = nearestWalkable(input.grid, wanted, 1.5) ?? nearestWalkable(input.grid, at);- if (!target) return null;- return { kind: "handoff", target, facing: Math.atan2(at.x - target.x, at.z - target.z), pose: "talk", dwellMs: HANDOFF_DWELL_MS, spotId: null, with: handoff.to };-}--function spotVisit(kind: ActivityKind, spot: Spot, rng: () => number, away: boolean): Plan {- if (kind === "couch") return spotPlan(kind, spot, "sit", away ? between(rng, 30000, 60000) : between(rng, 20000, 45000));- return spotPlan(kind, spot, poseOfSpot(spot) === "sleep" ? "sit" : poseOfSpot(spot), away ? between(rng, 15000, 35000) : between(rng, 8000, 25000));-}--/** The plain idle day of a floor without studios. */-function idlePlan(input: PlanInput): Plan {- const { rng, desk, previous } = input;- const colleagues = input.workingColleagues.filter((c) => c.agentId !== input.agentId);- const available = IDLE_WEIGHTS.filter(([kind]) => {- if (kind === "visit") return colleagues.length > 0;- if (kind === "desk") return desk !== null;- return true;- });- const options = available.length > 1 ? available.filter(([kind]) => kind !== previous) : available;- const kind = weighted(rng, options);-- if (kind === "wander") return wanderPlan(input, "stand", between(rng, 6000, 12000));- if (kind === "desk" && desk) return deskPlan(desk, between(rng, 15000, 30000));- if (kind === "visit") {- return visitPlan(input, "visit", pick(rng, colleagues), between(rng, 8000, 15000)) ?? wanderPlan(input, "stand", between(rng, 6000, 12000));- }- const spotKind = SPOT_KIND[kind];- const spot = spotKind ? claimSpot(input, (s) => s.kind === spotKind) : null;- if (!spot) return wanderPlan(input, "stand", between(rng, 6000, 12000));- return spotVisit(kind, spot, rng, false);-}--/** Which idle choice an activity came from, so the same one is not taken twice in a row. */-function choiceOf(kind: ActivityKind | null): IdleChoice | null {- if (kind === null) return null;- if (kind === "desk" || kind === "mate" || kind === "huddle" || kind === "studio" || kind === "wander" || kind === "visit") return kind;- return SPOT_KIND[kind] ? "commons" : null;-}--function strollPlan(input: PlanInput, kind: "studio" | "wander", within: Rect): Plan {- const target = strollPoint(input, within)- ?? nearestWalkable(input.grid, { x: (within.minX + within.maxX) / 2, z: (within.minZ + within.maxZ) / 2 })- ?? input.layout.spawn;- return { kind, target, facing: null, pose: "stand", dwellMs: between(input.rng, 6000, 12000), spotId: null, with: null };-}--/** Idle life with a home: mostly in and around the studio, sometimes at the shared places. */-function homeIdlePlan(input: PlanInput, studio: Studio): Plan {- const { rng, desk, previous, layout, book } = input;- const rect = studioRect(layout, studio);- const mates = (input.matesAtDesk ?? []).filter((m) => m.agentId !== input.agentId);- const colleagues = input.workingColleagues.filter((c) => c.agentId !== input.agentId);- const reach = Math.hypot(rect.maxX - rect.minX, rect.maxZ - rect.minZ) / 2 + NEAR_MARGIN_M;- const fromHome = (s: Point) => Math.hypot(s.x - studio.centre.x, s.z - studio.centre.z);- // Only kinds an activity exists for; a team room chair is a trip, not a place round the corner.- const hangout = (s: Spot) => HANGOUT_KINDS.has(s.kind) && s.kind !== "meeting" && book.isFree(s.id);- const nearby = layout.spots.filter((s) => hangout(s) && fromHome(s) <= reach);-- const table = studio.teamId === null ? POOL_IDLE_WEIGHTS : TEAM_IDLE_WEIGHTS;- const available = table.filter(([choice]) => {- if (choice === "desk") return desk !== null;- if (choice === "mate") return mates.length > 0;- if (choice === "huddle") return studio.board !== null;- if (choice === "near") return nearby.length > 0;- if (choice === "visit") return colleagues.length > 0;- return true;- });- const last = choiceOf(previous);- const options = available.length > 1 ? available.filter(([choice]) => choice !== last) : available;- const choice = weighted(rng, options);- const stroll = () => strollPlan(input, "studio", rect);-- // Its own desk is where an agent with a home spends its longest stretches.- if (choice === "desk" && desk) return deskPlan(desk, between(rng, 40000, 90000));- if (choice === "mate") return visitPlan(input, "mate", pick(rng, mates), between(rng, 12000, 24000)) ?? stroll();- if (choice === "visit") return visitPlan(input, "visit", pick(rng, colleagues), between(rng, 8000, 15000)) ?? stroll();- if (choice === "huddle") return huddlePlan(input, studio, null, "stand", between(rng, 12000, 25000)) ?? stroll();- if (choice === "studio") return stroll();- if (choice === "near") {- const spot = pick(rng, nearby);- book.claim(spot.id, input.agentId);- return spotVisit(spot.kind as ActivityKind, spot, rng, false);- }- if (choice === "commons") {- // Every free shared place is a candidate, weighted by what it is and by how far from home it lies: nobody- // crosses the campus for a window when there is a coffee round the corner, and a small roster stays near.- const reachM = tripReach(populationOf(layout));- const kindWeight = new Map(COMMONS_WEIGHTS);- const open = layout.spots.filter((s) => kindWeight.has(s.kind) && book.isFree(s.id));- if (open.length === 0) return stroll();- const perKind = new Map<SpotKind, number>();- for (const s of open) perKind.set(s.kind, (perKind.get(s.kind) ?? 0) + 1);- const spot = weighted(rng, open.map((s) => [s, ((kindWeight.get(s.kind) ?? 0) / (perKind.get(s.kind) ?? 1)) / (1 + (fromHome(s) / reachM) ** 2)] as const));- book.claim(spot.id, input.agentId);- return spotVisit(spot.kind as ActivityKind, spot, rng, true);- }- const c = studio.centre;- return strollPlan(input, "wander", { minX: c.x - STROLL_RADIUS_M, maxX: c.x + STROLL_RADIUS_M, minZ: c.z - STROLL_RADIUS_M, maxZ: c.z + STROLL_RADIUS_M });-}--/** Decide the next activity for one agent. Releases its previous spot claim first. */-export function planFor(input: PlanInput): Plan {- const { agentId, state, desk, book } = input;- const held = book.spotOf(agentId);- book.release(agentId);-- // A working agent stays at its screen: the map mirrors real work and never interrupts it, not even visually.- if (input.calledTo && input.state !== "working") {- // A meeting seats its members: the assigned chair, else any free chair at the table, else standing by it.- // A meeting at a studio's own board: the member stands on its place in the arcs.- if (input.calledSeat?.startsWith("fan:")) {- const seat = input.calledSeat;- const at = (input.layout.studios ?? []).filter((s) => seat.startsWith(`fan:${s.deptId}:`))- .flatMap((s) => huddlePlaces(input.layout, input.grid, s)).find((p) => p.id === seat);- if (at && book.claim(at.id, agentId)) return placePlan("huddle", at, "stand", Infinity);- } else if (input.calledSeat) {- const assigned = input.layout.spots.find((s) => s.id === input.calledSeat);- if (assigned && book.claim(assigned.id, agentId)) return spotPlan("meeting", assigned, "sit", Infinity);- const other = claimSpot(input, (s) => s.kind === "meeting");- if (other) return spotPlan("meeting", other, "sit", Infinity);- }- return calledPlan(input, input.calledTo);- }-- const studio = homeStudio(input.layout, agentId, desk);-- // A round of the agent's team: free members stand at the studio board until it ends. Working members stay at- // their screen, with one exception that is the round itself: the member contributing right now.- const roundStudio = (input.round?.teamId ? studioOfTeam(input.layout, input.round.teamId) : null) ?? studio;- if (input.round && roundStudio && (state === "idle" || (state === "working" && input.round.speaker))) {- const plan = huddlePlan(input, roundStudio, held, "stand", Infinity, true);- if (plan) return plan;- }-- if (state === "working") {- if (desk) {- const seat = seatOf(desk);- return { kind: "work", target: { x: seat.x, z: seat.z }, facing: seat.facing, pose: "work", dwellMs: Infinity, spotId: null, with: null };- }- const spot = claimSpot(input, (s) => s.kind === "window");- if (spot) return spotPlan("work", spot, "work", Infinity);- return { ...wanderPlan(input, "work", Infinity), kind: "work" };- }-- if (state === "waiting") {- if (desk) {- const stand = standOf(desk);- // It stands where a visitor to its desk would: holding that place keeps anyone from being sent there meanwhile.- const beside = visitSlots(desk, input.grid).find((p) => p.x > stand.x - 0.3 && Math.hypot(p.x - stand.x, p.z - stand.z) < BODY_SPACING);- const held = beside && book.claim(beside.id, agentId) ? beside.id : null;- return { kind: "wait", target: { x: stand.x, z: stand.z }, facing: stand.facing, pose: "wave", dwellMs: Infinity, spotId: held, with: null };- }- const spot = claimSpot(input, (s) => s.pose === "stand" && s.kind !== "huddle");- if (spot) return spotPlan("wait", spot, "wave", Infinity);- return { ...wanderPlan(input, "wave", Infinity), kind: "wait" };- }-- if (state === "paused") {- const bed = claimSpot(input, (s) => s.pose === "sleep");- if (bed) return spotPlan("nap", bed, "sleep", Infinity);- const couch = claimSpot(input, (s) => s.kind === "couch");- if (couch) return spotPlan("nap", couch, "sit", Infinity);- if (desk) {- const seat = seatOf(desk);- return { kind: "nap", target: { x: seat.x, z: seat.z }, facing: seat.facing, pose: "sit", dwellMs: Infinity, spotId: null, with: null };- }- return { ...wanderPlan(input, "sit", Infinity), kind: "nap" };- }-- const handoff = handoffPlan(input);- if (handoff) return handoff;- if (input.backToDesk && desk) return deskPlan(desk, between(input.rng, 12000, 24000));- return studio ? homeIdlePlan(input, studio) : idlePlan(input);-}--/**- * Does a plan made on an earlier floor plan still hold on this one? A spot- * must still exist where it was; a place to stand must still be floor. Plans- * bound to the agent's own desk are checked by their desk, not here.- */-export function planStillValid(plan: Plan, layout: OfficeLayout, grid: NavGrid): boolean {- if (plan.kind === "work" || plan.kind === "wait" || plan.kind === "desk") return true;- if (plan.spotId && !isOwnPlace(plan.spotId)) {- const spot = layout.spots.find((s) => s.id === plan.spotId);- return !!spot && Math.hypot(spot.x - plan.target.x, spot.z - plan.target.z) < 0.05;- }- if (plan.spotId) {- // A place of our own must still be one on this floor: at a studio's board, or beside a desk that stands there.- const id = plan.spotId;- const places = id.startsWith("fan:")- ? (layout.studios ?? []).filter((s) => id.startsWith(`fan:${s.deptId}:`)).flatMap((s) => huddlePlaces(layout, grid, s))- : layout.departments.flatMap((d) => d.desks).flatMap((d) => visitSlots(d, grid));- return places.some((p) => p.id === id && Math.hypot(p.x - plan.target.x, p.z - plan.target.z) < 0.05);- }- if (plan.kind === "nap") return true;- return isWalkable(grid, plan.target);-}--/**- * What a name plate may say an agent is doing. Standing at the studio board- * and looking in on a studio mate are part of an idle agent's day, and say- * nothing about teamwork: both read as being in the studio. "At the team- * board" is kept for a gathering that is real (`gathered`: a running round of- * the team, or a meeting the person called there).- */-export function shownActivity(kind: ActivityKind, gathered: boolean): ActivityKind {- if (kind === "mate") return "studio";- if (kind === "huddle" && !gathered) return "studio";- return kind;-}--/** The longest an idle activity is stretched to. */-const LONGEST_DWELL_MS = 150_000;-/** A stay lasts at least this many times as long as the walk to it would take at walking pace. */-const STAY_PER_WALK = 3.2;--/**- * How long to stay after walking `walkedM` metres to get there. A long way- * earns a long stay — at least about three times the time the walk would- * take at walking pace — so a large floor shows people being somewhere, not a- * crowd in transit. Calls, hand-offs and open-ended stays keep their own time.- */-export function dwellAfter(plan: Plan, walkedM: number): number {- if (!Number.isFinite(plan.dwellMs) || plan.kind === "called" || plan.kind === "handoff") return plan.dwellMs;- return Math.min(LONGEST_DWELL_MS, Math.max(plan.dwellMs, (walkedM / WALK_SPEED) * 1000 * STAY_PER_WALK));-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeCamera.test.ts b/dodaios/ui/web/frontend/src/components/society/office/officeCamera.test.tsdeleted file mode 100644index 7ed514b404..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeCamera.test.ts+++ /dev/null@@ -1,127 +0,0 @@-import { describe, expect, it } from "vitest";-import {- cameraHome, CAMERA_LIMITS, depthNear, farZoomBoost, FOLLOW_DISTANCE_M, followDistanceAfterOverview, frameDistance, settleView, WALK_VIEW_MAX_M, wheelZoomSpeed,-} from "./officeCamera";--/** OrbitControls' dolly factor for one wheel event at this zoom speed. */-const step = (speed: number) => 1 / Math.pow(0.95, speed);-/** Wheel events of this size needed to zoom from `from` to `to` metres. */-const eventsFor = (from: number, to: number, deltaY: number, deltaMode = 0) =>- Math.ceil(Math.log(from / to) / Math.log(step(wheelZoomSpeed(deltaY, deltaMode))));--describe("office wheel zoom", () => {- it("brings the overview down to the character in a handful of mouse notches", () => {- const overview = cameraHome({ minX: -14, maxX: 14, minZ: -22, maxZ: 22 }, 16 / 9);- const distance = Math.hypot(...overview.position.map((v, i) => v - overview.target[i]) as [number, number, number]);- expect(eventsFor(distance, 15, 100)).toBeLessThanOrEqual(12);- });-- it("zooms by how far the wheel turned, so a trackpad's small steps stay small", () => {- expect(wheelZoomSpeed(4)).toBeLessThan(wheelZoomSpeed(100) / 10);- expect(wheelZoomSpeed(-100)).toBe(wheelZoomSpeed(100));- // A whole trackpad swipe of 100 px moves about as far as one notch.- const swipe = Math.pow(step(wheelZoomSpeed(4)), 25);- expect(swipe).toBeCloseTo(step(wheelZoomSpeed(100)), 1);- });-- it("reads line and page wheel modes and caps a single huge event", () => {- expect(wheelZoomSpeed(3, 1)).toBeGreaterThan(wheelZoomSpeed(100));- expect(wheelZoomSpeed(1, 2)).toBe(wheelZoomSpeed(100_000));- expect(step(wheelZoomSpeed(100_000))).toBeLessThan(1.4);- expect(wheelZoomSpeed(0)).toBeGreaterThan(0);- });-- it("lets the camera come close enough to read a desk, and never inside the character", () => {- expect(CAMERA_LIMITS.minDistance).toBeLessThanOrEqual(3);- expect(CAMERA_LIMITS.minDistance).toBeGreaterThanOrEqual(2);- });-});--/** Smallest depth step a 24-bit buffer resolves at `depth` metres with this near plane. */-const depthStep = (depth: number, near: number) => (depth * depth) / (near * 2 ** 24);--describe("office depth precision", () => {- it("keeps the oak floor 1 mm above the slab resolvable at every zoom", () => {- for (const distance of [CAMERA_LIMITS.minDistance, 15, 40, 90, CAMERA_LIMITS.maxDistance]) {- // The far edge of the floor lies up to ~30 m behind the orbit target.- expect(depthStep(distance + 30, depthNear(distance))).toBeLessThan(0.001);- }- });-- it("never clips the floor or the walls in front of the camera", () => {- for (const distance of [CAMERA_LIMITS.minDistance, 15, 40, 90, CAMERA_LIMITS.maxDistance]) {- // At the flattest allowed tilt the camera still stands this high above the floor.- const height = distance * Math.cos(CAMERA_LIMITS.maxPolar);- expect(depthNear(distance)).toBeLessThan(Math.max(0.5, height - 3));- }- expect(depthNear(CAMERA_LIMITS.minDistance)).toBe(0.2);- });-});--describe("wheel zoom on a large floor", () => {- /** Mouse notches from `from` metres until the camera is within `to`, each notch zooming for the distance it starts at. */- const notches = (from: number, to: number) => {- let distance = from, count = 0;- while (distance > to && count < 100) { distance /= step(wheelZoomSpeed(100, 0, distance)); count += 1; }- return count;- };- // The overview of a campus of sixty agents in six teams.- const overview = frameDistance({ minX: -29.2, maxX: 29.2, minZ: -33.2, maxZ: 33.2 }, 16 / 9);-- it("comes down from the overview of a campus to a studio in a few notches", () => {- expect(overview).toBeGreaterThan(80);- expect(notches(overview, 30)).toBeLessThanOrEqual(5);- expect(notches(overview, FOLLOW_DISTANCE_M)).toBeLessThanOrEqual(10);- // The same way took more than twice as many notches at one fixed step.- expect(Math.ceil(Math.log(overview / FOLLOW_DISTANCE_M) / Math.log(step(wheelZoomSpeed(100))))).toBeGreaterThan(14);- });-- it("stays as fine as it was near the character", () => {- expect(farZoomBoost(0)).toBe(1);- expect(farZoomBoost(FOLLOW_DISTANCE_M)).toBe(1);- expect(wheelZoomSpeed(100, 0, 10)).toBe(wheelZoomSpeed(100));- expect(wheelZoomSpeed(4, 0, 10)).toBe(wheelZoomSpeed(4));- // Further out each notch reaches further, smoothly, and no further than a third of the way.- for (let d = 10; d < 200; d += 5) expect(farZoomBoost(d + 5)).toBeGreaterThanOrEqual(farZoomBoost(d));- expect(step(wheelZoomSpeed(100, 0, 400))).toBeLessThan(1.6);- // A trackpad's small steps stay small far out, too.- expect(wheelZoomSpeed(4, 0, 100)).toBeLessThan(wheelZoomSpeed(100, 0, 100) / 10);- });-});--describe("following after the overview", () => {- it("returns to the distance the person walked at, or to the default when that was no walking view", () => {- expect(followDistanceAfterOverview(11)).toBe(11);- expect(followDistanceAfterOverview(WALK_VIEW_MAX_M)).toBe(WALK_VIEW_MAX_M);- expect(followDistanceAfterOverview(80)).toBe(FOLLOW_DISTANCE_M);- expect(followDistanceAfterOverview(null)).toBe(FOLLOW_DISTANCE_M);- expect(followDistanceAfterOverview(0.5)).toBe(CAMERA_LIMITS.minDistance);- });-});--describe("a remembered view on a rebuilt floor", () => {- const bounds = { minX: -20, maxX: 20, minZ: -20, maxZ: 20 };- const wall = { minX: 4.94, maxX: 5.06, minZ: -10, maxZ: 10 };-- it("is kept as it is when it still fits", () => {- const pose = { position: [10, 9, 10] as [number, number, number], target: [0, 0.8, 0] as [number, number, number] };- expect(settleView(pose, bounds, [wall])).toBe(pose);- // High above a wall is not inside it.- const above = { position: [5, 6, 0] as [number, number, number], target: [0, 0.8, 0] as [number, number, number] };- expect(settleView(above, bounds, [wall])).toBe(above);- });-- it("is dropped when it looks at a place the floor no longer has", () => {- expect(settleView({ position: [40, 9, 40], target: [30, 0.8, 30] }, bounds, [])).toBeNull();- });-- it("backs a camera out of a wall along its line of sight", () => {- const settled = settleView({ position: [5, 2, 0], target: [1, 0.8, 0] }, bounds, [wall])!;- expect(settled.target).toEqual([1, 0.8, 0]);- // Outside the wall and its margin, further from the target, on the same line.- expect(settled.position[0]).toBeGreaterThan(5.06 + 0.35);- expect(settled.position[0]).toBeLessThan(7);- expect(settled.position[2]).toBeCloseTo(0);- expect((settled.position[1] - 0.8) / (settled.position[0] - 1)).toBeCloseTo((2 - 0.8) / (5 - 1), 6);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeCamera.testkit.ts b/dodaios/ui/web/frontend/src/components/society/office/officeCamera.testkit.tsdeleted file mode 100644index 66f9b1327e..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeCamera.testkit.ts+++ /dev/null@@ -1,41 +0,0 @@-/**- * Test support for the camera: projects a floor's corners through a camera- * pose with three.js itself, independent of the fit maths under test.- */-import { PerspectiveCamera, Vector3 } from "three";-import { CAMERA_FOV, cameraLimitsFor, type Bounds, type CameraPose } from "./officeCamera";--export interface ViewBox { minX: number; maxX: number; minY: number; maxY: number }--/**- * Are all corners of `bounds` (on the floor and 3 m up) inside the view, how close to an edge does the floor- * reach (0..1), and which box of the view (-1..1 on both axes) do they span?- */-export function cornersInView(bounds: Bounds, pose: CameraPose, aspect: number): { inside: boolean; widest: number; box: ViewBox } {- const camera = new PerspectiveCamera(CAMERA_FOV, aspect, 0.2, 5000);- camera.position.set(...pose.position);- camera.lookAt(new Vector3(...pose.target));- camera.updateMatrixWorld(true);- camera.updateProjectionMatrix();- let widest = 0;- let inside = true;- const box: ViewBox = { minX: Infinity, maxX: -Infinity, minY: Infinity, maxY: -Infinity };- for (const x of [bounds.minX, bounds.maxX]) {- for (const z of [bounds.minZ, bounds.maxZ]) {- for (const y of [0, 3]) {- const p = new Vector3(x, y, z).project(camera);- const reach = Math.max(Math.abs(p.x), Math.abs(p.y));- if (reach > 1 || p.z > 1 || p.z < -1) inside = false;- widest = Math.max(widest, reach);- box.minX = Math.min(box.minX, p.x); box.maxX = Math.max(box.maxX, p.x);- box.minY = Math.min(box.minY, p.y); box.maxY = Math.max(box.maxY, p.y);- }- }- }- return { inside, widest, box };-}--/** The limits for the most demanding common viewport (portrait side panel). */-export function campusLimits(bounds: Bounds) {- return cameraLimitsFor(bounds, 0.62);-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeCamera.ts b/dodaios/ui/web/frontend/src/components/society/office/officeCamera.tsdeleted file mode 100644index 4012a2fee2..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeCamera.ts+++ /dev/null@@ -1,287 +0,0 @@-/**- * The office camera: a three-quarter view from the south-east, looking down- * at about 40°, framed so the whole floor fits the viewport. Pure and tested.- */-export const CAMERA_FOV = 35;--export const CAMERA_LIMITS = {- /** Polar angle from straight down: ~20° (near top-down) to ~72° (near eye level). */- minPolar: 0.35,- maxPolar: 1.25,- /** Close enough to read a desk or a wardrobe shelf, far enough to stay outside the character. */- minDistance: 2.5,- maxDistance: 140,-} as const;--/** Near clip plane up close, and the most it may grow to when zoomed out (a whole campus in view). */-const NEAR_MIN = 0.2;-const NEAR_MAX = 20;-/** Near plane per metre of orbit distance: the closest geometry is always far more than this in front. */-const NEAR_PER_METRE = 0.04;--/**- * The near clip plane for a camera this far from its orbit target. Depth- * precision falls with distance squared over the near plane: with a fixed- * 0.2 m near plane, the oak floor 1 mm above the dark slab fought it in black- * bands once the camera was zoomed out (~0.6 cm of precision at 140 m).- * Growing the near plane with the zoom keeps it under a millimetre everywhere.- */-export function depthNear(distance: number): number {- return Math.min(NEAR_MAX, Math.max(NEAR_MIN, distance * NEAR_PER_METRE));-}--/**- * A press that travelled further than this (CSS px) turned the camera; the- * click it ends in is not a click. Measured over the whole press, so a drag- * that comes back to where it started still counts as a drag.- */-export const DRAG_CLICK_PX = 6;--/** One mouse-wheel notch, in CSS px, as browsers report it in pixel mode. */-const WHEEL_NOTCH_PX = 100;-/** How far one notch zooms, as OrbitControls' zoomSpeed: 0.95^2.4 ≈ 12 % closer or further. */-const ZOOM_SPEED_PER_NOTCH = 2.4;-/** From this orbit distance on a notch zooms further, up to FAR_ZOOM.boost times as far at FAR_ZOOM.full metres. */-const FAR_ZOOM = { from: 15, full: 90, boost: 3.5 } as const;--/** How much further one wheel notch zooms at this orbit distance than up close: 1 near the character, 3.5 from the overview of a campus. */-export function farZoomBoost(distance: number): number {- const t = Math.min(1, Math.max(0, (distance - FAR_ZOOM.from) / (FAR_ZOOM.full - FAR_ZOOM.from)));- return 1 + (FAR_ZOOM.boost - 1) * t;-}--/**- * OrbitControls' zoomSpeed for one wheel event, proportional to how far the- * wheel turned. The controls zoom a fixed step per event whatever its size:- * a mouse notch crawled (~20 notches from the overview to the character) and- * a trackpad, which sends dozens of tiny events, raced. `deltaMode` 1 is- * lines, 2 pages (Firefox, some mice).- *- * `distance` is the camera's orbit distance: far out a notch covers more of- * the way (12 % up close, 35 % from a campus overview), so zooming from the- * overview of a large floor down to a studio takes a few notches, and the- * last metres stay fine.- */-export function wheelZoomSpeed(deltaY: number, deltaMode = 0, distance = 0): number {- const px = Math.abs(deltaY) * (deltaMode === 1 ? 40 : deltaMode === 2 ? 800 : 1);- const perNotch = ZOOM_SPEED_PER_NOTCH * farZoomBoost(distance);- return Math.min(perNotch * 2.5, Math.max(0.02, (px / WHEEL_NOTCH_PX) * perNotch));-}--/** Look-down angle below the horizon and yaw east of south for the home view. */-export const HOME_PITCH_RAD = (40 * Math.PI) / 180;-export const HOME_YAW_RAD = (38 * Math.PI) / 180;--export interface Bounds { minX: number; maxX: number; minZ: number; maxZ: number }-export interface CameraPose { position: [number, number, number]; target: [number, number, number] }--/** Distance that fits a floor of this footprint into a viewport of this aspect. */-export function fitDistance(bounds: Bounds, aspect: number, fovDeg = CAMERA_FOV, tightness = 0.62, maxDistance: number = CAMERA_LIMITS.maxDistance): number {- const width = bounds.maxX - bounds.minX;- const depth = bounds.maxZ - bounds.minZ;- // Seen diagonally, the floor's screen width is roughly its diagonal; its- // screen height is the diagonal foreshortened by the look-down angle.- const diagonal = Math.hypot(width, depth);- const vHalf = ((fovDeg * Math.PI) / 180) / 2;- const hHalf = Math.atan(Math.tan(vHalf) * Math.max(0.3, aspect));- const needH = (diagonal * 0.5) / Math.tan(hHalf);- const needV = (diagonal * Math.sin(HOME_PITCH_RAD) * 0.5 + 1.5) / Math.tan(vHalf);- return Math.min(maxDistance, Math.max(CAMERA_LIMITS.minDistance, Math.max(needH, needV) * tightness));-}--/** How much of the viewport the overview fills: a margin stays for the HUD cards round the edge. */-const OVERVIEW_FILL = 0.9;-/** The overview also keeps what stands this high on the floor's edge in view (walls, signs, name plates). */-const OVERVIEW_HEADROOM_M = 3;--/** The home view's unit vectors: from the target towards the camera, and the camera's right and up. */-function homeAxes(): { back: [number, number, number]; right: [number, number, number]; up: [number, number, number] } {- const cp = Math.cos(HOME_PITCH_RAD), sp = Math.sin(HOME_PITCH_RAD);- const sy = Math.sin(HOME_YAW_RAD), cy = Math.cos(HOME_YAW_RAD);- return { back: [sy * cp, sp, cy * cp], right: [cy, 0, -sy], up: [-sy * sp, cp, -cy * sp] };-}--/**- * The distance from which the home view holds every corner of `bounds` (on- * the floor and `headroom` above it) inside the viewport: the exact fit, by- * projecting the corners, for a floor of any size and shape.- */-export function frameDistance(bounds: Bounds, aspect: number, fovDeg = CAMERA_FOV, fill = OVERVIEW_FILL, headroom = OVERVIEW_HEADROOM_M): number {- const { back, right, up } = homeAxes();- const tanV = Math.tan((fovDeg * Math.PI) / 360) * fill;- const tanH = Math.tan((fovDeg * Math.PI) / 360) * Math.max(0.3, aspect) * fill;- const cx = (bounds.minX + bounds.maxX) / 2, cz = (bounds.minZ + bounds.maxZ) / 2;- let need: number = CAMERA_LIMITS.minDistance;- for (const x of [bounds.minX, bounds.maxX]) {- for (const z of [bounds.minZ, bounds.maxZ]) {- for (const y of [0, headroom]) {- const p: [number, number, number] = [x - cx, y, z - cz];- const dot = (a: [number, number, number]) => p[0] * a[0] + p[1] * a[1] + p[2] * a[2];- // A point this far towards the camera is that much closer to it than the target is.- const towards = dot(back);- need = Math.max(need, Math.abs(dot(right)) / tanH + towards, Math.abs(dot(up)) / tanV + towards);- }- }- }- return need;-}--/** How much of the viewport's binding axis the floor spans in the overview. */-export const OVERVIEW_SPAN = 0.85;--/**- * Where the corners of `bounds` (on the floor and `headroom` above it) land- * in the view of a home-angle camera looking at `target` from `distance`:- * the box they span, in viewport units from -1 to 1.- */-function projectedBox(bounds: Bounds, target: readonly [number, number], distance: number, aspect: number, fovDeg: number, headroom: number) {- const { back, right, up } = homeAxes();- const tanV = Math.tan((fovDeg * Math.PI) / 360);- const tanH = tanV * Math.max(0.3, aspect);- let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;- for (const x of [bounds.minX, bounds.maxX]) {- for (const z of [bounds.minZ, bounds.maxZ]) {- for (const y of [0, headroom]) {- const p: [number, number, number] = [x - target[0], y, z - target[1]];- const dot = (a: [number, number, number]) => p[0] * a[0] + p[1] * a[1] + p[2] * a[2];- const depth = Math.max(0.01, distance - dot(back));- const sx = dot(right) / (depth * tanH), sy = dot(up) / (depth * tanV);- minX = Math.min(minX, sx); maxX = Math.max(maxX, sx); minY = Math.min(minY, sy); maxY = Math.max(maxY, sy);- }- }- }- return { minX, maxX, minY, maxY };-}--/**- * The overview: the whole floor, railing included, from the home angle,- * fitted to the viewport. The near corner of a floor seen at an angle looms- * larger than the far one, so looking at the floor's middle leaves the upper- * part of the view empty and the plan small; instead the look-at point is- * moved until the plan sits in the middle of the view, and the camera comes- * as close as the plan allows: it spans `OVERVIEW_SPAN` of whichever axis of- * the viewport binds (the height in a wide window, the width in a narrow- * panel).- */-export function campusOverview(bounds: Bounds, aspect: number, fovDeg = CAMERA_FOV): CameraPose {- const { back, right } = homeAxes();- const tanV = Math.tan((fovDeg * Math.PI) / 360);- const tanH = tanV * Math.max(0.3, aspect);- // The horizontal direction the camera looks along: moving the look-at point this way slides the plan down the view.- const ahead: [number, number] = [-Math.sin(HOME_YAW_RAD), -Math.cos(HOME_YAW_RAD)];- const target: [number, number] = [(bounds.minX + bounds.maxX) / 2, (bounds.minZ + bounds.maxZ) / 2];- let distance = frameDistance(bounds, aspect, fovDeg);- for (let i = 0; i < 12; i += 1) {- const box = projectedBox(bounds, target, distance, aspect, fovDeg, OVERVIEW_HEADROOM_M);- // Centre the plan: sideways along the camera's right, up and down along the floor.- const offX = (box.minX + box.maxX) / 2, offY = (box.minY + box.maxY) / 2;- target[0] += right[0] * offX * distance * tanH + (ahead[0] * offY * distance * tanV) / Math.sin(HOME_PITCH_RAD);- target[1] += right[2] * offX * distance * tanH + (ahead[1] * offY * distance * tanV) / Math.sin(HOME_PITCH_RAD);- // Then come as close as the plan allows.- const centred = projectedBox(bounds, target, distance, aspect, fovDeg, OVERVIEW_HEADROOM_M);- const span = Math.max(centred.maxX - centred.minX, centred.maxY - centred.minY) / 2;- distance = Math.max(CAMERA_LIMITS.minDistance, distance * (span / OVERVIEW_SPAN));- }- return {- target: [target[0], 0, target[1]],- position: [target[0] + back[0] * distance, back[1] * distance, target[1] + back[2] * distance],- };-}--/**- * Zoom limits for a floor: the wheel may always back away far enough for the- * overview (and a little beyond), never less than the default. A small floor- * keeps the default; a campus several times larger gets the room it needs.- */-export function cameraLimitsFor(bounds: Bounds, aspect: number): { minPolar: number; maxPolar: number; minDistance: number; maxDistance: number } {- return { ...CAMERA_LIMITS, maxDistance: Math.max(CAMERA_LIMITS.maxDistance, Math.ceil(frameDistance(bounds, aspect) * 1.15)) };-}--/** The distance the camera follows the character from when nothing else is known. */-export const FOLLOW_DISTANCE_M = 15;-/** A view from further away than this is an overview, not a view to walk in. */-export const WALK_VIEW_MAX_M = 36;--/**- * The distance following glides back to after the overview: what it was- * before the overview when that was a view to walk in, else the default.- * Without this "follow me" re-centred on the character but stayed a campus- * away from it.- */-export function followDistanceAfterOverview(before: number | null): number {- return before !== null && before <= WALK_VIEW_MAX_M ? Math.max(CAMERA_LIMITS.minDistance, before) : FOLLOW_DISTANCE_M;-}--/** A camera this low can stand inside a wall; higher it looks over every wall of the floor. */-const WALL_TOP_M = 3.8;-/** How close to a wall's footprint the camera may stand. */-const WALL_CLEAR_M = 0.35;--/**- * A remembered view checked against the floor it is restored on (the plan- * may have been rebuilt meanwhile): null when it looks at a point outside- * the floor, so the caller starts from the character instead; otherwise the- * view, with a camera that would stand inside a wall backed away from its- * target until it is clear.- */-export function settleView(pose: CameraPose, bounds: Bounds, walls: readonly Bounds[]): CameraPose | null {- const [tx, , tz] = pose.target;- if (tx < bounds.minX || tx > bounds.maxX || tz < bounds.minZ || tz > bounds.maxZ) return null;- const inWall = (x: number, y: number, z: number) => y < WALL_TOP_M- && walls.some((w) => x > w.minX - WALL_CLEAR_M && x < w.maxX + WALL_CLEAR_M && z > w.minZ - WALL_CLEAR_M && z < w.maxZ + WALL_CLEAR_M);- let [x, y, z] = pose.position;- if (!inWall(x, y, z)) return pose;- const dx = x - pose.target[0], dy = y - pose.target[1], dz = z - pose.target[2];- const length = Math.hypot(dx, dy, dz) || 1;- for (let back = 0.5; back <= 12; back += 0.5) {- const k = (length + back) / length;- x = pose.target[0] + dx * k; y = pose.target[1] + dy * k; z = pose.target[2] + dz * k;- if (!inWall(x, y, z)) break;- }- return { target: pose.target, position: [x, y, z] };-}--/** Further than this from the character, re-entering follow glides over like a fly-to instead of snapping across the floor. */-export const FOLLOW_CATCH_UP_M = 12;-/** How fast the view closes on the character while following (per second, exponential). */-export const FOLLOW_RATE = 8;--/**- * One frame of following: the share of the remaining gap the view closes.- * Exponential, so it is the same motion at any frame rate, and it eases out- * instead of stopping dead when the character does.- */-export function followBlend(dt: number): number {- return 1 - Math.exp(-FOLLOW_RATE * Math.max(0, dt));-}--/** Smallest area the home view frames, so a lone agent still shows its neighbourhood. */-const MIN_FOCUS_W = 18;-const MIN_FOCUS_D = 14;--/** Pad the occupied area to a readable neighbourhood around it. */-export function focusBounds(points: readonly { x: number; z: number }[]): Bounds | null {- if (points.length === 0) return null;- const xs = points.map((p) => p.x), zs = points.map((p) => p.z);- const cx = (Math.min(...xs) + Math.max(...xs)) / 2, cz = (Math.min(...zs) + Math.max(...zs)) / 2;- const w = Math.max(MIN_FOCUS_W, Math.max(...xs) - Math.min(...xs) + 6);- const d = Math.max(MIN_FOCUS_D, Math.max(...zs) - Math.min(...zs) + 6);- return { minX: cx - w / 2, maxX: cx + w / 2, minZ: cz - d / 2, maxZ: cz + d / 2 };-}--/** Home view: frame where the agents sit, or the whole floor when nobody does. */-export function cameraHome(bounds: Bounds, aspect: number, focus: Bounds | null = null): CameraPose {- const frame = focus ?? bounds;- const target: [number, number, number] = [(frame.minX + frame.maxX) / 2, 0, (frame.minZ + frame.maxZ) / 2];- // The whole floor must fit edge to edge; a focus area may crop its padding.- const distance = fitDistance(frame, aspect, CAMERA_FOV, focus ? 0.62 : 0.9);- const horizontal = Math.cos(HOME_PITCH_RAD) * distance;- return {- target,- position: [- target[0] + Math.sin(HOME_YAW_RAD) * horizontal,- Math.sin(HOME_PITCH_RAD) * distance,- target[2] + Math.cos(HOME_YAW_RAD) * horizontal,- ],- };-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeCameraRig.css b/dodaios/ui/web/frontend/src/components/society/office/officeCameraRig.cssdeleted file mode 100644index aeffa50519..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeCameraRig.css+++ /dev/null@@ -1,10 +0,0 @@-/* Seated first person at Mission Control (the camera rig sets data-first-person- on the viewport): the monitors fill the view, so the floating labels of the- rest of the floor (names, speech bubbles, place pills, the elevator call)- step aside. Seat prompts and the live monitor screens stay. */-.office-viewport[data-first-person] .office-plate:not(.office-seat-prompt),-.office-viewport[data-first-person] .office-bubble,-.office-viewport[data-first-person] .office-checkpoint,-.office-viewport[data-first-person] .office-call-pill {- visibility: hidden;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeControls.test.ts b/dodaios/ui/web/frontend/src/components/society/office/officeControls.test.tsdeleted file mode 100644index 0df4ecb636..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeControls.test.ts+++ /dev/null@@ -1,55 +0,0 @@-import { describe, expect, it } from "vitest";-import en from "@/i18n/locales/society/en.json";-import { arrowCap, CONTROL_GROUPS, controlsFor, mouseGesture, OFFICE_CONTROLS } from "./officeControls";-import { isRunning } from "./officeSettings";--const guide = (en as { society: { office: { guide: Record<string, string> } } }).society.office.guide;--describe("office controls guide", () => {- it("names every control, group and mouse gesture in the locale", () => {- for (const group of CONTROL_GROUPS) expect(guide[`group_${group}`]).toBeTruthy();- for (const control of OFFICE_CONTROLS) {- expect(guide[`ctl_${control.id}`], control.id).toBeTruthy();- for (const cap of control.keys.flat()) {- const gesture = mouseGesture(cap);- if (gesture) expect(guide[`mouse_${gesture}`], cap).toBeTruthy();- }- }- });-- it("keeps control ids unique and every group filled", () => {- const ids = OFFICE_CONTROLS.map((c) => c.id);- expect(new Set(ids).size).toBe(ids.length);- for (const group of CONTROL_GROUPS) expect(controlsFor(group, "agents").length).toBeGreaterThan(0);- // The courier stands on the agents floor's sky pad only.- for (const group of CONTROL_GROUPS) expect(controlsFor(group, "coding").length > 0).toBe(group !== "fly");- });-- it("drops the lead chair on the coding floor", () => {- expect(controlsFor("interact", "agents").some((c) => c.id === "sit")).toBe(true);- expect(controlsFor("interact", "coding").some((c) => c.id === "sit")).toBe(false);- });-- it("lists the hotkeys the office handles", () => {- const caps = new Set(OFFICE_CONTROLS.flatMap((c) => c.keys.flat()));- for (const key of ["W", "ArrowUp", "Shift", "E", "T", "M", "H", "Esc", "Space", "P"]) expect(caps.has(key), key).toBe(true);- });-});--describe("always run", () => {- it("makes Shift walk instead of run", () => {- expect(isRunning(false, false)).toBe(false);- expect(isRunning(true, false)).toBe(true);- expect(isRunning(false, true)).toBe(true);- expect(isRunning(true, true)).toBe(false);- });-});--describe("arrow caps", () => {- it("names each arrow's direction and nothing else", () => {- expect(arrowCap("ArrowUp")).toBe("up");- expect(arrowCap("ArrowRight")).toBe("right");- expect(arrowCap("W")).toBeNull();- for (const dir of ["up", "down", "left", "right"]) expect(guide[`key_${dir}`]).toBeTruthy();- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeControls.ts b/dodaios/ui/web/frontend/src/components/society/office/officeControls.tsdeleted file mode 100644index fc322536d5..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeControls.ts+++ /dev/null@@ -1,87 +0,0 @@-/**- * Every way to act in the office, in one list: the reception's controls guide- * renders it, and a new hotkey is added here next to its handler so the guide- * never goes stale. A binding is a list of alternatives; each alternative is a- * row of key caps ("+" joins a chord, e.g. Ctrl + drag). Caps starting with- * "mouse:" are mouse gestures and get a translated label, "Arrow…" caps are- * drawn as arrows; every other cap is printed as is.- */--import type { OfficeFloor } from "./officeStore";--export type ControlGroup = "move" | "camera" | "interact" | "map" | "fly" | "arcade";--export interface OfficeControl {- id: string;- group: ControlGroup;- keys: readonly (readonly string[])[];- /** Only on the agents floor (the coding floor has no lead chair). */- agentsOnly?: boolean;-}--export const CONTROL_GROUPS: readonly ControlGroup[] = ["move", "camera", "interact", "map", "fly", "arcade"];--export type MouseGesture = "click" | "double" | "drag" | "right_drag" | "wheel";--export const OFFICE_CONTROLS: readonly OfficeControl[] = [- { id: "walk", group: "move", keys: [["W", "A", "S", "D"], ["ArrowUp", "ArrowLeft", "ArrowDown", "ArrowRight"]] },- { id: "run", group: "move", keys: [["Shift"]] },- { id: "jump", group: "move", keys: [["Space"]] },- { id: "sprint_jump", group: "move", keys: [["Shift", "+", "Space"]] },- { id: "click_walk", group: "move", keys: [["mouse:click"]] },- { id: "rotate", group: "camera", keys: [["mouse:drag"]] },- { id: "pan", group: "camera", keys: [["mouse:right_drag"], ["Ctrl/⌘", "+", "mouse:drag"]] },- { id: "zoom", group: "camera", keys: [["mouse:wheel"]] },- { id: "interact", group: "interact", keys: [["E"]] },- { id: "talk", group: "interact", keys: [["T"]] },- { id: "sit", group: "interact", keys: [["E"]], agentsOnly: true },- { id: "screen", group: "interact", keys: [["mouse:click"]] },- { id: "close", group: "interact", keys: [["Esc"]] },- { id: "elevator_floor", group: "interact", keys: [["0", "1", "2"]] },- { id: "map", group: "map", keys: [["M"]] },- { id: "guide", group: "map", keys: [["H"]] },- { id: "minimap_focus", group: "map", keys: [["mouse:click"]] },- { id: "minimap_walk", group: "map", keys: [["mouse:double"]] },- { id: "minimap_zoom", group: "map", keys: [["mouse:wheel"]] },- // The courier's default keys (courierControls.ts); a pilot's own bindings show in the flight HUD's help.- { id: "fly_board", group: "fly", keys: [["E"]], agentsOnly: true },- { id: "fly_throttle", group: "fly", keys: [["W", "S"]], agentsOnly: true },- { id: "fly_turn", group: "fly", keys: [["A", "D"]], agentsOnly: true },- { id: "fly_pitch", group: "fly", keys: [["ArrowUp", "ArrowDown"]], agentsOnly: true },- { id: "fly_mouse", group: "fly", keys: [["mouse:click"]], agentsOnly: true },- { id: "fly_roll", group: "fly", keys: [["Q", "E"], ["ArrowLeft", "ArrowRight"]], agentsOnly: true },- { id: "fly_lift", group: "fly", keys: [["Space", "C"]], agentsOnly: true },- { id: "fly_boost", group: "fly", keys: [["Shift"]], agentsOnly: true },- { id: "fly_brake", group: "fly", keys: [["X"]], agentsOnly: true },- { id: "fly_assist", group: "fly", keys: [["T"]], agentsOnly: true },- { id: "fly_camera", group: "fly", keys: [["V"]], agentsOnly: true },- { id: "fly_land", group: "fly", keys: [["L"]], agentsOnly: true },- { id: "fly_leave", group: "fly", keys: [["E"], ["F"]], agentsOnly: true },- { id: "fly_settings", group: "fly", keys: [["Esc"]], agentsOnly: true },- { id: "arcade_play", group: "arcade", keys: [["E"]] },- { id: "arcade_start", group: "arcade", keys: [["Enter"], ["Space"]] },- { id: "arcade_action", group: "arcade", keys: [["Space"], ["J"]] },- { id: "arcade_action_b", group: "arcade", keys: [["Shift"], ["K"]] },- { id: "arcade_fly", group: "arcade", keys: [["W", "A", "S", "D"], ["ArrowUp", "ArrowLeft", "ArrowDown", "ArrowRight"]] },- { id: "arcade_shoot", group: "arcade", keys: [["Space"]] },- { id: "arcade_pause", group: "arcade", keys: [["P"]] },- { id: "arcade_leave", group: "arcade", keys: [["E"], ["Esc"]] },-];--/** The mouse gesture a cap names, or null for a plain key. */-export function mouseGesture(cap: string): MouseGesture | null {- return cap.startsWith("mouse:") ? (cap.slice(6) as MouseGesture) : null;-}--export type ArrowKey = "up" | "down" | "left" | "right";--/** The direction an "Arrow…" cap names, or null for any other cap. */-export function arrowCap(cap: string): ArrowKey | null {- const m = /^Arrow(Up|Down|Left|Right)$/.exec(cap);- return m ? (m[1]!.toLowerCase() as ArrowKey) : null;-}--/** The controls of one group that apply on this floor. */-export function controlsFor(group: ControlGroup, floor: OfficeFloor): OfficeControl[] {- return OFFICE_CONTROLS.filter((c) => c.group === group && (!c.agentsOnly || floor === "agents"));-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeFixtures.ts b/dodaios/ui/web/frontend/src/components/society/office/officeFixtures.tsdeleted file mode 100644index ecfec33f24..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeFixtures.ts+++ /dev/null@@ -1,51 +0,0 @@-/**- * Floors for the behaviour, teamwork and walking tests: a roster with teams- * built through the public floor-plan builder, and small hand-made rooms for- * the cases a real floor does not isolate (a door, a corridor, a dead end).- * Test support only; nothing at runtime imports it.- */-import { buildOfficeLayout, type OfficeAgentInput, type OfficeLayout, type OfficeTeamInput, type Rect } from "./officeLayout";-import { buildNavGrid, type NavGrid } from "./officeNav";--export function rosterOf(count: number): OfficeAgentInput[] {- return Array.from({ length: count }, (_, i) => ({- agentId: `a${i}`, name: `Agent ${i}`, tier: "specialist" as const, providerLabel: i % 2 ? "Codex" : "Gemini", state: "idle" as const, createdMs: i,- }));-}--/**- * Teams of the given sizes over the first agents of the roster, in order; whoever is left has no team.- * `leads[i]` names team i's lead by its place among the team's members (absent or null: the team has none).- */-export function teamsOf(roster: readonly OfficeAgentInput[], sizes: readonly number[], leads: readonly (number | null)[] = []): OfficeTeamInput[] {- let next = 0;- return sizes.map((size, i) => {- const members = roster.slice(next, next + size).map((a) => a.agentId);- next += size;- const lead = leads[i];- return { id: `team-${i}`, name: `Team ${i}`, members, createdMs: 100 + i, ...(lead != null ? { leadId: members[lead] } : {}) };- });-}--export interface Campus { roster: OfficeAgentInput[]; teams: OfficeTeamInput[]; layout: OfficeLayout; grid: NavGrid }--/** The agents floor for `count` agents in teams of `sizes` (the rest sit in the pool). */-export function campusOf(count: number, sizes: readonly number[], leads: readonly (number | null)[] = []): Campus {- const roster = rosterOf(count);- const teams = teamsOf(roster, sizes, leads);- const layout = buildOfficeLayout(roster, { teams });- return { roster, teams, layout, grid: buildNavGrid(layout) };-}--/** A bare rectangular floor `w` × `d` metres from the origin with the given solid rectangles on it. */-export function roomGrid(w: number, d: number, obstacles: readonly Rect[] = []): NavGrid {- return buildNavGrid({ floor: { minX: 0, maxX: w, minZ: 0, maxZ: d }, obstacles: [...obstacles] } as unknown as OfficeLayout);-}--/** A wall across a room at `x` (0.12 m thick) with one door: a gap `doorWidth` wide centred on `doorZ`. */-export function wallWithDoor(x: number, depth: number, doorZ: number, doorWidth: number): Rect[] {- return [- { minX: x - 0.06, maxX: x + 0.06, minZ: 0, maxZ: doorZ - doorWidth / 2 },- { minX: x - 0.06, maxX: x + 0.06, minZ: doorZ + doorWidth / 2, maxZ: depth },- ];-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeFloors.css b/dodaios/ui/web/frontend/src/components/society/office/officeFloors.cssdeleted file mode 100644index b6fcd91f8a..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeFloors.css+++ /dev/null@@ -1,116 +0,0 @@-/* Floors, the elevator ride and the compact (IDE side panel) HUD. Theme tokens only: light and dark mode both work. */--/*- * The floor change (ElevatorDoors): the elevator's two brushed-steel doors slide shut over the stage, the- * floor switches behind them, they slide open. Part of the diorama: one palette in light and dark mode.- */-.office-doors { position:absolute; inset:0; z-index:62; pointer-events:none; overflow:hidden; }-.office-doors-leaf {- position:absolute; top:0; bottom:0; width:50%;- background:repeating-linear-gradient(90deg, rgb(255 255 255 / .05) 0 1px, transparent 1px 3px), linear-gradient(90deg, #969ca4, #c4c8ce 50%, #9ca2a9);- transition:transform 640ms cubic-bezier(.45,0,.2,1);-}-.office-doors-leaf[data-side="left"] { left:0; transform:translateX(-101%); box-shadow:inset -3px 0 0 #2f3338, inset -18px 0 26px -16px rgb(0 0 0 / .5); }-.office-doors-leaf[data-side="right"] { right:0; transform:translateX(101%); box-shadow:inset 3px 0 0 #2f3338, inset 18px 0 26px -16px rgb(0 0 0 / .5); }-.office-doors[data-phase="closing"] .office-doors-leaf,-.office-doors[data-phase="closed"] .office-doors-leaf { transform:translateX(0); }-/* A fresh mount starts open, so closing slides in from the sides; opening slides back out. */-.office-doors[data-phase="closing"] .office-doors-leaf { animation:office-doors-close 640ms cubic-bezier(.45,0,.2,1); }-@keyframes office-doors-close { from { transform:translateX(var(--office-door-from, 0)); } }-.office-doors[data-phase="closing"] .office-doors-leaf[data-side="left"] { --office-door-from:-101%; }-.office-doors[data-phase="closing"] .office-doors-leaf[data-side="right"] { --office-door-from:101%; }-@media (prefers-reduced-motion: reduce) {- .office-doors-leaf { transition:none; animation:none !important; }-}--/* The pill over the elevator's call button. Like the name pills it is part of the diorama, which keeps one palette in both modes. */-.office-call-pill { display:inline-flex; flex-direction:column; align-items:center; gap:1px; padding:4px 10px; border-radius:10px; background:rgb(24 26 32 / .86); color:#f8fafc; white-space:nowrap; user-select:none; pointer-events:none; box-shadow:0 2px 8px rgb(0 0 0 / .35); }-.office-call-pill b { font-size:12px; font-weight:700; }-.office-call-pill small { font-size:10px; color:#f5b83d; font-weight:600; }--/* A coding session's facts in its panel. */-.office-facts { display:grid; grid-template-columns:auto 1fr; gap:3px 10px; margin:0; }-.office-facts dt { color:hsl(var(--muted-foreground)); font-size:11px; }-.office-facts dd { margin:0; min-width:0; overflow-wrap:anywhere; }-.office-facts-quote { display:-webkit-box; -webkit-line-clamp:4; -webkit-box-orient:vertical; overflow:hidden; font-style:italic; }-.office-dot[data-dot="error"] { background:hsl(var(--destructive)); }--/* Compact: the office inside a narrow side panel. No minimap or compass; cards and buttons shrink. */-.office-stage-compact .office-hud-left { left:8px; top:8px; gap:5px; max-width:calc(100% - 16px); }-.office-stage-compact .office-title { padding:5px 9px; font-size:12px; }-.office-stage-compact .office-counts { gap:8px; padding:4px 9px; font-size:11px; flex-wrap:wrap; }-.office-stage-compact .office-hud-right { right:8px; top:auto; bottom:8px; flex-direction:row; flex-wrap:wrap; justify-content:flex-end; max-width:calc(100% - 16px); }-.office-stage-compact .office-button { padding:4px 8px; font-size:11px; }-.office-stage-compact .office-panel-slot { top:auto; bottom:48px; right:8px; width:calc(100% - 16px); max-height:62%; }-.office-stage-compact .office-prompt { bottom:48px; max-width:calc(100% - 16px); font-size:12px; }-.office-stage-compact .office-note { font-size:11px; }--/*- * The elevator's button panel (ElevatorPanel): a steel plate with the floor indicator on top and one round- * push button per floor, its name engraved beside it. A pressed button lights its rim. Part of the diorama:- * one palette in light and dark mode.- */-.office-lift-backdrop { position:absolute; inset:0; z-index:64; display:flex; align-items:center; justify-content:center; padding:16px; background:rgb(8 9 12 / .32); }-.office-lift {- position:relative; width:min(230px, 100%); padding:18px 18px 14px; border-radius:10px;- background:- radial-gradient(circle, #6a7078 0 1.7px, transparent 2.3px) left 4px top 4px / 14px 14px no-repeat,- radial-gradient(circle, #6a7078 0 1.7px, transparent 2.3px) right 4px top 4px / 14px 14px no-repeat,- radial-gradient(circle, #6a7078 0 1.7px, transparent 2.3px) left 4px bottom 4px / 14px 14px no-repeat,- radial-gradient(circle, #6a7078 0 1.7px, transparent 2.3px) right 4px bottom 4px / 14px 14px no-repeat,- repeating-linear-gradient(90deg, rgb(255 255 255 / .05) 0 1px, transparent 1px 3px),- linear-gradient(180deg, #d5d9de, #aeb4bb);- box-shadow:0 18px 48px rgb(0 0 0 / .45), inset 0 1px 0 rgb(255 255 255 / .7), inset 0 0 0 1px rgb(0 0 0 / .16);- animation:office-lift-in 200ms cubic-bezier(.2,.8,.2,1);-}-@keyframes office-lift-in { from { opacity:0; transform:translateY(8px); } }-.office-lift-close {- position:absolute; top:8px; right:8px; width:24px; height:24px; border:0; border-radius:6px; background:transparent;- color:#4a4f56; font-size:17px; line-height:1; cursor:pointer;-}-.office-lift-close:hover { background:rgb(0 0 0 / .08); }-.office-lift-close:focus-visible { outline:2px solid #2f7fb0; outline-offset:1px; }-/* The indicator: black glass with an orange dot-matrix number and the direction arrow once a floor is pressed. */-.office-lift-display {- display:flex; align-items:center; justify-content:center; gap:8px; width:96px; height:46px; margin:0 auto 16px; border-radius:5px;- background:linear-gradient(180deg, #121316, #050506); box-shadow:inset 0 0 0 1px rgb(255 255 255 / .07), 0 1px 0 rgb(255 255 255 / .6);- color:#ff8a1f; font-family:'Pixelify Sans', ui-monospace, monospace; font-weight:600; line-height:1;-}-.office-lift-display b { font-size:30px; text-shadow:0 0 8px rgb(255 138 31 / .7); }-.office-lift-arrow { width:16px; height:16px; opacity:.16; transition:opacity 160ms ease; }-.office-lift-arrow[data-dir] { opacity:1; filter:drop-shadow(0 0 4px rgb(255 138 31 / .7)); }-.office-lift-arrow[data-dir="down"] { transform:rotate(180deg); }-.office-lift-rows { display:flex; flex-direction:column; gap:10px; }-/* A row: the push button and its engraved name; the whole row is the click target. */-.office-lift-row {- display:flex; align-items:center; gap:14px; width:100%; padding:2px 4px; border:0; border-radius:28px; background:transparent;- color:inherit; text-align:left; cursor:pointer;-}-/* Keyboard focus rings the button itself, like a lit rim, instead of boxing the whole row. */-.office-lift-row:focus-visible { outline:none; }-.office-lift-row:focus-visible .office-lift-button { box-shadow:0 2px 4px rgb(0 0 0 / .38), inset 0 -1px 2px rgb(0 0 0 / .25), 0 0 0 3px #2f7fb0; }-.office-lift-row:disabled { cursor:default; }-.office-lift-button {- position:relative; flex:none; width:46px; height:46px; border-radius:50%;- background:radial-gradient(circle at 35% 30%, #fdfdfd, #b6bcc3 55%, #737980);- box-shadow:0 2px 4px rgb(0 0 0 / .38), inset 0 -1px 2px rgb(0 0 0 / .25);- transition:transform 90ms ease;-}-.office-lift-button span {- position:absolute; inset:6px; display:grid; place-items:center; border-radius:50%;- background:radial-gradient(circle at 50% 38%, #e3e6ea, #b3b9c0); color:#40454c;- font-family:'Inter Variable', Inter, system-ui, sans-serif; font-size:16px; font-weight:650;- text-shadow:0 1px 0 rgb(255 255 255 / .65); box-shadow:inset 0 1px 2px rgb(0 0 0 / .25), 0 0 0 2px transparent;- transition:box-shadow 180ms ease, color 180ms ease, background 140ms ease;-}-.office-lift-row:enabled:hover .office-lift-button span { background:radial-gradient(circle at 50% 38%, #eef0f3, #c0c6cc); }-.office-lift-row:enabled:active .office-lift-button { transform:scale(.95); }-.office-lift-row[data-lit] .office-lift-button span { color:#1f6f96; box-shadow:inset 0 1px 2px rgb(0 0 0 / .2), 0 0 0 2px #8fd8ff, 0 0 12px rgb(143 216 255 / .95); }-.office-lift-label { font-size:13px; font-weight:600; color:#30353b; text-shadow:0 1px 0 rgb(255 255 255 / .55); }-.office-lift-row[data-here] .office-lift-label { color:#6b7179; }-.office-lift-row:disabled:not([data-here]):not([data-lit]) { opacity:.55; }-.office-lift-keys { margin:14px 0 0; text-align:center; font-size:10px; color:#5c626a; text-shadow:0 1px 0 rgb(255 255 255 / .45); }-.office-lift[data-reduced], .office-lift[data-reduced] * { animation:none !important; transition:none !important; }-@media (prefers-reduced-motion: reduce) {- .office-lift, .office-lift * { animation:none !important; transition:none !important; }-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeFloors.test.ts b/dodaios/ui/web/frontend/src/components/society/office/officeFloors.test.tsdeleted file mode 100644index 5915fc9575..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeFloors.test.ts+++ /dev/null@@ -1,115 +0,0 @@-import { afterEach, describe, expect, it } from "vitest";-import { buildOfficeLayout, type OfficeAgentInput } from "./officeLayout";-import { buildNavGrid, isWalkable } from "./officeNav";-import { arrivalPose, knownOnFloor, noteArrivals } from "./officeFloors";-import { floorLevel, OFFICE_FLOORS, officeSession, player, switchFloor, useOfficeStore } from "./officeStore";-import { callDirection } from "./ElevatorCallButton";-import { floorForKey, PANEL_FLOORS } from "./ElevatorPanel";-import { buildArcadeLayout } from "../arcade/arcadeFloorLayout";-import { buildHallLayout } from "./hallFloorLayout";--const AGENTS: OfficeAgentInput[] = [- { agentId: "a1", name: "One", tier: "specialist", providerLabel: "Codex", state: "working", createdMs: 1 },- { agentId: "a2", name: "Two", tier: "specialist", providerLabel: "Claude", state: "idle", createdMs: 2 },-];--function resetBuilding() {- useOfficeStore.setState({ floor: "agents", selection: null, nearby: null, summons: {}, walkTo: null, teamDraft: [] });- officeSession.playerPlaced = false;- officeSession.floors = {};- officeSession.arrival = null;- Object.assign(player, { x: 0, z: 0, heading: Math.PI, path: [], moving: false });-}--afterEach(resetBuilding);--describe("floors", () => {- it("stacks the floors bottom to top, and the elevator panel lists them top first", () => {- expect(OFFICE_FLOORS).toEqual(["agents", "coding", "arcade", "hall"]);- expect(OFFICE_FLOORS.map(floorLevel)).toEqual([0, 1, 2, 3]);- expect(PANEL_FLOORS).toEqual(["hall", "arcade", "coding", "agents"]);- expect(callDirection("agents")).toBe("up");- expect(callDirection("coding")).toBe("both");- expect(callDirection("arcade")).toBe("both");- expect(callDirection("hall")).toBe("down");- });-- it("picks a floor by its number key", () => {- expect(floorForKey("0")).toBe("agents");- expect(floorForKey("1")).toBe("coding");- expect(floorForKey("2")).toBe("arcade");- expect(floorForKey("3")).toBe("hall");- expect(floorForKey("4")).toBeNull();- expect(floorForKey("e")).toBeNull();- expect(floorForKey("12")).toBeNull();- });-- it("steps out of the elevator onto walkable floor, facing away from the doors, on every floor", () => {- for (const variant of ["agents", "coding", "arcade", "hall"] as const) {- const layout = variant === "arcade" ? buildArcadeLayout() : variant === "hall" ? buildHallLayout() : buildOfficeLayout(AGENTS, { variant });- const stop = layout.checkpoints.find((cp) => cp.id === "elevator");- expect(stop, variant).toBeDefined();- const pose = arrivalPose(layout, "elevator");- expect(pose.x).toBeCloseTo(stop!.x);- expect(pose.z).toBeCloseTo(stop!.z);- expect(isWalkable(buildNavGrid(layout), pose)).toBe(true);- const doors = layout.furniture.find((f) => f.kind === "elevator")!;- // One step along the heading leads away from the doors.- const ahead = { x: pose.x + Math.sin(pose.heading), z: pose.z + Math.cos(pose.heading) };- expect(Math.hypot(ahead.x - doors.x, ahead.z - doors.z)).toBeGreaterThan(Math.hypot(pose.x - doors.x, pose.z - doors.z));- }- });-- it("returns to the remembered spot, and falls back to the spawn without an elevator", () => {- const layout = buildOfficeLayout(AGENTS);- expect(arrivalPose(layout, "remembered", { x: 1, z: 2, heading: 0.5 })).toEqual({ x: 1, z: 2, heading: 0.5 });- const bare = { ...layout, checkpoints: layout.checkpoints.filter((cp) => cp.id !== "elevator") };- expect(arrivalPose(bare, "elevator")).toEqual({ x: layout.spawn.x, z: layout.spawn.z, heading: Math.PI });- });-- it("keeps newcomers per floor: the first sight of a floor knows everyone", () => {- const known = new Set<string>();- expect(noteArrivals(known, ["p1", "p2"])).toEqual([]);- expect(noteArrivals(known, ["p1", "p2", "p3"])).toEqual(["p3"]);- // p1 left and is forgotten; coming back later it arrives again.- expect(noteArrivals(known, ["p2", "p3"])).toEqual([]);- expect(noteArrivals(known, ["p1", "p2", "p3"])).toEqual(["p1"]);- expect(knownOnFloor("agents")).not.toBe(knownOnFloor("coding"));- // Nobody works in the arcade or the Level Hall: neither ever has a newcomer of the floors below.- expect(knownOnFloor("hall")).not.toBe(knownOnFloor("agents"));- expect(knownOnFloor("hall")).not.toBe(knownOnFloor("coding"));- });-- it("switching floors forgets the old floor's panels and calls, and remembers where the character stood", () => {- const store = useOfficeStore.getState();- store.select({ kind: "agent", id: "a1" });- store.setNearby({ kind: "checkpoint", id: "elevator" });- store.summon(["a1"], { x: 0, z: 0 }, 10_000);- store.requestWalk({ x: 3, z: 3 });- officeSession.playerPlaced = true;- Object.assign(player, { x: 4, z: -2, heading: 1, path: [{ x: 5, z: 5 }], moving: true });-- switchFloor("coding", true);- const after = useOfficeStore.getState();- expect(after.floor).toBe("coding");- expect(after.selection).toBeNull();- expect(after.nearby).toBeNull();- expect(after.summons).toEqual({});- expect(after.walkTo).toBeNull();- expect(player.path).toEqual([]);- expect(officeSession.floors.agents).toEqual({ x: 4, z: -2, heading: 1 });- expect(officeSession.arrival).toEqual({ floor: "coding", at: "elevator" });- });-- it("a mount that asks for a floor returns to the spot remembered there; the elevator always arrives at the doors", () => {- officeSession.playerPlaced = true;- officeSession.floors.coding = { x: 7, z: 7, heading: 0 };- switchFloor("coding", false);- expect(officeSession.arrival).toEqual({ floor: "coding", at: "remembered" });- switchFloor("agents", true);- expect(officeSession.arrival).toEqual({ floor: "agents", at: "elevator" });- // Asking for the floor already on screen changes nothing.- switchFloor("agents", false);- expect(officeSession.arrival).toEqual({ floor: "agents", at: "elevator" });- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeFloors.ts b/dodaios/ui/web/frontend/src/components/society/office/officeFloors.tsdeleted file mode 100644index ed9fdbb67b..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeFloors.ts+++ /dev/null@@ -1,50 +0,0 @@-/**- * The building has four floors joined by an elevator: the Jarvis agents'- * campus, one ride up the coding floor with a figure per IDE coding session,- * the arcade hall, and on top the Level Hall. Pure helpers for what differs- * per floor; the stage wires them.- */-import type { OfficeLayout } from "./officeLayout";-import type { OfficeFloor } from "./officeStore";-import { knownAgents } from "./walkerRegistry";--export interface FloorPose { x: number; z: number; heading: number }--/**- * Where the character steps out on arrival: at the elevator checkpoint,- * facing away from the doors — or where it last stood on that floor.- * Falls back to the spawn point when the plan has no elevator.- */-export function arrivalPose(layout: OfficeLayout, at: "elevator" | "remembered", remembered?: FloorPose): FloorPose {- if (at === "remembered" && remembered) return remembered;- const cp = layout.checkpoints.find((c) => c.id === "elevator");- if (!cp) return { x: layout.spawn.x, z: layout.spawn.z, heading: Math.PI };- const doors = layout.furniture.find((f) => f.kind === "elevator");- const heading = doors && Math.hypot(cp.x - doors.x, cp.z - doors.z) > 1e-3- ? Math.atan2(cp.x - doors.x, cp.z - doors.z)- : Math.PI;- return { x: cp.x, z: cp.z, heading };-}--/** Agent ids each floor has already seen; a newcomer on that floor arrives by the elevator. */-const codingKnown = new Set<string>();-/** The arcade and the Level Hall have no agents; they share one set that stays empty. */-const nobodyKnown = new Set<string>();-export function knownOnFloor(floor: OfficeFloor): Set<string> {- return floor === "agents" ? knownAgents : floor === "coding" ? codingKnown : nobodyKnown;-}--/**- * Newcomers among `ids` on a floor, updating what the floor knows. The first- * sight of a floor knows everyone (nobody "arrives" just because you came up);- * ids that left are forgotten so the set never outgrows the roster.- */-export function noteArrivals(known: Set<string>, ids: readonly string[]): string[] {- if (ids.length === 0) return [];- if (known.size === 0) { ids.forEach((id) => known.add(id)); return []; }- const present = new Set(ids);- for (const id of [...known]) if (!present.has(id)) known.delete(id);- const fresh = ids.filter((id) => !known.has(id));- fresh.forEach((id) => known.add(id));- return fresh;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeFrameBudget.test.ts b/dodaios/ui/web/frontend/src/components/society/office/officeFrameBudget.test.tsdeleted file mode 100644index 96fde13b8a..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeFrameBudget.test.ts+++ /dev/null@@ -1,46 +0,0 @@-import { describe, expect, it } from "vitest";-import { startOfficeFrameBudget } from "./officeFrameBudget";--function clock() {- let pending: FrameRequestCallback | undefined;- let count = 0;- let nextId = 0;- const stop = startOfficeFrameBudget(- () => { count += 1; }, 30,- (callback) => { pending = callback; return ++nextId; },- () => { pending = undefined; },- );- return {- step(now: number) { const callback = pending; pending = undefined; callback?.(now); },- get count() { return count; },- get pending() { return pending; },- stop,- };-}--describe("office side-panel frame budget", () => {- it.each([60, 120, 144])("renders 30 frames on a %i Hz display", (hz) => {- const timer = clock();- for (let frame = 0; frame < hz * 60; frame += 1) timer.step(frame * 1000 / hz);- expect(timer.count).toBe(30 * 60);- timer.stop();- });-- it("does not burst to catch up after the main thread stalls", () => {- const timer = clock();- timer.step(0);- timer.step(10000);- timer.step(10001);- expect(timer.count).toBe(2);- timer.stop();- });-- it("stops scheduling when hidden or unmounted, including an in-flight callback", () => {- const timer = clock();- const inFlight = timer.pending;- timer.stop();- inFlight?.(100);- expect(timer.count).toBe(0);- expect(timer.pending).toBeUndefined();- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeFrameBudget.ts b/dodaios/ui/web/frontend/src/components/society/office/officeFrameBudget.tsdeleted file mode 100644index 7a7d102175..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeFrameBudget.ts+++ /dev/null@@ -1,29 +0,0 @@-/** Keep a secondary 3D view from spending a full render on every display tick. */-export function startOfficeFrameBudget(- invalidate: () => void,- fps: number,- request: (callback: FrameRequestCallback) => number = requestAnimationFrame,- cancel: (handle: number) => void = cancelAnimationFrame,-): () => void {- const interval = 1000 / fps;- let last: number | undefined;- let stopped = false;- let frame: number;- const tick: FrameRequestCallback = (now) => {- if (stopped) return;- if (last === undefined || now - last >= interval - 0.1) {- // Retain fractional frame time without trying to repay missed frames- // after a stall. At 120/144 Hz the scene still receives at most 30 fps.- last = last === undefined- ? now- : last + Math.max(1, Math.floor((now - last + 0.1) / interval)) * interval;- invalidate();- }- frame = request(tick);- };- frame = request(tick);- return () => {- stopped = true;- cancel(frame);- };-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeHud.css b/dodaios/ui/web/frontend/src/components/society/office/officeHud.cssdeleted file mode 100644index 87fc34c0f3..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeHud.css+++ /dev/null@@ -1,39 +0,0 @@-/* The panels docked beside the map (an agent's walkie-talkie, the wardrobe): theme tokens only, so light and dark mode both work. */-/* Opens below the minimap card (14 + 236 px) in the top-right corner. */-.office-panel-slot { position:absolute; z-index:35; right:14px; top:258px; width:min(340px, calc(100% - 28px)); max-height:calc(100% - 276px); display:flex; }-/* A panel with a lot in it (the wardrobe) takes the whole edge and covers the minimap while it is open. */-.office-panel-slot[data-tall] { top:14px; width:min(360px, calc(100% - 28px)); max-height:calc(100% - 28px); }-.office-panel { display:flex; flex-direction:column; width:100%; min-height:0; overflow:hidden; }-.office-panel:focus { outline:none; }-.office-panel:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }-.office-panel-body { display:flex; flex-direction:column; gap:12px; padding:14px 16px 16px; overflow:auto; font-size:13px; line-height:1.45; }-.office-panel-body p { margin:0; }-.office-icon-button { border:0; background:none; color:hsl(var(--muted-foreground)); font-size:18px; line-height:1; cursor:pointer; padding:0 4px; border-radius:6px; }-.office-icon-button:hover { color:hsl(var(--foreground)); background:hsl(var(--secondary)); }-.office-icon-button:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:1px; color:hsl(var(--foreground)); }-.office-link { border:0; background:none; padding:0; color:hsl(var(--primary)); font-size:12px; cursor:pointer; text-decoration:underline; text-underline-offset:2px; }-.office-link:focus-visible, .office-chip:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }-.office-dot { display:inline-block; flex:none; width:8px; height:8px; border-radius:50%; background:hsl(var(--muted-foreground)); }-.office-dot[data-state="working"] { background:hsl(var(--success)); }-.office-dot[data-state="waiting"] { background:hsl(var(--warning)); }-.office-dot[data-state="paused"] { background:transparent; box-shadow:inset 0 0 0 1.5px hsl(var(--muted-foreground)); }-.office-subhead { margin:0; font-size:12px; font-weight:600; color:hsl(var(--muted-foreground)); }-.office-chip { border:1px solid hsl(var(--border)); border-radius:999px; padding:3px 10px; background:hsl(var(--background)); color:hsl(var(--foreground)); font-size:12px; cursor:pointer; }-.office-chip:hover:not([aria-pressed="true"]) { background:hsl(var(--secondary)); }-.office-chip[aria-pressed="true"] { background:hsl(var(--primary)); color:hsl(var(--primary-foreground)); border-color:transparent; }-.office-hint { margin:0; font-size:12px; color:hsl(var(--muted-foreground)); }-.office-error { color:hsl(var(--destructive)); }-.office-success { color:hsl(var(--foreground)); }-/* Narrow: the panel covers the map card while open. */-@media (max-width:760px) { .office-panel-slot { top:14px; max-height:calc(100% - 80px); } }-/* No minimap on short windows: the panel goes back under the toolbar. */-@media (max-height:520px) { .office-panel-slot { top:60px; max-height:calc(100% - 100px); } }-@media (max-width:600px) { .office-panel-slot, .office-panel-slot[data-tall] { top:auto; bottom:12px; max-height:55%; } }--/* The monitor dive ends in the chat view: the stage fades to the app background just before it opens. */-.office-dive-fade { position:absolute; inset:0; z-index:60; pointer-events:none; background:hsl(var(--background)); opacity:0; animation:office-dive-fade 1.4s ease-in forwards; }-@keyframes office-dive-fade { 0%, 72% { opacity:0; } 100% { opacity:1; } }-@media (prefers-reduced-motion: reduce) { .office-dive-fade { animation:none; } }--/* The real chat on a desk monitor: the app's own chat panel at window size, scaled onto the screen. */-.office-real-chat { width:100%; height:100%; overflow:hidden; background:hsl(var(--background)); color:hsl(var(--foreground)); border-radius:6px; }diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeJump.test.ts b/dodaios/ui/web/frontend/src/components/society/office/officeJump.test.tsdeleted file mode 100644index c3b919f24f..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeJump.test.ts+++ /dev/null@@ -1,92 +0,0 @@-import { describe, expect, it } from "vitest";-import { JUMP_BUFFER_S, jumpSquash, newJump, pressJump, SPRINT_JUMP_BOOST, stepJump } from "./officeJump";--const DT = 1 / 60;--function hop(running: boolean) {- const s = newJump();- pressJump(s);- let apex = 0, frames = 0, maxMul = 1;- stepJump(s, DT, false, running);- while (s.airborne && frames < 600) {- stepJump(s, DT, false, running);- apex = Math.max(apex, s.y);- maxMul = Math.max(maxMul, s.speedMul);- frames += 1;- }- return { s, apex, airS: (frames + 1) * DT, maxMul };-}--describe("office jump", () => {- it("makes a short hop that lands back on the floor", () => {- const { s, apex, airS } = hop(false);- expect(apex).toBeGreaterThan(0.45);- expect(apex).toBeLessThan(0.65);- expect(airS).toBeGreaterThan(0.45);- expect(airS).toBeLessThan(0.6);- expect(s.y).toBe(0);- expect(s.airborne).toBe(false);- });-- it("is smooth: the height never jumps by more than a few centimetres a frame", () => {- const s = newJump();- pressJump(s);- let last = 0;- for (let i = 0; i < 60; i += 1) {- stepJump(s, DT, false, false);- expect(Math.abs(s.y - last)).toBeLessThan(0.08);- last = s.y;- }- });-- it("boosts a sprint jump above sprint speed, easing in rather than snapping", () => {- const sprint = hop(true);- expect(sprint.maxMul).toBeGreaterThan(1.2);- expect(sprint.maxMul).toBeLessThanOrEqual(SPRINT_JUMP_BOOST);- const s = newJump();- pressJump(s);- stepJump(s, DT, false, true);- expect(s.speedMul).toBeLessThan(1.1);- });-- it("gives a jump from a walk no extra speed", () => {- expect(hop(false).maxMul).toBe(1);- });-- it("drops the boost again after landing", () => {- const { s } = hop(true);- for (let i = 0; i < 60; i += 1) stepJump(s, DT, false, true);- expect(s.speedMul).toBe(1);- });-- it("keeps a press made just before landing and jumps on touchdown", () => {- const s = newJump();- pressJump(s);- stepJump(s, DT, false, true);- while (s.vy > 0 || s.y > 0.05) stepJump(s, DT, false, true);- pressJump(s);- let again = false;- for (let t = 0; t < JUMP_BUFFER_S; t += DT) again = stepJump(s, DT, false, true) || again;- expect(again).toBe(true);- });-- it("does not jump again in mid-air", () => {- const s = newJump();- pressJump(s);- stepJump(s, DT, false, false);- const vy = s.vy;- expect(stepJump(s, DT, true, false)).toBe(false);- expect(s.vy).toBeLessThan(vy);- });-- it("squashes and stretches only around take-off and landing", () => {- const s = newJump();- expect(jumpSquash(s)).toEqual([1, 1]);- pressJump(s);- stepJump(s, 0.08, false, false);- expect(jumpSquash(s)[1]).toBeGreaterThan(1);- s.sinceTakeoff = 1;- s.sinceLanding = 0.09;- expect(jumpSquash(s)[1]).toBeLessThan(1);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeJump.ts b/dodaios/ui/web/frontend/src/components/society/office/officeJump.tsdeleted file mode 100644index 89e5062d64..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeJump.ts+++ /dev/null@@ -1,96 +0,0 @@-/**- * The person's jump (Space): a short, snappy hop computed per frame, so it is- * smooth at any frame rate. A jump taken while sprinting carries extra speed- * for as long as the character is in the air, so hopping along at a sprint is- * faster than sprinting on the ground. The boost eases in and out instead of- * snapping, and a press just before landing is kept and fires on touchdown,- * so chained hops never feel laggy.- */--/** Take-off speed (m/s) and gravity (m/s²): about a 0.5 m hop, 0.5 s in the air. */-export const JUMP_VELOCITY = 4.2;-export const JUMP_GRAVITY = 16;-/** Ground speed multiplier while airborne on a sprint jump. */-export const SPRINT_JUMP_BOOST = 1.3;-/** How fast the speed multiplier follows its target (1/s); higher is snappier. */-const BOOST_EASE = 9;-/** A press this long before landing still jumps on touchdown (s). */-export const JUMP_BUFFER_S = 0.14;-/** Take-off stretch and landing squash length (s). */-const STRETCH_S = 0.16;-const SQUASH_S = 0.18;--export interface JumpState {- /** Height of the feet above the floor (m). */- y: number;- /** Vertical speed (m/s). */- vy: number;- airborne: boolean;- /** This hop started at a sprint (and keeps its boost while the sprint is held). */- sprintJump: boolean;- /** Current ground-speed multiplier, eased toward its target. */- speedMul: number;- /** Seconds left in which a buffered press still counts. */- buffered: number;- /** Seconds since take-off / since landing (drive the stretch and squash). */- sinceTakeoff: number;- sinceLanding: number;-}--export function newJump(): JumpState {- return { y: 0, vy: 0, airborne: false, sprintJump: false, speedMul: 1, buffered: 0, sinceTakeoff: Infinity, sinceLanding: Infinity };-}--/** Space pressed: jump now if on the floor, else remember the press for a moment. */-export function pressJump(s: JumpState): void {- s.buffered = JUMP_BUFFER_S;-}--/**- * Advance one frame. `wantJump` is true while Space is held (holding keeps- * hopping); `running` whether the character is sprinting and moving right now.- * Returns true on the frame the character leaves the floor.- */-export function stepJump(s: JumpState, dt: number, wantJump: boolean, running: boolean): boolean {- let tookOff = false;- s.buffered = Math.max(0, s.buffered - dt);- if (!s.airborne && (s.buffered > 0 || wantJump)) {- s.airborne = true;- s.vy = JUMP_VELOCITY;- s.sprintJump = running;- s.buffered = 0;- s.sinceTakeoff = 0;- tookOff = true;- }- if (s.airborne) {- // Semi-implicit Euler: speed first, then position; exact enough for a hop.- s.vy -= JUMP_GRAVITY * dt;- s.y += s.vy * dt;- if (s.y <= 0) {- s.y = 0;- s.vy = 0;- s.airborne = false;- s.sinceLanding = 0;- }- }- s.sinceTakeoff += dt;- s.sinceLanding += dt;- // The boost holds while airborne on a sprint jump that is still a sprint.- const target = s.airborne && s.sprintJump && running ? SPRINT_JUMP_BOOST : 1;- s.speedMul += (target - s.speedMul) * (1 - Math.exp(-BOOST_EASE * dt));- if (Math.abs(target - s.speedMul) < 1e-3) s.speedMul = target;- return tookOff;-}--/**- * The figure's squash-and-stretch as [widthScale, heightScale]: a quick- * stretch on take-off, a soft squash on landing, 1 in between. Volume stays- * roughly constant (width shrinks as height grows).- */-export function jumpSquash(s: JumpState): [number, number] {- const pulse = (t: number, len: number) => (t < len ? Math.sin((t / len) * Math.PI) : 0);- const stretch = pulse(s.sinceTakeoff, STRETCH_S) * 0.1;- const squash = pulse(s.sinceLanding, SQUASH_S) * 0.12;- const h = 1 + stretch - squash;- return [1 / Math.sqrt(h), h];-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeLayout.test.ts b/dodaios/ui/web/frontend/src/components/society/office/officeLayout.test.tsdeleted file mode 100644index 5f3b907f74..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeLayout.test.ts+++ /dev/null@@ -1,308 +0,0 @@-import { describe, expect, it } from "vitest";-import { PRODUCT_NAME } from "@/lib/branding";-import {- allDesks, archPosts, buildOfficeLayout, countStates, departmentKey, FURNITURE_SIZE, footprint, groupDepartments,- MAX_DEPARTMENTS, MAX_SEATED, MIN_DEPARTMENTS, COMMAND_DESK, COMMAND_REACH, seatedCount, SPAWN, type OfficeAgentInput,-} from "./officeLayout";-import { buildNavGrid, isWalkable } from "./officeNav";-import { cameraHome, fitDistance, focusBounds } from "./officeCamera";--const agent = (id: string, provider: string, extra: Partial<OfficeAgentInput> = {}): OfficeAgentInput => ({- agentId: id, name: id, tier: "specialist", providerLabel: provider, state: "idle", createdMs: Number(id.replace(/\D/g, "")) || 0, ...extra,-});--describe("office layout", () => {- it("groups the coding floor by workspace and falls back to the product name", () => {- expect(departmentKey({ providerLabel: " " })).toBe(PRODUCT_NAME);- const groups = groupDepartments([agent("a1", "codex"), agent("a2", ""), agent("a3", "codex")]);- expect(groups.map((g) => g.label)).toEqual(["Codex", PRODUCT_NAME]);- expect(buildOfficeLayout([agent("a1", "codex")], { variant: "coding" }).departments.map((d) => d.label)).toEqual(["Codex", "", "", ""]);- });-- it("gives every staff agent exactly one desk and the lead its own office", () => {- const roster = [agent("a1", "Codex"), agent("a2", "Claude Code"), agent("a3", "Codex"), agent("a4", "", { tier: "lead" })];- const layout = buildOfficeLayout(roster);- const seated = allDesks(layout).map((d) => d.agentId).filter(Boolean);- expect(new Set(seated)).toEqual(new Set(["a1", "a2", "a3", "a4"]));- expect(seated).toHaveLength(4);- expect(layout.lead.desks[0].agentId).toBe("a4");- expect(seatedCount(layout)).toBe(4);- });-- for (const variant of ["agents", "coding"] as const) {- it(`keeps seating stable when run state changes or the roster is reordered (${variant})`, () => {- const roster = [agent("a1", "Codex"), agent("a2", "Codex"), agent("a3", "Gemini")];- const before = allDesks(buildOfficeLayout(roster, { variant })).map((d) => `${d.id}=${d.agentId}`);- const after = allDesks(buildOfficeLayout([...roster].reverse().map((a) => ({ ...a, state: "working" as const })), { variant }))- .map((d) => `${d.id}=${d.agentId}`);- expect(after).toEqual(before);- });- }-- it("folds surplus workspaces into one department on the coding floor and never overlaps departments", () => {- const roster = Array.from({ length: 10 }, (_, i) => agent(`a${i}`, `P${i}`));- const layout = buildOfficeLayout(roster, { variant: "coding" });- expect(layout.departments).toHaveLength(MAX_DEPARTMENTS);- expect(layout.departments.at(-1)?.label).toBe("Other");- for (const a of layout.departments) for (const b of layout.departments) {- if (a === b) continue;- const overlap = a.minX < b.maxX && b.minX < a.maxX && a.minZ < b.maxZ && b.minZ < a.maxZ;- expect(overlap).toBe(false);- }- for (const desk of allDesks(layout)) {- expect(desk.x).toBeGreaterThan(layout.bounds.minX);- expect(desk.x).toBeLessThan(layout.bounds.maxX);- expect(desk.z).toBeGreaterThan(layout.bounds.minZ);- expect(desk.z).toBeLessThan(layout.bounds.maxZ);- }- });-- it("builds a furnished floor for an empty roster", () => {- const coding = buildOfficeLayout([], { variant: "coding" });- expect(coding.departments).toHaveLength(MIN_DEPARTMENTS);- expect(coding.departments.every((d) => d.label === "" && d.desks.length > 0)).toBe(true);- // The agents floor: the pool studio with a few free desks, and nobody at the lead's desk yet.- const agents = buildOfficeLayout([]);- expect(agents.departments.map((d) => d.id)).toEqual(["studio-pool"]);- expect(agents.departments[0].desks.length).toBeGreaterThan(0);- expect(agents.lead.desks).toHaveLength(1);- expect(seatedCount(agents)).toBe(0);- });-- it("says how many desks the coding floor can hold", () => {- const roster = Array.from({ length: MAX_SEATED + 5 }, (_, i) => agent(`a${i}`, `P${i % 6}`));- expect(seatedCount(buildOfficeLayout(roster, { variant: "coding" }))).toBe(MAX_SEATED);- });-- for (const variant of ["agents", "coding"] as const) {- it(`makes the posts of an open room's name arch solid (${variant})`, () => {- const layout = buildOfficeLayout([agent("a1", "Codex")], { variant });- const open = layout.rooms.filter((r) => !r.walled);- expect(open.length).toBeGreaterThan(0);- for (const post of open.flatMap(archPosts)) {- const covered = layout.obstacles.some((o) => post.x >= o.minX && post.x <= o.maxX && post.z >= o.minZ && post.z <= o.maxZ);- expect(covered).toBe(true);- }- });-- it(`keeps every checkpoint centre clear of solid furniture (${variant})`, () => {- const layout = buildOfficeLayout(Array.from({ length: 12 }, (_, i) => agent(`a${i}`, i % 2 ? "Codex" : "Gemini")), { variant });- const solid = layout.furniture.filter((f) => FURNITURE_SIZE[f.kind].solid).map(footprint);- for (const cp of layout.checkpoints) {- // A ring centred on a solid prop (Mission Control's screen) walks to its approach point instead.- const at = cp.approach ?? cp;- const inside = solid.some((o) => at.x >= o.minX && at.x <= o.maxX && at.z >= o.minZ && at.z <= o.maxZ);- expect(inside, cp.id).toBe(false);- }- });-- it(`puts the elevator checkpoint right in front of the elevator (${variant})`, () => {- const layout = buildOfficeLayout([], { variant });- const elevator = layout.furniture.find((f) => f.kind === "elevator")!;- const stop = layout.checkpoints.find((c) => c.id === "elevator")!;- expect(stop.room).toBe("reception");- expect(stop.z).toBeCloseTo(elevator.z, 9);- expect(stop.x).toBeGreaterThan(elevator.x);- expect(Math.hypot(stop.x - elevator.x, stop.z - elevator.z)).toBeLessThan(1.5);- expect(new Set(layout.checkpoints.map((c) => c.id)).size).toBe(layout.checkpoints.length);- // The person starts in front of the doors.- expect(Math.hypot(layout.spawn.x - stop.x, layout.spawn.z - stop.z)).toBeLessThan(1);- });-- it(`keeps room, furniture and spot ids unique and inside the floor (${variant})`, () => {- const layout = buildOfficeLayout(Array.from({ length: 20 }, (_, i) => agent(`a${i}`, `P${i % 3}`)), {- variant, teams: [{ id: "t1", name: "Core", members: ["a1", "a2", "a3"], createdMs: 1 }, { id: "t2", name: "Web", members: ["a4", "a5"], createdMs: 2 }],- });- for (const list of [layout.rooms, layout.furniture, layout.spots]) {- expect(new Set(list.map((x) => x.id)).size).toBe(list.length);- }- for (const item of [...layout.furniture, ...layout.spots]) {- const room = item.room === "floor" ? layout.floor : layout.rooms.find((r) => r.kind === item.room)!;- expect(room, item.id).toBeDefined();- expect(item.x, item.id).toBeGreaterThanOrEqual(room.minX);- expect(item.x, item.id).toBeLessThanOrEqual(room.maxX);- expect(item.z, item.id).toBeGreaterThanOrEqual(room.minZ);- expect(item.z, item.id).toBeLessThanOrEqual(room.maxZ);- }- });- }-- it("builds the agents floor when no variant is named: its rooms and stations, no Level Hall", () => {- const roster = [agent("a1", "Codex"), agent("a2", "", { tier: "lead" })];- const plain = buildOfficeLayout(roster);- expect(plain).toEqual(buildOfficeLayout(roster, { variant: "agents" }));- expect(plain.variant).toBe("agents");- expect(plain.rooms.map((r) => r.kind)).toEqual(["lead", "team", "wardrobe", "reception", "break"]);- // The spawn point creates agents, the reception desk is the one directory and help station; the hall has its own floor.- expect(plain.checkpoints.map((c) => c.id)).toEqual(["spawn", "manage", "team", "wardrobe", "lead", "break", "elevator", "ship"]);- for (const kind of ["levelWall", "studioStage", "rewardPedestal", "levelGuide", "agentTotem"] as const) {- expect(plain.furniture.some((f) => f.kind === kind), kind).toBe(false);- }- });-- it("stands every agents-floor station in front of the thing the person uses there", () => {- const layout = buildOfficeLayout([agent("a1", "Codex"), agent("a2", "", { tier: "lead" })]);- const grid = buildNavGrid(layout);- const stop = (id: string) => layout.checkpoints.find((c) => c.id === id)!;- const prop = (kind: string) => layout.furniture.find((f) => f.kind === kind)!;- const near = (id: string, kind: string, reach: number) => {- const cp = stop(id), box = footprint(prop(kind));- const dx = Math.max(box.minX - cp.x, 0, cp.x - box.maxX), dz = Math.max(box.minZ - cp.z, 0, cp.z - box.maxZ);- expect(Math.hypot(dx, dz), `${id} to ${kind}`).toBeLessThanOrEqual(reach);- };- near("manage", "receptionDesk", 1.5);- near("team", "teamBoard", 1.5);- near("wardrobe", "dressingMirror", 2.0);- near("break", "coffeeBar", 1.5);- near("spawn", "spawnTerminal", 0.1);- // The reception desk's counter faces south: the person stands on that side.- expect(stop("manage").z).toBeGreaterThan(prop("receptionDesk").z);- const desk = layout.lead.desks[0];- expect(Math.hypot(stop("lead").x - desk.x, stop("lead").z - desk.z)).toBeLessThan(2.6);- for (const cp of layout.checkpoints) expect(isWalkable(grid, cp.approach ?? cp), cp.id).toBe(true);- });-- it("builds the coding floor: workspaces as departments, Mission Control and server room, no lead desks", () => {- const roster = [agent("p1", "Personal Jarvis"), agent("p2", "Website"), agent("p3", "Personal Jarvis")];- const layout = buildOfficeLayout(roster, { variant: "coding" });- expect(layout.variant).toBe("coding");- expect(layout.rooms.map((r) => r.kind)).toEqual(["command", "team", "server", "reception", "break"]);- expect(layout.lead.desks).toEqual([]);- expect(layout.checkpoints.map((c) => c.id)).toEqual(["launch", "mission", "elevator", "break"]);- expect(layout.departments.map((d) => d.label)).toEqual(["Personal Jarvis", "Website", "", ""]);- expect(layout.furniture.some((f) => f.room === "lead" || f.room === "wardrobe")).toBe(false);- expect(layout.spots.some((s) => s.room === "command")).toBe(true);- expect(layout.spots.some((s) => s.room === "server")).toBe(true);- // It keeps its own compact footprint, with no team studios, zones or planting of the campus below.- expect(layout.studios).toBeUndefined();- expect(layout.zones).toBeUndefined();- expect(layout.ambience).toBeUndefined();- // Two bays of 9 m either side of the 6.4 m concourse, plus the 1.6 m window strips.- expect(layout.bounds.maxX - layout.bounds.minX).toBeCloseTo(27.6, 6);- // The elevator stands on the lobby's west edge, by the south wall, like on every floor.- const lift = layout.checkpoints.find((c) => c.id === "elevator")!;- const lobby = layout.rooms.find((r) => r.kind === "reception")!;- expect(lift.x - lobby.minX).toBeCloseTo(1.2, 9);- expect(lobby.maxZ - lift.z).toBeCloseTo(2.6, 9);- });-- it("builds Mission Control as its own office: slat wall, desk, lounge, and a ring round the desk", () => {- const layout = buildOfficeLayout([agent("p1", "Personal Jarvis"), agent("p2", "Website")], { variant: "coding" });- const room = layout.rooms.find((r) => r.kind === "command")!;- const stop = layout.checkpoints.find((c) => c.id === "mission")!;- const inRoom = (p: { x: number; z: number }) => p.x > room.minX && p.x < room.maxX && p.z > room.minZ && p.z < room.maxZ;- for (const kind of ["commandWall", "commandDesk", "couch", "coffeeTable", "bookshelf"] as const) {- expect(layout.furniture.some((f) => f.kind === kind && f.room === "command" && inRoom(f)), kind).toBe(true);- }- expect(stop.room).toBe("command");- expect(stop.radius).toBe(COMMAND_REACH);- // The whole ring stays inside the room's walls.- expect(stop.x - stop.radius).toBeGreaterThan(room.minX);- expect(stop.x + stop.radius).toBeLessThan(room.maxX);- expect(stop.z - stop.radius).toBeGreaterThan(room.minZ);- expect(stop.z + stop.radius).toBeLessThan(room.maxZ);- expect(buildOfficeLayout([agent("a1", "codex")]).furniture.some((f) => f.kind === "commandDesk")).toBe(false);- });-- it("lets the person work Mission Control's desk from every side, with no invisible walls", () => {- const layout = buildOfficeLayout([agent("p1", "Personal Jarvis")], { variant: "coding" });- const stop = layout.checkpoints.find((c) => c.id === "mission")!;- const grid = buildNavGrid(layout);- // A loop round the desk and chair: free to stand on everywhere, and inside the ring.- for (let i = 0; i < 16; i += 1) {- const a = (i / 16) * Math.PI * 2;- // An ellipse: the desk is long and shallow, so the path round it is too.- const p = { x: stop.x + Math.cos(a) * 1.85, z: stop.z + Math.sin(a) * 1.6 };- expect(isWalkable(grid, p), `angle ${i}`).toBe(true);- expect(Math.hypot(p.x - stop.x, p.z - stop.z)).toBeLessThanOrEqual(stop.radius);- }- // Only the desk top and the chair are solid: right beside the chair is open floor.- // The desk faces the door; its chair stands between it and the wall.- const deskZ = stop.z + 0.3;- const chairZ = deskZ - COMMAND_DESK.chairZ;- expect(isWalkable(grid, { x: stop.x, z: deskZ })).toBe(false);- expect(isWalkable(grid, { x: stop.x, z: chairZ })).toBe(false);- // Beside the chair, a step back from the desk edge, the floor is open on both sides.- expect(isWalkable(grid, { x: stop.x + 0.75, z: chairZ - 0.25 })).toBe(true);- expect(isWalkable(grid, { x: stop.x - 0.75, z: chairZ - 0.25 })).toBe(true);- expect(isWalkable(grid, stop.approach!)).toBe(true);- });-- for (const count of [0, 12, 40]) {- it(`puts the coding floor's spawn point on the aisle crossing in the middle of the floor (${count} agents)`, () => {- const roster = Array.from({ length: count }, (_, i) => agent(`a${i}`, `P${i % 6}`));- const layout = buildOfficeLayout(roster, { variant: "coding" });- const stop = layout.checkpoints.find((c) => c.id === "launch")!;- const terminal = layout.furniture.find((f) => f.kind === "spawnTerminal")!;- const pad = layout.furniture.find((f) => f.kind === "spawnPad")!;- expect(stop.room).toBe("floor");- expect([terminal.x, terminal.z]).toEqual([stop.x, stop.z]);- expect([pad.x, pad.z]).toEqual([stop.x, stop.z]);- // On the centre line between the two department columns, in a cross aisle nearest the floor's middle.- const columns = { minX: Math.min(...layout.departments.map((d) => d.minX)), maxX: Math.max(...layout.departments.map((d) => d.maxX)) };- expect(stop.x).toBeCloseTo((columns.minX + columns.maxX) / 2, 9);- const rowStarts = [...new Set(layout.departments.map((d) => d.minZ))].sort((p, q) => p - q);- const crossings = rowStarts.slice(1).map((start, i) => {- const above = Math.max(...layout.departments.filter((d) => d.minZ === rowStarts[i]).map((d) => d.maxZ));- return (above + start) / 2;- });- expect(crossings.length).toBeGreaterThan(0);- const middle = (layout.bounds.minZ + layout.bounds.maxZ) / 2;- const nearest = Math.min(...crossings.map((c) => Math.abs(c - middle)));- expect(Math.abs(stop.z - middle)).toBeCloseTo(nearest, 6);- // The whole pad stays clear of every department, and the ring sits on the pad.- const padBox = footprint(pad);- for (const dept of layout.departments) {- const overlap = padBox.minX < dept.maxX && dept.minX < padBox.maxX && padBox.minZ < dept.maxZ && dept.minZ < padBox.maxZ;- expect(overlap, dept.id).toBe(false);- }- expect(stop.radius).toBeLessThanOrEqual(FURNITURE_SIZE.spawnPad.w / 2);- // Newcomers appear where "walk there" ends, south of the screen.- expect(layout.arrival).toEqual(stop.approach);- expect(layout.arrival.z - stop.z).toBeCloseTo(SPAWN.approach, 9);- expect(isWalkable(buildNavGrid(layout), layout.arrival)).toBe(true);- });- }-- it("keeps only one spawn point per floor, and the agents floor's directory at the reception desk", () => {- const agents = buildOfficeLayout([agent("a1", "Codex")]);- const coding = buildOfficeLayout([agent("p1", "Personal Jarvis")], { variant: "coding" });- for (const layout of [agents, coding]) {- expect(layout.furniture.filter((f) => f.kind === "spawnTerminal")).toHaveLength(1);- expect(layout.furniture.filter((f) => f.kind === "spawnPad")).toHaveLength(1);- }- const desk = agents.furniture.find((f) => f.kind === "receptionDesk")!;- expect(desk.room).toBe("reception");- const manage = agents.checkpoints.find((c) => c.id === "manage")!;- expect(manage.x).toBe(desk.x);- expect(manage.z - desk.z).toBeCloseTo(1.7, 9);- expect(agents.checkpoints.some((c) => c.id === "create")).toBe(false);- expect(coding.checkpoints.some((c) => c.id === "manage")).toBe(false);- });-- it("counts states", () => {- expect(countStates([{ state: "working" }, { state: "idle" }, { state: "working" }])).toEqual({ working: 2, idle: 1, waiting: 0, paused: 0 });- });-});--describe("office camera", () => {- const bounds = { minX: -12, maxX: 12, minZ: -15, maxZ: 15 };- it("looks at the floor centre from the south-east, above it", () => {- const pose = cameraHome(bounds, 16 / 9);- expect(pose.target).toEqual([0, 0, 0]);- expect(pose.position[0]).toBeGreaterThan(0);- expect(pose.position[1]).toBeGreaterThan(0);- expect(pose.position[2]).toBeGreaterThan(0);- });- it("backs off further for a narrow viewport and a bigger floor", () => {- expect(fitDistance(bounds, 0.6)).toBeGreaterThan(fitDistance(bounds, 2));- expect(fitDistance({ minX: -30, maxX: 30, minZ: -30, maxZ: 30 }, 1.6)).toBeGreaterThan(fitDistance(bounds, 1.6));- });- it("frames the occupied desks, padded to a readable neighbourhood", () => {- expect(focusBounds([])).toBeNull();- const focus = focusBounds([{ x: 10, z: -4 }])!;- expect((focus.minX + focus.maxX) / 2).toBe(10);- expect(focus.maxX - focus.minX).toBeGreaterThanOrEqual(18);- expect(cameraHome(bounds, 1.6, focus).target).toEqual([10, 0, -4]);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeLayout.ts b/dodaios/ui/web/frontend/src/components/society/office/officeLayout.tsdeleted file mode 100644index ff85278ce6..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeLayout.ts+++ /dev/null@@ -1,915 +0,0 @@-/**- * The office floors as data: rooms, departments, desks, furniture, hangout- * spots, checkpoints and the obstacles that navigation walks around.- *- * Pure and deterministic — the same roster always produces the same floor and- * seating, so an agent never "moves desks" on a refetch. Units are metres,- * +x east, +z south, origin at the floor centre. The camera looks from the- * south-east, so tall rooms stand in the north and the lobby lies in front.- *- * This module holds the shared vocabulary (types, footprints, desk and wall- * helpers) and the coding floor's plan. `buildOfficeLayout` hands the agents- * floor to `campusLayout.ts`: a team campus of studios round an atrium. The- * Level Hall has a floor of its own (`hallFloorLayout.ts`), the arcade too- * (`arcade/arcadeFloorLayout.ts`).- *- * ┌──── north strip: Mission Control · Team room · Server room ────┐- * │ departments (open office, 2 columns) · spawn point between │- * └──────── south strip: Reception + lobby · Break room ───────────┘- *- * The coding floor's departments are the Agentic IDE workspaces. It has no- * lead desks. Mission Control is a modern office: a walnut slat wall with a- * live video wall, a desk with three live monitors and a lounge corner;- * working it starts new coding agents and briefs several at once. Only it,- * the spawn point, the elevator and the break room are checkpoints there.- *- * Both working floors have a spawn point: a round pad with a terminal. It- * spawns new Jarvis agents downstairs (in the campus atrium) and new coding- * agents upstairs, and everyone new to the floor appears on its pad.- */-import { translate } from "@/i18n";-import { PRODUCT_NAME } from "@/lib/branding";-import type { AgentRunState, AgentTier } from "../data";-import type { AgentsAmbienceItem } from "./agentsAmbience";-import type { SkyPad } from "./skyPad";-import { buildCampusLayout } from "./campusLayout";-import { codingAmbience } from "./codingAmbience";--export interface OfficeAgentInput {- agentId: string;- name: string;- tier: AgentTier;- providerLabel: string;- state: AgentRunState;- createdMs: number;-}--export interface Rect { minX: number; maxX: number; minZ: number; maxZ: number }-export interface Point { x: number; z: number }--export type Facing = "north" | "south";--export interface DeskSlot {- id: string;- /** Desk centre on the floor. */- x: number;- z: number;- /** The direction the seated agent looks (towards its monitor). */- facing: Facing;- agentId: string | null;- /** The lead office's executive desk is larger than a bench desk; absent means DESK_SIZE. */- size?: { w: number; d: number };-}--export interface Department extends Rect {- id: string;- /** The name on the sign: the team (agents floor, "" for the pool) or the workspace (coding floor, "" for a spare open-space department). */- label: string;- desks: DeskSlot[];- /** Carpet tint index into the palette's department colours. */- tint: number;- /** Agents floor: the team whose studio this is; null = the pool of agents without a team. Absent on other floors. */- teamId?: string | null;-}--/** A team as the floor plan needs it: a society chat group's id, name, members and age. */-export interface OfficeTeamInput {- id: string;- name: string;- members: readonly string[];- createdMs: number;- /** The agent that leads the team, as the roster names it; never guessed. Absent or null = no lead. */- leadId?: string | null;-}--/**- * A team's neighbourhood on the agents floor: its desks (the department `deptId`), the wall board the team- * gathers at and the standing places round it. The pool studio (`teamId` null) seats everyone without a team.- */-export interface Studio {- deptId: string;- teamId: string | null;- name: string;- /** Member agent ids seated in this studio, in seating order: the lead first, at the head desk, then by arrival. */- members: string[];- /**- * The team's lead, seated at this studio's head desk (the first desk of the bench nearest the name wall). Null- * when the team has none, and when the agent named as its lead cannot sit here: not a member, not on the roster,- * in the lead office, or already at the head of an older team it leads too.- */- leadId: string | null;- /** The studio board (a `studioBoard` furniture piece): its id, where its face is and the yaw it faces. Null for a studio without one. */- board: (Point & { id: string; facing: number }) | null;- /** Ids of the `huddle` spots in front of the board. */- huddleSpotIds: string[];- centre: Point;-}--/**- * "command" (Mission Control) and "server" only exist on the coding floor, in place of the lead office and the wardrobe.- * The arcade floor has its own rooms: three game rooms ("classics", "puzzle", "action"), the open hall between them- * ("arcade"), and the "foyer" with the elevator, the prize shop ("prizes") and the "snack" bar.- */-export type RoomKind = "lead" | "team" | "wardrobe" | "reception" | "break" | "command" | "server"- | "arcade" | "classics" | "puzzle" | "action" | "foyer" | "prizes" | "snack"- // The Level Hall, on its own floor.- | "levels";--/** Which floor a layout draws: the society agents' campus, the coding agents' floor above it, the arcade floor, or the Level Hall on top. */-export type OfficeVariant = "agents" | "coding" | "arcade" | "hall";--export interface Door { side: "north" | "south" | "east" | "west"; /** Centre of the gap along the wall. */ at: number; width: number }--export interface Room extends Rect {- id: RoomKind;- kind: RoomKind;- /** Walled rooms get glass walls on every side except their doors; open rooms have none. */- walled: boolean;- doors: Door[];- /** Where an open room's name arch stands (the middle between its posts); absent = the middle of its north edge. */- arch?: Point;-}--export interface WallSegment { x1: number; z1: number; x2: number; z2: number; room: RoomKind }--/**- * "elevator" rides between the floors and stands in front of the elevator on every one of them.- * "mission" is Mission Control on the coding floor.- * "spawn" (agents floor) and "launch" (coding floor) are the spawn point in the floor's middle:- * a new Jarvis agent downstairs, a new coding agent upstairs.- * "manage" is the agents floor's reception desk: the one directory and help station.- * "studio" (the dais) and "levels" (the service guide) are the Level Hall floor's.- * "create" is no longer placed on any floor; the kind stays for the maps' label tables.- * "ship" is the courier on the agents floor's sky pad: board it and fly.- */-export type CheckpointKind = "spawn" | "launch" | "create" | "manage" | "team" | "wardrobe" | "lead" | "break" | "elevator" | "mission"- | "studio" | "levels" | "ship";--/** A place the person can walk to (or click from afar) to act. "floor" = the open office, outside every room. */-export interface Checkpoint extends Point {- id: CheckpointKind; room: RoomKind | "floor";- /** Walk-in radius in metres. */- radius: number;- /**- * Where "walk there" goes when the checkpoint's centre is inside something- * solid (Mission Control's ring is centred on its screen); absent = the centre.- */- approach?: Point;-}--export type FurnitureKind =- | "meetingTable" | "teamBoard" | "receptionDesk" | "lockers" | "mirror"- | "coffeeBar" | "waterCooler" | "couch" | "coffeeTable" | "arcade" | "beanbag"- | "bookshelf" | "plant" | "rug" | "elevator"- // Break room lounge: sofa modules and their corner, the oak coffee table, a kilim, the bookcase wall,- // the reading nook, foosball, monsteras and the arcade's game mat.- | "breakSofa" | "breakSofaCorner" | "breakTable" | "breakRug" | "breakBookcase" | "readingNook" | "foosball" | "breakPlant"- | "arcadeMat"- // Lead office: the executive suite.- | "leadWall" | "executiveRug" | "guestChair" | "chesterfield" | "loungeTable" | "executiveBar" | "globe" | "floorLamp"- | "dogBed" | "treatJar"- // Coding floor: Mission Control's console ring.- // Coding floor: Mission Control's slat wall with the video wall, and its desk with three monitors and a chair.- | "commandWall" | "commandDesk"- // Coding floor: the server room — rack rows round a cold aisle, the NOC console and status wall, UPS, fire suppression.- | "serverRack" | "coldAisle" | "nocConsole" | "statusWall" | "ups" | "fireSuppression"- // Team room: the slat wall behind the board, a credenza, fiddle-leaf figs and a wool rug.- | "teamWall" | "credenza" | "designerPlant" | "teamRug"- // Agents floor: the board of one team studio (id `studio-board:<deptId>`), and the stand on the free plot where a- // new team is started (id `team-stand`, at most one per plan).- | "studioBoard" | "teamStand"- // Wardrobe (agents floor): the oak wardrobe wall, a bulb-lit mirror, a tailor's dummy, a bench, a coat stand, a round rug.- | "wardrobeWall" | "dressingMirror" | "tailorDummy" | "dressingBench" | "coatStand" | "roundRug"- // Lobby (agents floor): the brand wall, the waiting lounge, olive trees, the award vitrine, the mat. The agent- // totem is a prop no floor places any more: the reception desk is the directory.- | "brandWall" | "agentTotem" | "lobbySofa" | "lobbyArmchair" | "lobbyTable" | "sideTable" | "lobbyLamp" | "oliveTree"- | "awardCase" | "entranceMat" | "lobbyRug"- // The spawn point in the middle of both floors: the flat pad and the terminal standing on it.- | "spawnPad" | "spawnTerminal"- // Arcade floor: the playable game cabinets (id `cabinet-<gameId>`, see arcade/arcadeGames.ts), the prize- // counter, the token changer, a claw machine, an air-hockey table, a pinball machine and a snack-bar counter.- | "retroCabinet" | "prizeCounter" | "tokenMachine" | "clawMachine" | "airHockey" | "pinball" | "snackCounter"- // Level Hall (agents floor): the Level Wall over the studio's stage, the round stage itself, a pedestal per reward- // (id `level-pedestal-<n>`, lowest unlock first), the Level Road between them, the double-sided level guide.- | "levelWall" | "studioStage" | "rewardPedestal" | "levelRoad" | "levelGuide";--/**- * Footprint (x-extent × z-extent before rotation) and height of each piece.- * The renderer MUST build every prop inside this box: navigation reads the- * same numbers, so a prop larger than its footprint makes figures clip into it.- */-export const FURNITURE_SIZE: Record<FurnitureKind, { w: number; d: number; h: number; solid: boolean }> = {- // The top is at 0.76 m; a carafe stands on it.- meetingTable: { w: 3.6, d: 1.6, h: 1.0, solid: true },- teamBoard: { w: 2.6, d: 0.2, h: 1.9, solid: true },- studioBoard: { w: 2.4, d: 0.16, h: 1.9, solid: true },- // A lectern: a slanted sign on a post, its face towards the prop's front.- teamStand: { w: 0.8, d: 0.5, h: 1.3, solid: true },- // The counter is 1.1 m; its slatted back wall with the help display rises to 2.2 m.- receptionDesk: { w: 2.8, d: 0.9, h: 2.2, solid: true },- lockers: { w: 2.4, d: 0.5, h: 1.9, solid: true },- mirror: { w: 0.9, d: 0.12, h: 1.9, solid: true },- coffeeBar: { w: 2.4, d: 0.7, h: 1.05, solid: true },- waterCooler: { w: 0.45, d: 0.45, h: 1.3, solid: true },- couch: { w: 2.2, d: 0.9, h: 0.85, solid: true },- coffeeTable: { w: 1.1, d: 1.1, h: 0.4, solid: true },- arcade: { w: 0.8, d: 0.8, h: 1.8, solid: true },- beanbag: { w: 0.9, d: 0.9, h: 0.6, solid: true },- bookshelf: { w: 1.8, d: 0.36, h: 1.4, solid: true },- plant: { w: 0.6, d: 0.6, h: 1.3, solid: true },- rug: { w: 1, d: 1, h: 0.02, solid: false },- elevator: { w: 2.2, d: 0.4, h: 2.4, solid: true },- // Break room: the sofa modules keep the couch's box; the coffee table carries a chess game and board games;- // the reading nook is the armchair plus its floor lamp; the foosball box includes the rod handles.- breakSofa: { w: 2.2, d: 0.9, h: 0.85, solid: true },- breakSofaCorner: { w: 0.9, d: 0.9, h: 0.85, solid: true },- breakTable: { w: 1.3, d: 0.75, h: 0.5, solid: true },- breakRug: { w: 1, d: 1, h: 0.02, solid: false },- breakBookcase: { w: 2.8, d: 0.4, h: 2.05, solid: true },- readingNook: { w: 0.9, d: 0.9, h: 1.75, solid: true },- foosball: { w: 1.3, d: 1.05, h: 0.8, solid: true },- breakPlant: { w: 0.7, d: 0.7, h: 1.9, solid: true },- arcadeMat: { w: 1, d: 1, h: 0.02, solid: false },- leadWall: { w: 7.9, d: 0.38, h: 2.9, solid: true },- executiveRug: { w: 1, d: 1, h: 0.02, solid: false },- guestChair: { w: 0.74, d: 0.74, h: 0.92, solid: true },- chesterfield: { w: 2.2, d: 0.95, h: 0.86, solid: true },- loungeTable: { w: 1.1, d: 0.64, h: 0.62, solid: true },- executiveBar: { w: 1.9, d: 0.52, h: 1.9, solid: true },- // The tilted meridian ring reaches further east-west than the stand.- globe: { w: 0.92, d: 0.72, h: 1.2, solid: true },- floorLamp: { w: 0.46, d: 0.46, h: 1.8, solid: true },- dogBed: { w: 0.9, d: 0.72, h: 0.45, solid: true },- treatJar: { w: 0.5, d: 0.5, h: 1.2, solid: true },- // Mission Control: a display on a floor stand; the box is the screen's width and the base plate's depth.- commandWall: { w: 7.8, d: 0.3, h: 2.7, solid: true },- // Desk and chair together; not a solid box, navigation walks round commandDeskObstacles.- commandDesk: { w: 2.8, d: 2.1, h: 1.7, solid: false },- // Server room: a row of five 42U racks, its ladder tray on top; the aisle between two rows (floor tiles,- // overhead trays, a light) is walkable; the NOC console includes its stool.- serverRack: { w: 3.0, d: 1.0, h: 2.3, solid: true },- coldAisle: { w: 2.44, d: 3.0, h: 2.3, solid: false },- nocConsole: { w: 2.0, d: 1.3, h: 1.3, solid: true },- statusWall: { w: 2.4, d: 0.3, h: 2.1, solid: true },- ups: { w: 1.2, d: 0.8, h: 1.9, solid: true },- fireSuppression: { w: 0.9, d: 0.5, h: 1.9, solid: true },- // Team room: the slat wall carries the board, felt panels and the video display.- teamWall: { w: 8.16, d: 0.12, h: 2.05, solid: true },- // The body is 0.61 m; books and a vase of branches stand on it.- credenza: { w: 2.2, d: 0.46, h: 1.1, solid: true },- designerPlant: { w: 0.8, d: 0.8, h: 2.0, solid: true },- teamRug: { w: 1, d: 1, h: 0.02, solid: false },- // Wardrobe: four open oak bays with rails, shelves and drawers; the mirror stands on splayed feet.- wardrobeWall: { w: 4.36, d: 0.62, h: 2.05, solid: true },- dressingMirror: { w: 1.1, d: 0.3, h: 2.05, solid: true },- tailorDummy: { w: 0.5, d: 0.5, h: 1.75, solid: true },- dressingBench: { w: 1.3, d: 0.5, h: 0.5, solid: true },- coatStand: { w: 0.5, d: 0.5, h: 1.85, solid: true },- roundRug: { w: 1, d: 1, h: 0.02, solid: false },- // Lobby: the ghost and the wordmark on the brand wall; the totem is a touch-screen stele (unplaced).- brandWall: { w: 3.2, d: 0.36, h: 2.9, solid: true },- agentTotem: { w: 0.9, d: 0.5, h: 2.1, solid: true },- lobbySofa: { w: 2.3, d: 0.95, h: 0.8, solid: true },- lobbyArmchair: { w: 0.8, d: 0.82, h: 0.82, solid: true },- // The top is at 0.4 m; magazines, a bowl and a sprig in a vase stand on it.- lobbyTable: { w: 1.2, d: 0.75, h: 0.6, solid: true },- sideTable: { w: 0.5, d: 0.5, h: 0.65, solid: true },- lobbyLamp: { w: 0.5, d: 0.5, h: 1.75, solid: true },- oliveTree: { w: 1.2, d: 1.2, h: 2.5, solid: true },- awardCase: { w: 1.3, d: 0.42, h: 1.95, solid: true },- entranceMat: { w: 1, d: 1, h: 0.02, solid: false },- lobbyRug: { w: 1, d: 1, h: 0.02, solid: false },- // The spawn point: a flat round pad everyone walks over, and the double-sided terminal on it (its crest- // tops out at 2.2 m). The pad fits the 3.2 m aisle crossing with a margin to every department.- spawnPad: { w: 2 * 1.42, d: 2 * 1.42, h: 0.02, solid: false },- spawnTerminal: { w: 1.2, d: 0.7, h: 2.2, solid: true },- // Arcade floor. A cabinet's screen and controls face its local +z; the person plays standing in front of it.- retroCabinet: { w: 0.8, d: 0.8, h: 1.95, solid: true },- prizeCounter: { w: 3.4, d: 0.9, h: 2.2, solid: true },- tokenMachine: { w: 0.6, d: 0.5, h: 1.7, solid: true },- clawMachine: { w: 1.0, d: 1.0, h: 2.0, solid: true },- airHockey: { w: 2.1, d: 1.2, h: 0.95, solid: true },- pinball: { w: 0.75, d: 1.45, h: 1.9, solid: true },- snackCounter: { w: 2.6, d: 0.8, h: 1.1, solid: true },- // Level Hall. The wall carries the live level display; the stage is a flat round disc anyone can step on (its- // ring of lights stays inside the box); a pedestal is a plinth with a glass case and the reward floating in it;- // the road is a lit floor strip, sized per instance; the guide is a free-standing screen, the same on both faces.- levelWall: { w: 6.6, d: 0.34, h: 3.1, solid: true },- studioStage: { w: 3.2, d: 3.2, h: 0.02, solid: false },- rewardPedestal: { w: 0.8, d: 0.8, h: 1.75, solid: true },- levelRoad: { w: 1, d: 1, h: 0.02, solid: false },- levelGuide: { w: 3.4, d: 0.36, h: 2.45, solid: true },-};--/**- * The studio board's face, in the board's own frame (origin on the floor under its centre, front towards +z):- * its size, the height of its centre and how far it stands in front of the board's centre plane. `Studio.board`- * is this face's point on the plan; live content is drawn a few millimetres in front of it.- */-export const STUDIO_BOARD_FACE = { w: 2.16, h: 1.16, y: 1.22, z: 0.059 } as const;--/**- * Where a studio board's face is in the world: its centre, the yaw it looks along (0 = south) and its size in- * metres. Takes a `Studio.board` (the face's point on the plan and its yaw).- */-export function studioBoardFace(board: Point & { facing: number }): { position: [number, number, number]; rotationY: number; size: [number, number] } {- return { position: [board.x, STUDIO_BOARD_FACE.y, board.z], rotationY: board.facing, size: [STUDIO_BOARD_FACE.w, STUDIO_BOARD_FACE.h] };-}--/**- * The spawn point's numbers, shared by the layout, the renderer and the tests:- * the walk-in radius round the terminal, how far south of it "walk there" and- * a newcomer's arrival stand, and the height of the beacon turning above the- * terminal's crest.- */-export const SPAWN = { reach: 1.15, approach: 0.95, beaconY: 2.85 } as const;--export interface Furniture extends Point {- id: string;- kind: FurnitureKind;- /** Rotation about +y. 0 = the prop's front faces +z (south, towards the camera). */- rotationY: number;- room: RoomKind | "floor";- /** Only rugs (plain, executive, team, lobby), the entrance mat and the Level Road are sized per instance (w × d); everything else uses FURNITURE_SIZE. */- size?: { w: number; d: number };-}--export type SpotKind = "couch" | "coffee" | "cooler" | "window" | "shelf" | "arcade" | "meeting" | "beanbag" | "board"- // A standing place in front of a studio board (id `huddle:<deptId>:<n>`).- | "huddle";-export type SpotPose = "sit" | "stand" | "sleep";--/** Where an idle agent (or the person) can hang out. `facing` is the figure's rotation about +y. */-export interface Spot extends Point { id: string; kind: SpotKind; pose: SpotPose; facing: number; room: RoomKind | "floor" }--/**- * What a part of the campus between the studios is: a street (the boulevard, the main boulevard's plaza with the- * atrium at its heart), a free plot, or one of the commons — a garden court, the focus booths, the library, the café.- */-export type CampusZoneKind = "boulevard" | "plaza" | "atrium" | "plot" | "garden" | "booths" | "library" | "cafe";--/** A named area of the agents floor outside rooms and studios; flat, never an obstacle by itself. */-export interface CampusZone extends Rect { id: string; kind: CampusZoneKind }--export interface OfficeLayout {- variant: OfficeVariant;- departments: Department[];- /** Team studios of the agents floor, one per department there; absent or empty on the other floors. */- studios?: Studio[];- /** Agents floor: the boulevard, the plaza and its atrium, the free plot and the commons. Absent on the other floors. */- zones?: CampusZone[];- /** Agents floor: every studio fitting, commons piece, tree, bench and planter; each one is also an obstacle. Absent on the other floors. */- ambience?: AgentsAmbienceItem[];- /** Lead desks live in the lead office; the coding floor has none (its rect is Mission Control). */- lead: Rect & { desks: DeskSlot[] };- /** Mission Control's desk on the coding floor, as a seat the person can take; absent downstairs. */- command?: DeskSlot;- rooms: Room[];- walls: WallSegment[];- furniture: Furniture[];- spots: Spot[];- checkpoints: Checkpoint[];- /** Solid footprints (desks, walls, furniture), un-inflated. Navigation inflates them by the walker radius. */- obstacles: Rect[];- /** Where the person's character starts. */- spawn: Point;- /** Where someone new to the floor (an agent created during the visit) appears: on the spawn pad. */- arrival: Point;- /** The walkable floor inside the railing. */- floor: Rect;- /** The whole slab, railing included. */- bounds: Rect;- /** Agents floor: the landing platform outside the east windows, walkable beyond `floor`. Absent on the other floors. */- skyPad?: SkyPad;-}--/** Desk pitch along a row and the depth of one bench (two rows back to back plus chairs). */-export const DESK_PITCH_X = 1.7;-export const BENCH_DEPTH_Z = 4.2;-/** Half the gap between the two monitors of a back-to-back pair. */-export const DESK_HALF_GAP = 0.45;-export const DESK_SIZE = { w: 1.5, d: 0.8 } as const;-/** The lead's executive desk: wider and a little deeper, same seat distance and height. */-export const EXECUTIVE_DESK_SIZE = { w: 2.4, d: 0.9 } as const;-/** A second lead's partner desk beside the executive desk. */-export const PARTNER_DESK_SIZE = { w: 1.7, d: 0.84 } as const;-/** Chair centre behind a desk, along the agent's back direction. */-export const SEAT_OFFSET = 0.62;-export const DESKS_PER_ROW = 4;-const SEATS_PER_BENCH = DESKS_PER_ROW * 2;-const MIN_BENCHES = 1;-const MAX_BENCHES = 4;-const DEPT_MARGIN_X = 1.1;-const DEPT_HEADER_Z = 1.8;-const DEPT_FOOTER_Z = 0.8;-const AISLE = 3.2;-/** The coding floor's centre aisle, the concourse: the Core stands at its middle crossing. */-export const CONCOURSE = 6.4;-/**- * Mission Control's desk, in its own space (origin = desk centre, +z = the- * side where the chair stands): the desk top and the chair the person works- * from. On the floor the desk is turned round, so the chair stands between- * it and the wall. The renderer and navigation both read these numbers.- */-/** `chairZ` equals SEAT_OFFSET, so the chair is exactly where seatOf() puts a seated person. */-export const COMMAND_DESK = { w: 2.6, d: 0.86, chairZ: 0.62 } as const;-/** How far round Mission Control's desk the person can use it, from the desk's centre. */-export const COMMAND_REACH = 1.9;-/** The desk piece's origin sits this far from the desk's centre, towards the chair: its box covers desk and chair. */-export const COMMAND_DESK_OFFSET = 0.5;-/** The window strip between the plan and the slab edge, on every floor. */-export const FLOOR_EDGE = 1.6;-const EDGE = FLOOR_EDGE;-/**- * How far a figure's centre stays from the slab edge. The railing stands 0.2 m- * in and the toy head is ~0.31 m wide each side (plus hair), so anything less- * lets the head poke through the glass and the handrail cap.- */-export const RAIL_CLEARANCE = 0.65;-const NORTH_DEPTH = 7;-const SOUTH_DEPTH = 8;-const COLUMNS = 2;-const WALL_THICKNESS = 0.12;-/** Coding floor: more departments than this fold into the last one — the floor stays one screen. */-export const MAX_DEPARTMENTS = 6;-/** Coding floor: it always shows at least this many departments; spare ones are open space with free desks. */-export const MIN_DEPARTMENTS = 4;-/** The most bench desks the coding floor can hold. The agents floor's capacity depends on its teams: see `seatedCount`. */-export const MAX_SEATED = MAX_DEPARTMENTS * MAX_BENCHES * SEATS_PER_BENCH;--/** Coding floor: the department an agent works in — its workspace, or the product's own brain. */-export function departmentKey(agent: Pick<OfficeAgentInput, "providerLabel">): string {- const label = agent.providerLabel.trim();- return label.length > 0 ? label.charAt(0).toUpperCase() + label.slice(1) : PRODUCT_NAME;-}--/** Seating order: who arrived first sits first, so a refetch never re-seats anyone. */-export function byArrival(a: OfficeAgentInput, b: OfficeAgentInput): number {- return a.createdMs - b.createdMs || a.agentId.localeCompare(b.agentId);-}--/** Coding floor: group staff (non-lead) agents into at most MAX_DEPARTMENTS stable departments. */-export function groupDepartments(agents: readonly OfficeAgentInput[]): { label: string; members: OfficeAgentInput[] }[] {- const groups = new Map<string, OfficeAgentInput[]>();- for (const agent of agents) {- if (agent.tier === "lead") continue;- const key = departmentKey(agent);- const list = groups.get(key) ?? [];- list.push(agent);- groups.set(key, list);- }- const ordered = [...groups.entries()]- .map(([label, members]) => ({ label, members: [...members].sort(byArrival) }))- .sort((a, b) => b.members.length - a.members.length || a.label.localeCompare(b.label));- if (ordered.length === 0) return [{ label: PRODUCT_NAME, members: [] }];- if (ordered.length <= MAX_DEPARTMENTS) return ordered;- const kept = ordered.slice(0, MAX_DEPARTMENTS - 1);- const rest = ordered.slice(MAX_DEPARTMENTS - 1).flatMap((g) => g.members).sort(byArrival);- return [...kept, { label: translate("society.floor.department_other"), members: rest }];-}--function benchCount(members: number): number {- return Math.min(MAX_BENCHES, Math.max(MIN_BENCHES, Math.ceil(members / SEATS_PER_BENCH)));-}--const DEPT_WIDTH = DESKS_PER_ROW * DESK_PITCH_X + DEPT_MARGIN_X * 2;--function deptDepth(benches: number): number {- return DEPT_HEADER_Z + benches * BENCH_DEPTH_Z + DEPT_FOOTER_Z;-}--/** Desk slots of one department, seated in arrival order: bench by bench, front row first. */-function layoutDesks(deptId: string, minX: number, minZ: number, benches: number, members: OfficeAgentInput[]): DeskSlot[] {- const desks: DeskSlot[] = [];- let seat = 0;- for (let bench = 0; bench < benches; bench += 1) {- const centreZ = minZ + DEPT_HEADER_Z + bench * BENCH_DEPTH_Z + BENCH_DEPTH_Z / 2;- for (const facing of ["north", "south"] as const) {- // A north-facing agent sits on the south side of the pair, looking at its monitor.- const z = facing === "north" ? centreZ + DESK_HALF_GAP : centreZ - DESK_HALF_GAP;- for (let col = 0; col < DESKS_PER_ROW; col += 1) {- const x = minX + DEPT_MARGIN_X + DESK_PITCH_X * (col + 0.5);- desks.push({ id: `${deptId}:${bench}:${facing}:${col}`, x, z, facing, agentId: members[seat]?.agentId ?? null });- seat += 1;- }- }- }- return desks;-}--/** The chair a desk's agent sits on, and the figure's heading while seated. */-export function seatOf(desk: Pick<DeskSlot, "x" | "z" | "facing">): Point & { facing: number } {- return desk.facing === "north"- ? { x: desk.x, z: desk.z + SEAT_OFFSET, facing: Math.PI }- : { x: desk.x, z: desk.z - SEAT_OFFSET, facing: 0 };-}--/** Where an agent stands beside its chair (e.g. waiting for the person). */-export function standOf(desk: Pick<DeskSlot, "x" | "z" | "facing">): Point & { facing: number } {- const seat = seatOf(desk);- return { x: seat.x + 0.55, z: seat.z, facing: seat.facing };-}--/** The footprint of a desk top (bench desks share DESK_SIZE; lead desks carry their own). */-export function deskRect(desk: Pick<DeskSlot, "x" | "z" | "size">): Rect {- const { w, d } = desk.size ?? DESK_SIZE;- return { minX: desk.x - w / 2, maxX: desk.x + w / 2, minZ: desk.z - d / 2, maxZ: desk.z + d / 2 };-}--/** A planter box at each end of a bench (both floors): its width, length and the gap to the end desk. */-export const BENCH_PLANTER = { w: 0.36, d: 1.56, gap: 0.14 } as const;--/**- * The planter boxes closing off each bench of a department, west and east,- * keyed "<deptId>:<bench>:w|e". They stand in the dead end between the two- * desk rows, clear of the chairs and the walkway behind them.- */-export function benchPlanters(dept: Pick<Department, "id" | "desks">): { key: string; rect: Rect }[] {- const benches = new Map<string, DeskSlot[]>();- for (const desk of dept.desks) {- const bench = desk.id.split(":").at(-3) ?? "0";- benches.set(bench, [...(benches.get(bench) ?? []), desk]);- }- const half = DESK_SIZE.w / 2 + BENCH_PLANTER.gap;- return [...benches.entries()].flatMap(([bench, desks]) => {- const z = desks.reduce((sum, d) => sum + d.z, 0) / desks.length;- const west = Math.min(...desks.map((d) => d.x)) - half, east = Math.max(...desks.map((d) => d.x)) + half;- const zs = { minZ: z - BENCH_PLANTER.d / 2, maxZ: z + BENCH_PLANTER.d / 2 };- return [- { key: `${dept.id}:${bench}:w`, rect: { minX: west - BENCH_PLANTER.w, maxX: west, ...zs } },- { key: `${dept.id}:${bench}:e`, rect: { minX: east, maxX: east + BENCH_PLANTER.w, ...zs } },- ];- });-}--/** Half the width of the executive chair; unlike bench chairs it is solid, so nobody walks through it. */-export const EXECUTIVE_CHAIR_HALF = 0.32;--/** The executive chair's footprint behind a lead desk (only desks with their own size have one). */-export function executiveChairRect(desk: Pick<DeskSlot, "x" | "z" | "facing">): Rect {- const seat = seatOf(desk);- return { minX: seat.x - EXECUTIVE_CHAIR_HALF, maxX: seat.x + EXECUTIVE_CHAIR_HALF, minZ: seat.z - EXECUTIVE_CHAIR_HALF, maxZ: seat.z + EXECUTIVE_CHAIR_HALF };-}--/** Half the width of a bench desk or meeting chair: its five-star base reaches ~0.29 m from the column. */-export const CHAIR_HALF = 0.28;--/** A chair's square footprint round its seat centre. Chairs are solid; walks to a seat snap onto it. */-export function chairRect(seat: Point, half = CHAIR_HALF): Rect {- return { minX: seat.x - half, maxX: seat.x + half, minZ: seat.z - half, maxZ: seat.z + half };-}--/** What a walker bumps into at Mission Control's desk: the desk top and the chair, nothing in between. */-export function commandDeskObstacles(desk: Point): Rect[] {- const { w, d } = COMMAND_DESK;- return [- { minX: desk.x - w / 2, maxX: desk.x + w / 2, minZ: desk.z - d / 2, maxZ: desk.z + d / 2 },- // The desk is turned round on the floor, facing south: its chair stands north of it,- // towards the wall (seatOf). A boss chair, so it takes the executive chair's footprint.- executiveChairRect({ x: desk.x, z: desk.z, facing: "south" }),- ];-}--/** Axis-aligned footprint of a rotated piece (rotations are multiples of 90°). */-export function footprint(item: Pick<Furniture, "x" | "z" | "kind" | "rotationY" | "size">): Rect {- const base = item.size ?? FURNITURE_SIZE[item.kind];- const quarter = Math.round(item.rotationY / (Math.PI / 2)) % 2 !== 0;- const w = quarter ? base.d : base.w;- const d = quarter ? base.w : base.d;- return { minX: item.x - w / 2, maxX: item.x + w / 2, minZ: item.z - d / 2, maxZ: item.z + d / 2 };-}--export function wallsOf(room: Room): WallSegment[] {- if (!room.walled) return [];- const sides: { side: Door["side"]; a: Point; b: Point }[] = [- { side: "north", a: { x: room.minX, z: room.minZ }, b: { x: room.maxX, z: room.minZ } },- { side: "south", a: { x: room.minX, z: room.maxZ }, b: { x: room.maxX, z: room.maxZ } },- { side: "west", a: { x: room.minX, z: room.minZ }, b: { x: room.minX, z: room.maxZ } },- { side: "east", a: { x: room.maxX, z: room.minZ }, b: { x: room.maxX, z: room.maxZ } },- ];- const out: WallSegment[] = [];- for (const { side, a, b } of sides) {- const horizontal = side === "north" || side === "south";- const start = horizontal ? a.x : a.z;- const end = horizontal ? b.x : b.z;- const gaps = room.doors.filter((d) => d.side === side).map((d) => [d.at - d.width / 2, d.at + d.width / 2] as const)- .sort((p, q) => p[0] - q[0]);- let cursor = start;- const push = (from: number, to: number) => {- if (to - from < 0.05) return;- out.push(horizontal- ? { x1: from, z1: a.z, x2: to, z2: a.z, room: room.kind }- : { x1: a.x, z1: from, x2: a.x, z2: to, room: room.kind });- };- for (const [g0, g1] of gaps) { push(cursor, Math.max(cursor, g0)); cursor = Math.max(cursor, g1); }- push(cursor, end);- }- return out;-}--/** The free-standing name arch of an open (unwalled) room: two posts on its north edge. */-export const ARCH = { halfSpan: 0.95, inset: 0.25, post: 0.08 } as const;--/** The desk every studio's lead sits at (its studio's head desk), with the studio's department. Empty off the agents floor. */-export function leadDesks(layout: Pick<OfficeLayout, "studios" | "departments">): { desk: DeskSlot; dept: Department }[] {- const out: { desk: DeskSlot; dept: Department }[] = [];- for (const studio of layout.studios ?? []) {- if (!studio.leadId) continue;- const dept = layout.departments.find((d) => d.id === studio.deptId);- const desk = dept?.desks.find((d) => d.agentId === studio.leadId);- if (dept && desk) out.push({ desk, dept });- }- return out;-}--/** Post centres of an open room's name arch; the renderer and navigation share them. */-export function archPosts(room: Rect & { arch?: Point }): Point[] {- const cx = room.arch?.x ?? (room.minX + room.maxX) / 2;- const z = room.arch?.z ?? room.minZ + ARCH.inset;- return [{ x: cx - ARCH.halfSpan, z }, { x: cx + ARCH.halfSpan, z }];-}--export function wallRect(w: WallSegment): Rect {- const t = WALL_THICKNESS / 2;- return { minX: Math.min(w.x1, w.x2) - t, maxX: Math.max(w.x1, w.x2) + t, minZ: Math.min(w.z1, w.z2) - t, maxZ: Math.max(w.z1, w.z2) + t };-}--export interface OfficeLayoutOptions {- /** "agents" (default) is the society campus; "coding" the IDE sessions' floor, departments per workspace. */- variant?: OfficeVariant;- /** Agents floor: the teams (society chat groups). Every team gets a studio; agents without one share the pool. */- teams?: readonly OfficeTeamInput[];-}--/**- * Build a working floor for a roster: the agents floor's team campus (the default), or the coding floor.- * Seating and the whole floor plan are stable for an unchanged roster and unchanged teams.- */-export function buildOfficeLayout(agents: readonly OfficeAgentInput[], options: OfficeLayoutOptions = {}): OfficeLayout {- return (options.variant ?? "agents") === "coding" ? buildCodingLayout(agents) : buildCampusLayout(agents, options.teams ?? []);-}--/** The coding floor: one department per IDE workspace between Mission Control, the team room and the server room. */-function buildCodingLayout(agents: readonly OfficeAgentInput[]): OfficeLayout {- const groups: { label: string; members: OfficeAgentInput[] }[] = groupDepartments(agents);- if (groups.length === 1 && groups[0].members.length === 0) groups.length = 0;- while (groups.length < MIN_DEPARTMENTS) groups.push({ label: "", members: [] });-- // The concourse between the two bay columns: wide enough for the Core at its middle- // crossing with a walkway on each side, and for the data rails running down it.- const centreAisle = CONCOURSE;- const floorWidth = COLUMNS * DEPT_WIDTH + (COLUMNS - 1) * centreAisle;- const minX = -floorWidth / 2;- const maxX = floorWidth / 2;- const rows = Math.ceil(groups.length / COLUMNS);- const rowDepths: number[] = [];- for (let row = 0; row < rows; row += 1) {- const inRow = groups.slice(row * COLUMNS, row * COLUMNS + COLUMNS);- rowDepths.push(Math.max(...inRow.map((g) => deptDepth(benchCount(g.members.length)))));- }- const floorDepth = NORTH_DEPTH + AISLE + rowDepths.reduce((s, d) => s + d, 0) + (rows - 1) * AISLE + AISLE + SOUTH_DEPTH;- const topZ = -floorDepth / 2;- const bottomZ = floorDepth / 2;-- // North strip: Mission Control · team room · server room, each with a door facing the office.- const leadW = 8.2, teamW = 8.4;- const northMaxZ = topZ + NORTH_DEPTH;- const leadRoom: Room = { id: "command", kind: "command", walled: true, minX, maxX: minX + leadW, minZ: topZ, maxZ: northMaxZ,- doors: [{ side: "south", at: minX + leadW / 2, width: 1.6 }] };- const teamRoom: Room = { id: "team", kind: "team", walled: true, minX: leadRoom.maxX, maxX: leadRoom.maxX + teamW, minZ: topZ, maxZ: northMaxZ,- doors: [{ side: "south", at: leadRoom.maxX + teamW / 2, width: 1.8 }] };- const serverRoom: Room = { id: "server", kind: "server", walled: true, minX: teamRoom.maxX, maxX, minZ: topZ, maxZ: northMaxZ,- doors: [{ side: "south", at: (teamRoom.maxX + maxX) / 2, width: 1.5 }] };-- // Departments between the strips, and the centre line of each cross aisle between two rows.- const departments: Department[] = [];- const crossAisles: number[] = [];- let z = northMaxZ + AISLE;- for (let row = 0; row < rows; row += 1) {- if (row > 0) crossAisles.push(z - AISLE / 2);- for (let col = 0; col < COLUMNS; col += 1) {- const index = row * COLUMNS + col;- const group = groups[index];- if (!group) continue;- const benches = benchCount(group.members.length);- const dMinX = minX + col * (DEPT_WIDTH + centreAisle);- const id = `dept-${index}`;- departments.push({- id, label: group.label, tint: index,- minX: dMinX, maxX: dMinX + DEPT_WIDTH, minZ: z, maxZ: z + deptDepth(benches),- desks: layoutDesks(id, dMinX, z, benches, group.members.slice(0, benches * SEATS_PER_BENCH)),- });- }- z += rowDepths[row] + AISLE;- }-- // South strip: an open reception/lobby in the west, a walled break room in the east.- const southMinZ = bottomZ - SOUTH_DEPTH;- // The spawn point: on the centre aisle, at the crossing nearest the floor's middle (a- // single row of departments, which the minimum never allows, falls back to the south aisle).- const plazaZ = (crossAisles.length > 0 ? crossAisles : [southMinZ - AISLE / 2])- .reduce((best, c) => (Math.abs(c - (topZ + bottomZ) / 2) < Math.abs(best - (topZ + bottomZ) / 2) ? c : best));- const plaza: Point = { x: minX + DEPT_WIDTH + centreAisle / 2, z: plazaZ };- const breakW = 10.5;- const receptionRoom: Room = { id: "reception", kind: "reception", walled: false, minX, maxX: maxX - breakW, minZ: southMinZ, maxZ: bottomZ, doors: [] };- const breakRoom: Room = { id: "break", kind: "break", walled: true, minX: maxX - breakW, maxX, minZ: southMinZ, maxZ: bottomZ,- doors: [{ side: "north", at: maxX - breakW / 2, width: 2.2 }, { side: "west", at: southMinZ + SOUTH_DEPTH / 2, width: 2 }] };- const rooms = [leadRoom, teamRoom, serverRoom, receptionRoom, breakRoom];-- const lx0 = leadRoom.minX, lz0 = leadRoom.minZ;- const lead = { minX: leadRoom.minX, maxX: leadRoom.maxX, minZ: leadRoom.minZ, maxZ: leadRoom.maxZ, desks: [] as DeskSlot[] };-- const tcx = (teamRoom.minX + teamRoom.maxX) / 2, tcz = (teamRoom.minZ + teamRoom.maxZ) / 2;- const wcx = (serverRoom.minX + serverRoom.maxX) / 2;- const bx0 = breakRoom.minX, bz0 = breakRoom.minZ;- const rx0 = receptionRoom.minX;- // West: Mission Control. The slat wall with the video wall along the north- // side, the desk in front of it turned towards the door: the person sits- // between desk and wall, facing into the room, and the monitors face them.- // A lounge corner with a sofa facing east, an open shelf on the east wall.- const commandDeskAt = { x: lx0 + leadW / 2, z: lz0 + 2.75 };- const wx0 = serverRoom.minX;- // Server room: the rack rows' centre line and the cold aisle between their fronts.- const serverRowZ = topZ + 3.5;- const serverAisleMinX = wx0 + 0.06 + FURNITURE_SIZE.serverRack.d;- const serverAisleMaxX = serverRoom.maxX - 0.06 - FURNITURE_SIZE.serverRack.d;- const furniture: Furniture[] = [- { id: "command-wall", kind: "commandWall", x: lx0 + leadW / 2, z: lz0 + 0.1 + FURNITURE_SIZE.commandWall.d / 2, rotationY: 0, room: "command" },- // The piece's box is desk + chair; its origin sits between them.- { id: "command-desk", kind: "commandDesk", x: commandDeskAt.x, z: commandDeskAt.z - COMMAND_DESK_OFFSET, rotationY: Math.PI, room: "command" },- { id: "command-rug", kind: "rug", x: lx0 + 1.55, z: lz0 + 5.1, rotationY: 0, room: "command", size: { w: 2.7, d: 2.6 } },- { id: "command-sofa", kind: "couch", x: lx0 + 0.6, z: lz0 + 5.1, rotationY: Math.PI / 2, room: "command" },- { id: "command-table", kind: "coffeeTable", x: lx0 + 1.9, z: lz0 + 5.1, rotationY: 0, room: "command" },- { id: "command-shelf", kind: "bookshelf", x: leadRoom.maxX - 0.3, z: lz0 + 4.7, rotationY: -Math.PI / 2, room: "command" },- { id: "command-plant-w", kind: "plant", x: lx0 + 0.5, z: lz0 + 0.95, rotationY: 0, room: "command" },- { id: "command-plant-e", kind: "plant", x: leadRoom.maxX - 0.5, z: lz0 + 0.95, rotationY: 0, room: "command" },- { id: "command-plant-s", kind: "plant", x: leadRoom.maxX - 0.55, z: northMaxZ - 0.55, rotationY: 0, room: "command" },- // Team room: a walnut table on a wool rug, the board on a slat wall with- // felt panels and a video display, a credenza under the display and one- // along the west wall, fiddle-leaf figs in both corners by the door.- { id: "team-rug", kind: "teamRug", x: tcx, z: tcz + 0.4, rotationY: 0, room: "team", size: { w: 5.4, d: 4.0 } },- { id: "team-table", kind: "meetingTable", x: tcx, z: tcz + 0.4, rotationY: 0, room: "team" },- { id: "team-wall", kind: "teamWall", x: tcx, z: topZ + 0.06 + FURNITURE_SIZE.teamWall.d / 2, rotationY: 0, room: "team" },- { id: "team-board", kind: "teamBoard", x: tcx, z: topZ + 0.25, rotationY: 0, room: "team" },- { id: "team-credenza", kind: "credenza", x: tcx + 2.7, z: topZ + 0.19 + FURNITURE_SIZE.credenza.d / 2, rotationY: 0, room: "team" },- { id: "team-credenza-w", kind: "credenza", x: teamRoom.minX + 0.07 + FURNITURE_SIZE.credenza.d / 2, z: tcz + 0.4, rotationY: Math.PI / 2, room: "team" },- { id: "team-plant", kind: "designerPlant", x: teamRoom.maxX - 0.6, z: northMaxZ - 0.6, rotationY: 0, room: "team" },- { id: "team-plant-w", kind: "designerPlant", x: teamRoom.minX + 0.6, z: northMaxZ - 0.6, rotationY: Math.PI / 2, room: "team" },- // East: a server room — two rack rows back to the side walls, fronts facing- // across a cold aisle that runs from the door to the NOC console and the- // status wall on the north side; the UPS and the fire-suppression bank- // stand in the corners by the door.- { id: "server-status", kind: "statusWall", x: wcx, z: topZ + 0.08 + FURNITURE_SIZE.statusWall.d / 2, rotationY: 0, room: "server" },- { id: "server-noc", kind: "nocConsole", x: wcx, z: topZ + 0.5 + FURNITURE_SIZE.nocConsole.d / 2, rotationY: 0, room: "server" },- { id: "server-rack-w", kind: "serverRack", x: wx0 + 0.06 + FURNITURE_SIZE.serverRack.d / 2, z: serverRowZ, rotationY: Math.PI / 2, room: "server" },- { id: "server-rack-e", kind: "serverRack", x: serverRoom.maxX - 0.06 - FURNITURE_SIZE.serverRack.d / 2, z: serverRowZ, rotationY: -Math.PI / 2, room: "server" },- { id: "server-aisle", kind: "coldAisle", x: wcx, z: serverRowZ, rotationY: 0, room: "server" },- { id: "server-ups", kind: "ups", x: wx0 + 0.06 + FURNITURE_SIZE.ups.d / 2, z: topZ + 6.0, rotationY: Math.PI / 2, room: "server" },- { id: "server-fire", kind: "fireSuppression", x: serverRoom.maxX - 0.06 - FURNITURE_SIZE.fireSuppression.d / 2, z: topZ + 6.0, rotationY: -Math.PI / 2, room: "server" },- // Reception and lobby: only plants beside the elevator; new coding agents are spawned in the middle of the floor.- { id: "elevator", kind: "elevator", x: rx0 + 0.25, z: bottomZ - 2.6, rotationY: Math.PI / 2, room: "reception" },- { id: "reception-desk", kind: "receptionDesk", x: rx0 + 3.2, z: southMinZ + 2.6, rotationY: 0, room: "reception" },- // The spawn point in the middle of the floor: the pad, and the terminal on it facing the lobby.- { id: "spawn-pad", kind: "spawnPad", x: plaza.x, z: plaza.z, rotationY: 0, room: "floor" },- { id: "spawn-terminal", kind: "spawnTerminal", x: plaza.x, z: plaza.z, rotationY: 0, room: "floor" },- { id: "lobby-plant-a", kind: "plant", x: rx0 + 0.6, z: southMinZ + 0.8, rotationY: 0, room: "reception" },- { id: "lobby-plant-b", kind: "plant", x: receptionRoom.maxX - 0.8, z: bottomZ - 0.7, rotationY: 0, room: "reception" },- // Break room lounge: an L-shaped sectional — module A along the south facing- // north, module B along the west facing east, the corner module joining- // them — round an oak coffee table on a kilim; the bookcase wall and the- // coffee bar on the north wall; the reading nook in the north-west corner;- // foosball, beanbags, the water station and the arcade on its pixel mat in- // the east; monsteras in two corners.- { id: "break-rug", kind: "breakRug", x: bx0 + 3.4, z: bz0 + 4.9, rotationY: 0, room: "break", size: { w: 5.2, d: 4.2 } },- { id: "break-sofa-a", kind: "breakSofa", x: bx0 + 3.3, z: bz0 + 6.3, rotationY: Math.PI, room: "break" },- { id: "break-sofa-b", kind: "breakSofa", x: bx0 + 1.75, z: bz0 + 4.75, rotationY: Math.PI / 2, room: "break" },- { id: "break-sofa-corner", kind: "breakSofaCorner", x: bx0 + 1.75, z: bz0 + 6.3, rotationY: Math.PI, room: "break" },- { id: "break-table", kind: "breakTable", x: bx0 + 3.35, z: bz0 + 4.8, rotationY: 0, room: "break" },- { id: "coffee-bar", kind: "coffeeBar", x: bx0 + 7.9, z: bz0 + 0.5, rotationY: 0, room: "break" },- { id: "water-cooler", kind: "waterCooler", x: breakRoom.maxX - 0.45, z: bz0 + 2.6, rotationY: -Math.PI / 2, room: "break" },- { id: "arcade", kind: "arcade", x: breakRoom.maxX - 0.6, z: bottomZ - 0.7, rotationY: -Math.PI / 2, room: "break" },- { id: "arcade-mat", kind: "arcadeMat", x: breakRoom.maxX - 1.5, z: bottomZ - 0.7, rotationY: 0, room: "break", size: { w: 1.1, d: 1.2 } },- { id: "foosball", kind: "foosball", x: bx0 + 8.1, z: bz0 + 4.1, rotationY: 0, room: "break" },- { id: "beanbag-a", kind: "beanbag", x: bx0 + 6.6, z: bz0 + 6.1, rotationY: 0, room: "break" },- { id: "beanbag-b", kind: "beanbag", x: bx0 + 7.8, z: bz0 + 6.75, rotationY: 0, room: "break" },- { id: "break-shelf", kind: "breakBookcase", x: bx0 + 2.4, z: bz0 + 0.06 + FURNITURE_SIZE.breakBookcase.d / 2, rotationY: 0, room: "break" },- { id: "break-nook", kind: "readingNook", x: bx0 + 0.53, z: bz0 + 0.58, rotationY: 0, room: "break" },- { id: "break-plant", kind: "breakPlant", x: bx0 + 0.6, z: bottomZ - 0.6, rotationY: 0, room: "break" },- { id: "break-plant-e", kind: "breakPlant", x: breakRoom.maxX - 0.45, z: bz0 + 5.9, rotationY: 0, room: "break" },- ];- for (const dept of departments) {- furniture.push({ id: `${dept.id}-plant-w`, kind: "plant", x: dept.minX + 0.45, z: dept.maxZ - 0.45, rotationY: 0, room: "floor" });- furniture.push({ id: `${dept.id}-plant-e`, kind: "plant", x: dept.maxX - 0.45, z: dept.maxZ - 0.45, rotationY: 0, room: "floor" });- }-- const table = furniture.find((f) => f.id === "team-table")!;- const spots: Spot[] = [- // Couch seats: sofa module A faces north (rotated π), module B faces east;- // the reading nook's armchair faces south, into the room.- { id: "couch-a1", kind: "couch", pose: "sit", x: bx0 + 2.7, z: bz0 + 6.15, facing: Math.PI, room: "break" },- { id: "couch-a2", kind: "couch", pose: "sit", x: bx0 + 3.7, z: bz0 + 6.15, facing: Math.PI, room: "break" },- { id: "couch-b1", kind: "couch", pose: "sit", x: bx0 + 1.9, z: bz0 + 4.3, facing: Math.PI / 2, room: "break" },- { id: "couch-b2", kind: "couch", pose: "sleep", x: bx0 + 1.9, z: bz0 + 5.35, facing: Math.PI / 2, room: "break" },- { id: "couch-nook", kind: "couch", pose: "sit", x: bx0 + 0.61, z: bz0 + 0.72, facing: 0, room: "break" },- { id: "coffee-1", kind: "coffee", pose: "stand", x: bx0 + 7.3, z: bz0 + 1.4, facing: Math.PI, room: "break" },- { id: "coffee-2", kind: "coffee", pose: "stand", x: bx0 + 8.5, z: bz0 + 1.4, facing: Math.PI, room: "break" },- { id: "cooler", kind: "cooler", pose: "stand", x: breakRoom.maxX - 1.2, z: bz0 + 2.6, facing: Math.PI / 2, room: "break" },- { id: "arcade", kind: "arcade", pose: "stand", x: breakRoom.maxX - 1.45, z: bottomZ - 0.7, facing: Math.PI / 2, room: "break" },- { id: "beanbag-a", kind: "beanbag", pose: "sit", x: bx0 + 6.6, z: bz0 + 6.1, facing: Math.PI * 1.25, room: "break" },- { id: "beanbag-b", kind: "beanbag", pose: "sit", x: bx0 + 7.8, z: bz0 + 6.75, facing: Math.PI * 1.25, room: "break" },- { id: "shelf-break", kind: "shelf", pose: "stand", x: bx0 + 2.2, z: bz0 + 1.1, facing: Math.PI, room: "break" },- // Mission Control: the sofa facing east, the open shelf on the east wall.- { id: "couch-command-1", kind: "couch", pose: "sit", x: lx0 + 0.75, z: lz0 + 4.55, facing: Math.PI / 2, room: "command" },- { id: "couch-command-2", kind: "couch", pose: "sit", x: lx0 + 0.75, z: lz0 + 5.65, facing: Math.PI / 2, room: "command" },- { id: "shelf-command", kind: "shelf", pose: "stand", x: leadRoom.maxX - 1.1, z: lz0 + 4.7, facing: Math.PI / 2, room: "command" },- // Server room: in the cold aisle, each looking at a rack row's glass fronts.- { id: "console-e", kind: "board", pose: "stand", x: serverAisleMaxX - 0.55, z: serverRowZ, facing: Math.PI / 2, room: "server" },- { id: "console-w", kind: "board", pose: "stand", x: serverAisleMinX + 0.55, z: serverRowZ, facing: -Math.PI / 2, room: "server" },- { id: "board", kind: "board", pose: "stand", x: tcx - 0.6, z: topZ + 1.2, facing: Math.PI, room: "team" },- ];- // Meeting chairs: three per long side of the team table.- for (let i = 0; i < 3; i += 1) {- const x = table.x - 1.1 + i * 1.1;- spots.push({ id: `meeting-n${i}`, kind: "meeting", pose: "sit", x, z: table.z - 1.25, facing: 0, room: "team" });- spots.push({ id: `meeting-s${i}`, kind: "meeting", pose: "sit", x, z: table.z + 1.25, facing: Math.PI, room: "team" });- }- // Window spots along the east and west railing, looking out at the stars.- for (const dept of departments) {- const side = dept.minX <= minX + 0.01 ? "west" : dept.maxX >= maxX - 0.01 ? "east" : null;- if (!side) continue;- const zc = (dept.minZ + dept.maxZ) / 2;- spots.push({- id: `window-${dept.id}`, kind: "window", pose: "stand", room: "floor",- x: side === "west" ? minX - EDGE + 0.9 : maxX + EDGE - 0.9, z: zc, facing: side === "west" ? -Math.PI / 2 : Math.PI / 2,- });- }-- const elevator = furniture.find((f) => f.id === "elevator")!;- // The spawn point's ring surrounds the terminal; "walk there" and newcomers stand south of it, facing the screen.- const arrival: Point = { x: plaza.x, z: plaza.z + SPAWN.approach };- const spawnStop: Checkpoint = { id: "launch", room: "floor", x: plaza.x, z: plaza.z, radius: SPAWN.reach, approach: arrival };- // The elevator's doors face east into the lobby; its checkpoint is the floor in front of them.- const elevatorStop: Checkpoint = { id: "elevator", room: "reception", x: elevator.x + 0.95, z: elevator.z, radius: 1.0 };- const breakStop: Checkpoint = { id: "break", room: "break", x: bx0 + 5.6, z: bz0 + 2.6, radius: 1.8 };- // Mission Control's stop is a ring round the desk, usable from every side; "walk there" ends in front of the desk.- const missionStop: Checkpoint = { id: "mission", room: "command", x: commandDeskAt.x, z: commandDeskAt.z - 0.3, radius: COMMAND_REACH,- approach: { x: commandDeskAt.x, z: commandDeskAt.z + COMMAND_DESK.d / 2 + 0.55 } };- const checkpoints: Checkpoint[] = [spawnStop, missionStop, elevatorStop, breakStop];-- const walls = rooms.flatMap(wallsOf);- const desks = departments.flatMap((d) => d.desks);- const obstacles: Rect[] = [- ...walls.map(wallRect),- ...desks.map(deskRect),- // Bench desk chairs and the meeting chairs: nobody walks through a chair.- ...desks.map((d) => chairRect(seatOf(d))),- ...spots.filter((s) => s.kind === "meeting").map((s) => chairRect(s)),- // Department sign walls along each department's north edge.- ...departments.map((d) => ({ minX: d.minX + 0.2, maxX: d.maxX - 0.2, minZ: d.minZ + 0.02, maxZ: d.minZ + 0.2 })),- ...furniture.filter((f) => FURNITURE_SIZE[f.kind].solid).map(footprint),- ...commandDeskObstacles(commandDeskAt),- // Walnut planter boxes at the bench ends.- ...departments.flatMap(benchPlanters).map((p) => p.rect),- // The tree planters, bookcases and troughs along the windows.- ...codingAmbience({ departments, rooms }).map(({ minX, maxX, minZ, maxZ }) => ({ minX, maxX, minZ, maxZ })),- // The posts of an open room's name arch are solid too; nobody walks through them.- ...rooms.filter((r) => !r.walled).flatMap(archPosts).map((p) => ({- minX: p.x - ARCH.post / 2, maxX: p.x + ARCH.post / 2, minZ: p.z - ARCH.post / 2, maxZ: p.z + ARCH.post / 2,- })),- ];-- return {- variant: "coding", departments, lead, rooms, walls, furniture, spots, checkpoints, obstacles,- // Its chair faces south, towards the door: seatOf() puts the person north of the desk.- command: { id: "command", x: commandDeskAt.x, z: commandDeskAt.z, facing: "south", agentId: null, size: { w: COMMAND_DESK.w, d: COMMAND_DESK.d } },- spawn: { x: rx0 + 1.4, z: bottomZ - 2.6 },- arrival,- floor: {- minX: minX - EDGE + RAIL_CLEARANCE, maxX: maxX + EDGE - RAIL_CLEARANCE,- minZ: topZ - EDGE + RAIL_CLEARANCE, maxZ: bottomZ + EDGE - RAIL_CLEARANCE,- },- bounds: { minX: minX - EDGE, maxX: maxX + EDGE, minZ: topZ - EDGE, maxZ: bottomZ + EDGE },- };-}--/** How many of the roster's agents have a desk on this floor plan. */-export function seatedCount(layout: OfficeLayout): number {- return allDesks(layout).filter((desk) => desk.agentId !== null).length;-}--/** Every desk on the floor, lead office first. */-export function allDesks(layout: OfficeLayout): DeskSlot[] {- return [...layout.lead.desks, ...layout.departments.flatMap((d) => d.desks)];-}--export function roomAt(layout: OfficeLayout, p: Point): Room | null {- return layout.rooms.find((r) => p.x >= r.minX && p.x <= r.maxX && p.z >= r.minZ && p.z <= r.maxZ) ?? null;-}--export interface StatusCounts { working: number; idle: number; waiting: number; paused: number }--export function countStates(agents: readonly Pick<OfficeAgentInput, "state">[]): StatusCounts {- const counts: StatusCounts = { working: 0, idle: 0, waiting: 0, paused: 0 };- for (const agent of agents) counts[agent.state] += 1;- return counts;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeMinimap.css b/dodaios/ui/web/frontend/src/components/society/office/officeMinimap.cssdeleted file mode 100644index b1652f855e..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeMinimap.css+++ /dev/null@@ -1,43 +0,0 @@-/* Office minimap, compass bar and full map. The painted map art keeps one- palette in both modes; every piece of chrome here reads theme tokens. */--/* Minimap: square card in the top-right corner, a thin light frame and a soft shadow. */-.office-minimap { right:14px; top:14px; display:flex; flex-direction:column; gap:4px; user-select:none; }-.office-minimap-map { position:relative; overflow:hidden; border-radius:14px; border:2px solid hsl(var(--popover) / .92); background:#121833; box-shadow:0 0 0 1px hsl(var(--border)), 0 6px 22px rgb(0 0 0 / .35); }-/* Inner shadow / vignette over the picture, like a game minimap's lens. */-.office-minimap-map::after { content:""; position:absolute; inset:0; border-radius:12px; pointer-events:none; box-shadow:inset 0 0 18px 4px rgb(0 0 0 / .38), inset 0 0 0 1px rgb(255 255 255 / .12); }-.office-minimap-canvas { display:block; cursor:crosshair; touch-action:manipulation; }-.office-minimap-north { position:absolute; z-index:1; top:3px; left:50%; transform:translateX(-50%); min-width:16px; padding:0 4px; border-radius:999px; background:hsl(var(--popover) / .92); color:hsl(var(--popover-foreground)); font-size:10px; font-weight:800; line-height:15px; text-align:center; pointer-events:none; box-shadow:0 1px 4px rgb(0 0 0 / .3); }-.office-minimap-tooltip { position:absolute; z-index:2; transform:translateY(-100%); padding:2px 7px; border-radius:6px; border:1px solid hsl(var(--border)); background:hsl(var(--popover)); color:hsl(var(--popover-foreground)); font-size:11px; font-weight:600; white-space:nowrap; max-width:160px; overflow:hidden; text-overflow:ellipsis; pointer-events:none; box-shadow:0 2px 8px rgb(0 0 0 / .2); }-.office-minimap-tooltip[data-side="left"] { transform:translate(-100%, -100%); }-.office-minimap-bar { display:flex; align-items:center; gap:4px; padding:2px; border:1px solid hsl(var(--border)); border-radius:10px; background:hsl(var(--popover) / .92); color:hsl(var(--popover-foreground)); backdrop-filter:blur(6px); box-shadow:0 2px 10px rgb(0 0 0 / .2); }-.office-minimap-btn { display:inline-flex; align-items:center; justify-content:center; gap:4px; height:22px; min-width:22px; padding:0 5px; border:0; border-radius:7px; background:none; color:hsl(var(--popover-foreground)); font-size:11px; font-weight:600; cursor:pointer; }-.office-minimap-btn:hover:not(:disabled) { background:hsl(var(--secondary)); }-.office-minimap-btn:disabled { opacity:.4; cursor:default; }-.office-minimap-btn:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:1px; }-.office-minimap-zoom { min-width:34px; text-align:center; font-size:10px; font-variant-numeric:tabular-nums; color:hsl(var(--muted-foreground)); }-.office-minimap-open { margin-left:auto; padding:0 8px; border:1px solid hsl(var(--border)); }--/* Compass bar: top centre, clear of the window caption above the stage and the side HUD. */-.office-compass { left:50%; top:8px; transform:translateX(-50%); width:min(440px, calc(100% - 720px)); height:34px; border:1px solid hsl(var(--border)); border-radius:10px; background:hsl(var(--popover) / .88); box-shadow:0 4px 16px rgb(0 0 0 / .25); backdrop-filter:blur(6px); pointer-events:none; }-.office-compass-canvas { display:block; width:100%; height:100%; -webkit-mask-image:linear-gradient(90deg, transparent, #000 14%, #000 86%, transparent); mask-image:linear-gradient(90deg, transparent, #000 14%, #000 86%, transparent); }-.office-compass-readout { position:absolute; top:100%; left:50%; transform:translate(-50%, 3px); padding:0 6px; border-radius:6px; border:1px solid hsl(var(--border)); background:hsl(var(--popover) / .92); color:hsl(var(--popover-foreground)); font-size:10px; font-weight:700; line-height:16px; font-variant-numeric:tabular-nums; }-.office-compass-readout:empty { display:none; }--/* Full map: a dialog over most of the stage. */-.office-fullmap-backdrop { position:absolute; inset:0; z-index:60; display:flex; align-items:center; justify-content:center; padding:3%; background:hsl(var(--background) / .55); backdrop-filter:blur(3px); }-.office-fullmap { display:flex; flex-direction:column; width:100%; height:100%; max-width:1200px; min-height:0; overflow:hidden; }-.office-fullmap:focus { outline:none; }-.office-fullmap-head { display:flex; align-items:center; gap:12px; padding:8px 10px 8px 14px; border-bottom:1px solid hsl(var(--border)); }-.office-fullmap-heading { display:flex; flex-direction:column; min-width:0; }-.office-fullmap-heading h2 { margin:0; font-size:14px; font-weight:700; }-.office-fullmap-heading span { font-size:11px; color:hsl(var(--muted-foreground)); }-.office-fullmap-readout { margin-left:auto; font-size:12px; font-weight:600; font-variant-numeric:tabular-nums; color:hsl(var(--muted-foreground)); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }-.office-fullmap-close { display:inline-flex; align-items:center; justify-content:center; width:28px; height:28px; }-.office-fullmap-body { position:relative; flex:1; min-height:0; overflow:hidden; background:hsl(var(--muted)); }-.office-fullmap-canvas { display:block; cursor:crosshair; }-.office-fullmap-axis { position:absolute; transform:translate(-50%, -50%); font-size:11px; font-weight:800; color:hsl(var(--foreground)); pointer-events:none; }--@media (max-width:960px) { .office-compass { display:none; } }-@media (max-height:520px), (max-width:600px) { .office-minimap { display:none; } }-@media (prefers-reduced-motion:reduce) { .office-fullmap-backdrop { backdrop-filter:none; } }diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeMotion.test.ts b/dodaios/ui/web/frontend/src/components/society/office/officeMotion.test.tsdeleted file mode 100644index 85ea69dcc1..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeMotion.test.ts+++ /dev/null@@ -1,274 +0,0 @@-import { describe, expect, it } from "vitest";-import {- BODY_SPACING, BRISK_SPEED, STUCK, WALK_SPEED, applySeparation, clearOfBodies, clickPaceFor, hurryPaceFor, newStuckWatch, paceFor, segmentWalkable, separation, stepClearOfBodies, stepMover,- stepMoverAvoiding, stepWalker, turnToward, watchProgress, type Mover, wrapAngle,-} from "./officeMotion";--describe("office motion", () => {- it("turns the short way and clamps the step", () => {- expect(turnToward(0, 1, 0.5)).toBeCloseTo(0.5);- expect(turnToward(0, 1, 2)).toBeCloseTo(1);- // From just below +π to just above -π is a tiny step across the seam.- expect(turnToward(3.1, -3.1, 0.2)).toBeCloseTo(wrapAngle(-3.1));- expect(turnToward(3.0, -3.0, 0.1)).toBeCloseTo(3.1);- });-- it("walks a path to its end at the given speed and faces the travel direction", () => {- const m: Mover = { x: 0, z: 0, heading: 0, path: [{ x: 2, z: 0 }, { x: 2, z: 3 }] };- let total = 0;- let arrived = false;- let ticks = 0;- let headingOnFirstLeg = NaN;- while (!arrived && ticks < 1000) {- const res = stepMover(m, WALK_SPEED, 1 / 60);- total += res.moved;- arrived = res.arrived;- ticks += 1;- if (m.x > 1 && m.x < 1.9 && m.z === 0) headingOnFirstLeg = m.heading;- }- expect(arrived).toBe(true);- expect(m.x).toBeCloseTo(2);- expect(m.z).toBeCloseTo(3);- expect(total).toBeCloseTo(5);- expect(ticks).toBeCloseTo(Math.ceil(5 / WALK_SPEED * 60), -1);- // East = +x = heading π/2; south = +z = heading 0.- expect(headingOnFirstLeg).toBeCloseTo(Math.PI / 2);- expect(m.heading).toBeCloseTo(0);- expect(m.path).toHaveLength(0);- });-- it("does nothing without a path", () => {- const m: Mover = { x: 1, z: 1, heading: 0.3, path: [] };- expect(stepMover(m, WALK_SPEED, 0.1)).toEqual({ moved: 0, arrived: true });- expect(m).toEqual({ x: 1, z: 1, heading: 0.3, path: [] });- });-- it("consumes several waypoints in one large step", () => {- const m: Mover = { x: 0, z: 0, heading: 0, path: [{ x: 0, z: 1 }, { x: 0, z: 2 }, { x: 0, z: 3 }] };- const res = stepMover(m, 1, 2.5);- expect(res.moved).toBeCloseTo(2.5);- expect(res.arrived).toBe(false);- expect(m.path).toHaveLength(1);- expect(m.z).toBeCloseTo(2.5);- });-});--describe("separation", () => {- it("is zero when nobody is near and pushes away from a close body", () => {- expect(separation({ x: 0, z: 0 }, 0, [{ x: 5, z: 5 }])).toEqual({ x: 0, z: 0 });- const push = separation({ x: 0, z: 0 }, Math.PI / 2, [{ x: 0.3, z: 0 }]);- expect(push.x).toBeLessThan(0);- });- it("adds a sidestep when someone stands straight ahead", () => {- // Walking towards +z, someone 0.5 m ahead: the push has a sideways component.- const push = separation({ x: 0, z: 0 }, 0, [{ x: 0, z: 0.5 }]);- expect(Math.abs(push.x)).toBeGreaterThan(0.1);- });- it("only nudges onto walkable ground and reports spacing", () => {- const m = { x: 0, z: 0, heading: 0, path: [] };- applySeparation(m, { x: 1, z: 0 }, 0.1, () => false);- expect(m.x).toBe(0);- applySeparation(m, { x: 1, z: 0 }, 0.1, () => true);- expect(m.x).toBeGreaterThan(0);- expect(clearOfBodies({ x: 0, z: 0 }, [{ x: BODY_SPACING / 2, z: 0 }])).toBe(false);- expect(clearOfBodies({ x: 0, z: 0 }, [{ x: BODY_SPACING * 2, z: 0 }])).toBe(true);- });- it("lets a figure pinned against someone step away even when others stand far off in that direction", () => {- // Touching a colleague to the west; the rest of the office lies south-east, beyond the step.- const from = { x: 0, z: 0 };- const others = [{ x: -0.4, z: 0 }, { x: 5, z: 5 }, { x: 8, z: -2 }];- expect(stepClearOfBodies({ x: 0.03, z: 0 }, from, others)).toBe(true);- expect(stepClearOfBodies({ x: 0, z: 0.03 }, from, others)).toBe(true);- // Never deeper into the one already touched, never into someone new.- expect(stepClearOfBodies({ x: -0.03, z: 0 }, from, others)).toBe(false);- expect(stepClearOfBodies({ x: 0.03, z: 0 }, from, [{ x: 0.5, z: 0 }])).toBe(false);- });- it("keeps two walkers crossing head-on apart", () => {- const a = { x: 0, z: -3, heading: 0, path: [{ x: 0, z: 3 }] };- const b = { x: 0.02, z: 3, heading: Math.PI, path: [{ x: 0.02, z: -3 }] };- let closest = Infinity;- for (let i = 0; i < 600; i += 1) {- stepMoverAvoiding(a, 1.35, 1 / 60, [b], () => true);- stepMoverAvoiding(b, 1.35, 1 / 60, [a], () => true);- closest = Math.min(closest, Math.hypot(a.x - b.x, a.z - b.z));- }- expect(closest).toBeGreaterThan(0.45);- // Both still reach their goals.- expect(a.path).toHaveLength(0);- expect(b.path).toHaveLength(0);- });-});--const open = () => true;-const DT = 1 / 60;--describe("stepWalker", () => {- it("lands exactly on the last waypoint and faces the way it walked", () => {- for (const dt of [1 / 144, 1 / 60, 1 / 30, 0.1]) {- const m: Mover = { x: 0, z: 0, heading: Math.PI / 2, path: [{ x: 3, z: 0 }, { x: 3, z: 2.37 }] };- let ticks = 0;- while (!stepWalker(m, WALK_SPEED, dt, [], open).arrived && ticks < 5000) ticks += 1;- expect([m.x, m.z], `dt ${dt}`).toEqual([3, 2.37]);- expect(m.heading, `dt ${dt}`).toBeCloseTo(0);- }- });-- it("turns before it walks instead of gliding sideways round a corner", () => {- // Facing east, the route goes west: a U-turn.- const m: Mover = { x: 0, z: 0, heading: Math.PI / 2, path: [{ x: -5, z: 0 }] };- let sideways = 0;- for (let i = 0; i < 120; i += 1) {- const before = m.x;- const { moved } = stepWalker(m, WALK_SPEED, DT, [], open);- // Moving west while still facing away from west by more than 60°.- if (Math.abs(wrapAngle(-Math.PI / 2 - m.heading)) > 1.05) sideways += Math.abs(m.x - before);- expect(moved).toBeLessThanOrEqual(WALK_SPEED * DT + 1e-9);- }- expect(sideways).toBeLessThan(0.03);- expect(m.heading).toBeCloseTo(-Math.PI / 2);- expect(m.x).toBeLessThan(-2);- });-- it("never steps onto blocked ground: it slides along a wall it is pushed against, or waits", () => {- // A wall along z < 0; someone beside the walker pushes it towards the wall.- const floor = (p: { x: number; z: number }) => p.z >= 0;- const m: Mover = { x: 0, z: 0.05, heading: Math.PI / 2, path: [{ x: 6, z: 0.05 }] };- const pusher = { x: 1.2, z: 0.75 };- for (let i = 0; i < 400 && m.path.length > 0; i += 1) {- stepWalker(m, WALK_SPEED, DT, [pusher], floor);- expect(m.z).toBeGreaterThanOrEqual(0);- expect(Math.hypot(m.x - pusher.x, m.z - pusher.z)).toBeGreaterThan(BODY_SPACING - 0.02);- }- expect([m.x, m.z]).toEqual([6, 0.05]);- });-- it("never steps into anybody: with no way round it waits and says so", () => {- // A corridor one body wide, someone standing in it.- const corridor = (p: { x: number; z: number }) => Math.abs(p.z) <= 0.3;- const m: Mover = { x: 0, z: 0, heading: Math.PI / 2, path: [{ x: 6, z: 0 }] };- const body = { x: 3, z: 0 };- let blocked = false;- for (let i = 0; i < 600; i += 1) {- const step = stepWalker(m, WALK_SPEED, DT, [body], corridor);- blocked = step.blocked;- expect(Math.hypot(m.x - body.x, m.z - body.z)).toBeGreaterThan(BODY_SPACING - 0.01);- }- expect(blocked).toBe(true);- expect(m.x).toBeLessThan(3);- expect(m.path).toHaveLength(1);- });-- it("walks out of a seat and onto one although both lie inside a footprint", () => {- // The chair's footprint covers x in [-0.5, 0.5]; a neighbour sits within arm's reach of the target seat.- const floor = (p: { x: number; z: number }) => Math.abs(p.x) > 0.5 && Math.abs(p.x - 6) > 0.5;- const m: Mover = { x: 0, z: 0, heading: 0, path: [{ x: 0.7, z: 0 }, { x: 5.3, z: 0 }, { x: 6, z: 0 }] };- let ticks = 0;- while (!stepWalker(m, WALK_SPEED, DT, [{ x: 6, z: 0.55 }], floor).arrived && ticks < 2000) ticks += 1;- expect([m.x, m.z]).toEqual([6, 0]);- });-- it("reports when steering carried it off its route", () => {- // The straight line to the waypoint crosses a pillar the route went round.- const pillar = (p: { x: number; z: number }) => !(p.x > 0.9 && p.x < 2 && Math.abs(p.z) < 0.3);- const m: Mover = { x: 0.9, z: 0, heading: Math.PI / 2, path: [{ x: 3, z: 0 }] };- const step = stepWalker(m, WALK_SPEED, DT, [], pillar);- expect(step.offPath).toBe(true);- expect(pillar(m)).toBe(true);- });-- it("goes for the next waypoint once it is in plain view, never back to one it was pushed past", () => {- const m: Mover = { x: 1.8, z: 0.4, heading: Math.PI / 2, path: [{ x: 2, z: 0 }, { x: 6, z: 0 }] };- stepWalker(m, WALK_SPEED, DT, [{ x: 1.4, z: -0.3 }], open);- expect(m.path).toEqual([{ x: 6, z: 0 }]);- });-});--describe("segmentWalkable", () => {- it("samples the first stretch of a line", () => {- const wall = (p: { x: number; z: number }) => p.x < 1 || p.x > 1.2;- expect(segmentWalkable({ x: 0, z: 0 }, { x: 0.9, z: 0 }, wall)).toBe(true);- expect(segmentWalkable({ x: 0, z: 0 }, { x: 3, z: 0 }, wall)).toBe(false);- // Only the first metres count: a wall far down the line is the route's business.- expect(segmentWalkable({ x: -5, z: 0 }, { x: 3, z: 0 }, wall)).toBe(true);- });-});--describe("paceFor", () => {- it("strolls on short legs and walks briskly across the campus", () => {- expect(paceFor(0)).toBe(WALK_SPEED);- expect(paceFor(8)).toBe(WALK_SPEED);- expect(paceFor(60)).toBe(BRISK_SPEED);- expect(paceFor(17)).toBeGreaterThan(WALK_SPEED);- expect(paceFor(17)).toBeLessThan(BRISK_SPEED);- expect(paceFor(20)).toBeGreaterThan(paceFor(15));- });-});--describe("hurryPaceFor", () => {- it("is brisk on anything but the last steps, and never slower than the ordinary pace", () => {- expect(hurryPaceFor(1)).toBe(WALK_SPEED);- expect(hurryPaceFor(8)).toBe(BRISK_SPEED);- expect(hurryPaceFor(40)).toBe(BRISK_SPEED);- for (let m = 0; m < 40; m += 1) expect(hurryPaceFor(m)).toBeGreaterThanOrEqual(paceFor(m));- });-});--describe("clickPaceFor", () => {- it("jogs a long click-to-move route and settles to a walk before it arrives", () => {- expect(clickPaceFor(60, 2, 4.4)).toBe(4.4);- expect(clickPaceFor(22, 2, 4.4)).toBe(4.4);- expect(clickPaceFor(7, 2, 4.4)).toBe(2);- expect(clickPaceFor(0, 2, 4.4)).toBe(2);- expect(clickPaceFor(14, 2, 4.4)).toBeGreaterThan(2);- expect(clickPaceFor(14, 2, 4.4)).toBeLessThan(4.4);- // Never a jump in pace: the change is spread over the metres in between.- for (let m = 0; m < 30; m += 0.5) expect(Math.abs(clickPaceFor(m + 0.5, 2, 4.4) - clickPaceFor(m, 2, 4.4))).toBeLessThan(0.1);- });-- it("crosses a campus in well under half the time a plain walk takes", () => {- const time = (pace: (left: number) => number) => {- const m: Mover = { x: 0, z: 0, heading: Math.PI / 2, path: [{ x: 70, z: 0 }] };- let seconds = 0;- while (seconds < 120 && !stepWalker(m, pace(70 - m.x), DT, [], open).arrived) seconds += DT;- return seconds;- };- const walked = time(() => 2);- const clicked = time((left) => clickPaceFor(left, 2, 4.4));- expect(walked).toBeCloseTo(35, 0);- expect(clicked).toBeLessThan(20);- expect(clicked).toBeGreaterThan(70 / 4.4);- });-});--describe("the stuck watch", () => {- it("stays quiet while a figure makes progress, however slowly it queues", () => {- const watch = newStuckWatch({ x: 0, z: 0 });- let x = 0;- for (let i = 0; i < 60 * 30; i += 1) {- x += 0.34 * DT;- expect(watchProgress(watch, { x, z: 0 }, DT)).toBe("ok");- }- });-- it("asks for a re-plan after 1.5 s without progress, twice, then for a rescue", () => {- const watch = newStuckWatch({ x: 0, z: 0 });- const verdicts: string[] = [];- for (let i = 0; i < 60 * 6.2; i += 1) {- // Shuffling on the spot is not progress.- const verdict = watchProgress(watch, { x: Math.sin(i / 5) * 0.15, z: 0 }, DT);- if (verdict !== "ok") verdicts.push(`${verdict}@${((i + 1) * DT).toFixed(1)}`);- }- // (Sixty frames of 1/60 s fall a hair short of a second, so each verdict comes a frame late.)- expect(verdicts).toEqual(["[email protected]", "[email protected]", "[email protected]", "[email protected]"]);- expect(STUCK.maxReplans).toBe(2);- });-- it("starts over with every unit of progress", () => {- const watch = newStuckWatch({ x: 0, z: 0 });- for (let i = 0; i < 80; i += 1) watchProgress(watch, { x: 0, z: 0 }, DT);- expect(watchProgress(watch, { x: 0, z: 0 }, 1)).toBe("replan");- expect(watch.replans).toBe(1);- expect(watchProgress(watch, { x: STUCK.progressM, z: 0 }, DT)).toBe("ok");- expect(watch).toMatchObject({ idleS: 0, replans: 0, x: STUCK.progressM });- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeMotion.ts b/dodaios/ui/web/frontend/src/components/society/office/officeMotion.tsdeleted file mode 100644index 094e08e0c1..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeMotion.ts+++ /dev/null@@ -1,344 +0,0 @@-/**- * Walking a figure along a waypoint path at a fixed speed, turning smoothly- * towards the direction of travel. Pure: callers own the Mover and the clock.- */-import type { Point } from "./officeLayout";--/** Metres per second. */-export const WALK_SPEED = 1.35;-export const RUN_SPEED = 3.2;-/** Maximum turn rate in radians per second. */-export const TURN_RATE = 10;--export interface Mover {- x: number;- z: number;- /** Rotation about +y; 0 = the figure faces +z. */- heading: number;- /** Remaining waypoints; the first one is the next target. */- path: Point[];-}--const TAU = Math.PI * 2;--/** Wrap an angle into (-π, π]. */-export function wrapAngle(angle: number): number {- let a = angle % TAU;- if (a <= -Math.PI) a += TAU;- else if (a > Math.PI) a -= TAU;- return a;-}--/** Turn `current` towards `target` along the shorter way by at most `maxStep` radians. */-export function turnToward(current: number, target: number, maxStep: number): number {- const diff = wrapAngle(target - current);- if (Math.abs(diff) <= maxStep) return wrapAngle(target);- return wrapAngle(current + Math.sign(diff) * maxStep);-}--/**- * Advance the mover by speed × dt metres along its path, consuming reached- * waypoints. Mutates `m`. `arrived` is true once the path is empty.- */-export function stepMover(m: Mover, speed: number, dt: number): { moved: number; arrived: boolean } {- let budget = Math.max(0, speed * dt);- let moved = 0;- let dirX = 0, dirZ = 0;- while (m.path.length > 0 && budget > 0) {- const next = m.path[0];- const dx = next.x - m.x, dz = next.z - m.z;- const dist = Math.hypot(dx, dz);- if (dist <= budget) {- m.x = next.x; m.z = next.z;- budget -= dist; moved += dist;- m.path.shift();- } else {- m.x += (dx / dist) * budget; m.z += (dz / dist) * budget;- moved += budget; budget = 0;- }- if (dist > 1e-9) { dirX = dx; dirZ = dz; }- }- // Drop waypoints that coincide with the current position.- while (m.path.length > 0 && Math.hypot(m.path[0].x - m.x, m.path[0].z - m.z) < 1e-9) m.path.shift();- if (dirX !== 0 || dirZ !== 0) m.heading = turnToward(m.heading, Math.atan2(dirX, dirZ), TURN_RATE * dt);- return { moved, arrived: m.path.length === 0 };-}--/** Two bodies never come closer than this (centre to centre), in metres. */-export const BODY_SPACING = 0.62;--/**- * Local avoidance: a sideways-biased push away from nearby bodies, strongest- * when they touch. Zero when nobody is within `radius`. Pure.- */-export function separation(self: Point, heading: number, others: Iterable<Point>, radius = BODY_SPACING * 1.4): Point {- let x = 0, z = 0;- const fx = Math.sin(heading), fz = Math.cos(heading);- for (const o of others) {- const dx = self.x - o.x, dz = self.z - o.z;- const d = Math.hypot(dx, dz);- if (d < 1e-6 || d >= radius) continue;- const w = (radius - d) / radius;- x += (dx / d) * w; z += (dz / d) * w;- // Someone straight ahead: add a sidestep to the right so two walkers pass instead of pushing head-on.- const ahead = -(dx * fx + dz * fz) / d;- if (ahead > 0.6) { x += fz * w * 0.8; z += -fx * w * 0.8; }- }- return { x, z };-}--/** True when a point keeps the spacing from every other body. */-export function clearOfBodies(p: Point, others: Iterable<Point>, spacing = BODY_SPACING): boolean {- for (const o of others) if (Math.hypot(p.x - o.x, p.z - o.z) < spacing) return false;- return true;-}--/**- * May a figure step from `from` to `next` among `others`? Yes when the step- * keeps the spacing from everyone, or when every body it would touch there is- * one it already touches and the step does not bring it closer. Only touching- * bodies count: a far-away figure must never veto the way out of a crowd,- * or someone pinned in a corner could not move at all.- */-export function stepClearOfBodies(next: Point, from: Point, others: Iterable<Point>, spacing = BODY_SPACING): boolean {- for (const o of others) {- const after = Math.hypot(next.x - o.x, next.z - o.z);- if (after >= spacing) continue;- if (after < Math.hypot(from.x - o.x, from.z - o.z)) return false;- }- return true;-}--/**- * Nudge a mover sideways out of others' way, only onto walkable ground.- * Called after `stepMover`; the path pulls it back on the next frames.- */-export function applySeparation(m: Mover, push: Point, dt: number, walkable: (p: Point) => boolean, maxSpeed = 0.9): void {- const len = Math.hypot(push.x, push.z);- if (len < 1e-6) return;- const step = Math.min(len, 1) * maxSpeed * dt;- const nx = m.x + (push.x / len) * step, nz = m.z + (push.z / len) * step;- if (walkable({ x: nx, z: nz })) { m.x = nx; m.z = nz; }-}--/**- * Walk the path while steering around other bodies: the heading blends the- * next waypoint with a push away from anyone close, and the walker slows when- * someone stands right ahead. Falls back to plain path following whenever the- * steered step would leave walkable ground.- */-export function stepMoverAvoiding(m: Mover, speed: number, dt: number, others: readonly Point[], walkable: (p: Point) => boolean): { moved: number; arrived: boolean } {- if (m.path.length === 0) return { moved: 0, arrived: true };- const next = m.path[0];- const dx = next.x - m.x, dz = next.z - m.z;- const dist = Math.hypot(dx, dz);- const push = separation(m, m.heading, others, 1.2);- const pushLen = Math.hypot(push.x, push.z);- if (pushLen < 1e-3 || dist < 0.2) return stepMover(m, speed, dt);- let ax = dx / dist + push.x * 1.6, az = dz / dist + push.z * 1.6;- const len = Math.hypot(ax, az) || 1;- ax /= len; az /= len;- // Slow down while someone blocks the way ahead.- let slow = 1;- for (const o of others) {- const ox = o.x - m.x, oz = o.z - m.z;- const d = Math.hypot(ox, oz);- if (d < 0.95 && d > 1e-6 && (ox * dx + oz * dz) / (d * dist) > 0.7) slow = Math.min(slow, Math.max(0.25, (d - BODY_SPACING) / 0.4));- }- const step = Math.min(speed * slow * dt, dist);- const cand = { x: m.x + ax * step, z: m.z + az * step };- if (!walkable(cand)) return stepMover(m, speed, dt);- m.x = cand.x; m.z = cand.z;- if (Math.hypot(next.x - m.x, next.z - m.z) < 0.12) m.path.shift();- m.heading = turnToward(m.heading, Math.atan2(ax, az), TURN_RATE * dt);- return { moved: step, arrived: m.path.length === 0 };-}--/** An agent's pace on a long leg: a walk across the campus is brisk, a few steps in the studio are not. */-export const BRISK_SPEED = 2.1;-const BRISK_FROM_M = 9;-const BRISK_FULL_M = 26;--/** Walking speed for a route with `remaining` metres left: WALK_SPEED on short legs, up to BRISK_SPEED on long ones. */-export function paceFor(remaining: number): number {- const t = Math.min(1, Math.max(0, (remaining - BRISK_FROM_M) / (BRISK_FULL_M - BRISK_FROM_M)));- return WALK_SPEED + (BRISK_SPEED - WALK_SPEED) * t;-}--/** An agent on its way to its screen walks briskly from this much route on. */-const HURRY_FROM_M = 3;-const HURRY_FULL_M = 8;--/**- * The pace of an agent that has somewhere it must be (its screen, once it- * works): brisk on anything but the last steps. A working agent that strolls- * home from the far end of the campus is "working" and absent for too long.- */-export function hurryPaceFor(remaining: number): number {- const t = Math.min(1, Math.max(0, (remaining - HURRY_FROM_M) / (HURRY_FULL_M - HURRY_FROM_M)));- return Math.max(paceFor(remaining), WALK_SPEED + (BRISK_SPEED - WALK_SPEED) * t);-}--/** The person's click-to-move jogs while more than this much route is left, and has settled to a walk by the last metres. */-const CLICK_JOG_FULL_M = 22;-const CLICK_WALK_WITHIN_M = 7;--/**- * The pace of the person's character on a click-to-move route with- * `remaining` metres left: `walk` near the target, `run` on a long way, a- * smooth change in between. A long click crosses the campus at a jog; the- * last steps are a walk, so the character does not overshoot what it was- * sent to.- */-export function clickPaceFor(remaining: number, walk: number, run: number): number {- const t = Math.min(1, Math.max(0, (remaining - CLICK_WALK_WITHIN_M) / (CLICK_JOG_FULL_M - CLICK_WALK_WITHIN_M)));- return walk + (run - walk) * t;-}--/** Above this angle between where a figure faces and where it must go, it turns before it walks. */-const TURN_FIRST_RAD = 0.5;-/** The crawl left while turning on the spot, as a share of the pace: feet never glide sideways. */-const TURN_CRAWL = 0.08;-/** Avoidance fades out this close to the route's end, so a figure can reach a place beside a seated colleague. */-const AVOID_FADE_M = 1.5;-/** A waypoint a steered figure passed this closely counts as reached. */-const WAYPOINT_REACH_M = 0.14;--export interface WalkStep {- /** Metres actually covered this step. */- moved: number;- arrived: boolean;- /** Nothing was free: a body or a wall is in the way. */- blocked: boolean;- /** Steering carried the figure off its route: the straight line to the next waypoint leaves the floor. */- offPath: boolean;-}--/** True when the first `maxLen` metres of a→b lie on walkable ground (sampled every 0.1 m). */-export function segmentWalkable(a: Point, b: Point, walkable: (p: Point) => boolean, maxLen = 1.5): boolean {- const dx = b.x - a.x, dz = b.z - a.z;- const len = Math.hypot(dx, dz);- if (len < 1e-6) return true;- const reach = Math.min(len, maxLen);- for (let d = 0.1; d <= reach + 1e-9; d += 0.1) {- if (!walkable({ x: a.x + (dx / len) * d, z: a.z + (dz / len) * d })) return false;- }- return true;-}--/**- * One step of a figure along its path among other bodies. Unlike- * `stepMoverAvoiding` it never leaves walkable ground and never steps into- * anybody: every candidate step (steered, straight, then a slide to the right- * or left) is checked against the floor and the bodies, and when none is free- * the figure waits. It turns before it walks, faces where it actually moves,- * and lands exactly on the last waypoint.- *- * Two legs may cross blocked cells, as the route itself does: the first steps- * out of a seat, and the final step onto a seat inside a footprint. Both go- * straight along the route. Getting up, a figure still waits for whoever- * stands in its way; the seat it walks to is reserved, so bodies do not veto- * that last step.- */-export function stepWalker(m: Mover, speed: number, dt: number, others: readonly Point[], walkable: (p: Point) => boolean): WalkStep {- while (m.path.length > 0 && Math.hypot(m.path[0].x - m.x, m.path[0].z - m.z) < 1e-6) m.path.shift();- if (m.path.length === 0) return { moved: 0, arrived: true, blocked: false, offPath: false };- const next = m.path[0];- const final = m.path.length === 1;- const dx = next.x - m.x, dz = next.z - m.z;- const dist = Math.hypot(dx, dz);- const ux = dx / dist, uz = dz / dist;- const here = walkable(m);- const seatLeg = final && !walkable(next);- // On the floor a figure steers; inside a footprint (leaving or taking a seat) it follows the route.- const steering = here && !seatLeg;-- let sx = ux, sz = uz;- let slow = 1;- if (steering && others.length > 0) {- const end = m.path[m.path.length - 1];- const fade = Math.min(1, Math.max(0, (Math.hypot(end.x - m.x, end.z - m.z) - 0.3) / (AVOID_FADE_M - 0.3)));- const push = separation(m, m.heading, others, 1.2);- if (fade > 0 && Math.hypot(push.x, push.z) > 1e-3) {- const ax = ux + push.x * 1.6 * fade, az = uz + push.z * 1.6 * fade;- const len = Math.hypot(ax, az);- if (len > 1e-6) { sx = ax / len; sz = az / len; }- }- // Slow down while someone blocks the way ahead.- for (const o of others) {- const ox = o.x - m.x, oz = o.z - m.z;- const d = Math.hypot(ox, oz);- if (d < 0.95 && d > 1e-6 && (ox * ux + oz * uz) / d > 0.7) slow = Math.min(slow, Math.max(0.25, (d - BODY_SPACING) / 0.4));- }- }- const pace = Math.max(0, speed * slow * dt);- const free = (p: Point) => (seatLeg ? true : (steering ? walkable(p) : true) && stepClearOfBodies(p, m, others));- const at = (cx: number, cz: number, len: number): Point => ({ x: m.x + cx * len, z: m.z + cz * len });-- // The wanted direction first, then straight at the waypoint, then a slide past whatever is in the way (right before left).- const rx = uz, rz = -ux;- const candidates: [number, number][] = [[sx, sz]];- if (sx !== ux || sz !== uz) candidates.push([ux, uz]);- if (steering) {- candidates.push([(ux + rx) * Math.SQRT1_2, (uz + rz) * Math.SQRT1_2], [(ux - rx) * Math.SQRT1_2, (uz - rz) * Math.SQRT1_2], [rx, rz], [-rx, -rz]);- }- const offPath = steering && !walkable(at(ux, uz, Math.min(pace, dist)));- let chosen: [number, number] | null = null;- for (const c of candidates) {- const straight = c[0] === ux && c[1] === uz;- if (free(at(c[0], c[1], straight ? Math.min(pace, dist) : pace))) { chosen = c; break; }- }- if (!chosen || pace <= 0) {- m.heading = turnToward(m.heading, Math.atan2(sx, sz), TURN_RATE * dt);- return { moved: 0, arrived: false, blocked: pace > 0, offPath };- }- const [cx, cz] = chosen;- const straight = cx === ux && cz === uz;- const off = Math.abs(wrapAngle(Math.atan2(cx, cz) - m.heading));- m.heading = turnToward(m.heading, Math.atan2(cx, cz), TURN_RATE * dt);- const align = off < TURN_FIRST_RAD ? 1 : Math.max(TURN_CRAWL, Math.cos(off) / Math.cos(TURN_FIRST_RAD));- const step = straight ? Math.min(pace * align, dist) : pace * align;- const to = at(cx, cz, step);- if (step < pace && !free(to)) return { moved: 0, arrived: false, blocked: true, offPath };- if (straight && step >= dist - 1e-9) { m.x = next.x; m.z = next.z; m.path.shift(); }- else {- m.x = to.x; m.z = to.z;- if (!final && !straight) {- const left = Math.hypot(next.x - m.x, next.z - m.z);- // Pushed past a corner: head for the next waypoint as soon as it is in plain view, never back to this one.- // A figure on its route takes every corner exactly where the route has it.- if (left < WAYPOINT_REACH_M || (left < 0.6 && segmentWalkable(m, m.path[1], walkable))) m.path.shift();- }- }- return { moved: step, arrived: m.path.length === 0, blocked: false, offPath };-}--/** Progress that counts as one unit of walking, how long without it before a re-plan, and how many re-plans before a rescue. */-export const STUCK = { progressM: 0.4, replanS: 1.5, maxReplans: 2 } as const;--/** Watches one walk for a figure that stopped getting anywhere. */-export interface StuckWatch { x: number; z: number; idleS: number; replans: number }--export function newStuckWatch(at: Point): StuckWatch {- return { x: at.x, z: at.z, idleS: 0, replans: 0 };-}--export type StuckVerdict = "ok" | "replan" | "rescue";--/**- * Feed the watch one frame. Every 0.4 m of real progress is a unit of work- * and resets it; without progress for 1.5 s it asks for a re-plan, and after- * two re-plans that did not help for a rescue (a safe placement).- */-export function watchProgress(watch: StuckWatch, at: Point, dt: number): StuckVerdict {- if (Math.hypot(at.x - watch.x, at.z - watch.z) >= STUCK.progressM) {- watch.x = at.x; watch.z = at.z; watch.idleS = 0; watch.replans = 0;- return "ok";- }- watch.idleS += dt;- if (watch.idleS < STUCK.replanS) return "ok";- watch.idleS = 0;- if (watch.replans < STUCK.maxReplans) { watch.replans += 1; return "replan"; }- watch.replans = 0;- return "rescue";-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeNav.test.ts b/dodaios/ui/web/frontend/src/components/society/office/officeNav.test.tsdeleted file mode 100644index d0756097b7..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeNav.test.ts+++ /dev/null@@ -1,176 +0,0 @@-import { describe, expect, it } from "vitest";-import { allDesks, buildOfficeLayout, seatOf, standOf, type OfficeAgentInput, type OfficeLayout, type OfficeTeamInput, type Point } from "./officeLayout";-import { buildNavGrid, findPath, hasLineOfSight, isWalkable, nearestWalkable, randomWalkablePoint, type NavGrid } from "./officeNav";-import { createRng } from "./officeBehavior";--const PROVIDERS = ["Codex", "Claude Code", "Gemini", "OpenCode", "Kimi", "GLM", "Jarvis"];--function roster(count: number): OfficeAgentInput[] {- return Array.from({ length: count }, (_, i) => ({- agentId: `a${i}`, name: `a${i}`, tier: i === 0 ? "lead" : "specialist",- providerLabel: PROVIDERS[i % PROVIDERS.length], state: "idle", createdMs: i,- }));-}--/** `count` teams of `size` staff agents each (a0 is the lead), oldest first. */-function teamsOf(count: number, size: number): OfficeTeamInput[] {- return Array.from({ length: count }, (_, t) => ({- id: `team-${t}`, name: `Team ${t}`, createdMs: t, members: Array.from({ length: size }, (_, i) => `a${1 + t * size + i}`),- }));-}--function targetsOf(layout: OfficeLayout): { name: string; p: Point }[] {- return [- ...allDesks(layout).flatMap((d) => [{ name: `seat ${d.id}`, p: seatOf(d) }, { name: `stand ${d.id}`, p: standOf(d) }]),- ...layout.spots.map((s) => ({ name: `spot ${s.id}`, p: s })),- ...layout.checkpoints.map((c) => ({ name: `checkpoint ${c.id}`, p: c.approach ?? c })),- ];-}--/** Every sampled point of every segment is walkable, except the final snap onto a blocked target. */-function assertClearPath(grid: NavGrid, from: Point, to: Point, path: Point[], name: string): void {- const last = path[path.length - 1];- expect(last.x, name).toBeCloseTo(to.x, 9);- expect(last.z, name).toBeCloseTo(to.z, 9);- const segments = path.length - (isWalkable(grid, to) ? 0 : 1);- let prev = from;- for (let i = 0; i < segments; i += 1) {- const next = path[i];- expect(hasLineOfSight(grid, prev, next), `${name}: segment ${i}`).toBe(true);- const len = Math.hypot(next.x - prev.x, next.z - prev.z);- const steps = Math.max(1, Math.ceil(len / 0.03));- for (let k = 0; k <= steps; k += 1) {- const t = k / steps;- const p = { x: prev.x + (next.x - prev.x) * t, z: prev.z + (next.z - prev.z) * t };- if (!isWalkable(grid, p)) throw new Error(`${name}: segment ${i} crosses a blocked cell at ${p.x.toFixed(2)},${p.z.toFixed(2)}`);- }- prev = next;- }- if (!isWalkable(grid, to)) {- const approach = path[path.length - 2] ?? from;- expect(Math.hypot(approach.x - to.x, approach.z - to.z), `${name}: snap length`).toBeLessThanOrEqual(1.0 + 1e-9);- }-}--describe("office navigation", () => {- for (const variant of ["agents", "coding"] as const) {- for (const count of [0, 10, 40]) {- it(`reaches every seat, spot and checkpoint from the spawn and the elevator (${variant}, ${count} agents)`, () => {- const layout = buildOfficeLayout(roster(count), { variant });- const grid = buildNavGrid(layout);- const elevator = layout.checkpoints.find((c) => c.id === "elevator")!;- for (const start of [layout.spawn, elevator]) {- expect(isWalkable(grid, start)).toBe(true);- for (const { name, p } of targetsOf(layout)) {- const path = findPath(grid, start, p);- if (!path) throw new Error(`${name} at ${p.x.toFixed(2)},${p.z.toFixed(2)} is unreachable`);- if (path.length === 0) continue; // already standing on it- assertClearPath(grid, start, p, path, name);- }- }- });- }-- it(`walks back from every target to the spawn, starting inside furniture if need be (${variant})`, () => {- const layout = buildOfficeLayout(roster(10), { variant });- const grid = buildNavGrid(layout);- for (const { name, p } of targetsOf(layout)) {- const path = findPath(grid, p, layout.spawn);- expect(path, name).not.toBeNull();- const tail = path!.at(-1)!;- expect(tail).toEqual(layout.spawn);- }- });- }-- // The agents floor is built from its teams: every studio's seats, huddle places and board must be reachable too.- const TEAM_CASES: [string, number, OfficeTeamInput[]][] = [- ["one team", 10, teamsOf(1, 4)],- ["three teams", 16, teamsOf(3, 4)],- ["eight teams", 40, teamsOf(8, 4)],- ["teams of two and of twelve", 20, [...teamsOf(1, 12), { id: "duo", name: "Duo", createdMs: 99, members: ["a13", "a14"] }]],- ["an agent in two teams and a team of unknown ids", 9, [- { id: "x", name: "X", createdMs: 1, members: ["a1", "a2", "a3"] }, { id: "y", name: "Y", createdMs: 2, members: ["a3", "a4"] },- { id: "ghosts", name: "Ghosts", createdMs: 3, members: ["nobody-1", "nobody-2"] },- ]],- ];- for (const [name, count, teams] of TEAM_CASES) {- it(`reaches every seat, spot and checkpoint of a team campus from the spawn and the elevator (${name})`, () => {- const layout = buildOfficeLayout(roster(count), { teams });- expect(layout.studios).toHaveLength(teams.length + 1);- const grid = buildNavGrid(layout);- const elevator = layout.checkpoints.find((c) => c.id === "elevator")!;- for (const start of [layout.spawn, elevator]) {- expect(isWalkable(grid, start)).toBe(true);- for (const { name: target, p } of targetsOf(layout)) {- const path = findPath(grid, start, p);- if (!path) throw new Error(`${target} at ${p.x.toFixed(2)},${p.z.toFixed(2)} is unreachable`);- if (path.length === 0) continue;- assertClearPath(grid, start, p, path, target);- }- }- });- }-- it("blocks obstacles and everything outside the floor", () => {- const layout = buildOfficeLayout(roster(4));- const grid = buildNavGrid(layout);- const desk = allDesks(layout)[0];- expect(isWalkable(grid, desk)).toBe(false);- expect(isWalkable(grid, { x: layout.floor.minX - 0.5, z: 0 })).toBe(false);- expect(isWalkable(grid, { x: 1e6, z: 1e6 })).toBe(false);- const near = nearestWalkable(grid, desk)!;- expect(isWalkable(grid, near)).toBe(true);- expect(Math.hypot(near.x - desk.x, near.z - desk.z)).toBeLessThan(1.5);- expect(nearestWalkable(grid, layout.spawn)).toEqual(layout.spawn);- });-- it("has no line of sight through a desk row", () => {- const layout = buildOfficeLayout(roster(4));- const grid = buildNavGrid(layout);- const desk = allDesks(layout).find((d) => d.id.includes(":0:south:"))!;- const seat = seatOf(desk);- const across = { x: seat.x, z: desk.z + 2 };- expect(hasLineOfSight(grid, seat, across)).toBe(false);- });-- it("returns an empty path when already at the target, and null when unreachable", () => {- const layout = buildOfficeLayout([]);- const grid = buildNavGrid(layout);- expect(findPath(grid, layout.spawn, layout.spawn)).toEqual([]);- expect(findPath(grid, layout.spawn, { x: 1e4, z: 1e4 })).toBeNull();- });-- it("draws random walkable points inside the requested rect", () => {- const layout = buildOfficeLayout(roster(10));- const grid = buildNavGrid(layout);- const rng = createRng("wander");- const within = layout.departments[0];- for (let i = 0; i < 50; i += 1) {- const p = randomWalkablePoint(grid, rng, within)!;- expect(isWalkable(grid, p)).toBe(true);- expect(p.x).toBeGreaterThanOrEqual(within.minX);- expect(p.x).toBeLessThanOrEqual(within.maxX);- expect(p.z).toBeGreaterThanOrEqual(within.minZ);- expect(p.z).toBeLessThanOrEqual(within.maxZ);- }- expect(randomWalkablePoint(grid, rng, { minX: 1e5, maxX: 1e5 + 1, minZ: 0, maxZ: 1 })).toBeNull();- });-- it("finds paths fast on a full floor", () => {- const layout = buildOfficeLayout(roster(40));- const grid = buildNavGrid(layout);- const rng = createRng("perf");- const points = Array.from({ length: 60 }, () => randomWalkablePoint(grid, rng)!);- findPath(grid, points[0], points[1]); // warm up caches- const started = performance.now();- let runs = 0;- for (let i = 0; i + 1 < points.length; i += 1) {- expect(findPath(grid, points[i], points[i + 1])).not.toBeNull();- runs += 1;- }- const perPath = (performance.now() - started) / runs;- // Typically well under 5 ms; the bound is generous for slow CI machines.- expect(perPath).toBeLessThan(25);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeNav.ts b/dodaios/ui/web/frontend/src/components/society/office/officeNav.tsdeleted file mode 100644index e997dfaadf..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeNav.ts+++ /dev/null@@ -1,404 +0,0 @@-/**- * Grid navigation for the office floor: an occupancy grid built from the- * layout's obstacles (inflated by the walker radius), A* over it, and- * line-of-sight smoothing so figures walk straight lines instead of- * staircases.- *- * Pure and allocation-light: per-grid scratch buffers are cached, so a path- * search on a full floor costs well under a few milliseconds.- */-import type { OfficeLayout, Point, Rect } from "./officeLayout";-import { onSkyPad, skyPadExtent } from "./skyPad";--/** Half the shoulder width of a walking figure, in metres. */-export const WALKER_RADIUS = 0.28;--export interface NavGrid {- /** Edge length of one square cell, in metres. */- cell: number;- cols: number;- rows: number;- /** World position of the grid's north-west corner. */- originX: number;- originZ: number;- /** 1 = blocked, 0 = walkable; index = row * cols + col. */- blocked: Uint8Array;- /**- * The floor inside the railing. The grid may reach beyond it (the sky pad); an idle wander stays on the floor.- * Absent on grids built by hand in tests.- */- home?: Rect;-}--/** A snapped approach may end at most this far from a blocked target. */-const SNAP_DISTANCE = 1.0;-/** How far a blocked start or an unreachable target may search for a walkable cell. */-const FALLBACK_SEARCH = 3.0;-const SQRT2 = Math.SQRT2;--export function buildNavGrid(layout: OfficeLayout, opts: { cell?: number; radius?: number } = {}): NavGrid {- const cell = opts.cell ?? 0.2;- const radius = opts.radius ?? WALKER_RADIUS;- const { floor, skyPad } = layout;- // The grid covers the floor and, on the agents floor, the bridge and the pad outside the east windows.- const extent = skyPad ? skyPadExtent(skyPad) : floor;- const minX = Math.min(floor.minX, extent.minX), maxX = Math.max(floor.maxX, extent.maxX);- const minZ = Math.min(floor.minZ, extent.minZ), maxZ = Math.max(floor.maxZ, extent.maxZ);- const cols = Math.max(1, Math.ceil((maxX - minX) / cell));- const rows = Math.max(1, Math.ceil((maxZ - minZ) / cell));- const originX = minX;- const originZ = minZ;- const blocked = new Uint8Array(cols * rows);-- // Cells whose centre lies outside the walkable floor (and off the pad).- for (let r = 0; r < rows; r += 1) {- const cz = originZ + (r + 0.5) * cell;- for (let c = 0; c < cols; c += 1) {- const cx = originX + (c + 0.5) * cell;- const onFloor = cx >= floor.minX && cx <= floor.maxX && cz >= floor.minZ && cz <= floor.maxZ;- if (!onFloor && !(skyPad && onSkyPad(skyPad, { x: cx, z: cz }))) blocked[r * cols + c] = 1;- }- }- // Cells whose centre lies inside an inflated obstacle.- for (const o of layout.obstacles) {- const minX = o.minX - radius, maxX = o.maxX + radius, minZ = o.minZ - radius, maxZ = o.maxZ + radius;- const c0 = Math.max(0, Math.ceil((minX - originX) / cell - 0.5));- const c1 = Math.min(cols - 1, Math.floor((maxX - originX) / cell - 0.5));- const r0 = Math.max(0, Math.ceil((minZ - originZ) / cell - 0.5));- const r1 = Math.min(rows - 1, Math.floor((maxZ - originZ) / cell - 0.5));- for (let r = r0; r <= r1; r += 1) {- for (let c = c0; c <= c1; c += 1) blocked[r * cols + c] = 1;- }- }- return { cell, cols, rows, originX, originZ, blocked, home: floor };-}--function colOf(grid: NavGrid, x: number): number {- return Math.floor((x - grid.originX) / grid.cell);-}--function rowOf(grid: NavGrid, z: number): number {- return Math.floor((z - grid.originZ) / grid.cell);-}--function walkableCell(grid: NavGrid, c: number, r: number): boolean {- return c >= 0 && r >= 0 && c < grid.cols && r < grid.rows && grid.blocked[r * grid.cols + c] === 0;-}--function centreOf(grid: NavGrid, index: number): Point {- const c = index % grid.cols;- const r = (index - c) / grid.cols;- return { x: grid.originX + (c + 0.5) * grid.cell, z: grid.originZ + (r + 0.5) * grid.cell };-}--/** Index of the cell containing p, or -1 when p lies outside the grid. */-function indexOf(grid: NavGrid, p: Point): number {- const c = colOf(grid, p.x);- const r = rowOf(grid, p.z);- if (c < 0 || r < 0 || c >= grid.cols || r >= grid.rows) return -1;- return r * grid.cols + c;-}--export function isWalkable(grid: NavGrid, p: Point): boolean {- return walkableCell(grid, colOf(grid, p.x), rowOf(grid, p.z));-}--/** Nearest walkable cell (by centre distance) within maxRadius that passes `accept`; -1 if none. */-function nearestCell(grid: NavGrid, p: Point, maxRadius: number, accept?: (index: number) => boolean): number {- const pc = Math.min(grid.cols - 1, Math.max(0, colOf(grid, p.x)));- const pr = Math.min(grid.rows - 1, Math.max(0, rowOf(grid, p.z)));- // Distance from p to its (clamped) cell, so points just off the grid still search correctly.- const offGrid = Math.hypot(- Math.max(0, grid.originX - p.x, p.x - (grid.originX + grid.cols * grid.cell)),- Math.max(0, grid.originZ - p.z, p.z - (grid.originZ + grid.rows * grid.cell)),- );- if (offGrid > maxRadius) return -1;- const maxRing = Math.ceil((maxRadius + offGrid) / grid.cell) + 1;- let best = -1;- let bestDist = Infinity;- for (let ring = 0; ring <= maxRing; ring += 1) {- // Every centre in this ring is at least this far from p.- if (best >= 0 && (ring - 1) * grid.cell - offGrid > bestDist) break;- for (let dr = -ring; dr <= ring; dr += 1) {- const r = pr + dr;- if (r < 0 || r >= grid.rows) continue;- const edgeRow = dr === -ring || dr === ring;- for (let dc = -ring; dc <= ring; dc += edgeRow ? 1 : ring * 2) {- const c = pc + dc;- if (c >= 0 && c < grid.cols) {- const index = r * grid.cols + c;- if (grid.blocked[index] === 0) {- const cx = grid.originX + (c + 0.5) * grid.cell;- const cz = grid.originZ + (r + 0.5) * grid.cell;- const d = Math.hypot(cx - p.x, cz - p.z);- if (d <= maxRadius && d < bestDist && (!accept || accept(index))) { best = index; bestDist = d; }- }- }- if (ring === 0) break;- }- }- }- return best;-}--/** Centre of the walkable cell nearest to p (p's own cell when walkable), or null within maxRadius. */-export function nearestWalkable(grid: NavGrid, p: Point, maxRadius = FALLBACK_SEARCH): Point | null {- if (isWalkable(grid, p)) return { x: p.x, z: p.z };- const index = nearestCell(grid, p, maxRadius);- return index < 0 ? null : centreOf(grid, index);-}--/**- * True when every cell the segment a→b touches is walkable (supercover walk).- * A segment through a cell corner must have both side cells free, which- * matches the "no corner cutting" rule of the path search.- */-export function hasLineOfSight(grid: NavGrid, a: Point, b: Point): boolean {- const ax = (a.x - grid.originX) / grid.cell, az = (a.z - grid.originZ) / grid.cell;- const bx = (b.x - grid.originX) / grid.cell, bz = (b.z - grid.originZ) / grid.cell;- let c = Math.floor(ax), r = Math.floor(az);- if (!walkableCell(grid, c, r)) return false;- const dx = bx - ax, dz = bz - az;- const stepX = dx > 0 ? 1 : dx < 0 ? -1 : 0;- const stepZ = dz > 0 ? 1 : dz < 0 ? -1 : 0;- const tDeltaX = stepX !== 0 ? 1 / Math.abs(dx) : Infinity;- const tDeltaZ = stepZ !== 0 ? 1 / Math.abs(dz) : Infinity;- let tMaxX = stepX > 0 ? (c + 1 - ax) * tDeltaX : stepX < 0 ? (ax - c) * tDeltaX : Infinity;- let tMaxZ = stepZ > 0 ? (r + 1 - az) * tDeltaZ : stepZ < 0 ? (az - r) * tDeltaZ : Infinity;- const limit = Math.abs(Math.floor(bx) - c) + Math.abs(Math.floor(bz) - r) + 4;- for (let i = 0; i < limit * 2; i += 1) {- const next = Math.min(tMaxX, tMaxZ);- if (next > 1) return true;- if (Math.abs(tMaxX - tMaxZ) < 1e-9) {- // Exactly through a corner: both side cells must be free.- if (!walkableCell(grid, c + stepX, r) || !walkableCell(grid, c, r + stepZ)) return false;- c += stepX; r += stepZ; tMaxX += tDeltaX; tMaxZ += tDeltaZ;- } else if (tMaxX < tMaxZ) {- c += stepX; tMaxX += tDeltaX;- } else {- r += stepZ; tMaxZ += tDeltaZ;- }- if (!walkableCell(grid, c, r)) return false;- }- return true;-}--interface Scratch {- g: Float64Array;- parent: Int32Array;- seen: Uint32Array;- closed: Uint32Array;- stamp: number;- heapIndex: Int32Array;- heapKey: Float64Array;- /** Connected-region label per cell (-1 = blocked). */- region: Int32Array | null;-}--const scratchCache = new WeakMap<NavGrid, Scratch>();--function scratchOf(grid: NavGrid): Scratch {- let s = scratchCache.get(grid);- if (!s) {- const n = grid.cols * grid.rows;- s = {- g: new Float64Array(n), parent: new Int32Array(n), seen: new Uint32Array(n), closed: new Uint32Array(n), stamp: 0,- heapIndex: new Int32Array(1024), heapKey: new Float64Array(1024), region: null,- };- scratchCache.set(grid, s);- }- return s;-}--/** Label 4-connected walkable regions (equivalent to 8-connected without corner cutting). */-function regionsOf(grid: NavGrid): Int32Array {- const s = scratchOf(grid);- if (s.region) return s.region;- const n = grid.cols * grid.rows;- const region = new Int32Array(n).fill(-1);- const queue = new Int32Array(n);- let label = 0;- for (let start = 0; start < n; start += 1) {- if (grid.blocked[start] !== 0 || region[start] !== -1) continue;- let head = 0, tail = 0;- queue[tail++] = start;- region[start] = label;- while (head < tail) {- const i = queue[head++];- const c = i % grid.cols;- const neighbours = [c > 0 ? i - 1 : -1, c < grid.cols - 1 ? i + 1 : -1, i - grid.cols, i + grid.cols];- for (const j of neighbours) {- if (j < 0 || j >= n || grid.blocked[j] !== 0 || region[j] !== -1) continue;- region[j] = label;- queue[tail++] = j;- }- }- label += 1;- }- s.region = region;- return region;-}--/** A* from cell s to cell t (8-connected, no corner cutting). Returns cells from s to t inclusive, or null. */-function aStar(grid: NavGrid, s: number, t: number): number[] | null {- const sc = scratchOf(grid);- sc.stamp += 1;- if (sc.stamp === 0xffffffff) { sc.seen.fill(0); sc.closed.fill(0); sc.stamp = 1; }- const stamp = sc.stamp;- const { g, parent, seen, closed } = sc;- const cols = grid.cols, rows = grid.rows, blocked = grid.blocked;- const tc = t % cols, tr = (t - tc) / cols;- const h = (i: number): number => {- const c = i % cols, r = (i - c) / cols;- const dx = Math.abs(c - tc), dz = Math.abs(r - tr);- return dx > dz ? dx + (SQRT2 - 1) * dz : dz + (SQRT2 - 1) * dx;- };-- // Binary min-heap with lazy deletion.- let size = 0;- const push = (index: number, key: number) => {- if (size >= sc.heapIndex.length) {- const grownI = new Int32Array(sc.heapIndex.length * 2); grownI.set(sc.heapIndex); sc.heapIndex = grownI;- const grownK = new Float64Array(sc.heapKey.length * 2); grownK.set(sc.heapKey); sc.heapKey = grownK;- }- const hi = sc.heapIndex, hk = sc.heapKey;- let pos = size++;- while (pos > 0) {- const up = (pos - 1) >> 1;- if (hk[up] <= key) break;- hi[pos] = hi[up]; hk[pos] = hk[up]; pos = up;- }- hi[pos] = index; hk[pos] = key;- };- const pop = (): number => {- const hi = sc.heapIndex, hk = sc.heapKey;- const top = hi[0];- size -= 1;- if (size > 0) {- const lastI = hi[size], lastK = hk[size];- let pos = 0;- for (;;) {- let child = pos * 2 + 1;- if (child >= size) break;- if (child + 1 < size && hk[child + 1] < hk[child]) child += 1;- if (hk[child] >= lastK) break;- hi[pos] = hi[child]; hk[pos] = hk[child]; pos = child;- }- hi[pos] = lastI; hk[pos] = lastK;- }- return top;- };-- g[s] = 0; parent[s] = -1; seen[s] = stamp;- push(s, h(s));- while (size > 0) {- const cur = pop();- if (closed[cur] === stamp) continue;- closed[cur] = stamp;- if (cur === t) {- const cells: number[] = [];- for (let i = t; i !== -1; i = parent[i]) cells.push(i);- return cells.reverse();- }- const c = cur % cols, r = (cur - c) / cols;- for (let dr = -1; dr <= 1; dr += 1) {- const nr = r + dr;- if (nr < 0 || nr >= rows) continue;- for (let dc = -1; dc <= 1; dc += 1) {- if (dc === 0 && dr === 0) continue;- const nc = c + dc;- if (nc < 0 || nc >= cols) continue;- const ni = nr * cols + nc;- if (blocked[ni] !== 0 || closed[ni] === stamp) continue;- let cost = 1;- if (dc !== 0 && dr !== 0) {- // No corner cutting: both orthogonal neighbours must be free.- if (blocked[r * cols + nc] !== 0 || blocked[nr * cols + c] !== 0) continue;- cost = SQRT2;- }- const ng = g[cur] + cost;- if (seen[ni] === stamp && ng >= g[ni]) continue;- seen[ni] = stamp; g[ni] = ng; parent[ni] = cur;- push(ni, ng + h(ni));- }- }- }- return null;-}--/**- * Waypoints from `from` to `to`, excluding the start, or null when `to` is- * genuinely unreachable.- *- * A blocked start first steps to its nearest walkable cell. A blocked target- * (a couch seat, a chair tucked against a desk) is approached through the- * nearest reachable cell; when that cell lies within 1 m, the exact target is- * appended as a final "snap" step that may cross the inflated margin.- */-export function findPath(grid: NavGrid, from: Point, to: Point): Point[] | null {- const region = regionsOf(grid);- let s = indexOf(grid, from);- let startSnapped = false;- if (s < 0 || grid.blocked[s] !== 0) {- s = nearestCell(grid, from, FALLBACK_SEARCH);- if (s < 0) return null;- startSnapped = true;- }- const home = region[s];- const sameRegion = (index: number) => region[index] === home;-- let t = indexOf(grid, to);- let goalSnap = false;- const targetWalkable = t >= 0 && grid.blocked[t] === 0;- if (targetWalkable) {- if (region[t] !== home) return null;- } else {- t = nearestCell(grid, to, SNAP_DISTANCE, sameRegion);- if (t >= 0) goalSnap = true;- else t = nearestCell(grid, to, FALLBACK_SEARCH, sameRegion);- if (t < 0) return null;- }-- const cells = aStar(grid, s, t);- if (!cells) return null;-- const startPoint = startSnapped ? centreOf(grid, s) : from;- const points = cells.slice(1).map((i) => centreOf(grid, i));- if (targetWalkable) {- if (points.length > 0) points[points.length - 1] = { x: to.x, z: to.z };- else if (Math.hypot(to.x - startPoint.x, to.z - startPoint.z) > 1e-6) points.push({ x: to.x, z: to.z });- }-- // String pulling: drop every waypoint the previous kept point can see past.- const smoothed: Point[] = [];- let anchor = startPoint;- for (let i = 0; i < points.length; i += 1) {- if (i === points.length - 1 || !hasLineOfSight(grid, anchor, points[i + 1])) {- smoothed.push(points[i]);- anchor = points[i];- }- }-- const out: Point[] = [];- if (startSnapped) out.push(startPoint);- out.push(...smoothed);- if (goalSnap) out.push({ x: to.x, z: to.z });- return out;-}--/** A uniformly drawn walkable cell centre (inside `within` when given), or null after a bounded number of tries. */-export function randomWalkablePoint(grid: NavGrid, rng: () => number, within: Rect | undefined = grid.home): Point | null {- const minX = Math.max(grid.originX, within?.minX ?? -Infinity);- const maxX = Math.min(grid.originX + grid.cols * grid.cell, within?.maxX ?? Infinity);- const minZ = Math.max(grid.originZ, within?.minZ ?? -Infinity);- const maxZ = Math.min(grid.originZ + grid.rows * grid.cell, within?.maxZ ?? Infinity);- if (maxX <= minX || maxZ <= minZ) return null;- for (let attempt = 0; attempt < 64; attempt += 1) {- const p = { x: minX + rng() * (maxX - minX), z: minZ + rng() * (maxZ - minZ) };- const index = indexOf(grid, p);- if (index < 0 || grid.blocked[index] !== 0) continue;- const centre = centreOf(grid, index);- if (centre.x >= minX && centre.x <= maxX && centre.z >= minZ && centre.z <= maxZ) return centre;- }- return null;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/officePalette.ts b/dodaios/ui/web/frontend/src/components/society/office/officePalette.tsdeleted file mode 100644index caaab38f98..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officePalette.ts+++ /dev/null@@ -1,238 +0,0 @@-/**- * The office's own colours: a contemporary workplace (docs/agent-society/office-map.md §2)- * — light microcement floor, light-oak tops on black steel, graphite screens,- * felt zone rugs, charcoal wayfinding with white type and lots of green.- * Like the earlier worlds, nothing inside the canvas reads a theme token: the- * scene is a lit diorama that looks the same in light and dark mode.- */-export const OFFICE = {- space: "#0d1320",- slab: "#2a2e35",- slabEdge: "#1c2027",- /** Microcement floor: base plus the soft cloud tones and panel seams drawn over it. */- floor: "#dcd8d1",- floorCloud: ["#d4d0c8", "#e2ded8", "#d8d4cd", "#e6e3dd"],- floorSeam: "rgba(120,114,104,0.22)",- wood: "#d8bc94",- woodDark: "#a88460",- walkway: "#dcd8d1",- deskTop: "#dcc39d",- deskEdge: "#c9ab81",- deskBody: "#f3f2ef",- deskLeg: "#1f2226",- steel: "#1f2226",- chair: "#1d2025",- chairSeat: "#3a3f47",- chairMesh: "#40454e",- monitor: "#16181c",- monitorArm: "#b8bdc5",- keyboard: "#e4e5e8",- mug: "#f7f5f1",- railing: "#23262b",- glass: "#d6ecff",- wallWhite: "#f6f5f2",- signBoard: "#23262c",- signText: "#ffffff",- couch: "#bdb6aa",- couchCushion: "#d8d1c4",- couchAccent: ["#7f9a86", "#c98f6f", "#7c8fa8"],- plantPot: "#34373d",- planterLight: "#ebe6de",- leaf: "#4f8f52",- leafDark: "#2f6b3f",- leafLight: "#77ad64",- trunk: "#6b5440",- book: ["#c8553d", "#e9b44c", "#4f7cac", "#5e9c76", "#8d6cab", "#e7e2d8"],- rug: "#cfc7ba",- ringWorking: "#4ade80",- ringIdle: "#e8ecf2",- ringWaiting: "#fbbf24",- ringPaused: "#94a3b8",-} as const;--/**- * Department zones: a felt rug, the matching acoustic wall panel and the seat- * fabric of every chair in it — muted, contemporary tones that read on the- * light floor without shouting.- */-export const DEPARTMENT_ZONES = [- { rug: "#bccab6", panel: "#8aa391", seat: "#6f8b77" },- { rug: "#b9c6d4", panel: "#7b91ab", seat: "#5f7894" },- { rug: "#ddd1bb", panel: "#bfa07a", seat: "#a8845a" },- { rug: "#e2cbc0", panel: "#c48e7a", seat: "#b0705b" },- { rug: "#c6c1d5", panel: "#918aad", seat: "#766e96" },- { rug: "#b8d0c9", panel: "#6f9f94", seat: "#528579" },- // The agents floor's campus holds up to twelve studios: mustard, rose, sky, olive, cocoa and indigo follow.- { rug: "#e2d3a2", panel: "#c2a24c", seat: "#a8873a" },- { rug: "#d8bfc7", panel: "#b0728a", seat: "#955a72" },- { rug: "#b5cbd8", panel: "#5e93b0", seat: "#467a96" },- { rug: "#cbcfa6", panel: "#92975a", seat: "#787d44" },- { rug: "#d5c0b0", panel: "#a67a5e", seat: "#8b624a" },- { rug: "#bbc2d5", panel: "#6d7aac", seat: "#566392" },-] as const;--/** Rug tints per department (kept for callers that only need the floor colour). */-export const DEPARTMENT_TINTS = DEPARTMENT_ZONES.map((z) => z.rug);--/**- * The coding floor's own look: a tech campus floor. Polished pale concrete is- * the ground, a terrazzo main street runs down the middle, and every team- * neighbourhood is an island of white oak with long shared tables, a living- * moss wall carrying its name, and phone booths in its colour along the- * glass. The agents floor below keeps its wide oak planks and limestone.- */-export const CODING_SCENE = {- slabEdge: "#2b2a28",- rim: "#ffe2bd",- /** Daylight from a pale sky, a warm bounce off the oak. */- sky: "#f6f4ef",- ground: "#8a8076",- /** Polished concrete: base, soft clouds of tone, and the saw-cut joints. */- concrete: { base: "#d9d6d0", cloud: ["#d2cec7", "#e0ddd8", "#cfcbc4"], joint: "#b9b4ac" },- /** The terrazzo main street, its chips, and the brass strip along its edges. */- terrazzo: { base: "#ece7de", chips: ["#cfc5b5", "#b3a690", "#ddd2bf", "#93887a", "#c2a97e", "#7f8f86"] },- /** White oak: the neighbourhoods' floor and the long tables. */- oak: { seam: "#c4ad8c", planks: ["#e8dac2", "#e2d2b6", "#ecdfc9", "#ddcbad", "#efe4d0", "#e4d5bb"] },- /** The living walls: moss tones, fern tones, and the white-oak frame. */- moss: { base: "#4f6b3a", tones: ["#5d7b42", "#46613a", "#6e8a4b", "#3d5532", "#7a9655"], fern: "#86a85c", frame: "#d9c7a8" },- /** The long tables' spine, legs and screens. */- table: { top: "#e6d6ba", edge: "#cdb894", leg: "#2a2c30", spine: "#3a3d42", screen: "#eceae5" },- brass: "#c9a24a",- /** Linear pendants over the tables: body, lit underside and the pool of light below. */- pendant: { body: "#f2f1ee", glow: "#fff1dc", pool: "#fff0d6" },- /** The town square round the spawn terminal: the terrazzo medallion and its chips. */- plaza: { terrazzo: "#efe9df", chips: ["#cbc0ae", "#a99b86", "#dccfb8", "#8d806d", "#b99f72"] },- /** The desk's busy light: working, waiting for the person, failed, idle. */- busy: { working: "#3ccf6e", waiting: "#ffb020", error: "#ff4d4d", idle: "#6b6f76" },-} as const;--/** A team neighbourhood's colour: the phone booths, chair seats and the stripe under its name. */-export interface TeamColours {- /** The team's colour itself. */- accent: string;- /** A soft felt in that colour: booth interiors and seat fabric. */- felt: string;-}--/**- * One colour per neighbourhood, cycled by the department's tint index: clear,- * friendly colours a company would paint its team areas in, each distinct- * from the others and from the status colours of the busy lights.- */-export const CODING_TEAMS: readonly TeamColours[] = [- { accent: "#3f7fd9", felt: "#6f9ee0" },- { accent: "#e36a4f", felt: "#e99079" },- { accent: "#e2b33c", felt: "#e8c56c" },- { accent: "#2f9e8f", felt: "#62b5a9" },- { accent: "#8a63c9", felt: "#a68bd6" },- { accent: "#d1557f", felt: "#dc7f9e" },-];--export function codingTeam(index: number): TeamColours {- const n = CODING_TEAMS.length;- return CODING_TEAMS[((index % n) + n) % n];-}--/** Colours of the room props (lobby, team room, wardrobe, break room). */-export const PROP_COLOURS = {- steel: "#aab2bc",- steelDark: "#6f7782",- elevatorShaft: "#e7e4de",- indicator: "#ffb347",- lockers: ["#5fa8a0", "#e2856e", "#f2c14e", "#9b8ac4"],- lockerVent: "#2f3440",- mirror: "#d6ecf8",- waterBottle: "#6fb7ea",- waterTap: ["#e05a4f", "#4f8fe0"],- mug: "#fdfbf7",- coffee: "#5a3a24",- espresso: "#c9ced4",- chalkboard: "#2c3a33",- arcadeBody: "#5b4a9e",- arcadeTrim: "#2a2140",- arcadeMarquee: "#ff7ab8",- joystick: "#e0463c",- arcadeButtons: ["#f2c14e", "#4fb3e0", "#6fd07a"],- beanbag: ["#e27d60", "#85cdca", "#e8a87c", "#c38d9e", "#7d9bd6"],- bell: "#e0b64a",- boardFrame: "#d7d9dd",- boardWhite: "#fbfbf8",- /** The dark frame of the reception's help display (and the counter's brochure tray). */- displayFrame: "#2a2e36",- paper: "#fdfcf9",- rugInner: "#c9b28f",-} as const;--/** Floor overlays per room kind: base colour plus the pattern's accent tones. */-export const ROOM_FLOOR_COLOURS = {- lead: { base: "#6a432a", accents: ["#74492d", "#5e3a24", "#6c4429", "#7d5133", "#553420"] },- // Contemporary rooms: slate felt (team), light terrazzo (wardrobe), large pale stone (reception),- // light-oak planks (break room); on the coding floor a soft sage felt and a raised-floor grid.- team: { base: "#b4bec6", accents: ["#aab4bd", "#bcc6cd", "#b0bac2"] },- wardrobe: { base: "#ece8e2", accents: ["#c9c2b8", "#9aa4ad", "#d9b8aa", "#aebcaa"] },- reception: { base: "#e9e6e1", accents: ["#ece9e4", "#e5e2dc", "#efece8"] },- break: { base: "#d9c09b", accents: ["#dcc39f", "#d2b791", "#e0c8a6", "#cfb48c"] },- // Mission Control: dark graphite microcement.- command: { base: "#454b54", accents: ["#3e444c", "#4d535c", "#41474f", "#51575f"] },- server: { base: "#c3c8cf", accents: ["#c9ced4", "#bcc2c9"] },- // Arcade floor: the hall's midnight carpet, the game rooms' violet, teal and ember carpets, the foyer's terrazzo,- // the prize shop's plum, the snack bar's checker red.- arcade: { base: "#1a1430", accents: ["#211a3d", "#151027", "#2a1f4a"] },- classics: { base: "#241446", accents: ["#2c1a55", "#1d1039"] },- puzzle: { base: "#0f2a33", accents: ["#13343f", "#0b2129"] },- action: { base: "#2e160c", accents: ["#3a1c0f", "#241008"] },- foyer: { base: "#24202e", accents: ["#2c2838", "#1d1a26"] },- prizes: { base: "#3a1838", accents: ["#431c41", "#33152f"] },- snack: { base: "#5a1e22", accents: ["#e9e2d6", "#4c191c"] },- // Level Hall: deep midnight-blue polished stone with gold veins.- levels: { base: "#e7e0d0", accents: ["#e7e0d0", "#2b2d33", "#bdb3a0", "#b8964f"] },-} as const;--/**- * The agents floor's rooms take their floors from the campus's own finishes instead: the plank oak of the open- * floor (break room), the same oak a tone deeper and laid as a chevron (lead office), the limestone of the window- * band (lobby, and as terrazzo with oak and stone chips in the wardrobe) and the slate felt of the focus booths- * (team room). One floor family from the studios to the last room.- */-export const CAMPUS_ROOM_FLOORS = {- lead: { base: "#a98a64", accents: ["#b08f69", "#9f805b", "#a98964", "#b89872", "#967752"] },- team: { base: "#c3cbd3", accents: ["#bac3cc", "#cbd2d9", "#bfc7cf"] },- wardrobe: { base: "#e7e0d4", accents: ["#d3cabb", "#c9ad8c", "#b9b0a3", "#efe9df"] },- reception: { base: "#e7e0d4", accents: ["#ddd5c7", "#efe9df", "#e2dace"] },- break: { base: "#dcc6a1", accents: ["#e4d0ae", "#dcc6a1", "#e9d8ba", "#d8bf98"] },-} as const;--/** Checkpoint gold: floor ring, hexagon token and the label badge. */-export const CHECKPOINT_GOLD = { ring: "#f5b83d", rim: "#e0a02a", face: "#f7c65a", faceDeep: "#e39b1f", icon: "#ffffff" } as const;--/**- * The lead office's executive suite, in the campus's own materials a tone- * deeper: smoked oak, bronze, cognac leather and a slate rug. (The keys keep- * the names the suite was built with: `walnut*` is its timber, `brass` its- * metal.) Bronze is the one metallic accent beside the floor's dark steel, so- * the boss's room reads as the most precious place on the floor without- * leaving its family.- */-export const LEAD_SUITE = {- walnut: "#8b6b4a",- walnutDark: "#6a4f37",- walnutLight: "#ad8a63",- brass: "#b08d5c",- leather: "#8e5a3a",- leatherDark: "#6b4129",- leatherTan: "#b98558",- velvetGold: "#c9a25a",- chrome: "#c9ced6",- blackGlass: "#12141a",- marble: "#eeeae3",- led: "#ffd08a",- lampGlass: "#2f7a4f",- shade: "#fff0d2",- backlight: "#a07a52",- glass: "#e8d3a8",- rug: { field: "#39414d", inner: "#48515e", border: "#b08d5c", accent: "#8e5a3a" },- globe: { ocean: "#5f8f96", land: "#e2cd98", line: "#3d5c61" },- bottles: ["#b8661e", "#4f7a3a", "#d9e6ea", "#8c2a2a", "#c79a3a"],- trophy: "#e8b949",- dog: { basket: "#8b6b4a", cushion: "#8e5a3a" },-} as const;diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeSettings.ts b/dodaios/ui/web/frontend/src/components/society/office/officeSettings.tsdeleted file mode 100644index 22081da8cc..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeSettings.ts+++ /dev/null@@ -1,74 +0,0 @@-/**- * The office's own settings, kept per viewer in browser storage. Reception is- * their home: every setting the map gains (and, later, rebindable keys) lands- * in this one store and in the reception's Settings tab.- */-import { create } from "zustand";--export interface OfficeSettings {- /** Walk at sprint pace by default; Shift then slows to a walk. */- alwaysRun: boolean;- /** The first-visit control hints were dismissed; they stay away until the person asks for them again. */- hintsSeen: boolean;-}--export const DEFAULT_OFFICE_SETTINGS: OfficeSettings = { alwaysRun: false, hintsSeen: false };--const STORAGE_KEY = "jarvis.office.settings.v1";--export function loadOfficeSettings(): OfficeSettings {- try {- const raw = typeof localStorage === "undefined" ? null : localStorage.getItem(STORAGE_KEY);- if (!raw) return { ...DEFAULT_OFFICE_SETTINGS };- const parsed = JSON.parse(raw) as Partial<OfficeSettings> & { showHintBar?: unknown };- return {- alwaysRun: typeof parsed.alwaysRun === "boolean" ? parsed.alwaysRun : DEFAULT_OFFICE_SETTINGS.alwaysRun,- // Someone who had switched the old permanent hint bar off has seen the hints.- hintsSeen: typeof parsed.hintsSeen === "boolean" ? parsed.hintsSeen : parsed.showHintBar === false,- };- } catch (error) {- // Blocked or corrupt storage: the defaults are a complete, working set.- console.warn("Office settings unreadable, using defaults", error);- return { ...DEFAULT_OFFICE_SETTINGS };- }-}--function saveOfficeSettings(settings: OfficeSettings): void {- try {- localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));- } catch (error) {- // The setting still applies for this visit; it just will not survive a reload.- console.warn("Office settings not saved", error);- }-}--interface OfficeSettingsState extends OfficeSettings {- set: (patch: Partial<OfficeSettings>) => void;- reset: () => void;-}--export const useOfficeSettings = create<OfficeSettingsState>((set, get) => ({- ...loadOfficeSettings(),- set: (patch) => {- set(patch);- const { alwaysRun, hintsSeen } = get();- saveOfficeSettings({ alwaysRun, hintsSeen });- },- reset: () => {- set({ ...DEFAULT_OFFICE_SETTINGS });- saveOfficeSettings({ ...DEFAULT_OFFICE_SETTINGS });- },-}));--/** Sprint when exactly one of "Shift held" and "always run" is on. */-export function isRunning(shiftHeld: boolean, alwaysRun: boolean): boolean {- return shiftHeld !== alwaysRun;-}--/** The reception's tabs; H opens reception on the controls tab from anywhere. */-export type ReceptionTab = "agents" | "places" | "controls" | "settings";--export const useReceptionTab = create<{ tab: ReceptionTab; setTab: (tab: ReceptionTab) => void }>((set) => ({- tab: "agents",- setTab: (tab) => set({ tab }),-}));diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeStore.ts b/dodaios/ui/web/frontend/src/components/society/office/officeStore.tsdeleted file mode 100644index 6081008e41..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeStore.ts+++ /dev/null@@ -1,214 +0,0 @@-/**- * Office interaction state shared between the canvas and the DOM HUD.- *- * Positions that change every frame live in the mutable `player` object and- * are never React state; the store only carries what the HUD renders or what- * the walkers must react to (selection, nearby target, calls, gatherings).- */-import { create } from "zustand";-import type { CheckpointKind, Point } from "./officeLayout";-import { courierSession } from "./courierStore";--/**- * `arcade` is a playable arcade cabinet, by furniture id. `team` is a team studio's board, by its- * `Studio.board.id` (`studio-board:<deptId>`); the stage resolves the team through `layout.studios`.- */-export type Selection = { kind: "agent"; id: string } | { kind: "checkpoint"; id: CheckpointKind } | { kind: "arcade"; id: string }- | { kind: "team"; id: string };--/**- * The floors of the building, bottom to top: the Jarvis agents' campus, the- * coding agents one elevator ride up, the arcade hall, and the Level Hall on- * the top floor.- */-export type OfficeFloor = "agents" | "coding" | "arcade" | "hall";--export const OFFICE_FLOORS: readonly OfficeFloor[] = ["agents", "coding", "arcade", "hall"];--/** The floor number shown in the elevator (0 = ground floor). */-export function floorLevel(floor: OfficeFloor): number {- return OFFICE_FLOORS.indexOf(floor);-}--export interface PlayerBody { x: number; z: number; heading: number; path: Point[]; moving: boolean }--/** Agents walking over to a point for a while (called by the person, or a team gathering). */-export interface Summon {- target: Point;- untilMs: number;- /** A team meeting's chair (a `meeting-*` spot id): the agent sits there instead of standing by `target`. */- spotId?: string;-}--/** A team meeting at the team-room table; its members hold summons with a chair each until it ends. */-export interface TeamMeeting {- groupId: string; name: string; members: string[]; untilMs: number;- /** The studio board the team gathers at (`Studio.board.id`); absent = the team room's table. */- boardId?: string;-}--interface OfficeState {- /** The floor on screen; lives here so leaving the map and coming back keeps it. */- floor: OfficeFloor;- /**- * Switch floors: forgets panels, the nearby target, calls and a pending walk- * (they belong to the floor that was left). The character's position is the- * job of `switchFloor` + the scene, because only the new floor plan knows the elevator.- */- setFloor: (floor: OfficeFloor) => void;- selection: Selection | null;- /** The closest thing the character can interact with (E), or null. */- nearby: Selection | null;- /** What the pointer rests on in the world (a station's object, an agent), or null. */- hover: Selection | null;- setHover: (hover: Selection | null) => void;- /** Camera follows the character; any manual pan turns it off, moving turns it back on. */- follow: boolean;- /** One-shot camera fly-to request, consumed by the camera rig. */- focus: { point: Point; seq: number } | null;- summons: Record<string, Summon>;- /** The meeting running in the team room, if any; one at a time. */- meeting: TeamMeeting | null;- /** Seat a team at the table (replacing any running meeting), each member on the chair `seats` gives it. */- startMeeting: (meeting: TeamMeeting, seats: Record<string, { target: Point; spotId?: string }>) => void;- /** End the running meeting: its members go back to their day. */- endMeeting: () => void;- /** One-shot camera dive into a desk monitor (then the chat opens), consumed by the camera rig. */- zoom: { target: [number, number, number]; facing: number; size?: [number, number]; seq: number } | null;- /** Dive into a monitor centred on `target`, whose screen faces yaw `facing`; `size` is the screen in metres (default: a desk monitor). */- zoomInto: (target: [number, number, number], facing: number, size?: [number, number]) => void;- /** One-shot: a Mission Control monitor was clicked; the stage dives in, then opens this app section. */- sectionDive: { section: MonitorSection; seq: number } | null;- /** Dive into a Mission Control monitor, then open the app section it shows. */- diveToSection: (section: MonitorSection, target: [number, number, number], facing: number, size: [number, number]) => void;- /** Walk the character to this point (click-to-move / "walk there"), consumed by the player. */- walkTo: { point: Point; seq: number } | null;- /** Agents picked for a new team, carried from agent panels to the team room. */- teamDraft: string[];- toggleDraft: (agentId: string) => void;- clearDraft: () => void;- clearSummons: () => void;- /** Let these agents go back to their day; other calls and a running meeting stay. */- release: (agentIds: readonly string[]) => void;- select: (selection: Selection | null) => void;- setNearby: (nearby: Selection | null) => void;- setFollow: (follow: boolean) => void;- focusOn: (point: Point) => void;- summon: (agentIds: readonly string[], target: Point, durationMs: number) => void;- requestWalk: (point: Point) => void;-}--/** The app sections Mission Control's desk monitors show live. */-export type MonitorSection = "costs" | "agents" | "agentic-ide";--let seq = 0;--export const useOfficeStore = create<OfficeState>((set) => ({- floor: "agents",- setFloor: (floor) => set((s) => (s.floor === floor ? s : {- floor, selection: null, nearby: null, hover: null, summons: {}, meeting: null, walkTo: null, zoom: null, sectionDive: null, focus: null, teamDraft: [], follow: true,- })),- selection: null,- nearby: null,- hover: null,- // In the courier a click steers the ship: nothing in the office is hovered, picked or walked to meanwhile.- setHover: (hover) => set((s) => (sameSelection(s.hover, hover) || (hover && courierSession.flying) ? s : { hover })),- follow: true,- focus: null,- summons: {},- meeting: null,- startMeeting: (meeting, seats) => set((s) => {- const now = Date.now();- const ended = new Set(s.meeting?.members ?? []);- const next = Object.fromEntries(Object.entries(s.summons).filter(([id, summon]) => summon.untilMs > now && !ended.has(id)));- for (const [id, seat] of Object.entries(seats)) next[id] = { ...seat, untilMs: meeting.untilMs };- return { meeting, summons: next };- }),- endMeeting: () => set((s) => {- if (!s.meeting) return s;- const members = new Set(s.meeting.members);- return { meeting: null, summons: Object.fromEntries(Object.entries(s.summons).filter(([id]) => !members.has(id))) };- }),- walkTo: null,- zoom: null,- zoomInto: (target, facing, size) => set({ zoom: { target, facing, size, seq: ++seq }, follow: false }),- sectionDive: null,- diveToSection: (section, target, facing, size) => set({- zoom: { target, facing, size, seq: ++seq }, sectionDive: { section, seq: ++seq }, follow: false, selection: null,- }),- teamDraft: [],- toggleDraft: (agentId) => set((s) => ({- teamDraft: s.teamDraft.includes(agentId) ? s.teamDraft.filter((id) => id !== agentId) : [...s.teamDraft, agentId],- })),- clearDraft: () => set({ teamDraft: [] }),- clearSummons: () => set({ summons: {}, meeting: null }),- release: (agentIds) => set((s) => {- const gone = new Set(agentIds);- return { summons: Object.fromEntries(Object.entries(s.summons).filter(([id]) => !gone.has(id))) };- }),- select: (selection) => { if (!(selection && courierSession.flying)) set({ selection }); },- setNearby: (nearby) => set((s) => (sameSelection(s.nearby, nearby) ? s : { nearby })),- setFollow: (follow) => set((s) => (s.follow === follow ? s : { follow })),- focusOn: (point) => set({ focus: { point, seq: ++seq }, follow: false }),- summon: (agentIds, target, durationMs) => set((s) => {- const now = Date.now();- const untilMs = now + durationMs;- // Expired calls are dropped here, so the map never grows with old calls.- const next = Object.fromEntries(Object.entries(s.summons).filter(([, summon]) => summon.untilMs > now));- agentIds.forEach((id, i) => {- // Fan the group out around the target so nobody stands inside anybody.- const angle = (i / Math.max(1, agentIds.length)) * Math.PI * 2;- const r = agentIds.length > 1 ? 0.9 + 0.15 * agentIds.length : 1.2;- next[id] = { target: { x: target.x + Math.sin(angle) * r, z: target.z + Math.cos(angle) * r }, untilMs };- });- return { summons: next };- }),- requestWalk: (point) => { if (!courierSession.flying) set({ walkTo: { point, seq: ++seq }, follow: true }); },-}));--/**- * Where the camera looks on the floor, mutated by the camera rig every frame (for the minimap).- * `firstPerson` is true while the camera is (or glides into) the character's eyes at Mission Control:- * whatever flies beside the character, like Gigi, must step out of that view.- */-export const cameraView = { x: 0, z: 0, yaw: 0, halfWidth: 0.5, ready: false, firstPerson: false };--/**- * What the office remembers while the app runs: where the character stands- * and how the camera looked. Leaving the map (e.g. into an agent's chat) and- * coming back puts you where you were; only an app reload starts fresh.- */-export const officeSession: {- playerPlaced: boolean;- camera: { position: [number, number, number]; target: [number, number, number] } | null;- follow: boolean;- /** Where the character stood on each floor when it last left it. */- floors: Partial<Record<OfficeFloor, { x: number; z: number; heading: number }>>;- /**- * A pending arrival: the next floor plan of `floor` places the character- * (at the elevator after a ride, else where it last stood there).- */- arrival: { floor: OfficeFloor; at: "elevator" | "remembered" } | null;-} = { playerPlaced: false, camera: null, follow: true, floors: {}, arrival: null };--/**- * Leave the current floor for `to`: remember where the character stands, then- * switch. `ride` = the elevator (arrive at its doors); otherwise (a mount that- * asks for another floor) the character returns to where it last stood there.- */-export function switchFloor(to: OfficeFloor, ride: boolean): void {- const store = useOfficeStore.getState();- if (store.floor === to) return;- if (officeSession.playerPlaced) officeSession.floors[store.floor] = { x: player.x, z: player.z, heading: player.heading };- officeSession.arrival = { floor: to, at: ride || !officeSession.floors[to] ? "elevator" : "remembered" };- player.path = [];- player.moving = false;- store.setFloor(to);-}--/** The character's body, mutated by the player controller every frame. */-export const player: PlayerBody = { x: 0, z: 0, heading: Math.PI, path: [], moving: false };--export function sameSelection(a: Selection | null, b: Selection | null): boolean {- return a === b || (!!a && !!b && a.kind === b.kind && a.id === b.id);-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeTalk.css b/dodaios/ui/web/frontend/src/components/society/office/officeTalk.cssdeleted file mode 100644index 1d57eca7b1..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeTalk.css+++ /dev/null@@ -1,82 +0,0 @@-/* Talking in the office: the walkie-talkie panel (theme tokens, light + dark) and the- in-world comic bubbles (part of the diorama, one light-paper look in both modes). */--/* ---- bubbles ---------------------------------------------------------- */-.office-bubble { position:absolute; left:0; bottom:10px; transform:translateX(-50%); transform-origin:center bottom; width:max-content; max-width:240px; padding:7px 11px; border-radius:14px; background:#fffdf7; color:#1c1917; border:1.5px solid #1c1917; box-shadow:0 3px 10px rgb(0 0 0 / .35); font-size:12px; line-height:1.35; font-weight:600; font-family:inherit; cursor:pointer; user-select:none; animation:office-bubble-pop .22s cubic-bezier(.2,1.4,.5,1) both; }-.office-bubble p { margin:0; display:-webkit-box; -webkit-line-clamp:5; -webkit-box-orient:vertical; overflow:hidden; overflow-wrap:anywhere; }-.office-bubble-tail { position:absolute; left:50%; bottom:-8px; width:12px; height:12px; margin-left:-6px; background:inherit; border-right:1.5px solid #1c1917; border-bottom:1.5px solid #1c1917; transform:rotate(45deg) skew(8deg, 8deg); border-bottom-right-radius:3px; }-/* Thought: a soft cloud with two puffs trailing down to the head. */-.office-bubble[data-kind="thought"] { border-radius:18px; background:#f1f5ff; border-style:dashed; border-color:#475569; color:#334155; font-weight:500; font-style:italic; max-width:200px; }-.office-bubble-puffs i { position:absolute; left:50%; border-radius:50%; background:#f1f5ff; border:1.5px dashed #475569; }-.office-bubble-puffs i:nth-child(1) { width:10px; height:10px; bottom:-13px; margin-left:-9px; }-.office-bubble-puffs i:nth-child(2) { width:6px; height:6px; bottom:-21px; margin-left:-3px; }-/* Asking: the agent waits for the person. */-.office-bubble[data-kind="ask"] { background:#fff4d6; border-color:#b45309; color:#451a03; }-.office-bubble[data-kind="ask"] .office-bubble-tail { border-color:#b45309; }-.office-bubble[data-kind="ask"] p::before { content:"?"; display:inline-flex; align-items:center; justify-content:center; width:16px; height:16px; margin-right:6px; border-radius:50%; background:#f59e0b; color:#1c1917; font-size:11px; font-weight:800; font-style:normal; vertical-align:-2px; }-.office-bubble[data-kind="error"] { background:#fff1f2; border-color:#be123c; color:#4c0519; }-.office-bubble[data-kind="error"] .office-bubble-tail { border-color:#be123c; }-.office-bubble-dots { display:inline-flex; gap:3px; margin-left:6px; vertical-align:middle; }-.office-bubble-dots i { width:4px; height:4px; border-radius:50%; background:currentColor; opacity:.35; animation:office-bubble-dot 1.2s infinite ease-in-out; }-.office-bubble-dots i:nth-child(2) { animation-delay:.2s; }-.office-bubble-dots i:nth-child(3) { animation-delay:.4s; }-@keyframes office-bubble-dot { 0%, 80%, 100% { opacity:.25; transform:translateY(0); } 40% { opacity:1; transform:translateY(-2px); } }-@keyframes office-bubble-pop { from { opacity:0; margin-bottom:-6px; } to { opacity:1; margin-bottom:0; } }-@media (prefers-reduced-motion:reduce) { .office-bubble, .office-bubble-dots i { animation:none; } .office-bubble-dots i { opacity:.7; } }-/* The lead's memory receipt: which file it is writing, then whether it saved. In-world colours, like the bubble. */-.office-bubble-memory { display:flex; align-items:center; gap:5px; margin-top:5px; padding-top:5px; border-top:1px dashed #94a3b8; color:#334155; font-size:11px; font-style:normal; font-weight:600; line-height:1.3; }-.office-bubble-memory:first-child { margin-top:0; padding-top:0; border-top:0; }-.office-bubble-memory svg { flex:none; width:12px; height:12px; }-.office-bubble-memory-text { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }-.office-bubble-memory[data-phase="pending"] svg { animation:office-bubble-spin 1s linear infinite; }-.office-bubble-memory[data-phase="saved"] { color:#15803d; }-.office-bubble-memory[data-phase="failed"] { color:#be123c; }-@keyframes office-bubble-spin { to { transform:rotate(360deg); } }-@media (prefers-reduced-motion:reduce) { .office-bubble-memory[data-phase="pending"] svg { animation:none; } }--/* ---- the walkie-talkie panel ------------------------------------------ */-.office-talk { gap:0; }-.office-talk-head { display:flex; align-items:center; gap:10px; padding:10px 10px 8px 12px; border-bottom:1px solid hsl(var(--border)); }-.office-talk-avatar { display:inline-flex; flex:none; align-items:center; justify-content:center; width:32px; height:32px; color:#fff; font-size:14px; font-weight:800; clip-path:polygon(25% 3%, 75% 3%, 100% 50%, 75% 97%, 25% 97%, 0 50%); }-.office-talk-who { flex:1; min-width:0; }-.office-talk-who h2 { margin:0; font-size:14px; font-weight:700; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }-.office-talk-who span { display:flex; align-items:center; gap:6px; margin-top:2px; font-size:11px; color:hsl(var(--muted-foreground)); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }-.office-talk-log { list-style:none; margin:0; padding:10px 12px; display:flex; flex-direction:column; gap:6px; flex:1 1 auto; min-height:56px; max-height:260px; overflow:auto; font-size:12px; line-height:1.45; }-.office-talk-empty { margin:auto 0; color:hsl(var(--muted-foreground)); text-align:center; font-size:12px; }-.office-talk-msg { display:flex; }-.office-talk-msg p { margin:0; max-width:88%; padding:6px 10px; border-radius:12px; white-space:pre-wrap; overflow-wrap:anywhere; }-.office-talk-msg[data-from="you"] { justify-content:flex-end; }-.office-talk-msg[data-from="you"] p { background:hsl(var(--primary)); color:hsl(var(--primary-foreground)); border-bottom-right-radius:4px; }-.office-talk-msg[data-from="agent"] p { background:hsl(var(--secondary)); color:hsl(var(--foreground)); border-bottom-left-radius:4px; }-.office-talk-msg[data-live] p { color:hsl(var(--muted-foreground)); font-style:italic; }-.office-talk-msg[data-from="error"] p { background:hsl(var(--destructive) / .12); color:hsl(var(--destructive)); }-.office-talk-alert { display:flex; flex-wrap:wrap; align-items:center; gap:6px; margin:0 12px 8px; padding:6px 9px; border-radius:9px; font-size:12px; background:hsl(var(--warning) / .15); color:hsl(var(--foreground)); }-.office-talk-error { margin:0 12px 6px; font-size:11px; color:hsl(var(--destructive)); }-.office-talk-composer { display:flex; align-items:flex-end; gap:6px; margin:0 10px; padding:5px; border:1px solid hsl(var(--border-strong, var(--border))); border-radius:14px; background:hsl(var(--background)); transition:box-shadow .15s, border-color .15s; }-.office-talk-composer:focus-within { box-shadow:0 0 0 2px hsl(var(--ring) / .5); }-.office-talk-composer[data-listening] { border-color:hsl(var(--success)); box-shadow:0 0 0 3px hsl(var(--success) / .25); }-.office-talk-composer textarea { flex:1; min-width:0; min-height:34px; max-height:120px; resize:none; border:0; padding:8px 4px; background:transparent; color:hsl(var(--foreground)); font:inherit; font-size:13px; line-height:1.35; field-sizing:content; }-.office-talk-composer textarea:focus { outline:none; }-.office-talk-composer textarea::placeholder { color:hsl(var(--muted-foreground)); }-.office-talk-mic, .office-talk-send { display:inline-flex; flex:none; align-items:center; justify-content:center; width:34px; height:34px; border:0; border-radius:10px; cursor:pointer; touch-action:none; }-.office-talk-mic svg, .office-talk-send svg { width:17px; height:17px; }-.office-talk-mic { background:hsl(var(--secondary)); color:hsl(var(--foreground)); }-.office-talk-mic:hover:not(:disabled) { background:hsl(var(--secondary) / .7); }-.office-talk-mic[aria-pressed="true"] { background:hsl(var(--success)); color:hsl(var(--background)); animation:office-talk-live 1.4s ease-in-out infinite; }-.office-talk-send { background:hsl(var(--primary)); color:hsl(var(--primary-foreground)); }-.office-talk-send[data-stop] { background:hsl(var(--secondary)); color:hsl(var(--foreground)); }-.office-talk-send[data-stop] svg { width:13px; height:13px; }-.office-talk-mic:disabled, .office-talk-send:disabled { opacity:.45; cursor:not-allowed; }-.office-talk-mic:focus-visible, .office-talk-send:focus-visible, .office-talk-tools button:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }-@keyframes office-talk-live { 0%, 100% { box-shadow:0 0 0 0 hsl(var(--success) / .45); } 50% { box-shadow:0 0 0 6px hsl(var(--success) / 0); } }-.office-talk-status { margin:5px 14px 0; min-height:16px; font-size:11px; color:hsl(var(--muted-foreground)); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }-.office-talk-status[data-listening] { color:hsl(var(--success)); font-weight:600; }-.office-talk-tools { display:grid; grid-template-columns:repeat(5, 1fr); gap:2px; margin:8px 6px 8px; padding-top:6px; border-top:1px solid hsl(var(--border)); }-.office-talk-tools button { display:flex; flex-direction:column; align-items:center; gap:3px; min-width:0; padding:6px 2px; border:0; border-radius:9px; background:none; color:hsl(var(--muted-foreground)); font-size:10px; font-weight:600; cursor:pointer; }-.office-talk-tools button svg { width:16px; height:16px; }-.office-talk-tools button span { max-width:100%; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }-.office-talk-tools button:hover:not(:disabled) { background:hsl(var(--secondary)); color:hsl(var(--foreground)); }-.office-talk-tools button[aria-pressed="true"] { color:hsl(var(--primary)); background:hsl(var(--secondary)); }-.office-talk-tools button:disabled { opacity:.4; cursor:not-allowed; }-.office-talk-note { margin:0 14px 10px; }-@media (prefers-reduced-motion:reduce) { .office-talk-mic[aria-pressed="true"] { animation:none; } }diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeTalk.test.ts b/dodaios/ui/web/frontend/src/components/society/office/officeTalk.test.tsdeleted file mode 100644index 29ccb3e955..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeTalk.test.ts+++ /dev/null@@ -1,83 +0,0 @@-import { describe, expect, it } from "vitest";-import type { TimelineItem, TurnItem } from "@/components/agentchat/reduce";-import { EMPTY_TIMELINE } from "@/components/agentchat/reduce";-import { ambientBubble, bubbleText, conversationBubble, itemsFor, type BubbleLabels } from "./officeTalk";--const LABELS: BubbleLabels = {- thinking: "Thinking", tool: "Using {0}", failed: "Failed", cancelled: "Stopped", done: "Done", approval: "Need OK", waiting: "Waiting",-};--function turn(patch: Partial<TurnItem>): TurnItem {- return {- type: "turn", id: "t1", provider: "p", model: "m", effort: "", runner: "api", status: "done", blocks: [],- startedMs: 1000, durationMs: 500, usage: null, liveUsage: null, costUsd: null, error: null, ...patch,- };-}--const user: TimelineItem = { type: "user", id: "u1", text: "Hi", attachments: [], tsMs: 900 };--describe("bubbleText", () => {- it("strips markdown and flattens whitespace", () => {- expect(bubbleText("## Plan\n- **Fix** the `login` [bug](http://x)\n\n```js\ncode()\n```")).toBe("Plan Fix the login bug");- });-- it("cuts long text at a word boundary with an ellipsis", () => {- const out = bubbleText("word ".repeat(80), 40);- expect(out.length).toBeLessThanOrEqual(40);- expect(out.endsWith("…")).toBe(true);- expect(out).not.toMatch(/\s…$/);- });-});--describe("conversationBubble", () => {- it("is empty before anything was said", () => {- expect(conversationBubble([], 0, LABELS)).toBeNull();- });-- it("thinks while the sent message waits for its turn", () => {- expect(conversationBubble([user], 0, LABELS)).toMatchObject({ kind: "thought", text: "Thinking", live: true });- });-- it("names the running tool in a thought bubble", () => {- const running = turn({ status: "running", blocks: [{ kind: "tool", callId: "c", name: "mcp__jarvis__web_search", input: {}, output: null, isError: false, durationMs: null, approval: null, startedMs: 1 }] });- expect(conversationBubble([user, running], 0, LABELS)).toMatchObject({ kind: "thought", text: "Using web_search", live: true });- });-- it("speaks the streaming text live, then the finished reply", () => {- const streaming = turn({ status: "running", blocks: [{ kind: "text", id: "x", text: "Working on **it**" }] });- expect(conversationBubble([user, streaming], 0, LABELS)).toMatchObject({ kind: "speech", text: "Working on it", live: true });- const done = turn({ blocks: [{ kind: "text", id: "x", text: "All done." }] });- expect(conversationBubble([user, done], 0, LABELS)).toEqual({ kind: "speech", text: "All done.", live: false, atMs: 1500 });- });-- it("reports a failed turn and asks when an approval is pending", () => {- expect(conversationBubble([turn({ status: "error", error: "Rate limited" })], 0, LABELS)).toMatchObject({ kind: "error", text: "Rate limited" });- expect(conversationBubble([user], 1, LABELS)).toMatchObject({ kind: "ask", text: "Need OK" });- });-});--describe("itemsFor", () => {- const timeline = { ...EMPTY_TIMELINE, items: [user] };- it("reads a specialist's items only from its own open session", () => {- expect(itemsFor({ tier: "specialist", chatSessionId: "s1" }, "s1", timeline)).toEqual([user]);- expect(itemsFor({ tier: "specialist", chatSessionId: "s1" }, "s2", timeline)).toEqual([]);- expect(itemsFor({ tier: "specialist", chatSessionId: null }, null, timeline)).toEqual([]);- });-- it("reads the lead from the Jarvis chat", () => {- expect(itemsFor({ tier: "lead", chatSessionId: null }, "any", timeline)).toEqual([user]);- });-});--describe("ambientBubble", () => {- it("lets working agents think about their current step", () => {- expect(ambientBubble("working", [{ kind: "tool", text: "read_file" }], LABELS)).toMatchObject({ kind: "thought", text: "Using read_file" });- expect(ambientBubble("working", undefined, LABELS)).toMatchObject({ kind: "thought", text: "Thinking" });- });-- it("lets waiting agents ask, and keeps idle agents quiet", () => {- expect(ambientBubble("waiting", [{ kind: "agent", text: "Which repo?" }, { kind: "tool", text: "x" }], LABELS)).toMatchObject({ kind: "ask", text: "Which repo?" });- expect(ambientBubble("waiting", [], LABELS)).toMatchObject({ kind: "ask", text: "Waiting" });- expect(ambientBubble("idle", [{ kind: "agent", text: "hi" }], LABELS)).toBeNull();- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeTalk.ts b/dodaios/ui/web/frontend/src/components/society/office/officeTalk.tsdeleted file mode 100644index 1b3a7b525b..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeTalk.ts+++ /dev/null@@ -1,144 +0,0 @@-/**- * Talking to an agent inside the office, without leaving the map.- *- * The person picks an agent and speaks (or types); the words go into that- * agent's own canonical chat — the same session the chat view shows — and the- * answer comes back as a bubble over the agent's head: a thought bubble while- * it works, a speech bubble with its reply once it is done.- *- * Specialists share one office-only chat store (its own socket through the- * shared connect budget), so the chat the rest of the app has open is never- * switched underneath it. The lead is Jarvis itself and answers in the Jarvis- * chat store, exactly like the lead's card does.- *- * The bubble text is derived here, pure and tested (`officeTalk.test.ts`).- */-import { create } from "zustand";-import { createAgentChatStore, useAgentChatStore, type AgentChatStoreHook } from "@/store/agentChat";-import type { Timeline, TimelineItem, TurnItem } from "@/components/agentchat/reduce";-import type { SocietyAgent } from "../data";-import { toolLabel, type ChatLine } from "./deskChat";--/** One socket for every specialist the person talks to in the office. */-export const officeTalkChat: AgentChatStoreHook = createAgentChatStore("society", "office-talk");--/** The chat store an agent answers in: the lead speaks through Jarvis's own chat. */-export function talkStoreFor(agent: Pick<SocietyAgent, "tier">): AgentChatStoreHook {- return agent.tier === "lead" ? useAgentChatStore : officeTalkChat;-}--/** A spoken line the person's character shows over its head. */-export interface PlayerLine { text: string; atMs: number }--interface TalkState {- /** The agent the person is talking to right now; its bubble follows that chat. */- agentId: string | null;- /** The microphone is open for the office (push-to-talk or tap). */- listening: boolean;- /** Last thing the person said, shown over their character for a moment. */- playerLine: PlayerLine | null;- setAgent: (agentId: string | null) => void;- setListening: (listening: boolean) => void;- say: (text: string) => void;-}--export const useOfficeTalk = create<TalkState>((set) => ({- agentId: null,- listening: false,- playerLine: null,- setAgent: (agentId) => set((s) => (s.agentId === agentId ? s : { agentId })),- setListening: (listening) => set((s) => (s.listening === listening ? s : { listening })),- say: (text) => set({ playerLine: { text, atMs: Date.now() } }),-}));--/** How long a finished reply stays over the agent's head once its panel is closed. */-export const REPLY_LINGER_MS = 20_000;-/** How long the person's own line stays over their character. */-export const PLAYER_LINE_MS = 7_000;--export type BubbleKind = "thought" | "speech" | "ask" | "error";--export interface Bubble {- kind: BubbleKind;- text: string;- /** Still streaming or working: the bubble shows its "…" and never expires. */- live: boolean;- /** When the content was last settled; a finished bubble expires from here. */- atMs: number;-}--/**- * Plain text for a small bubble: markdown marks, code fences and link targets- * removed, whitespace flattened, cut at a word boundary with an ellipsis.- */-export function bubbleText(raw: string, max = 220): string {- const plain = raw- .replace(/```[\s\S]*?```/g, " ")- .replace(/`([^`]*)`/g, "$1")- .replace(/!\[[^\]]*]\([^)]*\)/g, " ")- .replace(/\[([^\]]+)]\([^)]*\)/g, "$1")- .replace(/^\s{0,3}(#{1,6}|>|[-*+]|\d+\.)\s+/gm, "")- .replace(/(\*\*|__|~~|\*|_)(?=\S)([^*_~]+?)\1/g, "$2")- .replace(/\s+/g, " ")- .trim();- if (plain.length <= max) return plain;- const cut = plain.slice(0, max - 1);- const space = cut.lastIndexOf(" ");- return `${(space > max * 0.6 ? cut.slice(0, space) : cut).replace(/[\s,.;:]+$/, "")}…`;-}--/** The items the office may read: only the agent's own session, never whatever else the store holds. */-export function itemsFor(agent: Pick<SocietyAgent, "tier" | "chatSessionId">, activeSessionId: string | null, timeline: Timeline): TimelineItem[] {- if (agent.tier === "lead") return timeline.items;- return agent.chatSessionId && agent.chatSessionId === activeSessionId ? timeline.items : [];-}--export function turnBubble(turn: TurnItem, labels: BubbleLabels): Bubble {- const last = turn.blocks[turn.blocks.length - 1];- if (turn.status === "running") {- if (last?.kind === "text" && last.text.trim()) return { kind: "speech", text: bubbleText(last.text, 160), live: true, atMs: turn.startedMs };- if (last?.kind === "tool") return { kind: "thought", text: labels.tool.replace("{0}", toolLabel(last.name)), live: true, atMs: turn.startedMs };- const thinking = last?.kind === "reasoning" && last.text.trim() ? bubbleText(last.text.slice(-240), 90) : "";- return { kind: "thought", text: thinking || labels.thinking, live: true, atMs: turn.startedMs };- }- const settled = turn.startedMs + (turn.durationMs ?? 0);- if (turn.status === "error") return { kind: "error", text: bubbleText(turn.error || labels.failed, 140), live: false, atMs: settled };- const text = [...turn.blocks].reverse().find((b) => b.kind === "text" && b.text.trim());- if (text && text.kind === "text") return { kind: "speech", text: bubbleText(text.text), live: false, atMs: settled };- if (turn.status === "cancelled") return { kind: "thought", text: labels.cancelled, live: false, atMs: settled };- return { kind: "speech", text: labels.done, live: false, atMs: settled };-}--export interface BubbleLabels { thinking: string; tool: string; failed: string; cancelled: string; done: string; approval: string; waiting: string }--/** What the agent the person talks to shows over its head, from its live chat. */-export function conversationBubble(items: readonly TimelineItem[], pendingApprovals: number, labels: BubbleLabels): Bubble | null {- if (pendingApprovals > 0) return { kind: "ask", text: labels.approval, live: true, atMs: Date.now() };- for (let i = items.length - 1; i >= 0; i -= 1) {- const item = items[i];- if (item.type === "turn") return turnBubble(item, labels);- // Sent, and the turn has not started yet: the agent is already mulling it over.- if (item.type === "user") return { kind: "thought", text: labels.thinking, live: true, atMs: item.tsMs };- if (item.type === "error") return { kind: "error", text: bubbleText(item.text, 140), live: false, atMs: item.tsMs };- }- return null;-}--/**- * What every other agent thinks out loud, from the tail its desk monitor- * already polls: working agents think about their current step, waiting- * agents ask. Idle agents keep quiet — the office must not turn into noise.- */-export function ambientBubble(state: SocietyAgent["state"], lines: readonly ChatLine[] | undefined, labels: Pick<BubbleLabels, "tool" | "thinking" | "waiting">): Bubble | null {- const last = lines && lines.length > 0 ? lines[lines.length - 1] : null;- if (state === "working") {- if (last?.kind === "tool") return { kind: "thought", text: labels.tool.replace("{0}", bubbleText(last.text, 48)), live: true, atMs: 0 };- if (last?.kind === "agent") return { kind: "thought", text: bubbleText(last.text, 70), live: true, atMs: 0 };- return { kind: "thought", text: labels.thinking, live: true, atMs: 0 };- }- if (state === "waiting") {- const asked = lines ? [...lines].reverse().find((l) => l.kind === "agent") : undefined;- return { kind: "ask", text: asked ? bubbleText(asked.text, 90) : labels.waiting, live: true, atMs: 0 };- }- return null;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeTeams.test.ts b/dodaios/ui/web/frontend/src/components/society/office/officeTeams.test.tsdeleted file mode 100644index f8c0ae6121..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeTeams.test.ts+++ /dev/null@@ -1,123 +0,0 @@-import { describe, expect, it } from "vitest";-import { allDesks, chairRect, deskRect, seatOf, type DeskSlot, type Point, type Rect } from "./officeLayout";-import { type Mover } from "./officeMotion";-import { isWalkable } from "./officeNav";-import { PERSON_CLEAR_M, standingPlaceFor } from "./officeTeams";-import { advanceWalk, beginWalk } from "./officeWalk";-import { SEAT_REACH } from "./leadSeat";-import { campusOf } from "./officeFixtures";--// Fourteen agents, a team of five and a team of four; everybody sits at their desk.-const campus = campusOf(14, [5, 4]);-const benchDesks = allDesks(campus.layout).filter((d) => !d.size);-const occupied = benchDesks.filter((d) => d.agentId);-const seated: Point[] = occupied.map((d) => { const seat = seatOf(d); return { x: seat.x, z: seat.z }; });-const inside = (rect: Rect, p: Point) => p.x > rect.minX && p.x < rect.maxX && p.z > rect.minZ && p.z < rect.maxZ;--/** A place the person may stand on: floor, outside every chair and desk, and beside everybody rather than in them. */-function expectStandingPlace(place: Point | null, label: string): asserts place is Point {- expect(place, label).not.toBeNull();- expect(isWalkable(campus.grid, place!), label).toBe(true);- for (const desk of benchDesks) {- expect(inside(chairRect(seatOf(desk)), place!), `${label} in the chair of ${desk.id}`).toBe(false);- expect(inside(deskRect(desk), place!), `${label} in the desk ${desk.id}`).toBe(false);- }- for (const body of seated) expect(Math.hypot(body.x - place!.x, body.z - place!.z), label).toBeGreaterThanOrEqual(PERSON_CLEAR_M);-}--/** Walk the person's character to wherever a click on \`goal\` resolves, as OfficePlayer does; returns where it ends. */-function clickAndWalk(goal: Point, from: Point = campus.layout.spawn): Point {- const place = standingPlaceFor(campus.layout, campus.grid, goal, seated)!;- const m: Mover = { x: from.x, z: from.z, heading: 0, path: [] };- const walk = beginWalk(campus.grid, m, place, seated)!;- for (let i = 0; i < 60 * 240; i += 1) {- const step = advanceWalk(walk, m, campus.grid, 1 / 60, seated, { speed: 2, place: false });- if (step.arrived || step.event === "blocked" || step.event === "lost") break;- }- return { x: m.x, z: m.z };-}--describe("where a click sends the person", () => {- it("is the clicked point itself on free floor", () => {- const goal = campus.layout.arrival;- expect(standingPlaceFor(campus.layout, campus.grid, goal, seated)).toEqual({ x: goal.x, z: goal.z });- });-- it("is a place beside the chair for a click on a seated agent, never the chair or the agent", () => {- for (const desk of occupied) {- const seat = seatOf(desk);- // On the figure, a little off its centre, as a click on it lands.- for (const goal of [{ x: seat.x + 0.3, z: seat.z + 0.2 }, { x: seat.x, z: seat.z }, { x: seat.x - 0.2, z: seat.z - 0.1 }]) {- const place = standingPlaceFor(campus.layout, campus.grid, goal, seated);- expectStandingPlace(place, desk.id);- // Beside this desk, within a step or two of what was clicked.- expect(Math.hypot(place.x - seat.x, place.z - seat.z), desk.id).toBeLessThan(1.4);- }- }- });-- it("walks there and ends beside the seated agent, on its feet", () => {- for (const desk of occupied.slice(0, 6)) {- const seat = seatOf(desk);- const end = clickAndWalk({ x: seat.x + 0.3, z: seat.z + 0.2 });- expectStandingPlace(end, desk.id);- expect(Math.hypot(end.x - seat.x, end.z - seat.z), desk.id).toBeLessThan(1.4);- }- });-- it("is a place at the desk for a click on a desk top", () => {- for (const desk of benchDesks.slice(0, 10)) {- const place = standingPlaceFor(campus.layout, campus.grid, { x: desk.x + 0.1, z: desk.z }, seated);- expectStandingPlace(place, desk.id);- expect(Math.hypot(place.x - desk.x, place.z - desk.z), desk.id).toBeLessThan(2.2);- expectStandingPlace(clickAndWalk({ x: desk.x + 0.1, z: desk.z }), desk.id);- }- });-- it("does not sit the person on an empty chair either: it stands beside it", () => {- const empty: DeskSlot[] = benchDesks.filter((d) => !d.agentId);- expect(empty.length).toBeGreaterThan(0);- for (const desk of empty) {- const seat = seatOf(desk);- const place = standingPlaceFor(campus.layout, campus.grid, { x: seat.x, z: seat.z }, seated);- expectStandingPlace(place, desk.id);- expect(Math.hypot(place.x - seat.x, place.z - seat.z), desk.id).toBeGreaterThan(0.5);- expect(Math.hypot(place.x - seat.x, place.z - seat.z), desk.id).toBeLessThan(1.4);- expectStandingPlace(clickAndWalk({ x: seat.x, z: seat.z }), desk.id);- }- });-- it("steps aside when a visitor already stands in the place beside the chair", () => {- const desk = occupied[0];- const seat = seatOf(desk);- const first = standingPlaceFor(campus.layout, campus.grid, seat, seated)!;- const second = standingPlaceFor(campus.layout, campus.grid, seat, [...seated, first]);- expectStandingPlace(second, desk.id);- expect(Math.hypot(second.x - first.x, second.z - first.z)).toBeGreaterThanOrEqual(PERSON_CLEAR_M);- });-- it("stops beside a standing agent instead of in it", () => {- const agent = campus.layout.arrival;- const place = standingPlaceFor(campus.layout, campus.grid, { x: agent.x + 0.1, z: agent.z }, [agent])!;- expect(isWalkable(campus.grid, place)).toBe(true);- expect(Math.hypot(place.x - agent.x, place.z - agent.z)).toBeGreaterThanOrEqual(PERSON_CLEAR_M);- expect(Math.hypot(place.x - agent.x, place.z - agent.z)).toBeLessThan(1.3);- });-- it("still brings the person within reach of the lead's chair, which has its own sit action", () => {- for (const desk of campus.layout.lead.desks) {- const seat = seatOf(desk);- const place = standingPlaceFor(campus.layout, campus.grid, seat, seated)!;- expect(isWalkable(campus.grid, place)).toBe(true);- expect(Math.hypot(place.x - seat.x, place.z - seat.z)).toBeLessThanOrEqual(SEAT_REACH);- }- });-- it("finds floor beside any piece of furniture that was clicked", () => {- for (const item of campus.layout.furniture.slice(0, 40)) {- const place = standingPlaceFor(campus.layout, campus.grid, { x: item.x, z: item.z }, seated);- expect(place, item.id).not.toBeNull();- expect(isWalkable(campus.grid, place!), item.id).toBe(true);- }- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeTeams.ts b/dodaios/ui/web/frontend/src/components/society/office/officeTeams.tsdeleted file mode 100644index 6784229d96..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeTeams.ts+++ /dev/null@@ -1,220 +0,0 @@-/**- * Where an agent belongs on the agents floor: its team's studio, the places- * round the studio board, and where a visitor stands at a teammate's desk.- *- * Studios come from the floor plan (`layout.studios`); a floor without them- * (the coding floor, the arcade) simply has no homes, and every caller keeps- * its studio-less behaviour. Pure.- */-import { chairRect, DESK_PITCH_X, deskRect, seatOf, type DeskSlot, type OfficeLayout, type Point, type Rect, type Studio } from "./officeLayout";-import { clearOfBodies } from "./officeMotion";-import { isWalkable, nearestWalkable, type NavGrid } from "./officeNav";--/** A place a figure can stand on that the floor plan does not list as a spot; reserved through the same book by its id. */-export interface Place extends Point { id: string; facing: number }--interface StudioIndex {- studios: readonly Studio[];- byAgent: Map<string, Studio>;- byDept: Map<string, Studio>;- byTeam: Map<string, Studio>;- deptOfDesk: Map<string, string>;-}--const indexCache = new WeakMap<OfficeLayout, StudioIndex>();--function indexOf(layout: OfficeLayout): StudioIndex {- let index = indexCache.get(layout);- if (!index) {- const studios = layout.studios ?? [];- index = {- studios,- byAgent: new Map(studios.flatMap((s) => s.members.map((id) => [id, s] as const))),- byDept: new Map(studios.map((s) => [s.deptId, s])),- byTeam: new Map(studios.filter((s) => s.teamId !== null).map((s) => [s.teamId as string, s])),- deptOfDesk: new Map(layout.departments.flatMap((d) => d.desks.map((desk) => [desk.id, d.id] as const))),- };- indexCache.set(layout, index);- }- return index;-}--/** The floor's studios; empty where the floor plan has none. */-export function studiosOf(layout: OfficeLayout): readonly Studio[] {- return indexOf(layout).studios;-}--/** The studio an agent belongs to: the one that lists it, else the one its desk stands in. Null without studios. */-export function homeStudio(layout: OfficeLayout, agentId: string, desk: Pick<DeskSlot, "id"> | null): Studio | null {- const index = indexOf(layout);- if (index.studios.length === 0) return null;- const listed = index.byAgent.get(agentId);- if (listed) return listed;- const dept = desk ? index.deptOfDesk.get(desk.id) : undefined;- return dept ? index.byDept.get(dept) ?? null : null;-}--export function studioOfTeam(layout: OfficeLayout, teamId: string): Studio | null {- return indexOf(layout).byTeam.get(teamId) ?? null;-}--/** The studio's floor: its department's rectangle, or a square round its centre when the department is gone. */-export function studioRect(layout: OfficeLayout, studio: Studio): Rect {- const dept = layout.departments.find((d) => d.id === studio.deptId);- if (dept) return { minX: dept.minX, maxX: dept.maxX, minZ: dept.minZ, maxZ: dept.maxZ };- return { minX: studio.centre.x - 4, maxX: studio.centre.x + 4, minZ: studio.centre.z - 4, maxZ: studio.centre.z + 4 };-}--/** The desks of an agent's studio mates (everyone seated in the same studio, itself excluded). */-export function mateDesks(layout: OfficeLayout, studio: Studio, agentId: string): DeskSlot[] {- const dept = layout.departments.find((d) => d.id === studio.deptId);- if (!dept) return [];- const members = new Set(studio.members);- return dept.desks.filter((d) => d.agentId !== null && d.agentId !== agentId && members.has(d.agentId));-}--/**- * Where a visitor stands relative to the chair: in the middle of the gap to the next chair, east or west, a- * small step back from the chairs' line (the desk's clearance reaches just past that line). There it is out of- * the aisle behind the chairs, which stays free for everyone walking to a seat, and out of the way the seated- * colleague gets up (straight back), even with a visitor on either side.- */-const VISIT_SIDE_M = DESK_PITCH_X / 2;-const VISIT_BACK_M = 0.3;--/**- * Where visitors stand at a desk: between its chair and the next one, east- * and west. Only places on walkable ground count. The gap between two chairs- * belongs to both desks, so a place's id is its position (`visit:<x>,<z>`):- * the visitors of two neighbouring desks can never be given the same patch of- * floor. A place is a step from where the owner of the desk to its west stands- * while it waits for the person; that owner holds the place meanwhile, and- * callers skip one somebody already stands at.- */-export function visitSlots(desk: DeskSlot, grid: NavGrid): Place[] {- const seat = seatOf(desk);- // Behind the chair is away from the desk.- const back = desk.facing === "north" ? 1 : -1;- const candidates: Point[] = [- { x: seat.x + VISIT_SIDE_M, z: seat.z + back * VISIT_BACK_M },- { x: seat.x - VISIT_SIDE_M, z: seat.z + back * VISIT_BACK_M },- ];- return candidates.flatMap((p) => (isWalkable(grid, p)- ? [{ id: `visit:${p.x.toFixed(2)},${p.z.toFixed(2)}`, x: p.x, z: p.z, facing: Math.atan2(seat.x - p.x, seat.z - p.z) }]- : []));-}--/** The person's character keeps this far from everybody when a click sends it somewhere: beside a figure, never in it. */-export const PERSON_CLEAR_M = 0.75;-/** A click this close to a bench desk's chair or top means that desk. */-const DESK_CLICK_MARGIN_M = 0.3;-/** How far behind a chair the person stands when both places beside it are taken. */-const BEHIND_CHAIR_M = 1.0;--function within(rect: Rect, p: Point, margin: number): boolean {- return p.x >= rect.minX - margin && p.x <= rect.maxX + margin && p.z >= rect.minZ - margin && p.z <= rect.maxZ + margin;-}--/**- * Where the person's character stands when a click (or "walk there") names- * `goal`. Free floor is the goal itself. A click on a bench desk, on its- * chair or on whoever sits there resolves to a standing place at that desk:- * beside the chair where a visiting colleague would stand, else behind it.- * Anything else solid or occupied (a couch, a counter, a standing agent)- * resolves to the nearest free floor beside it. The person never ends up on a- * chair, in a desk or inside a figure; taking a seat is its own action (the- * executive chair and Mission Control's chair have one).- *- * `bodies` are everybody else's positions. Null only when there is no floor- * within reach at all.- */-export function standingPlaceFor(layout: OfficeLayout, grid: NavGrid, goal: Point, bodies: readonly Point[]): Point | null {- const free = (p: Point) => isWalkable(grid, p) && clearOfBodies(p, bodies, PERSON_CLEAR_M);- if (free(goal)) return { x: goal.x, z: goal.z };- const nearest = (candidates: readonly Point[]): Point | null => candidates.filter(free)- .reduce<Point | null>((best, p) => (!best || Math.hypot(p.x - goal.x, p.z - goal.z) < Math.hypot(best.x - goal.x, best.z - goal.z) ? p : best), null);-- // A bench desk (sittable desks carry a size and keep their own sit action).- const desk = layout.departments.flatMap((d) => d.desks)- .filter((d) => within(deskRect(d), goal, DESK_CLICK_MARGIN_M) || within(chairRect(seatOf(d)), goal, DESK_CLICK_MARGIN_M))- .reduce<DeskSlot | null>((best, d) => {- const seat = seatOf(d);- return !best || Math.hypot(seat.x - goal.x, seat.z - goal.z) < Math.hypot(seatOf(best).x - goal.x, seatOf(best).z - goal.z) ? d : best;- }, null);- if (desk) {- const seat = seatOf(desk);- const back = desk.facing === "north" ? 1 : -1;- const beside = nearest([...visitSlots(desk, grid), { x: seat.x, z: seat.z + back * BEHIND_CHAIR_M }]);- if (beside) return { x: beside.x, z: beside.z };- }- // The nearest floor to the goal, when nobody is in the way there (the executive chair is sat on from it).- const cell = nearestWalkable(grid, goal, 1.2);- if (cell && free(cell)) return cell;- // Else the nearest free floor round the goal, ring by ring.- for (let radius = 0.2; radius <= 3.01; radius += 0.2) {- const ring: Point[] = [];- for (let i = 0; i < 16; i += 1) {- const angle = (i / 16) * Math.PI * 2;- ring.push({ x: goal.x + Math.sin(angle) * radius, z: goal.z + Math.cos(angle) * radius });- }- const found = nearest(ring);- if (found) return found;- }- // Crowded all round: free ground at least; the walk stops beside whoever stands there.- return nearestWalkable(grid, goal);-}--/**- * The arcs a team stands in at its board: each row's distance from the board- * and the angles (degrees off the board's centre line) of its places. Every- * place is more than a metre from its neighbours in the row and from the rows- * before and behind it, so name plates and bubbles stay apart and the person- * can walk in between. The first row is a conversation's distance from the- * board; the rows behind it look over its shoulders (the angles interleave).- */-export const HUDDLE_ARCS: readonly { radius: number; angles: readonly number[] }[] = [- { radius: 2.2, angles: [-14, 14, -42, 42] },- { radius: 3.3, angles: [0, -20, 20, -40, 40, -60, 60] },- { radius: 4.4, angles: [-7.5, 7.5, -22.5, 22.5, -37.5, 37.5] },-];-/**- * The lead's place in a gathering at the board: the place of the front arc- * nearest the board's centre line. Null for a studio without a lead (then the- * arcs have no special place at all) or without a walkable front arc.- */-export function leadPlace(places: readonly Place[], studio: Pick<Studio, "deptId" | "leadId" | "board">): Place | null {- const board = studio.board;- if (!studio.leadId || !board) return null;- const front = places.filter((p) => p.id.startsWith(`fan:${studio.deptId}:0:`));- // How far to the side of the board's centre line a place lies.- const aside = (p: Place) => Math.abs((p.x - board.x) * Math.cos(board.facing) - (p.z - board.z) * Math.sin(board.facing));- return front.reduce<Place | null>((best, p) => (!best || aside(p) < aside(best) - 1e-6 ? p : best), null);-}--/** The least two places of the arcs are apart; the tests hold the geometry to it. */-export const HUDDLE_SPACE_M = 1.05;--/**- * Everywhere a team can stand at its board: loose arcs round it, each place- * facing the board (ids `fan:<deptId>:<row>:<n>`), the row nearest the board- * first. Only places on walkable ground count. Empty for a studio without a- * board. The floor plan's own huddle spots mark where the huddle is; the arcs- * are where people actually stand, with room between them.- */-export function huddlePlaces(_layout: OfficeLayout, grid: NavGrid, studio: Studio): Place[] {- if (!studio.board) return [];- const { x: bx, z: bz, facing } = studio.board;- const nx = Math.sin(facing), nz = Math.cos(facing);- // The board's own right-hand direction on the floor.- const tx = nz, tz = -nx;- const places: Place[] = [];- HUDDLE_ARCS.forEach((arc, row) => {- arc.angles.forEach((degrees, n) => {- const a = (degrees * Math.PI) / 180;- const along = Math.cos(a) * arc.radius, across = Math.sin(a) * arc.radius;- const p = { x: bx + nx * along + tx * across, z: bz + nz * along + tz * across };- if (isWalkable(grid, p)) places.push({ id: `fan:${studio.deptId}:${row}:${n}`, x: p.x, z: p.z, facing: Math.atan2(bx - p.x, bz - p.z) });- });- });- return places;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeWalk.test.ts b/dodaios/ui/web/frontend/src/components/society/office/officeWalk.test.tsdeleted file mode 100644index fd7476a641..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeWalk.test.ts+++ /dev/null@@ -1,312 +0,0 @@-import { describe, expect, it } from "vitest";-import type { Point } from "./officeLayout";-import { BODY_SPACING, BRISK_SPEED, WALK_SPEED, wrapAngle, type Mover } from "./officeMotion";-import { findPath, isWalkable, type NavGrid } from "./officeNav";-import { advanceWalk, beginWalk, findDetour, pathLength, PLACE_WITHIN_M, routeMarks, safePlacement, type Walk, type WalkEvent } from "./officeWalk";-import { campusOf, roomGrid, wallWithDoor } from "./officeFixtures";--const DT = 1 / 60;--interface Trace { seconds: number; events: WalkEvent[]; offFloor: number; sideways: number; arrived: boolean }--/** Walk `m` to the end of `walk`, checking every frame that it stays on the floor and faces where it goes. */-function walkThrough(walk: Walk, m: Mover, grid: () => NavGrid, bodies: () => Point[], limitS = 400, options: { place?: boolean; far?: boolean } = {}): Trace {- const trace: Trace = { seconds: 0, events: [], offFloor: 0, sideways: 0, arrived: false };- const start = { x: m.x, z: m.z };- while (trace.seconds < limitS) {- const before = { x: m.x, z: m.z };- const step = advanceWalk(walk, m, grid(), DT, bodies(), options);- trace.seconds += DT;- if (step.event) trace.events.push(step.event);- if (step.event !== "rescue" && step.moved > 1e-6) {- // Metres covered while facing more than about 60° away from the direction of travel: gliding.- const off = Math.abs(wrapAngle(Math.atan2(m.x - before.x, m.z - before.z) - m.heading));- if (off > 1.05) trace.sideways += step.moved;- // The first steps out of a seat and the last onto one cross its footprint; everything between is floor.- const nearEnds = Math.hypot(m.x - start.x, m.z - start.z) < 1.2 || Math.hypot(m.x - walk.target.x, m.z - walk.target.z) < 1.2;- if (!nearEnds && !isWalkable(grid(), m)) trace.offFloor += 1;- }- if (step.arrived) { trace.arrived = true; break; }- if (step.event === "lost" || step.event === "blocked") break;- }- return trace;-}--const mover = (at: Point): Mover => ({ x: at.x, z: at.z, heading: Math.PI, path: [] });--describe("an agent's pace on real routes", () => {- it("covers a route from the lobby to a desk at the walking pace or better, corners and all", () => {- const { layout, grid } = campusOf(14, [5, 4]);- const desks = layout.departments.flatMap((d) => d.desks).filter((d) => d.agentId);- const seats = desks.map((d) => ({ x: d.x, z: d.facing === "north" ? d.z + 0.62 : d.z - 0.62 }));- for (const [i, seat] of seats.entries()) {- // Everybody else sits at their desk while this one walks in.- const others = seats.filter((_, j) => j !== i);- const m = mover(layout.spawn);- const walk = beginWalk(grid, m, seat, others)!;- const trace = walkThrough(walk, m, () => grid, () => others);- expect(trace.arrived, `desk ${i}`).toBe(true);- // Metres of route per second of the walker's own clock.- expect(walk.length / trace.seconds, `desk ${i}`).toBeGreaterThan(WALK_SPEED);- expect(walk.length / trace.seconds, `desk ${i}`).toBeLessThanOrEqual(BRISK_SPEED);- }- });-});--describe("a walk across the campus", () => {- it("takes a long diagonal route across a large floor without leaving it, gliding or getting stuck", () => {- const { layout, grid } = campusOf(60, [10, 9, 8, 7, 6, 6]);- // The two hangout places furthest apart: one corner of the campus to the other.- const spots = layout.spots.filter((s) => s.kind !== "huddle");- const from = spots.reduce((a, b) => (a.x + a.z < b.x + b.z ? a : b));- const to = spots.reduce((a, b) => (a.x + a.z > b.x + b.z ? a : b));- const m = mover(from);- const walk = beginWalk(grid, m, to)!;- expect(walk).not.toBeNull();- expect(walk.length).toBeGreaterThan(40);- const trace = walkThrough(walk, m, () => grid, () => []);- expect(trace.arrived).toBe(true);- expect(m.x).toBe(to.x);- expect(m.z).toBe(to.z);- expect(trace.offFloor).toBe(0);- expect(trace.sideways).toBeLessThan(0.2);- expect(trace.events.filter((e) => e === "rescue" || e === "replan")).toEqual([]);- // Brisk on the long legs: clearly faster than a stroll, never faster than the brisk pace allows.- expect(trace.seconds).toBeLessThan(walk.length / WALK_SPEED);- expect(trace.seconds).toBeGreaterThan(walk.length / BRISK_SPEED);- });-- it("reaches every desk seat of a large floor exactly, from the lobby", () => {- const { layout, grid } = campusOf(48, [8, 8, 8, 8]);- for (const desk of layout.departments.flatMap((d) => d.desks).filter((d) => d.agentId).slice(0, 12)) {- const seat = { x: desk.x, z: desk.facing === "north" ? desk.z + 0.62 : desk.z - 0.62 };- const m = mover(layout.spawn);- const walk = beginWalk(grid, m, seat)!;- const trace = walkThrough(walk, m, () => grid, () => []);- expect(trace.arrived, desk.id).toBe(true);- expect([m.x, m.z], desk.id).toEqual([seat.x, seat.z]);- expect(trace.offFloor, desk.id).toBe(0);- }- });-});--/**- * Two figures walking towards each other's start, each with somewhere it has to be (as an agent going to its- * screen): a walk given up is begun again from where it stands, and after two of those it may be placed.- * Returns how close they came and how each walk ended.- */-function swap(grid: NavGrid, a0: Point, b0: Point) {- const a = mover(a0), b = mover(b0);- const walks = { a: beginWalk(grid, a, b0)!, b: beginWalk(grid, b, a0)! };- const givenUp = { a: 0, b: 0 };- let closest = Infinity, seconds = 0, doneA = false, doneB = false;- const events: WalkEvent[] = [];- const stepOne = (who: "a" | "b", m: Mover, other: Mover, goal: Point): boolean => {- const s = advanceWalk(walks[who], m, grid, DT, [other], { far: givenUp[who] >= 2 });- if (s.event) events.push(s.event);- if (s.event === "blocked") { givenUp[who] += 1; walks[who] = beginWalk(grid, m, goal, [other])!; }- return s.arrived;- };- while (seconds < 120 && !(doneA && doneB)) {- if (!doneA) doneA = stepOne("a", a, b, b0);- if (!doneB) doneB = stepOne("b", b, a, a0);- seconds += DT;- if (!doneA && !doneB) closest = Math.min(closest, Math.hypot(a.x - b.x, a.z - b.z));- expect(isWalkable(grid, a) && isWalkable(grid, b)).toBe(true);- }- return { a, b, closest, seconds, events, done: doneA && doneB };-}--describe("two walkers meeting head-on", () => {- it("swap places through a door without touching, each passing on its right", () => {- const grid = roomGrid(12, 8, wallWithDoor(6, 8, 4, 1.6));- const result = swap(grid, { x: 2, z: 4 }, { x: 10, z: 4 });- expect(result.done).toBe(true);- expect([result.a.x, result.a.z]).toEqual([10, 4]);- expect([result.b.x, result.b.z]).toEqual([2, 4]);- expect(result.closest).toBeGreaterThan(BODY_SPACING - 0.03);- expect(result.events).not.toContain("rescue");- // No standing about: both are through in little more than the plain walking time.- expect(result.seconds).toBeLessThan(8 / WALK_SPEED + 6);- });-- it("pass each other in a narrow aisle", () => {- // A 1.6 m aisle between two benches: 1.04 m of floor for the two of them.- const grid = roomGrid(14, 1.6);- const result = swap(grid, { x: 1, z: 0.8 }, { x: 13, z: 0.8 });- expect(result.done).toBe(true);- expect(result.closest).toBeGreaterThan(BODY_SPACING - 0.03);- expect(result.events).not.toContain("rescue");- });-- it("still both arrive where a door is too narrow for two: nobody is left standing in it", () => {- const grid = roomGrid(12, 8, wallWithDoor(6, 8, 4, 1.0));- const result = swap(grid, { x: 2, z: 4 }, { x: 10, z: 4 });- expect(result.done).toBe(true);- expect([result.a.x, result.a.z]).toEqual([10, 4]);- expect([result.b.x, result.b.z]).toEqual([2, 4]);- });-});--describe("a floor plan that changes under a walker", () => {- it("finds the new way when a studio is built on its route, and still arrives exactly", () => {- const before = campusOf(30, [6, 6]);- const after = campusOf(30, [6, 6, 6, 6]);- // A walk the new studios stand in the way of: across the studio rows, between two places both plans share.- const from = before.layout.spawn;- const to = before.layout.checkpoints.find((c) => c.id === "lead")!;- expect(isWalkable(after.grid, to)).toBe(true);- const m = mover(from);- const walk = beginWalk(before.grid, m, to)!;- let grid = before.grid;- for (let i = 0; i < 6 / DT; i += 1) advanceWalk(walk, m, grid, DT, []);- expect(m.path.length).toBeGreaterThan(0);- grid = after.grid;- const trace = walkThrough(walk, m, () => grid, () => []);- expect(trace.events[0]).toBe("repath");- expect(trace.arrived).toBe(true);- expect([m.x, m.z]).toEqual([to.x, to.z]);- expect(trace.offFloor).toBe(0);- expect(walk.grid).toBe(after.grid);- });-- it("reports a target the new plan walls off, instead of walking at a wall for ever", () => {- const open = roomGrid(12, 8);- const walled = roomGrid(12, 8, [{ minX: 5.9, maxX: 6.1, minZ: 0, maxZ: 8 }]);- const m = mover({ x: 2, z: 4 });- const walk = beginWalk(open, m, { x: 10, z: 4 })!;- for (let i = 0; i < 60; i += 1) advanceWalk(walk, m, open, DT, []);- const step = advanceWalk(walk, m, walled, DT, []);- expect(step).toMatchObject({ arrived: false, event: "lost" });- expect(m.path).toEqual([]);- });-});--describe("a walker that stops getting anywhere", () => {- it("takes a detour round people standing in its way", () => {- const grid = roomGrid(12, 8);- // Three people standing shoulder to shoulder across the straight line.- const standing = [{ x: 6, z: 3.4 }, { x: 6, z: 4 }, { x: 6, z: 4.6 }];- const m = mover({ x: 2, z: 4 });- const walk = beginWalk(grid, m, { x: 10, z: 4 })!;- let closest = Infinity;- const trace = walkThrough(walk, m, () => grid, () => { closest = Math.min(closest, ...standing.map((b) => Math.hypot(b.x - m.x, b.z - m.z))); return standing; });- expect(trace.arrived).toBe(true);- expect([m.x, m.z]).toEqual([10, 4]);- expect(closest).toBeGreaterThan(BODY_SPACING - 0.03);- expect(trace.events).not.toContain("rescue");- });-- it("plans a detour that avoids the bodies, and none where they close the only way", () => {- const grid = roomGrid(12, 8);- const direct = findPath(grid, { x: 2, z: 4 }, { x: 10, z: 4 })!;- const round = findDetour(grid, { x: 2, z: 4 }, { x: 10, z: 4 }, [{ x: 6, z: 4 }])!;- expect(pathLength({ x: 2, z: 4 }, round)).toBeGreaterThan(pathLength({ x: 2, z: 4 }, direct));- // A corridor one body wide: whoever stands in it closes it.- const corridor = roomGrid(12, 1.2);- expect(findDetour(corridor, { x: 2, z: 0.6 }, { x: 10, z: 0.6 }, [{ x: 6, z: 0.6 }])).toBeNull();- });-- it("is placed at a target a few steps away after two detours that did not help, and never before", () => {- const corridor = roomGrid(12, 1.2);- const blocker = [{ x: 6, z: 0.6 }];- const m = mover({ x: 4.5, z: 0.6 });- const target = { x: 7.3, z: 0.6 };- const walk = beginWalk(corridor, m, target)!;- const trace = walkThrough(walk, m, () => corridor, () => blocker);- expect(trace.events).toEqual(["replan", "replan", "rescue"]);- expect(trace.arrived).toBe(true);- expect([m.x, m.z]).toEqual([target.x, target.z]);- // Never through the person in the way: it waited in front of them until it was placed.- expect(trace.seconds).toBeGreaterThan(4.5);- expect(walk.rescues).toBe(1);- });-- it("gives a walk up rather than being moved across the floor, unless it has to be there", () => {- const corridor = roomGrid(12, 1.2);- const blocker = [{ x: 6, z: 0.6 }];- const m = mover({ x: 2, z: 0.6 });- const walk = beginWalk(corridor, m, { x: 10, z: 0.6 })!;- const trace = walkThrough(walk, m, () => corridor, () => blocker);- expect(trace.events).toEqual(["replan", "replan", "blocked"]);- expect(trace.arrived).toBe(false);- // It stands where it was stopped, with no route left: its owner plans again from here.- expect(m.x).toBeLessThan(6);- expect(Math.hypot(10 - m.x, 0.6 - m.z)).toBeGreaterThan(PLACE_WITHIN_M);- expect(m.path).toEqual([]);- expect(walk.rescues).toBe(0);- // An agent that must be there (its screen while it works) and failed twice is placed after all.- const again = beginWalk(corridor, m, { x: 10, z: 0.6 })!;- const insisted = walkThrough(again, m, () => corridor, () => blocker, 400, { far: true });- expect(insisted.events).toEqual(["replan", "replan", "rescue"]);- expect([m.x, m.z]).toEqual([10, 0.6]);- });-- it("stops where it is instead of being placed when it is the person's own character", () => {- const corridor = roomGrid(12, 1.2);- const m = mover({ x: 4.5, z: 0.6 });- const walk = beginWalk(corridor, m, { x: 7.3, z: 0.6 })!;- const trace = walkThrough(walk, m, () => corridor, () => [{ x: 6, z: 0.6 }], 60, { place: false });- expect(trace.events).toEqual(["replan", "replan", "blocked"]);- expect(trace.arrived).toBe(false);- // In front of the person in its way, at arm's length: not through them, and not at its target.- expect(m.x).toBeLessThan(6);- expect(Math.hypot(m.x - 6, m.z - 0.6)).toBeGreaterThan(BODY_SPACING - 0.01);- expect(m.path).toEqual([]);- });-- it("stops beside someone who stands on the place it was heading for", () => {- const grid = roomGrid(12, 8);- const squatter = [{ x: 9, z: 4 }];- const m = mover({ x: 2, z: 4 });- const walk = beginWalk(grid, m, { x: 9, z: 4 })!;- const trace = walkThrough(walk, m, () => grid, () => squatter);- expect(trace.arrived).toBe(true);- expect(trace.events).toContain("near");- const gap = Math.hypot(m.x - 9, m.z - 4);- expect(gap).toBeGreaterThan(BODY_SPACING - 0.03);- expect(gap).toBeLessThan(1.2);- });-- it("ends a walk that keeps moving without ever arriving: placed when nearly there, given up when not", () => {- const grid = roomGrid(12, 8);- const far = mover({ x: 2, z: 4 });- const long = beginWalk(grid, far, { x: 10, z: 4 })!;- long.budgetS = 1;- expect(walkThrough(long, far, () => grid, () => []).events).toEqual(["blocked"]);- expect(far.x).toBeLessThan(5);- const near = mover({ x: 8, z: 4 });- const short = beginWalk(grid, near, { x: 10, z: 4 })!;- short.budgetS = 0.5;- expect(walkThrough(short, near, () => grid, () => []).events).toEqual(["rescue"]);- expect([near.x, near.z]).toEqual([10, 4]);- });-});--describe("safePlacement", () => {- const grid = roomGrid(12, 8, [{ minX: 5, maxX: 7, minZ: 3, maxZ: 5 }]);- it("is the seat itself for a place inside a footprint, the place when free, else free ground beside it", () => {- expect(safePlacement(grid, { x: 6, z: 4 }, [{ x: 6, z: 4.4 }])).toEqual({ x: 6, z: 4 });- expect(safePlacement(grid, { x: 2, z: 2 }, [])).toEqual({ x: 2, z: 2 });- const beside = safePlacement(grid, { x: 2, z: 2 }, [{ x: 2, z: 2 }]);- expect(isWalkable(grid, beside)).toBe(true);- expect(Math.hypot(beside.x - 2, beside.z - 2)).toBeGreaterThanOrEqual(BODY_SPACING);- });-});--describe("routeMarks", () => {- it("dots the route evenly, starts a step ahead and leaves the destination to its ring", () => {- const marks = routeMarks({ x: 0, z: 0 }, [{ x: 9, z: 0 }, { x: 9, z: 9 }], 0.9, 40);- expect(marks.length).toBeGreaterThan(15);- expect(marks[0]).toEqual({ x: 0.9, z: 0 });- const last = marks[marks.length - 1];- expect(Math.hypot(last.x - 9, last.z - 9)).toBeGreaterThan(0.4);- for (let i = 1; i < marks.length; i += 1) {- expect(Math.abs(marks[i].x - marks[i - 1].x) + Math.abs(marks[i].z - marks[i - 1].z)).toBeCloseTo(0.9, 5);- }- });- it("spreads its dots over a long route and draws none on a short one", () => {- expect(routeMarks({ x: 0, z: 0 }, [{ x: 200, z: 0 }], 0.9, 40)).toHaveLength(40);- expect(routeMarks({ x: 0, z: 0 }, [{ x: 1, z: 0 }])).toEqual([]);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/officeWalk.ts b/dodaios/ui/web/frontend/src/components/society/office/officeWalk.tsdeleted file mode 100644index 142c441b52..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/officeWalk.ts+++ /dev/null@@ -1,246 +0,0 @@-/**- * One walk of a figure to a place, from the first step to the arrival: the- * route, the pace, and everything that can go wrong on the way.- *- * - The route is recomputed when steering carried the figure off it, and when- * the floor plan changed under its feet (teams are created and deleted while- * people walk).- * - A figure that stops getting anywhere first takes a detour round whoever- * stands in its way. After two detours that did not help it is placed when- * its target is a few steps away (on its reserved seat, or on the nearest- * free ground beside the target); further away it gives the walk up, and its- * owner plans again from where it stands. Nobody is moved across the floor,- * unless the caller insists (`far`: a place the agent's real state demands,- * after it failed to get there twice).- * - A walk has a time budget, so a figure that keeps moving without arriving- * (back and forth in a doorway) ends the same way.- *- * Pure: the caller owns the mover, the clock and the list of other bodies.- */-import type { Point } from "./officeLayout";-import { clearOfBodies, newStuckWatch, paceFor, stepWalker, watchProgress, WALK_SPEED, BODY_SPACING, type Mover, type StuckWatch } from "./officeMotion";-import { findPath, isWalkable, nearestWalkable, type NavGrid } from "./officeNav";--/** Blocked by a body this close to a place to stand, the figure has arrived: it stops beside whoever is there. */-const NEAR_ENOUGH_M = 0.5;-/** A figure is placed at a target this close; a target further away is given up instead. */-export const PLACE_WITHIN_M = 3;-/** A walk may take this many times its expected duration, plus a margin, before it ends by placement or is given up. */-const BUDGET_FACTOR = 3;-const BUDGET_MARGIN_S = 8;-/** Seconds between two route repairs after steering left the route. */-const REPATH_EVERY_S = 0.4;-/** Bodies further away than this play no part in a detour. */-const DETOUR_RANGE_M = 7;-/** A body blocks the cells this close to its centre while a detour is planned: the spacing two bodies keep, and a little more. */-const DETOUR_BODY_M = BODY_SPACING + 0.08;--/**- * What happened on this step besides walking: a detour round a body- * ("replan"), a placement ("rescue"), a repaired route ("repath"), an arrival- * beside an occupied place ("near"), a walk given up because the way stays- * closed ("blocked"), or a target that can no longer be reached on the new- * floor plan ("lost"). After "blocked" and "lost" the walk is over without an- * arrival: the caller plans again.- */-export type WalkEvent = "replan" | "rescue" | "repath" | "near" | "blocked" | "lost" | null;--export interface Walk {- target: Point;- /** The floor plan the route was computed on. */- grid: NavGrid;- watch: StuckWatch;- elapsedS: number;- budgetS: number;- /** Metres of route left, for the pace. */- remaining: number;- /** The whole route's length when the walk began. */- length: number;- sinceRepathS: number;- /** Counters for the dev handle: detours, placements and route repairs on this walk. */- replans: number;- rescues: number;- repaths: number;-}--export interface WalkResult { moved: number; arrived: boolean; event: WalkEvent }--export function pathLength(from: Point, path: readonly Point[]): number {- let total = 0;- let at = from;- for (const p of path) { total += Math.hypot(p.x - at.x, p.z - at.z); at = p; }- return total;-}--function budgetFor(length: number): number {- return (length / WALK_SPEED) * BUDGET_FACTOR + BUDGET_MARGIN_S;-}--/** A figure getting up looks for a way out round anyone standing this close to its seat. */-const SEAT_EXIT_RANGE_M = 1.6;--/**- * Start walking `m` to `target`. Null when no route exists; the caller places- * the figure instead. A figure that starts inside a footprint (it gets up- * from a seat) leaves on the side where nobody of `bodies` stands.- */-export function beginWalk(grid: NavGrid, m: Mover, target: Point, bodies: readonly Point[] = []): Walk | null {- const crowded = !isWalkable(grid, m) && bodies.some((b) => Math.hypot(b.x - m.x, b.z - m.z) <= SEAT_EXIT_RANGE_M);- const path = (crowded ? findDetour(grid, m, target, bodies) : null) ?? findPath(grid, m, target);- if (!path) return null;- m.path = path;- const length = pathLength(m, path);- return {- target: { x: target.x, z: target.z }, grid, watch: newStuckWatch(m), elapsedS: 0, budgetS: budgetFor(length),- remaining: length, length, sinceRepathS: REPATH_EVERY_S, replans: 0, rescues: 0, repaths: 0,- };-}--/**- * A route to `to` that also walks round the bodies standing nearby. Null when- * there is none (they close the only way), so the caller can keep its route.- */-export function findDetour(grid: NavGrid, from: Point, to: Point, bodies: readonly Point[]): Point[] | null {- const near = bodies.filter((b) => Math.hypot(b.x - from.x, b.z - from.z) <= DETOUR_RANGE_M- // Whoever stands on the target itself is not walked round: the figure stops beside them.- && Math.hypot(b.x - to.x, b.z - to.z) > DETOUR_BODY_M + grid.cell);- if (near.length === 0) return null;- // A copy with its own search buffers: the labelled regions of the real grid stay valid.- const blocked = new Uint8Array(grid.blocked);- const reach = Math.ceil(DETOUR_BODY_M / grid.cell);- for (const body of near) {- const bc = Math.floor((body.x - grid.originX) / grid.cell), br = Math.floor((body.z - grid.originZ) / grid.cell);- for (let r = Math.max(0, br - reach); r <= Math.min(grid.rows - 1, br + reach); r += 1) {- for (let c = Math.max(0, bc - reach); c <= Math.min(grid.cols - 1, bc + reach); c += 1) {- const cx = grid.originX + (c + 0.5) * grid.cell, cz = grid.originZ + (r + 0.5) * grid.cell;- // The figure's own cell stays free, however close the body stands.- if (Math.hypot(cx - body.x, cz - body.z) <= DETOUR_BODY_M && Math.hypot(cx - from.x, cz - from.z) > grid.cell) blocked[r * grid.cols + c] = 1;- }- }- }- return findPath({ ...grid, blocked }, from, to);-}--/** Somebody this close to a seat is on it, however the seat was reserved. */-const ON_SEAT_M = 0.3;--/**- * Where a figure that cannot walk to `target` is put. A seat inside a- * footprint is reserved, so it is the place itself (the neighbours on a couch- * sit closer than two walkers pass); a place to stand is taken when nobody is- * on it. Otherwise it is the nearest free ground round the target: never on- * top of anybody.- */-export function safePlacement(grid: NavGrid, target: Point, bodies: readonly Point[]): Point {- const free = isWalkable(grid, target) ? clearOfBodies(target, bodies) : clearOfBodies(target, bodies, ON_SEAT_M);- if (free) return { x: target.x, z: target.z };- for (const radius of [0.75, 1.1, 1.6, 2.4]) {- for (let i = 0; i < 8; i += 1) {- const angle = (i / 8) * Math.PI * 2;- const p = { x: target.x + Math.sin(angle) * radius, z: target.z + Math.cos(angle) * radius };- if (isWalkable(grid, p) && clearOfBodies(p, bodies)) return p;- }- }- return nearestWalkable(grid, target) ?? { x: target.x, z: target.z };-}--/**- * Marks along a route for the person to see where a click sends the- * character: a dot every `spacing` metres from `from` along `path`, the- * first one a step ahead, none on the destination itself (it has its own- * ring). At most `max` dots; a longer route spreads them out.- */-export function routeMarks(from: Point, path: readonly Point[], spacing = 0.9, max = 40): Point[] {- const total = pathLength(from, path);- if (total < spacing * 1.5) return [];- const gap = Math.max(spacing, total / (max + 1));- const marks: Point[] = [];- let at = from;- let next = gap;- let walked = 0;- for (const p of path) {- const leg = Math.hypot(p.x - at.x, p.z - at.z);- while (leg > 1e-9 && next <= walked + leg && next < total - gap * 0.5 && marks.length < max) {- const t = (next - walked) / leg;- marks.push({ x: at.x + (p.x - at.x) * t, z: at.z + (p.z - at.z) * t });- next += gap;- }- walked += leg;- at = p;- }- return marks;-}--function reroute(walk: Walk, m: Mover, path: Point[]): void {- m.path = path;- walk.remaining = pathLength(m, path);-}--function place(walk: Walk, m: Mover, grid: NavGrid, bodies: readonly Point[]): WalkResult {- const spot = safePlacement(grid, walk.target, bodies);- m.x = spot.x; m.z = spot.z; m.path = [];- walk.rescues += 1;- walk.remaining = 0;- return { moved: 0, arrived: true, event: "rescue" };-}--/**- * Advance a walk by one frame on the current floor plan `grid`. `bodies` are- * the other figures (already without the walker itself). With `place: false`- * (the person's own character) a walk that fails always stops where it is;- * with `far: true` it is placed however far away its target is.- */-export function advanceWalk(walk: Walk, m: Mover, grid: NavGrid, dt: number, bodies: readonly Point[],- options: { speed?: number; place?: boolean; far?: boolean } = {}): WalkResult {- const mayPlace = options.place !== false;- const walkable = (p: Point) => isWalkable(grid, p);- let event: WalkEvent = null;-- if (grid !== walk.grid) {- // The floor plan changed under the walk: find the new way (a route out of anything that now stands here included).- walk.grid = grid;- const path = findPath(grid, m, walk.target);- if (!path) { m.path = []; return { moved: 0, arrived: false, event: "lost" }; }- reroute(walk, m, path);- walk.watch = newStuckWatch(m);- walk.budgetS = walk.elapsedS + budgetFor(walk.remaining);- walk.repaths += 1;- event = "repath";- }-- walk.elapsedS += dt;- walk.sinceRepathS += dt;- const step = stepWalker(m, options.speed ?? paceFor(walk.remaining), dt, bodies, walkable);- walk.remaining = Math.max(0, walk.remaining - step.moved);- if (step.arrived) return { moved: step.moved, arrived: true, event };-- if (step.offPath && walk.sinceRepathS >= REPATH_EVERY_S) {- const path = findPath(grid, m, walk.target);- if (path) { reroute(walk, m, path); walk.repaths += 1; event = "repath"; }- walk.sinceRepathS = 0;- }-- const verdict = walk.elapsedS > walk.budgetS ? "rescue" : watchProgress(walk.watch, m, dt);- if (verdict === "ok") return { moved: step.moved, arrived: false, event };-- // Someone stands on (or right beside) a place to stand: stop next to them, that is an arrival.- const left = Math.hypot(walk.target.x - m.x, walk.target.z - m.z);- if (walkable(walk.target) && walkable(m) && left <= NEAR_ENOUGH_M + BODY_SPACING- && bodies.some((b) => Math.hypot(b.x - walk.target.x, b.z - walk.target.z) < BODY_SPACING)) {- m.path = [];- walk.remaining = 0;- return { moved: step.moved, arrived: true, event: "near" };- }- if (verdict === "replan") {- const path = findDetour(grid, m, walk.target, bodies) ?? findPath(grid, m, walk.target);- if (path) reroute(walk, m, path);- walk.replans += 1;- return { moved: step.moved, arrived: false, event: "replan" };- }- if (!mayPlace || (!options.far && left > PLACE_WITHIN_M)) {- m.path = [];- walk.remaining = 0;- return { moved: step.moved, arrived: false, event: "blocked" };- }- return place(walk, m, grid, bodies);-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/paneCommand.css b/dodaios/ui/web/frontend/src/components/society/office/paneCommand.cssdeleted file mode 100644index 3d58548920..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/paneCommand.css+++ /dev/null@@ -1,81 +0,0 @@-/* A coding session's window on the office map, drawn as an Agentic IDE pane:- 36 px title bar over the IDE's own live terminal, floating over the scene.- Position and size are set inline from ./paneWindow; every colour is a- --pane-* variable the component sets from the pane appearance tables- (terminalThemes.ts), so it follows light and dark panes. */-.office-pane { position:absolute; z-index:36; display:flex; flex-direction:column; min-width:0; min-height:0; overflow:hidden; border:1px solid var(--pane-edge); border-radius:12px; background:var(--pane-ground); color:var(--pane-ink); box-shadow:0 24px 60px rgb(0 0 0 / .45), 0 4px 14px rgb(0 0 0 / .22); backdrop-filter:blur(14px); animation:office-pane-in .16s ease-out; }-.office-pane[data-appearance="light"] { box-shadow:0 24px 60px rgb(20 18 10 / .24), 0 4px 14px rgb(20 18 10 / .12); }-.office-pane:focus { outline:none; }-.office-pane:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }-.office-pane[data-gesture] { user-select:none; }-@keyframes office-pane-in { from { opacity:0; transform:translateY(6px); } }-@media (prefers-reduced-motion: reduce) { .office-pane { animation:none; } }--/* The title bar is the window's handle: drag to move, double-click to put it back. */-.office-pane-head { position:relative; display:flex; flex:none; align-items:center; gap:8px; height:36px; min-height:36px; padding:0 4px 0 12px; border-bottom:1px solid var(--pane-rule); background:color-mix(in srgb, var(--pane-float) 45%, transparent); cursor:grab; user-select:none; touch-action:none; }-.office-pane[data-gesture="move"] .office-pane-head { cursor:grabbing; }-.office-pane-dot { flex:none; width:7px; height:7px; border-radius:50%; }-.office-pane-head h2 { flex:0 1 auto; min-width:0; margin:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:13px; font-weight:500; color:var(--pane-ink); }-.office-pane-meta { flex:1 1 auto; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:11px; color:var(--pane-ink-muted); }-.office-pane-actions { display:flex; flex:none; align-items:center; gap:1px; }-.office-pane-actions button { display:inline-flex; align-items:center; justify-content:center; width:28px; height:28px; padding:0; border:0; border-radius:6px; background:none; color:var(--pane-ink-muted); cursor:pointer; }-.office-pane-actions button svg { width:15px; height:15px; }-.office-pane-actions button:hover:not(:disabled) { background:var(--pane-chip); color:var(--pane-ink); }-.office-pane-actions button:focus-visible { outline:1px solid var(--pane-ink); outline-offset:-1px; }-.office-pane-actions button:disabled { opacity:.35; cursor:default; }-.office-pane-actions button[data-danger]:hover:not(:disabled), .office-pane-actions button[data-danger][aria-pressed="true"] { color:var(--pane-fault); }-.office-pane-actions button[data-danger][aria-pressed="true"] { background:var(--pane-chip); }-.office-pane-sep { width:1px; height:16px; margin:0 3px; background:var(--pane-rule); }--/* The IDE's own terminal, attached to the same PTY. The box takes whatever- the window leaves under the title bar and the terminal fills it- absolutely, so xterm's canvas can never feed back into the window's size. */-.office-pane-term { position:relative; flex:1 1 0; min-height:0; }-.office-pane-term > * { position:absolute; inset:0; }--/* An action's result floats over the terminal's foot: a line below it would- take rows away and resize the agent every time one appears. */-.office-pane-status { position:absolute; z-index:2; left:12px; right:12px; bottom:10px; margin:0; padding:6px 10px; border:1px solid var(--pane-rule); border-radius:8px; background:var(--pane-float); box-shadow:0 6px 18px rgb(0 0 0 / .22); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:12px; color:var(--pane-ink-muted); cursor:pointer; }-.office-pane-status[data-tone="ok"] { color:var(--pane-ok); }-.office-pane-status[data-tone="error"] { color:var(--pane-fault); white-space:normal; }--/* Resize grips: 4 px strips along each edge and squares on the corners, inside- the window's rounded clip — thin enough to stay clear of the terminal's- text and scroll rail inside its padding. Only the bottom-right one is drawn. */-.office-pane-grip { position:absolute; z-index:3; touch-action:none; }-.office-pane-grip[data-edge="n"] { top:0; left:12px; right:12px; height:4px; cursor:ns-resize; }-.office-pane-grip[data-edge="s"] { bottom:0; left:12px; right:12px; height:4px; cursor:ns-resize; }-.office-pane-grip[data-edge="e"] { right:0; top:12px; bottom:12px; width:4px; cursor:ew-resize; }-.office-pane-grip[data-edge="w"] { left:0; top:12px; bottom:12px; width:4px; cursor:ew-resize; }-.office-pane-grip[data-edge="nw"] { top:0; left:0; width:12px; height:12px; cursor:nwse-resize; }-.office-pane-grip[data-edge="ne"] { top:0; right:0; width:12px; height:12px; cursor:nesw-resize; }-.office-pane-grip[data-edge="sw"] { bottom:0; left:0; width:14px; height:14px; cursor:nesw-resize; }-.office-pane-grip[data-edge="se"] { bottom:0; right:0; width:16px; height:16px; cursor:nwse-resize; }-.office-pane-grip[data-edge="se"]::after { content:""; position:absolute; right:4px; bottom:4px; width:8px; height:8px; opacity:.55; background:linear-gradient(135deg, transparent 0 45%, var(--pane-ink-faint) 45% 55%, transparent 55% 70%, var(--pane-ink-faint) 70% 80%, transparent 80%); }-.office-pane:hover .office-pane-grip[data-edge="se"]::after { opacity:.9; }--/* The minimal pane style (the IDE's Workspace options): the window is a tile- like the panes in the grid — square, a slim title row in the terminal font,- square controls — and while the reader works in it (keyboard focus anywhere- inside, the terminal included) its edge and title take the signal hue. The- inner half of that two-pixel edge is its own layer over everything, so the- title row's ground cannot dim it along the top. */-.office-pane[data-style="minimal"] { border-radius:0; }-.office-pane[data-style="minimal"] .office-pane-head { height:28px; min-height:28px; padding:0 2px 0 10px; gap:7px; }-.office-pane[data-style="minimal"] .office-pane-head h2 { font-size:12px; }-.office-pane[data-style="minimal"] .office-pane-actions button { width:24px; height:24px; border-radius:0; }-.office-pane[data-style="minimal"] .office-pane-actions button svg { width:14px; height:14px; }-.office-pane[data-style="minimal"] .office-pane-status { border-radius:0; }-.office-pane[data-style="minimal"]:focus-within { border-color:var(--pane-focus); }-.office-pane[data-style="minimal"]:focus-within::after { content:""; position:absolute; inset:0; z-index:4; pointer-events:none; box-shadow:inset 0 0 0 1px var(--pane-focus); }-.office-pane[data-style="minimal"]:focus-within .office-pane-head h2 { color:var(--pane-focus); font-weight:600; }-.office-pane[data-style="minimal"]:focus-visible { outline:none; }--/* Mission Control's still screens of the sessions (./PaneLiveScreen). Fixed- height, rows absolutely placed: the grid is fitted to this box, so the text- can never feed back into its size. */-.office-pane-screen { position:relative; flex:1 1 clamp(200px, 38vh, 420px); min-height:110px; margin:0 12px; cursor:zoom-in; }-.office-pane-screen pre { position:absolute; inset:8px 0 0; margin:0; overflow:hidden; display:flex; flex-direction:column; justify-content:flex-end; color:var(--pane-ink); white-space:pre; text-shadow:none; font-variant-ligatures:none; }-.office-pane-screen pre > div { overflow:hidden; }-.office-pane-cursor { background:var(--pane-caret); color:var(--pane-ground); }-.office-pane-empty { position:absolute; inset:0; display:flex; align-items:center; justify-content:center; margin:0; font-size:12px; color:var(--pane-ink-faint); }diff --git a/dodaios/ui/web/frontend/src/components/society/office/paneWindow.test.ts b/dodaios/ui/web/frontend/src/components/society/office/paneWindow.test.tsdeleted file mode 100644index 9144bc0cb5..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/paneWindow.test.ts+++ /dev/null@@ -1,90 +0,0 @@-import { afterEach, describe, expect, it } from "vitest";-import {- EDGE, MIN_H, MIN_W, defaultRect, fitRect, loadStoredWindow, moveRect, placeStored, resizeRect, saveStoredWindow, toStored,- type WindowRect,-} from "./paneWindow";--const IDE = { width: 1795, height: 1030 };-const inside = (rect: WindowRect, stage: { width: number; height: number }) =>- rect.x >= EDGE && rect.y >= EDGE && rect.x + rect.w <= stage.width - EDGE && rect.y + rect.h <= stage.height - EDGE;--describe("pane window geometry", () => {- afterEach(() => {- window.localStorage.clear();- });-- it("opens as a window, not a strip: about half the stage wide, bottom-right, clear of the HUD", () => {- const rect = defaultRect(IDE, true);- expect(rect.w).toBeLessThanOrEqual(860);- expect(rect.w).toBeGreaterThanOrEqual(460);- expect(rect.w).toBeLessThan(IDE.width * 0.6);- expect(rect.h).toBeGreaterThanOrEqual(280);- expect(rect.h).toBeLessThanOrEqual(480);- expect(rect.x + rect.w).toBe(IDE.width - EDGE);- // The compact stage's buttons run along its bottom edge.- expect(IDE.height - (rect.y + rect.h)).toBe(48);- });-- it("fits a small stage without leaving it", () => {- const stage = { width: 420, height: 300 };- const rect = defaultRect(stage, true);- expect(inside(rect, stage)).toBe(true);- expect(rect.w).toBe(stage.width - 2 * EDGE);- });-- it("stops a move at the stage edges", () => {- const start = defaultRect(IDE, true);- const far = moveRect(start, 5000, 5000, IDE);- expect(inside(far, IDE)).toBe(true);- expect(far.w).toBe(start.w);- const back = moveRect(start, -5000, -5000, IDE);- expect(back.x).toBe(EDGE);- expect(back.y).toBe(EDGE);- });-- it("resizes from the top-left corner with the bottom-right corner held", () => {- const start = defaultRect(IDE, true);- const grown = resizeRect(start, "nw", -100, -60, IDE);- expect(grown.w).toBe(start.w + 100);- expect(grown.h).toBe(start.h + 60);- expect(grown.x + grown.w).toBe(start.x + start.w);- expect(grown.y + grown.h).toBe(start.y + start.h);- });-- it("never resizes below the minimum or past the stage", () => {- const start = defaultRect(IDE, true);- const tiny = resizeRect(start, "se", -5000, -5000, IDE);- expect(tiny.w).toBe(MIN_W);- expect(tiny.h).toBe(MIN_H);- const huge = resizeRect(start, "nw", -5000, -5000, IDE);- expect(inside(huge, IDE)).toBe(true);- expect(huge.x).toBe(EDGE);- expect(huge.y).toBe(EDGE);- });-- it("keeps the window's distance from the bottom-right corner when the stage changes", () => {- const rect = fitRect({ x: 900, y: 500, w: 600, h: 400 }, IDE);- const stored = toStored(rect, IDE);- const wider = { width: IDE.width + 200, height: IDE.height };- expect(placeStored(stored, wider)).toEqual({ ...rect, x: rect.x + 200 });- // A stage too small for it shrinks the window rather than pushing it off.- const narrow = { width: 500, height: 400 };- expect(inside(placeStored(stored, narrow), narrow)).toBe(true);- });-- it("remembers the window per stage kind and forgets it on request", () => {- const stored = { r: 10, b: 50, w: 700, h: 420 };- saveStoredWindow(true, stored);- expect(loadStoredWindow(true)).toEqual(stored);- expect(loadStoredWindow(false)).toBeNull();- saveStoredWindow(true, null);- expect(loadStoredWindow(true)).toBeNull();- });-- it("ignores a stored value that is not a window", () => {- window.localStorage.setItem("jarvis.office.paneWindow.compact", JSON.stringify({ r: "x", b: 1 }));- expect(loadStoredWindow(true)).toBeNull();- window.localStorage.setItem("jarvis.office.paneWindow.compact", "{not json");- expect(loadStoredWindow(true)).toBeNull();- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/paneWindow.ts b/dodaios/ui/web/frontend/src/components/society/office/paneWindow.tsdeleted file mode 100644index e1e8612472..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/paneWindow.ts+++ /dev/null@@ -1,120 +0,0 @@-/**- * Geometry of the coding-session window on the office map: where it opens,- * how it moves and resizes, and how it stays inside the stage. Pure, apart- * from the two storage helpers at the bottom.- *- * The window is placed in stage pixels (top-left origin) but remembered as a- * distance from the stage's bottom-right corner, where it opens: a stage that- * grows or shrinks (the IDE's side panel dragged wider) keeps the window where- * the reader put it relative to that corner instead of stranding it mid-map.- */--export interface WindowRect { x: number; y: number; w: number; h: number }-export interface StageSize { width: number; height: number }-/** The edge or corner a resize grips, by compass point. */-export type ResizeEdge = "n" | "s" | "e" | "w" | "ne" | "nw" | "se" | "sw";-/** How the window is remembered: its size and its distance from the stage's bottom-right corner. */-interface StoredWindow { r: number; b: number; w: number; h: number }--/** Space kept between the window and every stage edge. */-export const EDGE = 8;-/** Smallest window: a title bar and a terminal a coding CLI can still draw a prompt in. */-export const MIN_W = 360;-export const MIN_H = 220;--/** Room left under the window, per stage: the compact stage's HUD buttons sit along its bottom. */-function bottomGap(compact: boolean): number {- return compact ? 48 : 16;-}--const clamp = (value: number, lo: number, hi: number) => Math.min(Math.max(value, lo), hi);--/** Where the window opens: bottom-right, about half the stage wide, the old panel's height. */-export function defaultRect(stage: StageSize, compact: boolean): WindowRect {- const right = compact ? EDGE : 14;- const bottom = bottomGap(compact);- const w = Math.round(clamp(stage.width * 0.48, 460, 860));- const h = Math.round(clamp(stage.height * 0.42, 280, 480));- return fitRect({ x: stage.width - right - w, y: stage.height - bottom - h, w, h }, stage);-}--/** The rect made to fit the stage: shrunk if it is too big, then moved fully inside. */-export function fitRect(rect: WindowRect, stage: StageSize): WindowRect {- const maxW = Math.max(0, stage.width - 2 * EDGE);- const maxH = Math.max(0, stage.height - 2 * EDGE);- const w = Math.round(clamp(rect.w, Math.min(MIN_W, maxW), maxW));- const h = Math.round(clamp(rect.h, Math.min(MIN_H, maxH), maxH));- return {- x: Math.round(clamp(rect.x, EDGE, Math.max(EDGE, stage.width - EDGE - w))),- y: Math.round(clamp(rect.y, EDGE, Math.max(EDGE, stage.height - EDGE - h))),- w,- h,- };-}--/** The window carried by its title bar `dx`/`dy` pixels from where the drag began. */-export function moveRect(start: WindowRect, dx: number, dy: number, stage: StageSize): WindowRect {- return fitRect({ ...start, x: start.x + dx, y: start.y + dy }, stage);-}--/**- * The window resized by one edge or corner. The opposite edge stays where it- * was, and the gripped one stops at the minimum size and at the stage edge.- */-export function resizeRect(start: WindowRect, edge: ResizeEdge, dx: number, dy: number, stage: StageSize): WindowRect {- let { x, y, w, h } = start;- const minW = Math.min(MIN_W, stage.width - 2 * EDGE);- const minH = Math.min(MIN_H, stage.height - 2 * EDGE);- if (edge.includes("e")) w = clamp(start.w + dx, minW, stage.width - EDGE - start.x);- if (edge.includes("w")) {- const right = start.x + start.w;- w = clamp(start.w - dx, minW, right - EDGE);- x = right - w;- }- if (edge.includes("s")) h = clamp(start.h + dy, minH, stage.height - EDGE - start.y);- if (edge.includes("n")) {- const bottom = start.y + start.h;- h = clamp(start.h - dy, minH, bottom - EDGE);- y = bottom - h;- }- return fitRect({ x, y, w, h }, stage);-}--/** The remembered window placed on a stage of this size. */-export function placeStored(stored: StoredWindow, stage: StageSize): WindowRect {- return fitRect({ x: stage.width - stored.r - stored.w, y: stage.height - stored.b - stored.h, w: stored.w, h: stored.h }, stage);-}--/** What to remember of a window on a stage of this size. */-export function toStored(rect: WindowRect, stage: StageSize): StoredWindow {- return { r: stage.width - rect.x - rect.w, b: stage.height - rect.y - rect.h, w: rect.w, h: rect.h };-}--/** One place per stage kind: the IDE's side panel and the full office page differ a lot in size. */-const storageKey = (compact: boolean) => `jarvis.office.paneWindow.${compact ? "compact" : "full"}`;--/** The window the reader last left, or null (never moved, storage blocked, or garbage). */-export function loadStoredWindow(compact: boolean): StoredWindow | null {- try {- const raw = window.localStorage.getItem(storageKey(compact));- if (!raw) return null;- const value = JSON.parse(raw) as Partial<StoredWindow>;- const numbers = [value.r, value.b, value.w, value.h];- if (!numbers.every((n) => typeof n === "number" && Number.isFinite(n))) return null;- return value as StoredWindow;- } catch {- // Storage can be blocked outright (private windows, site data off): the- // window simply opens in its default place.- return null;- }-}--/** Remember the window, or forget it (null) so it opens in its default place again. */-export function saveStoredWindow(compact: boolean, stored: StoredWindow | null): void {- try {- if (stored) window.localStorage.setItem(storageKey(compact), JSON.stringify(stored));- else window.localStorage.removeItem(storageKey(compact));- } catch {- // Blocked storage only costs the remembered place; the window still works.- }-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/plateCrowd.test.ts b/dodaios/ui/web/frontend/src/components/society/office/plateCrowd.test.tsdeleted file mode 100644index 1fa98b78e1..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/plateCrowd.test.ts+++ /dev/null@@ -1,153 +0,0 @@-import { beforeEach, describe, expect, it } from "vitest";-import {- arrangePlates, BUBBLE_ROOM, joinPlates, PLATE_GAP, plateSeating, plateStages, reportPlate, resetPlateSeating, type PlateBox,-} from "./plateCrowd";--/** A plate 150 px wide and 22 px high, like a name plate with a rank chip. */-function plate(id: string, x: number, y: number, extra: Partial<PlateBox> = {}): PlateBox {- return { id, x, y, w: 150, h: 22, pinned: false, speaker: false, shown: false, distance: 5, ...extra };-}--/** Five figures 60 px apart on screen: every plate covers its neighbours. */-function huddle(extra: Record<string, Partial<PlateBox>> = {}): PlateBox[] {- return ["a", "b", "c", "d", "e"].map((id, i) => plate(id, 400 + i * 60, 300, { distance: 3 + i, ...extra[id] }));-}--function coversAnother(boxes: PlateBox[], open: Set<string>): boolean {- const seated = boxes.filter((box) => open.has(box.id));- return seated.some((a, i) => seated.slice(i + 1).some((b) => Math.abs(a.x - b.x) * 2 < a.w + b.w && Math.abs(a.y - b.y) * 2 < a.h + b.h));-}--describe("name plates in a crowd", () => {- it("opens every plate when nobody stands in anybody's way", () => {- const row = [plate("a", 100, 100), plate("b", 400, 100), plate("c", 700, 100), plate("d", 400, 200)];- expect(arrangePlates(row)).toEqual(new Set(["a", "b", "c", "d"]));- });-- it("keeps a huddle of five readable: open plates never cover one another", () => {- const boxes = huddle();- const open = arrangePlates(boxes);- expect(open.size).toBeGreaterThan(0);- expect(open.size).toBeLessThan(boxes.length);- expect(coversAnother(boxes, open)).toBe(false);- // Among equals the one nearest to the person is the one that opens.- expect(open.has("a")).toBe(true);- });-- it("always opens the selected or pointed-at agent, and seats the others round it", () => {- const boxes = huddle({ c: { pinned: true } });- const open = arrangePlates(boxes);- expect(open.has("c")).toBe(true);- // The neighbours its plate covers stay dots.- expect(open.has("b")).toBe(false);- expect(open.has("d")).toBe(false);- expect(coversAnother(boxes, open)).toBe(false);- });-- it("puts the speaker ahead of the bystanders, even the nearer ones", () => {- const boxes = huddle({ d: { speaker: true } });- const open = arrangePlates(boxes);- expect(open.has("d")).toBe(true);- expect(open.has("c")).toBe(false);- expect(open.has("e")).toBe(false);- });-- it("keeps a speaker's bubble clear: no plate opens in the room above it", () => {- const speaker = plate("s", 400, 300, { speaker: true });- const behind = plate("x", 400, 300 - BUBBLE_ROOM.h + 10);- const far = plate("y", 400, 300 - BUBBLE_ROOM.h - 60);- const open = arrangePlates([behind, far, speaker]);- expect(open).toEqual(new Set(["s", "y"]));- // Without a speaker the same two plates do not touch and both open.- expect(arrangePlates([behind, plate("s", 400, 300)])).toEqual(new Set(["s", "x"]));- });-- it("does not reshuffle while people shift: an open plate keeps its seat against a nearer newcomer", () => {- const boxes = [plate("old", 400, 300, { shown: true, distance: 6 }), plate("new", 460, 300, { distance: 2 })];- expect(arrangePlates(boxes)).toEqual(new Set(["old"]));- });-- it("opens and closes at different gaps, so a plate at the edge of another does not flicker", () => {- const gap = (PLATE_GAP.keep + PLATE_GAP.open) / 2;- const anchor = plate("a", 400, 300, { shown: true, distance: 1 });- const beside = (shown: boolean) => plate("b", 400 + 150 + gap, 300, { shown, distance: 2 });- // Just outside the other plate: a closed one stays closed, an open one stays open.- expect(arrangePlates([anchor, beside(false)]).has("b")).toBe(false);- expect(arrangePlates([anchor, beside(true)]).has("b")).toBe(true);- });-- it("keeps clear of the person's own plate", () => {- const person = { x: 400, y: 300, w: 150, h: 26 };- expect(arrangePlates([plate("a", 430, 300), plate("b", 700, 300)], [person])).toEqual(new Set(["b"]));- // The agent the person points at opens all the same.- expect(arrangePlates([plate("a", 430, 300, { pinned: true })], [person])).toEqual(new Set(["a"]));- });-- it("is the same answer whatever order the plates report in", () => {- const boxes = huddle({ b: { speaker: true } });- expect(arrangePlates([...boxes].reverse())).toEqual(arrangePlates(boxes));- });-});--describe("plate seating from frame to frame", () => {- beforeEach(resetPlateSeating);- const nothingTaken = () => [];- const stage = {};-- it("seats this frame from what the plates reported in the frame before", () => {- expect(plateSeating(stage, 1, nothingTaken).size).toBe(0);- for (const box of huddle()) reportPlate(stage, box);- // Still frame 1: the answer does not change under the plates that already asked.- expect(plateSeating(stage, 1, nothingTaken).size).toBe(0);- const next = plateSeating(stage, 2, nothingTaken);- expect(next.has("a")).toBe(true);- expect(next.size).toBeLessThan(5);- });-- it("forgets a plate that stopped reporting", () => {- reportPlate(stage, plate("gone", 100, 100));- expect(plateSeating(stage, 1, nothingTaken).has("gone")).toBe(true);- reportPlate(stage, plate("here", 100, 100));- expect(plateSeating(stage, 2, nothingTaken)).toEqual(new Set(["here"]));- });-});--describe("two offices awake at once", () => {- beforeEach(resetPlateSeating);- const nothingTaken = () => [];-- it("seat their plates apart: the same agent sits on different screens, on different clocks", () => {- const agentsView = {}, idePanel = {};- // The same agent id, far apart on one screen and under another plate on the other.- reportPlate(agentsView, plate("a", 100, 100));- reportPlate(agentsView, plate("b", 600, 100));- reportPlate(idePanel, plate("b", 100, 100, { distance: 1 }));- reportPlate(idePanel, plate("a", 130, 100, { distance: 9 }));- expect(plateSeating(agentsView, 10.5, nothingTaken)).toEqual(new Set(["a", "b"]));- expect(plateSeating(idePanel, 3.25, nothingTaken)).toEqual(new Set(["b"]));- // One stage asking again on its own clock does not re-seat or empty the other.- reportPlate(agentsView, plate("a", 100, 100, { shown: true }));- expect(plateSeating(agentsView, 10.6, nothingTaken)).toEqual(new Set(["a"]));- expect(plateSeating(idePanel, 3.25, nothingTaken)).toEqual(new Set(["b"]));- });-- it("releases a stage's seating when its last plate has left", () => {- const stage = {}, other = {};- const leaveA = joinPlates(stage), leaveB = joinPlates(stage), leaveOther = joinPlates(other);- reportPlate(stage, plate("a", 100, 100));- expect(plateStages()).toBe(2);- leaveA();- expect(plateStages()).toBe(2);- leaveB();- // Leaving twice (an effect cleaned up again) must not take somebody else's count.- leaveB();- expect(plateStages()).toBe(1);- leaveOther();- expect(plateStages()).toBe(0);- // A stage that mounts again starts clean: nothing of the old reports is seated.- const leaveAgain = joinPlates(stage);- expect(plateSeating(stage, 1, nothingTaken).size).toBe(0);- leaveAgain();- expect(plateStages()).toBe(0);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/plateCrowd.ts b/dodaios/ui/web/frontend/src/components/society/office/plateCrowd.tsdeleted file mode 100644index 02268becbb..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/plateCrowd.ts+++ /dev/null@@ -1,140 +0,0 @@-/**- * Name plates in a crowd. A plate is a good deal wider than the figure under- * it, so a team huddled at its board would stack five plates into one- * unreadable pile. Each frame every plate that wants to open reports where it- * would sit on screen; the plates are then seated in order of importance, and- * one that would cover a plate already seated stays a dot.- *- * Order: the agent the person selected or points at (always open), whoever is- * speaking in a team round (its speech bubble gets room above the plate), a- * plate that is already open (so the picture does not reshuffle while people- * shift about), then whoever stands closest to the person. Pure and tested;- * the small registry below only carries the reports from one frame to the- * next.- */--/** A plate's place on screen, in CSS pixels: centre and size. */-export interface PlateBox {- id: string;- x: number;- y: number;- w: number;- h: number;- /** Selected or pointed at: opens whatever it covers. */- pinned: boolean;- /** Speaking in a team round right now: ahead of the bystanders, with room for its bubble. */- speaker: boolean;- /** Open in the last frame. */- shown: boolean;- /** Metres to the person's character; the nearer one wins among equals. */- distance: number;-}--export interface ScreenRect { x: number; y: number; w: number; h: number }--/** An open plate keeps its seat until something comes this close (px); a closed one needs this much clear space to open. */-export const PLATE_GAP = { keep: 2, open: 12 } as const;-/** A speaker's bubble sits above its plate: this much room (px) is kept free there. */-export const BUBBLE_ROOM = { w: 220, h: 84 } as const;--function overlaps(a: ScreenRect, b: ScreenRect, gap: number): boolean {- return Math.abs(a.x - b.x) * 2 < a.w + b.w + gap * 2 && Math.abs(a.y - b.y) * 2 < a.h + b.h + gap * 2;-}--/** The space a plate claims: itself, plus the bubble above it while its agent speaks. */-function claim(box: PlateBox): ScreenRect {- if (!box.speaker) return box;- const h = box.h + BUBBLE_ROOM.h;- return { x: box.x, y: box.y - BUBBLE_ROOM.h / 2, w: Math.max(box.w, BUBBLE_ROOM.w), h };-}--function rank(box: PlateBox): number {- return box.pinned ? 0 : box.speaker ? 1 : box.shown ? 2 : 3;-}--/**- * The plates that may open, given everyone who wants to. `taken` are places- * that are occupied whatever happens (the person's own plate).- */-export function arrangePlates(boxes: readonly PlateBox[], taken: readonly ScreenRect[] = []): Set<string> {- const seated: ScreenRect[] = [...taken];- const open = new Set<string>();- const order = [...boxes].sort((a, b) => rank(a) - rank(b) || a.distance - b.distance || a.id.localeCompare(b.id));- for (const box of order) {- const space = claim(box);- if (!box.pinned) {- const gap = box.shown ? PLATE_GAP.keep : PLATE_GAP.open;- // A bystander only has to keep its own plate clear of what is seated; a speaker also needs its bubble's room.- if (seated.some((other) => overlaps(space, other, gap))) continue;- }- seated.push(space);- open.add(box.id);- }- return open;-}--/**- * One stage's seating: the reports of its running frame, and who was seated from the frame before. Every office- * stage has its own (two can be awake at once: the Agents view and the IDE side panel's tab show the same agent- * ids on different screens and clocks), keyed by the stage's scene.- */-interface StageSeating { reports: Map<string, PlateBox>; seatedAt: number; open: Set<string>; plates: number }--const stages = new Map<object, StageSeating>();--function seatingOf(stage: object): StageSeating {- let seating = stages.get(stage);- if (!seating) {- seating = { reports: new Map(), seatedAt: Number.NaN, open: new Set(), plates: 0 };- stages.set(stage, seating);- }- return seating;-}--/**- * A plate joins its stage's seating for as long as it is mounted. Returns the- * leave function; when the stage's last plate has left, its seating is- * released, so nothing of an unmounted stage is kept.- */-export function joinPlates(stage: object): () => void {- seatingOf(stage).plates += 1;- let left = false;- return () => {- if (left) return;- left = true;- const seating = stages.get(stage);- if (!seating) return;- seating.plates -= 1;- if (seating.plates <= 0) stages.delete(stage);- };-}--/**- * Who may be open on this stage this frame. The first plate that asks in a- * frame seats everyone from the reports of the frame before; a plate that- * stopped reporting (walked off, unmounted) drops out by itself.- */-export function plateSeating(stage: object, frame: number, taken: () => readonly ScreenRect[]): ReadonlySet<string> {- const seating = seatingOf(stage);- if (frame !== seating.seatedAt) {- seating.seatedAt = frame;- seating.open = arrangePlates([...seating.reports.values()], taken());- seating.reports.clear();- }- return seating.open;-}--/** A plate that wants to be open says where it would sit on its stage. */-export function reportPlate(stage: object, box: PlateBox): void {- seatingOf(stage).reports.set(box.id, box);-}--/** How many stages hold a seating right now (for tests: an unmounted stage must leave none behind). */-export function plateStages(): number {- return stages.size;-}--/** Forget everything (tests). */-export function resetPlateSeating(): void {- stages.clear();-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/reception.css b/dodaios/ui/web/frontend/src/components/society/office/reception.cssdeleted file mode 100644index 4622b99196..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/reception.css+++ /dev/null@@ -1,8 +0,0 @@-/* Key caps, shared by the reception's controls guide, the HUD prompt and the first-visit hints. Theme tokens only. */-.office-key { display:inline-flex; align-items:center; justify-content:center; min-width:22px; height:22px; padding:0 6px; border-radius:6px; border:1px solid hsl(var(--border)); box-shadow:inset 0 -2px 0 hsl(var(--border)); background:hsl(var(--background)); color:hsl(var(--foreground)); font-family:inherit; font-size:11px; font-weight:600; line-height:1; white-space:nowrap; }-/* A mouse gesture is not a key: a flat pill. */-.office-key[data-mouse] { box-shadow:none; border-radius:999px; padding:0 9px; font-weight:500; background:hsl(var(--secondary)); color:hsl(var(--muted-foreground)); }-.office-keys { display:flex; flex-wrap:wrap; justify-content:flex-end; align-items:center; gap:4px; }-.office-keys-alt { display:inline-flex; align-items:center; gap:3px; }-.office-keys-or { margin:0 3px 0 1px; font-size:11px; color:hsl(var(--muted-foreground)); }-.office-keys-plus { font-size:11px; color:hsl(var(--muted-foreground)); }diff --git a/dodaios/ui/web/frontend/src/components/society/office/screenTextures.ts b/dodaios/ui/web/frontend/src/components/society/office/screenTextures.tsdeleted file mode 100644index 540bd7cdb9..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/screenTextures.ts+++ /dev/null@@ -1,67 +0,0 @@-/**- * Monitor faces, drawn once on a 2D canvas and shared by every desk.- *- * The screen tells the agent's state at a glance, like the status pill:- * code lines while working, a friendly face while idle, an amber prompt while- * waiting for the person, a dark glass when paused or when the desk is empty.- */-import { CanvasTexture, SRGBColorSpace, type Texture } from "three";-import type { AgentRunState } from "../data";--export type ScreenFace = AgentRunState | "empty";--const cache = new Map<ScreenFace, Texture | null>();--function draw(face: ScreenFace, ctx: CanvasRenderingContext2D, w: number, h: number): void {- ctx.fillStyle = face === "paused" || face === "empty" ? "#15181e" : face === "waiting" ? "#2a2413" : "#1b2a44";- ctx.fillRect(0, 0, w, h);- if (face === "working") {- const colours = ["#7dd3fc", "#a7f3d0", "#fcd34d", "#f9a8d4", "#c4b5fd"];- for (let line = 0; line < 9; line += 1) {- const indent = [0, 1, 1, 2, 2, 1, 0, 1, 2][line] * 10;- const length = 30 + ((line * 37) % 60);- ctx.fillStyle = colours[line % colours.length];- ctx.fillRect(10 + indent, 9 + line * 12, length, 5);- }- } else if (face === "idle") {- // The friendly "^ ^" face of an idle machine.- ctx.strokeStyle = "#9cc8ff";- ctx.lineWidth = 6;- ctx.lineCap = "round";- for (const cx of [w * 0.36, w * 0.64]) {- ctx.beginPath();- ctx.moveTo(cx - 9, h * 0.48);- ctx.lineTo(cx, h * 0.38);- ctx.lineTo(cx + 9, h * 0.48);- ctx.stroke();- }- ctx.beginPath();- ctx.arc(w / 2, h * 0.58, 12, 0.15 * Math.PI, 0.85 * Math.PI);- ctx.stroke();- } else if (face === "waiting") {- ctx.fillStyle = "#fbbf24";- for (const dx of [-18, 0, 18]) {- ctx.beginPath();- ctx.arc(w / 2 + dx, h / 2, 5, 0, Math.PI * 2);- ctx.fill();- }- }-}--/** The shared texture for a face; null where no 2D canvas exists (tests, bare hosts). */-export function screenTexture(face: ScreenFace): Texture | null {- if (cache.has(face)) return cache.get(face) ?? null;- let texture: Texture | null = null;- const canvas = typeof document !== "undefined" ? document.createElement("canvas") : null;- const ctx = canvas?.getContext("2d") ?? null;- if (canvas && ctx) {- canvas.width = 128;- canvas.height = 128;- draw(face, ctx, canvas.width, canvas.height);- const made = new CanvasTexture(canvas);- made.colorSpace = SRGBColorSpace;- texture = made;- }- cache.set(face, texture);- return texture;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/skyPad.ts b/dodaios/ui/web/frontend/src/components/society/office/skyPad.tsdeleted file mode 100644index 8dd8dfef6d..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/skyPad.ts+++ /dev/null@@ -1,104 +0,0 @@-/**- * The sky pad: a landing platform that stands out of the agents floor on its- * east side. The main boulevard runs on across the window line as a bridge to- * a round pad in the open air, where the courier stands ready to board. Pure- * and tested; the drawing is SkyPadStructure.tsx, the ship and its flight- * SkyCourier.tsx with courierFlight.ts.- *- * Everything here lies outside the slab (`layout.bounds`), inside the city's- * empty plaza, at floor level: the pad's top is the floor's top (y = 0).- */-import type { Point, Rect } from "./officeLayout";--export const SKY_PAD = {- /** The bridge: as wide as the boulevard, this long between the slab's edge and the pad's rim. */- bridgeWidth: 5,- bridgeLength: 9,- /** The pad's radius and the depth of its deck. */- radius: 12,- thickness: 0.9,- /** How far inside a rail a walker's centre stays (as on the slab). */- railClearance: 0.65,-} as const;--/** The courier's size on the pad (metres): its authored ship (a 30 m hull) scaled to the Verse's people. */-export const COURIER = {- scale: 0.6,- /** Nose tip and pod-spike tips from the hull's middle, the length between them, the span over the pods' fins. */- nose: 15.6 * 0.6,- tail: 20.8 * 0.6,- length: 36.4 * 0.6,- span: 13.9 * 0.6,- clearance: 0.6,- /** The hull's middle above the deck when it stands on its gear (authored 0.63 m to the gear roots + 2.3 m gear). */- standHeight: (0.7 * 0.9 + 2.3) * 0.6,-} as const;--/** How far the hull's middle stands from the pad's middle towards the tail, so the whole ship sits centred on the deck. */-const SHIP_SHIFT = (COURIER.tail - COURIER.nose) / 2;--export interface SkyPad {- side: "east";- /** The walkable deck of the bridge (a walker's centre may stand anywhere in it). */- bridge: Rect;- /** The pad's centre and its full radius; walkers keep `railClearance` from the rim. */- pad: Point & { r: number };- /** Where the courier stands: the pad's centre, nose to the north (heading in radians, 0 = facing -z). */- ship: Point & { heading: number };- /** The courier's footprint on the deck, solid for walkers. */- shipRect: Rect;- /** The place beside the courier's hatch where the person boards (and steps out again). */- board: Point & { facing: number };- /** The opening the bridge cuts into the floor's east rail and window wall, as a z range. */- gap: { minZ: number; maxZ: number };-}--/**- * The pad for a slab whose boulevard runs along z = `boulevardZ`: a bridge out of the east edge on that line,- * the pad beyond it.- */-export function skyPadFor(bounds: Rect, floor: Rect, boulevardZ: number): SkyPad {- const half = SKY_PAD.bridgeWidth / 2;- const padX = bounds.maxX + SKY_PAD.bridgeLength + SKY_PAD.radius;- const shipRect = {- minX: padX - COURIER.span / 2 - COURIER.clearance, maxX: padX + COURIER.span / 2 + COURIER.clearance,- minZ: boulevardZ - COURIER.length / 2 - COURIER.clearance, maxZ: boulevardZ + COURIER.length / 2 + COURIER.clearance,- };- return {- side: "east",- bridge: {- // From inside the floor's walkable edge (so the two grids join) to a metre onto the pad.- minX: floor.maxX - 0.4, maxX: bounds.maxX + SKY_PAD.bridgeLength + 1,- minZ: boulevardZ - half + SKY_PAD.railClearance, maxZ: boulevardZ + half - SKY_PAD.railClearance,- },- pad: { x: padX, z: boulevardZ, r: SKY_PAD.radius },- // Nose to the north (-z): the longer tail half reaches south, so the middle stands a little north of centre.- ship: { x: padX, z: boulevardZ - SHIP_SHIFT, heading: 0 },- shipRect,- // Beside the hatch on the courier's west flank, facing it: the first thing the bridge leads to.- board: { x: shipRect.minX - 0.9, z: boulevardZ + 1.2, facing: Math.PI / 2 },- gap: { minZ: boulevardZ - half, maxZ: boulevardZ + half },- };-}--/** Whether a walker's centre may stand at p on the pad or its bridge (the courier excluded). */-export function onSkyPad(pad: SkyPad, p: Point): boolean {- const { bridge } = pad;- if (p.x >= bridge.minX && p.x <= bridge.maxX && p.z >= bridge.minZ && p.z <= bridge.maxZ) return true;- return Math.hypot(p.x - pad.pad.x, p.z - pad.pad.z) <= pad.pad.r - SKY_PAD.railClearance;-}--/** The rectangle round the bridge and the pad. */-export function skyPadExtent(pad: SkyPad): Rect {- return {- minX: Math.min(pad.bridge.minX, pad.pad.x - pad.pad.r), maxX: pad.pad.x + pad.pad.r,- minZ: Math.min(pad.bridge.minZ, pad.pad.z - pad.pad.r), maxZ: Math.max(pad.bridge.maxZ, pad.pad.z + pad.pad.r),- };-}--/** The slab and, where there is one, the sky pad: what the camera frames and the full map shows. */-export function boundsWithPad(bounds: Rect, pad?: SkyPad): Rect {- if (!pad) return bounds;- const e = skyPadExtent(pad);- return { minX: Math.min(bounds.minX, e.minX), maxX: Math.max(bounds.maxX, e.maxX), minZ: Math.min(bounds.minZ, e.minZ), maxZ: Math.max(bounds.maxZ, e.maxZ) };-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/spawnFiles.test.tsx b/dodaios/ui/web/frontend/src/components/society/office/spawnFiles.test.tsxdeleted file mode 100644index a3c8db6573..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/spawnFiles.test.tsx+++ /dev/null@@ -1,56 +0,0 @@-import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";-import { afterEach, describe, expect, it, vi } from "vitest";-import { WORKSPACE_PATH_TYPE, setWorkspaceDragPaths } from "@/components/agentic/paneDrop";-import { NATIVE_DROP_EVENT } from "@/lib/nativeDrop";-import { useSpawnFiles } from "./spawnFiles";--function Holder() {- const { handlers, held } = useSpawnFiles();- return <div data-testid="holder" {...handlers}>{JSON.stringify(held.map(({ path, file }) => ({ path, file: file?.name })))}</div>;-}--function transfer(files: File[] = []) {- const data = new Map<string, string>();- return {- types: ["Files", WORKSPACE_PATH_TYPE, "text/uri-list"],- files,- items: [],- getData: (type: string) => data.get(type) ?? "",- setData: (type: string, value: string) => data.set(type, value),- } as unknown as DataTransfer;-}--afterEach(() => { cleanup(); vi.unstubAllGlobals(); });--describe("spawn attachments keep the drag source boundary", () => {- it("rejects a forged workspace path and file URI", () => {- render(<Holder />);- const dt = transfer();- dt.setData(WORKSPACE_PATH_TYPE, "/private/secret.txt");- dt.setData("text/uri-list", "file:///private/secret.txt");- fireEvent.drop(screen.getByTestId("holder"), { dataTransfer: dt });- expect(screen.getByTestId("holder").textContent).toBe("[]");- });-- it("retains granted bytes without following native path hints", async () => {- vi.stubGlobal("__JARVIS_EMBEDDED_DESKTOP", true);- render(<Holder />);- await act(async () => {- fireEvent.drop(screen.getByTestId("holder"), {- dataTransfer: transfer([new File(["offered"], "photo.png", { type: "image/png" })]),- });- window.dispatchEvent(new CustomEvent(NATIVE_DROP_EVENT, {- detail: { paths: ["/private/photo.png"], names: ["photo.png"] },- }));- });- expect(JSON.parse(screen.getByTestId("holder").textContent!)).toEqual([{ file: "photo.png" }]);- });-- it("retains the selected internal explorer path", () => {- render(<Holder />);- const dt = transfer();- setWorkspaceDragPaths(dt, ["/project/selected.txt"]);- fireEvent.drop(screen.getByTestId("holder"), { dataTransfer: dt });- expect(JSON.parse(screen.getByTestId("holder").textContent!)).toEqual([{ path: "/project/selected.txt" }]);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/spawnFiles.ts b/dodaios/ui/web/frontend/src/components/society/office/spawnFiles.tsdeleted file mode 100644index ebd2bf1822..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/spawnFiles.ts+++ /dev/null@@ -1,116 +0,0 @@-/**- * Files dropped on the spawn point, held until the agents they are for exist.- *- * A drop on a pane goes straight to that pane's terminal. Here the terminal- * does not exist yet, so a drop is only READ now and handed to each new pane- * once it is live. The reading is the pane's own — the same drag tracking- * (`usePaneFileDrag`) and payload extraction (`paneDrop`) so the surfaces agree about- * what a drop is.- */-import { useCallback, useState, type ClipboardEvent } from "react";-import {- extractPaneDrop,- extractPasteFiles,- isEmptyPayload,- nameClipboardFile,- type PaneDropPayload,-} from "@/components/agentic/paneDrop";-import { usePaneFileDrag } from "@/components/agentic/paneFileDrag";-import type { DropAttachment } from "@/lib/agenticIdeApi";--/** One held file: a real path the drag carried, or bytes it gave no path for. */-export interface HeldFile {- key: string;- name: string;- path?: string;- file?: File;-}--function baseName(path: string): string {- return path.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || path;-}--/** `held` plus whatever in `payload` is not held yet. Pure. */-export function holdDrop(held: readonly HeldFile[], payload: PaneDropPayload): HeldFile[] {- const next = [...held];- const seen = new Set(held.map((h) => h.key));- const add = (item: HeldFile) => {- if (seen.has(item.key)) return;- seen.add(item.key);- next.push(item);- };- for (const path of payload.paths) {- add({ key: `path:${path.replace(/\\/g, "/").toLowerCase()}`, name: baseName(path), path });- }- for (const file of payload.files) {- add({ key: `file:${file.name}:${file.size}:${file.lastModified}`, name: file.name, file });- }- return next;-}--/** The held files in the shape the attach endpoint takes. Pure. */-export function heldPayload(held: readonly HeldFile[]): PaneDropPayload {- return {- paths: held.flatMap((h) => (h.path ? [h.path] : [])),- files: held.flatMap((h) => (h.file ? [h.file] : [])),- };-}--/**- * The brief, plus every attached file the analysis did not cover. Pure.- *- * A described file travels as an attachment and reaches the agent that way; a- * file too large to read would otherwise vanish from the brief, so its- * reference is written in. Never at the very end: a trailing `@path` holds the- * CLI's completion popup open, and the Enter that follows picks a suggestion- * instead of submitting.- */-export function briefWithFiles(- brief: string,- references: readonly string[],- analysis: readonly DropAttachment[],-): string {- const described = new Set(analysis.map((a) => a.reference));- const loose = references.filter((r) => !described.has(r));- if (loose.length === 0) return brief;- return `${brief}\n\nFiles for this task: ${loose.join(" ")} - open them as needed.`;-}--export function useSpawnFiles() {- const [held, setHeld] = useState<HeldFile[]>([]);- const hold = useCallback((payload: PaneDropPayload) => {- if (!isEmptyPayload(payload)) setHeld((prev) => holdDrop(prev, payload));- }, []);-- const { dragging, handlers } = usePaneFileDrag(- useCallback(- (dt: DataTransfer) => {- // Native path hints can originate in foreign drag metadata on some- // WebViews. Only granted bytes and internal explorer receipts attach.- hold(extractPaneDrop(dt));- },- [hold],- ),- );-- /** On the text box: claims a pasted IMAGE, never pasted text. */- const onPaste = useCallback(- (event: ClipboardEvent) => {- const files = extractPasteFiles(event.clipboardData).map((f) => nameClipboardFile(f, "spawn"));- if (files.length === 0) return;- event.preventDefault();- hold({ paths: [], files });- },- [hold],- );-- const addFiles = useCallback((files: File[]) => hold({ paths: [], files }), [hold]);- const remove = useCallback((key: string) => setHeld((prev) => prev.filter((h) => h.key !== key)), []);- /** Forget exactly these — a file dropped while a launch ran stays for the next one. */- const release = useCallback((used: readonly HeldFile[]) => {- const keys = new Set(used.map((h) => h.key));- setHeld((prev) => prev.filter((h) => !keys.has(h.key)));- }, []);-- return { held, dragging, handlers, onPaste, addFiles, remove, release };-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/stationIcons.tsx b/dodaios/ui/web/frontend/src/components/society/office/stationIcons.tsxdeleted file mode 100644index 06cd58f556..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/stationIcons.tsx+++ /dev/null@@ -1,13 +0,0 @@-/** The icon each station wears in the HUD's places menu and in the reception's directory. */-import { ArrowUpDown, Coffee, ConciergeBell, Radar, Rocket, Shirt, Sparkles, SquareTerminal, Star, Trophy, UserPlus, Users, type LucideIcon } from "lucide-react";-import type { StationIcon } from "./stations";--const ICONS: Record<StationIcon, LucideIcon> = {- spawn: UserPlus, launch: SquareTerminal, reception: ConciergeBell, team: Users, wardrobe: Shirt, lead: Star, break: Coffee,- elevator: ArrowUpDown, mission: Radar, studio: Sparkles, levels: Trophy, ship: Rocket,-};--export function StationGlyph({ icon, size = 16 }: { icon: StationIcon; size?: number }) {- const Icon = ICONS[icon];- return <Icon size={size} aria-hidden />;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/stationRim.test.ts b/dodaios/ui/web/frontend/src/components/society/office/stationRim.test.tsdeleted file mode 100644index 4c7370a1f2..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/stationRim.test.ts+++ /dev/null@@ -1,65 +0,0 @@-import { describe, expect, it } from "vitest";-import { BackSide, BoxGeometry, Group, InstancedMesh, Mesh, MeshBasicMaterial, PlaneGeometry, Scene } from "three";-import { attachRim, attachedTo, createRimMaterial, detachRim, rimTargets } from "./stationRim";--function prop() {- const root = new Group();- root.name = "prop:reception-desk";- const counter = new Mesh(new BoxGeometry(2, 1, 0.8), new MeshBasicMaterial());- const wall = new Mesh(new BoxGeometry(2.6, 2.2, 0.1), new MeshBasicMaterial());- // A drawn face, a hidden hit box and an instanced detail: none of them has a silhouette to rim.- const face = new Mesh(new PlaneGeometry(1, 0.6), new MeshBasicMaterial());- const hidden = new Mesh(new BoxGeometry(1, 1, 1), new MeshBasicMaterial());- hidden.visible = false;- const slats = new InstancedMesh(new BoxGeometry(0.05, 2, 0.05), new MeshBasicMaterial(), 12);- const inner = new Group();- inner.add(wall, face);- root.add(counter, inner, hidden, slats);- return { root, counter, wall, face, hidden, slats };-}--describe("station rim", () => {- it("draws only back faces, so the object hides all of it but its edge", () => {- const material = createRimMaterial();- expect(material.side).toBe(BackSide);- expect(material.depthWrite).toBe(false);- expect(material.uniforms.rimOpacity.value).toBe(0);- });-- it("wraps the solid, visible meshes of an object and nothing else", () => {- const { root, counter, wall } = prop();- expect(rimTargets(root)).toEqual([counter, wall]);- });-- it("puts a shell on each of them that shares their geometry and takes no clicks", () => {- const { root, counter, wall } = prop();- const material = createRimMaterial();- const shells = attachRim(root, material);- expect(shells.map((shell) => shell.parent)).toEqual([counter, wall]);- expect(shells[0]!.geometry).toBe(counter.geometry);- expect(shells.every((shell) => shell.material === material && !shell.castShadow)).toBe(true);- const hits: unknown[] = [];- shells[0]!.raycast(undefined as never, hits as never);- expect(hits).toEqual([]);- // Lighting it a second time must not rim the rim.- expect(rimTargets(root)).toEqual([counter, wall]);- });-- it("leaves the object exactly as it was when the rim comes off", () => {- const { root, counter, wall } = prop();- const before = [counter.children.length, wall.children.length];- const shells = attachRim(root, createRimMaterial());- detachRim(shells);- expect([counter.children.length, wall.children.length]).toEqual(before);- expect(shells.every((shell) => shell.parent === null)).toBe(true);- });-- it("notices an object that was rebuilt and left the scene", () => {- const scene = new Scene();- const { root, wall } = prop();- scene.add(root);- expect(attachedTo(wall, scene)).toBe(true);- scene.remove(root);- expect(attachedTo(wall, scene)).toBe(false);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/stationRim.ts b/dodaios/ui/web/frontend/src/components/society/office/stationRim.tsdeleted file mode 100644index 98062bbb3a..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/stationRim.ts+++ /dev/null@@ -1,101 +0,0 @@-/**- * The rim a station's object wears while the person is near it or points at- * it: a thin lit edge round the object's own silhouette. Every mesh under the- * object gets a shell of the same geometry, pushed out along its normals and- * drawn back faces only, so the object hides all of it but the edge. Nothing- * is added to the room at rest.- */-import { BackSide, Color, Mesh, ShaderMaterial, type InstancedMesh, type Object3D, type SkinnedMesh } from "three";--/**- * One blue for "you can use this", the same family as a selected agent's ring. Mid-bright and saturated on- * purpose: it has to read on the pale floor and light oak of the agents floor as well as on dark walnut and- * the coding floor's night.- */-export const STATION_RIM_COLOUR = "#3f8cff";-/** Edge width in metres up close; beyond `RIM_FAR_M` it grows with distance so it stays visible from the overview. */-const RIM_WIDTH_M = 0.016;-const RIM_FAR_M = 11;--/** Flat geometry has no silhouette to rim; its shell would only show as a stray sheet from behind. */-const FLAT_GEOMETRY = new Set(["PlaneGeometry", "CircleGeometry", "RingGeometry", "ShapeGeometry"]);--const RIM_FLAG = "stationRim";--export function createRimMaterial(): ShaderMaterial {- return new ShaderMaterial({- uniforms: {- rimColour: { value: new Color(STATION_RIM_COLOUR) },- rimOpacity: { value: 0 },- rimWidth: { value: RIM_WIDTH_M },- rimFar: { value: RIM_FAR_M },- },- vertexShader: /* glsl */ `- uniform float rimWidth;- uniform float rimFar;- void main() {- vec4 viewPosition = modelViewMatrix * vec4(position, 1.0);- vec3 viewNormal = normalize(normalMatrix * normal);- viewPosition.xyz += viewNormal * rimWidth * max(1.0, -viewPosition.z / rimFar);- gl_Position = projectionMatrix * viewPosition;- }- `,- fragmentShader: /* glsl */ `- uniform vec3 rimColour;- uniform float rimOpacity;- void main() {- gl_FragColor = vec4(rimColour, rimOpacity);- }- `,- side: BackSide,- transparent: true,- depthWrite: false,- toneMapped: false,- });-}--/** Can this object carry a shell? Plain, visible meshes with normals only. */-function rimmable(object: Object3D): object is Mesh {- const mesh = object as Mesh;- if (!mesh.isMesh || mesh.userData[RIM_FLAG]) return false;- if ((mesh as InstancedMesh).isInstancedMesh || (mesh as SkinnedMesh).isSkinnedMesh) return false;- const geometry = mesh.geometry;- if (!geometry?.attributes?.normal || !geometry.attributes.position) return false;- // Text and other instanced-attribute geometry needs its own shader to make sense.- if ((geometry as { isInstancedBufferGeometry?: boolean }).isInstancedBufferGeometry) return false;- return !FLAT_GEOMETRY.has(geometry.type);-}--/** The visible meshes under `root` that get a shell. */-export function rimTargets(root: Object3D): Mesh[] {- const targets: Mesh[] = [];- root.traverseVisible((object) => { if (rimmable(object)) targets.push(object); });- return targets;-}--/** Add a rim shell to every visible mesh under `root`; returns the shells so they can be taken off again. */-export function attachRim(root: Object3D, material: ShaderMaterial): Mesh[] {- return rimTargets(root).map((mesh) => {- const shell = new Mesh(mesh.geometry, material);- shell.userData[RIM_FLAG] = true;- shell.name = "station-rim";- // The shell is light, not a thing: no clicks, no shadows.- shell.raycast = () => undefined;- shell.castShadow = false;- shell.receiveShadow = false;- shell.frustumCulled = mesh.frustumCulled;- mesh.add(shell);- return shell;- });-}--/** Take the shells off again. Their geometry belongs to the meshes they copied, so nothing is disposed here. */-export function detachRim(shells: readonly Mesh[]): void {- for (const shell of shells) shell.removeFromParent();-}--/** Is `object` still part of the scene under `scene`? A re-rendered prop leaves its old group detached. */-export function attachedTo(object: Object3D, scene: Object3D): boolean {- for (let node: Object3D | null = object; node; node = node.parent) if (node === scene) return true;- return false;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/stationText.ts b/dodaios/ui/web/frontend/src/components/society/office/stationText.tsdeleted file mode 100644index e07708a714..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/stationText.ts+++ /dev/null@@ -1,19 +0,0 @@-/** A station in words: what it is called and what using it does. Shared by the prompt, the places menu and the directory. */-import type { Station } from "./stations";--type Translate = (key: string) => string;--/**- * What a station is called. A team studio's board is called after its team;- * the board of the studio for agents without a team says so, so no row of a- * list is ever a bare "Team board".- */-export function stationLabel(station: Pick<Station, "id" | "name">, t: Translate): string {- if (station.name) return station.name;- return t(station.id === "board" ? "society.office.team_pool" : `society.office.cp_${station.id}`);-}--/** The action a station offers, in words; the coffee bar's flips while a break is on. */-export function stationAction(station: Pick<Station, "id">, t: Translate, breakOn = false): string {- return t(`society.office.use_${station.id === "break" && breakOn ? "break_end" : station.id}`);-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/stations.test.ts b/dodaios/ui/web/frontend/src/components/society/office/stations.test.tsdeleted file mode 100644index a21cb438c7..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/stations.test.ts+++ /dev/null@@ -1,211 +0,0 @@-import { describe, expect, it } from "vitest";-import { buildOfficeLayout, FURNITURE_SIZE, type OfficeAgentInput, type OfficeLayout, type Studio } from "./officeLayout";-import { buildNavGrid, isWalkable, nearestWalkable } from "./officeNav";-import {- isReception, isTeamStand, loungeCentre, nearestInteractable, selectionKey, spawnScreenDive, stationOf, stationsFor, TEAM_STAND_ID, TEAM_STAND_STATION,-} from "./stations";--function roster(count: number): OfficeAgentInput[] {- return Array.from({ length: count }, (_, i) => ({- agentId: `a${i}`, name: `Agent ${i}`, tier: i === 0 ? "lead" as const : "specialist" as const,- providerLabel: i % 2 ? "Codex" : "Gemini", state: "idle" as const, createdMs: i,- }));-}--const REACH = { agent: 1.8, arcade: 0.9 };-const NOBODY: [string, { x: number; z: number }][] = [];-const NO_PETS = new Set<string>();--describe("stations", () => {- const agentsFloor = buildOfficeLayout(roster(8));- const codingFloor = buildOfficeLayout(roster(4), { variant: "coding" });-- it("turns every checkpoint of a floor into one station", () => {- for (const layout of [agentsFloor, codingFloor]) {- const stations = stationsFor(layout);- const checkpoints = stations.filter((s) => s.selection.kind === "checkpoint");- expect(checkpoints.map((s) => s.selection.id)).toEqual(layout.checkpoints.map((cp) => cp.id));- expect(new Set(stations.map((s) => s.key)).size).toBe(stations.length);- // The same plan gives the same list back, so a frame loop can ask every frame.- expect(stationsFor(layout)).toBe(stations);- }- });-- it("binds each station to an object of the room, never to a marker of its own", () => {- const props = new Map(agentsFloor.furniture.map((f) => [`prop:${f.id}`, f]));- const kindOf = (id: string) => {- const station = stationsFor(agentsFloor).find((s) => s.selection.id === id);- expect(station, id).toBeTruthy();- return station!.objects.map((name) => props.get(name)?.kind);- };- expect(kindOf("spawn")).toEqual(["spawnTerminal"]);- expect(kindOf("team")).toEqual(["teamBoard"]);- expect(kindOf("wardrobe")).toEqual(["dressingMirror"]);- expect(kindOf("break")).toEqual(["coffeeBar"]);- expect(kindOf("elevator")).toEqual(["elevator"]);- const codingProps = new Map(codingFloor.furniture.map((f) => [`prop:${f.id}`, f.kind]));- const codingKind = (id: string) => stationsFor(codingFloor).find((s) => s.selection.id === id)!.objects.map((name) => codingProps.get(name));- expect(codingKind("launch")).toEqual(["spawnTerminal"]);- expect(codingKind("mission")).toEqual(["commandWall"]);- });-- it("gives the reception desk the directory, whatever the plan calls its checkpoint", () => {- const desks = stationsFor(agentsFloor).filter((s) => isReception(s.selection));- expect(desks.length).toBeGreaterThan(0);- for (const desk of desks) {- expect(desk.id).toBe("manage");- expect(desk.icon).toBe("reception");- }- expect(desks.some((desk) => desk.objects.includes("prop:reception-desk"))).toBe(true);- expect(isReception({ kind: "checkpoint", id: "team" })).toBe(false);- expect(isReception({ kind: "agent", id: "manage" })).toBe(false);- });-- it("sizes a click target to the object's own footprint", () => {- const terminal = agentsFloor.furniture.find((f) => f.kind === "spawnTerminal")!;- const spawn = stationsFor(agentsFloor).find((s) => s.selection.id === "spawn")!;- expect(spawn.hits).toEqual([{- x: terminal.x, z: terminal.z, y: FURNITURE_SIZE.spawnTerminal.h / 2, rotationY: terminal.rotationY,- w: FURNITURE_SIZE.spawnTerminal.w, h: FURNITURE_SIZE.spawnTerminal.h, d: FURNITURE_SIZE.spawnTerminal.d,- }]);- });-- it("lights the lead's desks and puts their click target on the visitor side, clear of chair and monitors", () => {- const lead = stationsFor(agentsFloor).find((s) => s.selection.id === "lead")!;- const desks = agentsFloor.lead.desks;- expect(desks.length).toBeGreaterThan(0);- expect(lead.objects).toEqual(desks.map((d) => `desk:${d.id}`));- lead.hits.forEach((hit, i) => {- const desk = desks[i]!;- const seatSide = desk.facing === "north" ? 1 : -1;- // On the far side of the desk from the chair, and no taller than the desk top.- expect(Math.sign(hit.z - desk.z)).toBe(-seatSide);- expect(hit.y + hit.h / 2).toBeLessThan(0.76);- });- });-- it("stands the person somewhere they can actually walk to", () => {- for (const layout of [agentsFloor, codingFloor]) {- const grid = buildNavGrid(layout);- for (const station of stationsFor(layout)) {- const spot = isWalkable(grid, station.approach) ? station.approach : nearestWalkable(grid, station.approach);- expect(spot, station.key).toBeTruthy();- expect(Math.hypot(spot!.x - station.approach.x, spot!.z - station.approach.z), station.key).toBeLessThan(1.5);- }- }- });-- it("adds a station for every team studio's board, selected by the board's id", () => {- const board = { id: "studio-board:dept-0", x: 4, z: -6, facing: 0 };- const studios: Studio[] = [- { deptId: "dept-0", teamId: "g1", name: "Launch crew", members: ["a1", "a2"], leadId: null, board, huddleSpotIds: [], centre: { x: 4, z: -3 } },- { deptId: "dept-1", teamId: null, name: "", members: ["a3"], leadId: null, board: null, huddleSpotIds: [], centre: { x: 9, z: -3 } },- ];- const layout: OfficeLayout = { ...agentsFloor, studios };- const boards = stationsFor(layout).filter((s) => s.selection.kind === "team" && s.id !== TEAM_STAND_STATION);- expect(boards).toHaveLength(1);- const station = boards[0]!;- expect(station.selection).toEqual({ kind: "team", id: board.id });- expect(station.name).toBe("Launch crew");- expect(station.objects).toEqual([`prop:${board.id}`]);- // The person stands in front of the face, where the board looks.- expect(station.z).toBeGreaterThan(board.z);- expect(stationOf(layout, { kind: "team", id: board.id })).toBe(station);- expect(stationOf(layout, { kind: "team", id: "studio-board:gone" })).toBeNull();- expect(stationOf(layout, { kind: "agent", id: "a1" })).toBeNull();- // Standing there, E reaches the board.- expect(nearestInteractable(layout, station, NOBODY, NO_PETS, REACH)).toEqual(station.selection);- });-});--describe("the free plot's stand", () => {- // The plan's own stand is taken out, so the stand-in below is the only one.- const plan = buildOfficeLayout(roster(4));- const base: OfficeLayout = { ...plan, furniture: plan.furniture.filter((item) => !item.id.startsWith(TEAM_STAND_ID)) };- // Any piece will do for the plan: the stand is found by its id, not by its kind.- const stand = { id: `${TEAM_STAND_ID}`, kind: "lobbyLamp" as const, x: 6, z: 4, rotationY: Math.PI / 2, room: "floor" as const };- const layout: OfficeLayout = { ...base, furniture: [...base.furniture, stand] };-- it("is a station that selects the stand like a board, lights it and takes clicks on it", () => {- const station = stationsFor(layout).find((s) => s.id === TEAM_STAND_STATION)!;- expect(station.selection).toEqual({ kind: "team", id: stand.id });- expect(station.objects).toEqual([`prop:${stand.id}`]);- expect(station.hits).toEqual([{- x: stand.x, z: stand.z, y: FURNITURE_SIZE.lobbyLamp.h / 2, rotationY: stand.rotationY,- w: FURNITURE_SIZE.lobbyLamp.w, h: FURNITURE_SIZE.lobbyLamp.h, d: FURNITURE_SIZE.lobbyLamp.d,- }]);- // The person stands in front of its face (rotated a quarter turn: to the east of it).- expect(station.approach.x).toBeGreaterThan(stand.x + 0.9);- expect(station.approach.z).toBeCloseTo(stand.z);- expect(nearestInteractable(layout, station.approach, NOBODY, NO_PETS, REACH)).toEqual(station.selection);- });-- it("is told apart from a studio's board, and from a plan without one", () => {- expect(isTeamStand(layout, { kind: "team", id: stand.id })).toBe(true);- expect(isTeamStand(layout, { kind: "team", id: "studio-board:dept-0" })).toBe(false);- expect(isTeamStand(layout, { kind: "checkpoint", id: "team" })).toBe(false);- expect(isTeamStand(base, { kind: "team", id: stand.id })).toBe(false);- expect(stationsFor(base).some((s) => s.id === TEAM_STAND_STATION)).toBe(false);- });-});--describe("nearest interactable", () => {- const layout = buildOfficeLayout(roster(6));- const spawn = stationsFor(layout).find((s) => s.selection.id === "spawn")!;-- it("is the station whose reach the person stands in", () => {- expect(nearestInteractable(layout, spawn.approach, NOBODY, NO_PETS, REACH)).toEqual(spawn.selection);- });-- it("is nothing in the open, outside every reach", () => {- const far = { x: spawn.x + spawn.radius + 0.6, z: spawn.z };- const clear = stationsFor(layout).every((s) => Math.hypot(s.x - far.x, s.z - far.z) > s.radius);- expect(clear).toBe(true);- expect(nearestInteractable(layout, far, NOBODY, NO_PETS, REACH)).toBeNull();- });-- it("prefers whoever is closer: an agent at arm's length beats the station behind them", () => {- const at = spawn.approach;- const beside: [string, { x: number; z: number }][] = [["a2", { x: at.x + 0.3, z: at.z }]];- expect(Math.hypot(spawn.x - at.x, spawn.z - at.z)).toBeGreaterThan(0.3);- expect(nearestInteractable(layout, at, beside, NO_PETS, REACH)).toEqual({ kind: "agent", id: "a2" });- // The person's own pet walks beside them and is never the target.- expect(nearestInteractable(layout, at, beside, new Set(["a2"]), REACH)).toEqual(spawn.selection);- });-- it("offers a game cabinet only from in front of its screen", () => {- const cabinet = layout.furniture.find((f) => f.kind === "arcade")!;- const front = { x: cabinet.x + Math.sin(cabinet.rotationY) * 0.85, z: cabinet.z + Math.cos(cabinet.rotationY) * 0.85 };- expect(nearestInteractable(layout, front, NOBODY, NO_PETS, REACH)).toEqual({ kind: "arcade", id: cabinet.id });- });-});--describe("station helpers", () => {- const layout = buildOfficeLayout(roster(3));-- it("keys a selection by kind and id", () => {- expect(selectionKey({ kind: "checkpoint", id: "team" })).toBe("checkpoint:team");- expect(selectionKey({ kind: "team", id: "studio-board:d" })).toBe("team:studio-board:d");- });-- it("dives into the terminal face on the viewer's side", () => {- const terminal = layout.furniture.find((f) => f.kind === "spawnTerminal")!;- const south = spawnScreenDive(layout, { x: terminal.x, z: terminal.z + 3 })!;- const north = spawnScreenDive(layout, { x: terminal.x, z: terminal.z - 3 })!;- expect(south.target[2]).toBeGreaterThan(terminal.z);- expect(north.target[2]).toBeLessThan(terminal.z);- expect(Math.abs(north.facing - south.facing)).toBeCloseTo(Math.PI);- expect(south.target[1]).toBeLessThan(FURNITURE_SIZE.spawnTerminal.h);- expect(spawnScreenDive({ ...layout, furniture: [] }, { x: 0, z: 0 })).toBeNull();- });-- it("gathers a coffee break among the break room's couches", () => {- const centre = loungeCentre(layout);- const room = layout.rooms.find((r) => r.kind === "break")!;- expect(centre.x).toBeGreaterThan(room.minX);- expect(centre.x).toBeLessThan(room.maxX);- expect(centre.z).toBeGreaterThan(room.minZ);- expect(centre.z).toBeLessThan(room.maxZ);- expect(loungeCentre({ ...layout, spots: [] })).toEqual(layout.spawn);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/stations.ts b/dodaios/ui/web/frontend/src/components/society/office/stations.tsdeleted file mode 100644index 4467c28b89..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/stations.ts+++ /dev/null@@ -1,291 +0,0 @@-/**- * Stations: the things in the office the person can use. A station is never a- * marker of its own — it IS an object of the room (the reception desk, the- * spawn terminal, the team board, the wardrobe mirror, the coffee bar, a team- * studio's board, …). This module binds every checkpoint and every studio- * board of a floor plan to that object: which scene groups carry its rim,- * where the invisible click target sits, and where the person stands to use- * it. Pure and tested; the renderer (StationObjects), the HUD prompt and the- * player's nearest-interactable test all read this one list.- */-import { FURNITURE_SIZE, type Checkpoint, type Furniture, type FurnitureKind, type OfficeLayout, type Point } from "./officeLayout";-import type { Selection } from "./officeStore";--export type StationIcon = "spawn" | "launch" | "reception" | "team" | "wardrobe" | "lead" | "break" | "elevator" | "mission" | "studio" | "levels" | "ship";--/** A box in world space: centre, size (x-extent × height × z-extent before rotation) and rotation about +y. */-export interface StationBox { x: number; y: number; z: number; w: number; h: number; d: number; rotationY: number }--export interface Station {- /** Stable React key and lookup id: `<selection kind>:<selection id>`. */- key: string;- /** What using the station selects. */- selection: Selection;- icon: StationIcon;- /** The i18n id of its name and action (`cp_<id>`, `use_<id>`): the checkpoint id, or `board` for a studio board. */- id: string;- /** A studio board is called after its team; every other station is named by its i18n key. */- name: string | null;- /** Centre and radius of the place where E reaches the station. */- x: number;- z: number;- radius: number;- /** Where "walk there" ends. */- approach: Point;- /** Names of the scene groups that are the station (`prop:<furniture id>`, `desk:<desk id>`); they light up. */- objects: string[];- /** Invisible click and hover targets; empty when nothing in the room stands for the station. */- hits: StationBox[];-}--/**- * The furniture kind that stands for each checkpoint, most typical first. The- * piece of one of these kinds nearest to the checkpoint is the station, so a- * floor plan may rename or move its pieces without touching this table.- */-const STATION_PROPS: Readonly<Record<string, readonly FurnitureKind[]>> = {- spawn: ["spawnTerminal"],- launch: ["spawnTerminal"],- manage: ["receptionDesk", "agentTotem"],- create: ["receptionDesk"],- team: ["teamBoard"],- wardrobe: ["dressingMirror", "mirror"],- break: ["coffeeBar"],- elevator: ["elevator"],- mission: ["commandWall"],- studio: ["studioStage"],- levels: ["levelGuide"],-};--const STATION_ICONS: Readonly<Record<string, StationIcon>> = {- spawn: "spawn", launch: "launch", manage: "reception", team: "team", wardrobe: "wardrobe", lead: "lead", break: "break",- elevator: "elevator", mission: "mission", studio: "studio", levels: "levels", ship: "ship",-};--/** A flat piece (a stage, a pad) still needs something a pointer can hit. */-const MIN_HIT_HEIGHT = 0.12;-/** The lead desk's click target is its visitor-side front panel, so the monitors and the chair keep their own clicks. */-const DESK_FRONT = { h: 0.74, d: 0.1, gap: 0.04 } as const;-const DEFAULT_LEAD_DESK = { w: 2.4, d: 1.05 } as const;-/** The scene group of the courier on its pad (the ship station's object). */-export const COURIER_GROUP = "courier";--/** How far in front of a studio board the person stands, and how far around that spot E reaches. */-export const BOARD_STAND_M = 1.05;-export const BOARD_REACH_M = 1.25;--export function selectionKey(selection: Selection): string {- return `${selection.kind}:${selection.id}`;-}--function boxOf(item: Furniture): StationBox {- const size = FURNITURE_SIZE[item.kind];- const h = Math.max(size.h, MIN_HIT_HEIGHT);- return { x: item.x, y: h / 2, z: item.z, w: item.size?.w ?? size.w, h, d: item.size?.d ?? size.d, rotationY: item.rotationY };-}--function propFor(layout: OfficeLayout, checkpoint: Checkpoint): Furniture | null {- const kinds = STATION_PROPS[checkpoint.id];- if (!kinds) return null;- let best: Furniture | null = null;- let bestDistance = Infinity;- for (const item of layout.furniture) {- if (!kinds.includes(item.kind)) continue;- const d = Math.hypot(item.x - checkpoint.x, item.z - checkpoint.z);- if (d < bestDistance) { best = item; bestDistance = d; }- }- return best;-}--/** The reception desk is one station whatever a floor plan calls its checkpoint. */-const RECEPTION_IDS: ReadonlySet<string> = new Set(["manage", "create"]);--/** Is this selection the reception (the directory)? */-export function isReception(selection: Selection | null): boolean {- return selection?.kind === "checkpoint" && RECEPTION_IDS.has(selection.id);-}--function checkpointStation(layout: OfficeLayout, checkpoint: Checkpoint): Station {- const id = RECEPTION_IDS.has(checkpoint.id) ? "manage" : checkpoint.id as string;- const base = {- key: `checkpoint:${checkpoint.id}`,- selection: { kind: "checkpoint", id: checkpoint.id } as Selection,- icon: STATION_ICONS[id] ?? "reception",- id,- name: null,- x: checkpoint.x, z: checkpoint.z, radius: checkpoint.radius,- approach: checkpoint.approach ?? { x: checkpoint.x, z: checkpoint.z },- };- if (checkpoint.id === "lead") {- // The lead's desks are desk slots, not furniture: each one is drawn under a `desk:<id>` group.- const desks = layout.lead.desks;- return {- ...base,- objects: desks.map((desk) => `desk:${desk.id}`),- hits: desks.map((desk) => {- const size = desk.size ?? DEFAULT_LEAD_DESK;- // The seated lead looks at its monitors; visitors stand on the far side of the desk from the chair.- const towardsVisitor = desk.facing === "north" ? -1 : 1;- return {- x: desk.x, y: DESK_FRONT.h / 2, z: desk.z + towardsVisitor * (size.d / 2 + DESK_FRONT.gap),- w: size.w, h: DESK_FRONT.h, d: DESK_FRONT.d, rotationY: 0,- };- }),- };- }- if (checkpoint.id === "ship" && layout.skyPad) {- // The courier itself is the station: its scene group lights up and its body takes the click.- const { shipRect } = layout.skyPad;- return {- ...base,- objects: [COURIER_GROUP],- hits: [{- x: (shipRect.minX + shipRect.maxX) / 2, y: 2, z: (shipRect.minZ + shipRect.maxZ) / 2,- w: shipRect.maxX - shipRect.minX, h: 4, d: shipRect.maxZ - shipRect.minZ, rotationY: 0,- }],- };- }- const prop = propFor(layout, checkpoint);- return { ...base, objects: prop ? [`prop:${prop.id}`] : [], hits: prop ? [boxOf(prop)] : [] };-}--function boardStations(layout: OfficeLayout): Station[] {- const out: Station[] = [];- for (const studio of layout.studios ?? []) {- const board = studio.board;- if (!board) continue;- const item = layout.furniture.find((f) => f.id === board.id);- const size = FURNITURE_SIZE.studioBoard;- const front = { x: board.x + Math.sin(board.facing) * BOARD_STAND_M, z: board.z + Math.cos(board.facing) * BOARD_STAND_M };- out.push({- key: `team:${board.id}`,- selection: { kind: "team", id: board.id },- icon: "team",- id: "board",- name: studio.name || null,- x: front.x, z: front.z, radius: BOARD_REACH_M,- approach: front,- objects: [`prop:${board.id}`],- hits: [item ? boxOf(item) : { x: board.x, y: size.h / 2, z: board.z, w: size.w, h: size.h, d: size.d, rotationY: board.facing }],- });- }- return out;-}--/**- * The free plot's stand ("start a team here"): the furniture piece whose id starts with this, whatever its kind.- * Its station selects `{ kind: "team", id: <furniture id> }` like a studio board, but there is no team behind it- * yet: it opens the new-team form.- */-export const TEAM_STAND_ID = "team-stand";-/** The i18n id of the stand's station (`cp_found`, `use_found`). */-export const TEAM_STAND_STATION = "found";-/** How far in front of the stand's face the person stands. */-const STAND_FRONT_M = 0.95;--function standStations(layout: OfficeLayout): Station[] {- return layout.furniture.filter((item) => item.id.startsWith(TEAM_STAND_ID)).map((item) => {- const box = boxOf(item);- const reach = box.d / 2 + STAND_FRONT_M;- // A piece's front faces its local +z (rotationY 0 = south, towards the camera).- const front = { x: item.x + Math.sin(item.rotationY) * reach, z: item.z + Math.cos(item.rotationY) * reach };- return {- key: `team:${item.id}`,- selection: { kind: "team", id: item.id } as Selection,- icon: "team" as const,- id: TEAM_STAND_STATION,- name: null,- x: front.x, z: front.z, radius: BOARD_REACH_M,- approach: front,- objects: [`prop:${item.id}`],- hits: [box],- };- });-}--/** Is this selection the free plot's stand, where a new team is started? */-export function isTeamStand(layout: OfficeLayout, selection: Selection | null): boolean {- return stationOf(layout, selection)?.id === TEAM_STAND_STATION;-}--const cache = new WeakMap<OfficeLayout, Station[]>();--/** Every station of a floor plan: its checkpoints first, then the team studios' boards and the free plot's stand. Cached per plan. */-export function stationsFor(layout: OfficeLayout): Station[] {- let stations = cache.get(layout);- if (!stations) {- stations = [...layout.checkpoints.map((checkpoint) => checkpointStation(layout, checkpoint)), ...boardStations(layout), ...standStations(layout)];- cache.set(layout, stations);- }- return stations;-}--export function stationOf(layout: OfficeLayout, selection: Selection | null): Station | null {- if (!selection || (selection.kind !== "checkpoint" && selection.kind !== "team")) return null;- const key = selectionKey(selection);- return stationsFor(layout).find((station) => station.key === key) ?? null;-}--/** How long called agents (one called over, a coffee break) stay before they drift back to their day. */-export const CALL_MS = 25_000;--/** Game cabinets are played standing this far in front of the screen (it faces the cabinet's local +z). */-const CABINET_STAND_M = 0.85;--/**- * The closest thing the person can use from where they stand (E): a station- * whose reach they are in, an agent within talking range, or a game cabinet- * they stand in front of. `agents` are the walkers' positions; `skip` are- * agents that keep the person company (their pet), which are never a target.- */-export function nearestInteractable(- layout: OfficeLayout, at: Point, agents: Iterable<readonly [string, Point]>, skip: { has: (id: string) => boolean },- ranges: { agent: number; arcade: number },-): Selection | null {- let best: Selection | null = null;- let bestDistance = Infinity;- for (const station of stationsFor(layout)) {- const d = Math.hypot(station.x - at.x, station.z - at.z);- if (d <= station.radius && d < bestDistance) { best = station.selection; bestDistance = d; }- }- for (const [id, p] of agents) {- if (skip.has(id)) continue;- const d = Math.hypot(p.x - at.x, p.z - at.z);- if (d <= ranges.agent && d < bestDistance) { best = { kind: "agent", id }; bestDistance = d; }- }- for (const item of layout.furniture) {- // The break room's cabinet, and every game cabinet on the arcade floor.- if (item.kind !== "arcade" && item.kind !== "retroCabinet") continue;- const fx = item.x + Math.sin(item.rotationY) * CABINET_STAND_M, fz = item.z + Math.cos(item.rotationY) * CABINET_STAND_M;- const d = Math.hypot(fx - at.x, fz - at.z);- if (d <= ranges.arcade && d < bestDistance) { best = { kind: "arcade", id: item.id }; bestDistance = d; }- }- return best;-}--/**- * The spawn terminal's screen, in the terminal's own frame (SpawnPoint.tsx- * draws it there): the camera dives into it before the create dialog opens.- */-export const SPAWN_SCREEN = { y: 1.42, z: 0.0355, w: 0.86, h: 0.58 } as const;--/** The screen face of the spawn terminal that looks at `viewer`, as a dive target; null on a floor without a terminal. */-export function spawnScreenDive(layout: OfficeLayout, viewer: Point): { target: [number, number, number]; facing: number; size: [number, number] } | null {- const terminal = layout.furniture.find((f) => f.kind === "spawnTerminal");- if (!terminal) return null;- const sin = Math.sin(terminal.rotationY), cos = Math.cos(terminal.rotationY);- // The terminal is double-sided: take the face on the viewer's side.- const side = (viewer.x - terminal.x) * sin + (viewer.z - terminal.z) * cos >= 0 ? 1 : -1;- return {- target: [terminal.x + sin * SPAWN_SCREEN.z * side, SPAWN_SCREEN.y, terminal.z + cos * SPAWN_SCREEN.z * side],- facing: terminal.rotationY + (side === 1 ? 0 : Math.PI),- size: [SPAWN_SCREEN.w, SPAWN_SCREEN.h],- };-}--/** The middle of the break room's couches, where a coffee break gathers; the floor's entrance on a floor without any. */-export function loungeCentre(layout: OfficeLayout): Point {- const couches = layout.spots.filter((spot) => spot.kind === "couch" && spot.room === "break");- if (couches.length === 0) return layout.spawn;- return { x: couches.reduce((sum, p) => sum + p.x, 0) / couches.length, z: couches.reduce((sum, p) => sum + p.z, 0) / couches.length };-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/statusWall.test.ts b/dodaios/ui/web/frontend/src/components/society/office/statusWall.test.tsdeleted file mode 100644index 6111a533cc..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/statusWall.test.ts+++ /dev/null@@ -1,32 +0,0 @@-import { describe, expect, it } from "vitest";-import type { CostSummary } from "@/hooks/useCosts";-import { formatCount, formatUsd, ideSpendFrom } from "./ServerRoom";--const bucket = (key: string, cost_usd: number) => ({ key, cost_usd }) as CostSummary["series"][number];--describe("server room status wall: Agentic IDE spend", () => {- it("reads cost, what an API key paid, tokens, sessions and the costliest models", () => {- const summary = {- totals: { cost_usd: 120, subscription_usd: 100, tokens_total: 3_400_000 },- refs_total: 12,- series: [bucket("d1", 20), bucket("d2", 100)],- by_model: [bucket("small", 5), bucket("big", 90), bucket("mid", 25)],- } as unknown as CostSummary;- const spend = ideSpendFrom(summary, 30);- expect(spend).toMatchObject({ days: 30, cost: 120, billed: 20, tokens: 3_400_000, sessions: 12 });- expect(spend?.series.map((s) => s.cost)).toEqual([20, 100]);- expect(spend?.models.map((m) => m.name)).toEqual(["big", "mid", "small"]);- expect(ideSpendFrom(undefined, 30)).toBeNull();- });-- it("formats money and counts to fit a tile", () => {- expect(formatUsd(12694.39)).toBe("$12,694");- expect(formatUsd(202.85)).toBe("$202.85");- expect(formatUsd(0.0421)).toBe("$0.042");- expect(formatUsd(0)).toBe("$0");- expect(formatCount(16_775_188_426)).toBe("16.8B");- expect(formatCount(34_500_000)).toBe("34.5M");- expect(formatCount(812_400)).toBe("812K");- expect(formatCount(950)).toBe("950");- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/studioBoardContent.test.ts b/dodaios/ui/web/frontend/src/components/society/office/studioBoardContent.test.tsdeleted file mode 100644index f1b5c93bdd..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/studioBoardContent.test.ts+++ /dev/null@@ -1,123 +0,0 @@-import { describe, expect, it } from "vitest";-import type { AgentRunState } from "../data";-import { emptyRound, type TeamRound } from "./teamwork";-import {- MAX_BOARD_LINES, MAX_BOARD_MEMBERS, MAX_LIVE_BOARDS, boardModel, boardSignature, pickBoards, type BoardLabels,-} from "./studioBoardContent";--const labels: BoardLabels = {- pool: "Open studio", members: "{0} members", live: "Live", speaking: "Speaking", you: "You",- empty: "Nothing has been said yet.", poolNote: "No team yet.", loading: "Reading…", unavailable: "Cannot be read.", lead: "Lead: {0}", more: "+{0} more",- state: { working: "Working", waiting: "Waiting", idle: "Idle", paused: "Paused" },-};-const agent = (name: string, state: AgentRunState) => ({ name, state });-const agents = new Map([["nora", agent("Nora", "working")], ["ben", agent("Ben", "idle")], ["kai", agent("Kai", "waiting")], ["zoe", agent("Zoe", "paused")]]);-const studio = { name: "Launch crew", teamId: "t", members: ["nora", "ben", "kai"] };-const round = (extra: Partial<TeamRound>): TeamRound => ({ ...emptyRound("t"), loaded: true, ...extra });--describe("what a studio board shows", () => {- it("names the team and lists its members with the state each is really in", () => {- const model = boardModel(studio, agents, round({}), labels);- expect(model).toMatchObject({ title: "Launch crew", count: "3 members", live: false, hidden: 0 });- expect(model.members).toEqual([- { id: "nora", name: "Nora", state: "working", speaking: false, lead: false },- { id: "ben", name: "Ben", state: "idle", speaking: false, lead: false },- { id: "kai", name: "Kai", state: "waiting", speaking: false, lead: false },- ]);- });-- it("marks a running round and the member contributing to it", () => {- const model = boardModel(studio, agents, round({ running: true, speakerId: "nora" }), labels);- expect(model.live).toBe(true);- expect(model.members.map((m) => m.speaking)).toEqual([true, false, false]);- // A speaker left over from a settled round is nobody's turn.- expect(boardModel(studio, agents, round({ running: false, speakerId: "nora" }), labels).members.some((m) => m.speaking)).toBe(false);- });-- it("shows the newest real lines of the team's chat, the person's as theirs, in plain text", () => {- const lines = Array.from({ length: 9 }, (_, i) => ({ id: `e${i}`, speaker: i % 3 === 0 ? "user" : "nora", text: `**line** ${i} with a [link](https://example.test)` }));- const model = boardModel(studio, agents, round({ lines }), labels);- expect(model.lines).toHaveLength(MAX_BOARD_LINES);- expect(model.lines[model.lines.length - 1]).toEqual({ id: "e8", who: "Nora", text: "line 8 with a link", fromPerson: false });- expect(model.lines.find((l) => l.fromPerson)?.who).toBe("You");- expect(model.note).toBeNull();- });-- it("is honest when there is nothing to show", () => {- expect(boardModel(studio, agents, round({}), labels).note).toBe(labels.empty);- expect(boardModel(studio, agents, undefined, labels).note).toBe(labels.loading);- expect(boardModel(studio, agents, { ...emptyRound("t") }, labels).note).toBe(labels.loading);- // A team whose chat could never be read says so instead of "reading" for ever.- expect(boardModel(studio, agents, { ...emptyRound("t"), unavailable: true }, labels).note).toBe(labels.unavailable);- // What was read before a failure stays on the board.- expect(boardModel(studio, agents, round({ unavailable: true, lines: [{ id: "e1", speaker: "nora", text: "hi" }] }), labels).note).toBeNull();- // The pool has no team chat: it says so, and never borrows lines.- const pool = boardModel({ name: "", teamId: null, members: ["zoe"] }, agents, round({ lines: [{ id: "e1", speaker: "nora", text: "hi" }] }), labels);- expect(pool).toMatchObject({ title: "Open studio", note: labels.poolNote, lines: [], count: "1 members" });- });-- it("adds team members who sit in another studio, skips who left the roster, and counts who does not fit", () => {- const model = boardModel(studio, agents, round({ members: ["nora", "zoe", "gone"] }), labels);- expect(model.members.map((m) => m.id)).toEqual(["nora", "ben", "kai", "zoe"]);- const crowd = new Map(Array.from({ length: 9 }, (_, i) => [`m${i}`, agent(`M${i}`, "idle")] as const));- const big = boardModel({ name: "Big", teamId: "t", members: [...crowd.keys()] }, crowd, round({}), labels);- expect(big.members).toHaveLength(MAX_BOARD_MEMBERS);- expect(big.hidden).toBe(9 - MAX_BOARD_MEMBERS);- expect(big.count).toBe("9 members");- });-- it("changes its signature only when the face would look different", () => {- const a = boardModel(studio, agents, round({ lines: [{ id: "e1", speaker: "nora", text: "hi" }] }), labels);- const same = boardModel(studio, new Map(agents), round({ lines: [{ id: "e1", speaker: "nora", text: "hi" }], fetchedMs: 999, dirty: true }), labels);- expect(boardSignature(same, labels)).toBe(boardSignature(a, labels));- const busy = new Map(agents).set("ben", agent("Ben", "working"));- expect(boardSignature(boardModel(studio, busy, round({ lines: [{ id: "e1", speaker: "nora", text: "hi" }] }), labels), labels)).not.toBe(boardSignature(a, labels));- expect(boardSignature(boardModel(studio, agents, round({ running: true, lines: [{ id: "e1", speaker: "nora", text: "hi" }] }), labels), labels)).not.toBe(boardSignature(a, labels));- });-});--describe("a team with a lead", () => {- it("lists the lead first and marks it, whatever its seat", () => {- const model = boardModel({ ...studio, leadId: "kai" }, agents, round({}), labels);- expect(model.members.map((m) => [m.id, m.lead])).toEqual([["kai", true], ["nora", false], ["ben", false]]);- expect(model.count).toBe("3 members");- // A lead that sits in another studio is still this team's lead while its round lists it.- const elsewhere = boardModel({ ...studio, leadId: "zoe" }, agents, round({ members: ["nora", "zoe"] }), labels);- expect(elsewhere.members.map((m) => [m.id, m.lead])).toEqual([["zoe", true], ["nora", false], ["ben", false], ["kai", false]]);- // The mark changes the face.- expect(boardSignature(model, labels)).not.toBe(boardSignature(boardModel(studio, agents, round({}), labels), labels));- });-- it("keeps the lead in view on a team larger than the list", () => {- const crowd = new Map(Array.from({ length: 9 }, (_, i) => [`m${i}`, agent(`M${i}`, "idle")] as const));- const big = boardModel({ name: "Big", teamId: "t", members: [...crowd.keys()], leadId: "m8" }, crowd, round({}), labels);- expect(big.members[0]).toMatchObject({ id: "m8", lead: true });- expect(big.members).toHaveLength(MAX_BOARD_MEMBERS);- });-- it("is the board it always was without one, or when the lead is not on the roster", () => {- const plain = boardModel(studio, agents, round({}), labels);- for (const leadId of [null, undefined, "stranger", ""]) {- const model = boardModel({ ...studio, leadId }, agents, round({}), labels);- expect(model).toEqual(plain);- expect(boardSignature(model, labels)).toBe(boardSignature(plain, labels));- }- expect(plain.members.some((m) => m.lead)).toBe(false);- });-});--describe("which boards are live", () => {- it("draws the boards in view and keeps only the nearest few teams current", () => {- const boards = [- { id: "b-pool", teamId: null, distance: 5 }, { id: "b1", teamId: "t1", distance: 12 }, { id: "b2", teamId: "t2", distance: 8 },- { id: "b3", teamId: "t3", distance: 20 }, { id: "b4", teamId: "t4", distance: 25 }, { id: "b5", teamId: "t5", distance: 45 }, { id: "b6", teamId: "t6", distance: 90 },- ];- const { drawn, live } = pickBoards(boards);- expect([...drawn].sort()).toEqual(["b-pool", "b1", "b2", "b3", "b4", "b5"]);- expect([...live]).toEqual(["t2", "t1", "t3"]);- expect(live.size).toBe(MAX_LIVE_BOARDS);- });- it("keeps nothing live from the overview", () => {- expect(pickBoards([{ id: "b1", teamId: "t1", distance: 120 }])).toEqual({ drawn: new Set(), live: new Set() });- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/studioBoardContent.ts b/dodaios/ui/web/frontend/src/components/society/office/studioBoardContent.tsdeleted file mode 100644index 8c89e85d99..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/studioBoardContent.ts+++ /dev/null@@ -1,216 +0,0 @@-/**- * What a studio board shows: the team's name, its members with their real- * run state, and the newest real lines of the team's chat — or an honest- * empty state. The model is pure and tested; the drawing puts it on a canvas.- */-import type { AgentRunState, SocietyAgent } from "../data";-import type { Studio } from "./officeLayout";-import { bubbleText } from "./officeTalk";-import type { TeamRound } from "./teamwork";--/** The live content lies this far in front of the board's own paper face (`studioBoardFace` in the layout). */-export const BOARD_LIFT_M = 0.012;-/** The canvas, in the face's proportion (2.16 m × 1.16 m). */-export const BOARD_CANVAS = { w: 1024, h: 550 } as const;--/** Boards within this camera distance are drawn; nearer than BOARD_LIVE_RANGE_M they are also kept current. */-export const BOARD_DRAW_RANGE_M = 60;-export const BOARD_LIVE_RANGE_M = 30;-/** At most this many boards are live at once: the nearest ones. */-export const MAX_LIVE_BOARDS = 3;--/**- * Which boards to draw (their ids) and which teams to keep live (their team ids), from each board's distance to- * the camera. A pool studio's board is drawn but never live: it has no team chat to read.- */-export function pickBoards(boards: readonly { id: string; teamId: string | null; distance: number }[]): { drawn: Set<string>; live: Set<string> } {- const drawn = new Set(boards.filter((b) => b.distance <= BOARD_DRAW_RANGE_M).map((b) => b.id));- const live = new Set(boards.filter((b) => b.teamId !== null && b.distance <= BOARD_LIVE_RANGE_M)- .sort((a, b) => a.distance - b.distance || a.id.localeCompare(b.id)).slice(0, MAX_LIVE_BOARDS).map((b) => b.teamId as string));- return { drawn, live };-}--/** Rows that fit the member column, and chat lines the model keeps for the other one. */-export const MAX_BOARD_MEMBERS = 6;-export const MAX_BOARD_LINES = 5;--export interface BoardLabels {- /** Title of a studio without a name of its own (the pool). */- pool: string;- /** "{0} members" */- members: string;- live: string;- speaking: string;- you: string;- /** A team whose chat holds nothing yet. */- empty: string;- /** The pool studio: there is no team chat to show. */- poolNote: string;- /** The transcript has not been read yet. */- loading: string;- /** The transcript cannot be read right now. */- unavailable: string;- /** How the team's lead is named in the member list: "Lead: {0}". */- lead: string;- /** "+{0} more" */- more: string;- state: Record<AgentRunState, string>;-}--export interface BoardMember { id: string; name: string; state: AgentRunState; speaking: boolean; /** The team's lead, listed first. */ lead: boolean }-export interface BoardLine { id: string; who: string; text: string; fromPerson: boolean }--export interface BoardModel {- title: string;- count: string;- /** A round is answering right now. */- live: boolean;- members: BoardMember[];- /** Members that did not fit the column. */- hidden: number;- lines: BoardLine[];- /** Shown instead of chat lines when there are none. */- note: string | null;-}--export function boardModel(- studio: Pick<Studio, "name" | "teamId" | "members"> & { leadId?: string | null }, agents: ReadonlyMap<string, Pick<SocietyAgent, "name" | "state">>,- round: TeamRound | undefined, labels: BoardLabels,-): BoardModel {- // Everyone seated here, then team members who sit elsewhere (an agent can be in several teams).- const listed = [...studio.members, ...(round?.members ?? []).filter((id) => !studio.members.includes(id))];- // The team's lead, when it has one among its members, comes first.- const leadId = studio.leadId && listed.includes(studio.leadId) ? studio.leadId : null;- const ids = leadId ? [leadId, ...listed.filter((id) => id !== leadId)] : listed;- const present = ids.flatMap((id) => {- const agent = agents.get(id);- return agent ? [{ id, name: agent.name, state: agent.state, speaking: !!round?.running && round.speakerId === id, lead: id === leadId }] : [];- });- const lines: BoardLine[] = (round?.lines ?? []).slice(-MAX_BOARD_LINES).map((line) => ({- id: line.id, fromPerson: line.speaker === "user",- who: line.speaker === "user" ? labels.you : agents.get(line.speaker)?.name ?? "—",- text: bubbleText(line.text, 170),- }));- let note: string | null = null;- if (studio.teamId === null) note = labels.poolNote;- else if (!round?.loaded && lines.length === 0) note = round?.unavailable ? labels.unavailable : labels.loading;- else if (lines.length === 0) note = labels.empty;- return {- title: studio.name.trim() || labels.pool,- count: labels.members.replace("{0}", String(present.length)),- live: !!round?.running,- members: present.slice(0, MAX_BOARD_MEMBERS),- hidden: Math.max(0, present.length - MAX_BOARD_MEMBERS),- lines: studio.teamId === null ? [] : lines,- note,- };-}--/** A cheap identity for "does the face need a redraw". */-export function boardSignature(model: BoardModel, labels: BoardLabels): string {- return JSON.stringify([model.title, model.count, model.live, model.hidden, model.note,- model.members.map((m) => [m.name, m.state, m.speaking, m.lead]), model.lines.map((l) => [l.id, l.who, l.text]),- labels.live, labels.speaking, labels.more, labels.state, labels.lead]);-}--/** Ink on the board's paper face: the same sheet the board shows at rest, now written on. */-const PAPER = { sheet: "#f6f3ec", dots: "rgba(60,56,50,0.16)", ink: "#1f2430", soft: "#5b6475", faint: "#8a8f98", rule: "#3b4250", live: "#2f9e5b", person: "#2f6fd0" } as const;-const STATE_COLOUR: Record<AgentRunState, string> = { working: "#2f9e5b", waiting: "#c98a12", idle: "#8a8f98", paused: "#b9bcc2" };-const FONT = "system-ui, -apple-system, 'Segoe UI', sans-serif";--function clipped(ctx: CanvasRenderingContext2D, text: string, maxWidth: number): string {- if (ctx.measureText(text).width <= maxWidth) return text;- let cut = text;- while (cut.length > 1 && ctx.measureText(`${cut}…`).width > maxWidth) cut = cut.slice(0, -1);- return `${cut.trimEnd()}…`;-}--function wrap(ctx: CanvasRenderingContext2D, text: string, width: number, maxRows: number): string[] {- const rows: string[] = [];- let row = "";- for (const word of text.split(" ")) {- const next = row ? `${row} ${word}` : word;- if (ctx.measureText(next).width > width && row) { rows.push(row); row = word; } else row = next;- }- if (row) rows.push(row);- if (rows.length <= maxRows) return rows;- const kept = rows.slice(0, maxRows);- kept[maxRows - 1] = clipped(ctx, `${kept[maxRows - 1]} …`, width);- return kept;-}--export function drawStudioBoard(ctx: CanvasRenderingContext2D, model: BoardModel, labels: BoardLabels): void {- const { w: W, h: H } = BOARD_CANVAS;- ctx.fillStyle = PAPER.sheet;- ctx.fillRect(0, 0, W, H);- ctx.fillStyle = PAPER.dots;- for (let y = 28; y < H; y += 47) for (let x = 28; x < W; x += 47) ctx.fillRect(x, y, 4, 4);- // Header: the team's name, and whether a round is answering.- ctx.fillStyle = PAPER.rule;- ctx.fillRect(36, 90, W - 72, 4);- ctx.textBaseline = "middle";- ctx.textAlign = "left";- ctx.font = `600 28px ${FONT}`;- const right = model.live ? labels.live : model.count;- const rightW = ctx.measureText(right).width;- if (model.live) {- ctx.fillStyle = PAPER.live;- ctx.beginPath();- ctx.roundRect(W - 36 - rightW - 44, 24, rightW + 44, 44, 22);- ctx.fill();- ctx.fillStyle = "#ffffff";- ctx.fillText(right, W - 36 - rightW - 22, 47);- } else {- ctx.fillStyle = PAPER.soft;- ctx.fillText(right, W - 36 - rightW, 47);- }- ctx.fillStyle = PAPER.ink;- ctx.font = `700 42px ${FONT}`;- ctx.fillText(clipped(ctx, model.title, W - 72 - rightW - 80), 36, 48);-- // Left: the members and what each is really doing.- const colW = 340, rowH = 68, top = 112;- model.members.forEach((member, i) => {- const y = top + i * rowH + rowH / 2;- ctx.fillStyle = member.speaking ? PAPER.live : STATE_COLOUR[member.state];- ctx.beginPath(); ctx.arc(50, y, 10, 0, Math.PI * 2); ctx.fill();- ctx.fillStyle = PAPER.ink;- ctx.font = `600 29px ${FONT}`;- ctx.fillText(clipped(ctx, member.lead ? labels.lead.replace("{0}", member.name) : member.name, colW - 60), 76, y - 12);- ctx.fillStyle = member.speaking ? PAPER.live : PAPER.soft;- ctx.font = `500 21px ${FONT}`;- ctx.fillText(clipped(ctx, member.speaking ? labels.speaking : labels.state[member.state], colW - 60), 76, y + 17);- });- if (model.hidden > 0) {- ctx.fillStyle = PAPER.faint;- ctx.font = `500 22px ${FONT}`;- ctx.fillText(labels.more.replace("{0}", String(model.hidden)), 76, H - 22);- }- ctx.fillStyle = "rgba(59,66,80,0.28)";- ctx.fillRect(colW + 44, 112, 2, H - 136);-- // Right: the newest lines of the team's chat, the latest at the bottom.- const left = colW + 72, width = W - left - 36, lineH = 31;- if (model.lines.length === 0) {- if (!model.note) return;- ctx.fillStyle = PAPER.soft;- ctx.font = `500 27px ${FONT}`;- wrap(ctx, model.note, width, 4).forEach((row, i) => ctx.fillText(row, left, 150 + i * 36));- return;- }- ctx.font = `500 25px ${FONT}`;- const blocks = model.lines.map((line) => ({ line, rows: wrap(ctx, line.text, width, 3) }));- let y = H - 22;- for (let i = blocks.length - 1; i >= 0; i -= 1) {- const { line, rows } = blocks[i];- const height = 30 + rows.length * lineH + 10;- if (y - height < 104) break;- y -= height;- ctx.fillStyle = line.fromPerson ? PAPER.person : PAPER.ink;- ctx.font = `700 23px ${FONT}`;- ctx.fillText(clipped(ctx, line.who, width), left, y + 15);- ctx.fillStyle = PAPER.soft;- ctx.font = `500 25px ${FONT}`;- rows.forEach((row, r) => ctx.fillText(row, left, y + 30 + r * lineH + lineH / 2));- }-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/teamMeeting.test.ts b/dodaios/ui/web/frontend/src/components/society/office/teamMeeting.test.tsdeleted file mode 100644index 1cf2500e50..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/teamMeeting.test.ts+++ /dev/null@@ -1,171 +0,0 @@-import { describe, expect, it } from "vitest";-import { huddlePlaces, studioOfTeam } from "./officeTeams";-import { campusOf } from "./officeFixtures";-import type { SocietyAgent } from "../data";-import { allDesks, buildOfficeLayout, type OfficeAgentInput } from "./officeLayout";-import { buildNavGrid, isWalkable } from "./officeNav";-import { createRng, planFor, SpotBook, type PlanInput } from "./officeBehavior";-import { boardSeats, MEETING_MS, meetingProgress, meetingSeats, minutesLeft } from "./teamMeeting";-import type { TeamMeeting } from "./officeStore";--const roster: OfficeAgentInput[] = Array.from({ length: 9 }, (_, i) => ({- agentId: `a${i}`, name: `a${i}`, tier: "specialist", providerLabel: "Codex", state: "idle", createdMs: i,-}));-const layout = buildOfficeLayout(roster);-const grid = buildNavGrid(layout);-const ids = roster.map((r) => r.agentId);--function agent(agentId: string, state: SocietyAgent["state"]): SocietyAgent {- return { agentId, name: agentId, state } as SocietyAgent;-}--function input(agentId: string, book: SpotBook, extra: Partial<PlanInput>): PlanInput {- return {- agentId, state: "idle", desk: allDesks(layout).find((d) => d.agentId === agentId) ?? null, layout, grid,- rng: createRng(agentId), book, previous: null, workingColleagues: [], calledTo: null, ...extra,- };-}--describe("meetingSeats", () => {- it("gives every member its own chair, middle chairs first, facing pairs together", () => {- const seats = meetingSeats(layout, ["a0", "a1"]);- const [s0, s1] = [seats.a0, seats.a1];- expect(s0.spotId).toMatch(/^meeting-/);- expect(s1.spotId).toMatch(/^meeting-/);- expect(s0.spotId).not.toBe(s1.spotId);- // Across the table from each other: same x, opposite sides.- expect(s0.target.x).toBeCloseTo(s1.target.x);- expect(s0.target.z).not.toBeCloseTo(s1.target.z);- });-- it("lets members beyond the chairs stand at the table's ends on walkable floor", () => {- const seats = meetingSeats(layout, ids);- const chairs = layout.spots.filter((s) => s.kind === "meeting").length;- const standing = ids.filter((id) => !seats[id].spotId);- expect(standing).toHaveLength(ids.length - chairs);- for (const id of standing) expect(isWalkable(grid, seats[id].target)).toBe(true);- });-});--describe("planFor with a meeting chair", () => {- it("sits a called member on its chair", () => {- const seat = meetingSeats(layout, ["a3"]).a3;- const plan = planFor(input("a3", new SpotBook(), { calledTo: seat.target, calledSeat: seat.spotId }));- expect(plan.kind).toBe("meeting");- expect(plan.pose).toBe("sit");- expect(plan.spotId).toBe(seat.spotId);- expect(plan.target).toEqual(seat.target);- });-- it("takes another free chair when its own is occupied", () => {- const book = new SpotBook();- const seat = meetingSeats(layout, ["a3"]).a3;- book.claim(seat.spotId!, "stranger");- const plan = planFor(input("a3", book, { calledTo: seat.target, calledSeat: seat.spotId }));- expect(plan.kind).toBe("meeting");- expect(plan.spotId).not.toBe(seat.spotId);- expect(plan.spotId).toMatch(/^meeting-/);- });-- it("never pulls a working agent away from its screen", () => {- const seat = meetingSeats(layout, ["a3"]).a3;- expect(planFor(input("a3", new SpotBook(), { state: "working", calledTo: seat.target, calledSeat: seat.spotId })).kind).toBe("work");- });-});--describe("meetingProgress", () => {- it("sorts members into seated, arriving, busy and missing", () => {- const meeting: TeamMeeting = { groupId: "g", name: "Crew", members: ["a0", "a1", "a2", "gone"], untilMs: 1 };- const seats = meetingSeats(layout, meeting.members);- const summons = Object.fromEntries(Object.entries(seats).map(([id, s]) => [id, { ...s, untilMs: 1 }]));- const positions = new Map([- ["a0", seats.a0.target],- ["a1", { x: seats.a1.target.x + 3, z: seats.a1.target.z }],- ["a2", { x: 0, z: 0 }],- ]);- const progress = meetingProgress(meeting, [agent("a0", "idle"), agent("a1", "idle"), agent("a2", "working")], summons, positions);- expect(progress).toEqual({ seated: ["a0"], arriving: ["a1"], busy: ["a2"], missing: ["gone"] });- });-- it("counts minutes left, rounded up, and none after the end", () => {- const meeting: TeamMeeting = { groupId: "g", name: "Crew", members: [], untilMs: 1_000 + MEETING_MS };- expect(minutesLeft(meeting, 1_000)).toBe(10);- expect(minutesLeft(meeting, 1_000 + MEETING_MS - 30_000)).toBe(1);- expect(minutesLeft(meeting, 2_000 + MEETING_MS)).toBe(0);- });-});--describe("a meeting at a studio's own board", () => {- const campus = campusOf(12, [5]);- const studio = studioOfTeam(campus.layout, "team-0")!;- const places = huddlePlaces(campus.layout, campus.grid, studio);-- it("gives every member a place in the arcs, the arc nearest the board first", () => {- const seats = boardSeats(campus.layout, studio, studio.members);- expect(Object.keys(seats)).toEqual(studio.members);- const ids = Object.values(seats).map((s) => s.spotId);- expect(new Set(ids).size).toBe(studio.members.length);- const from = (id: string) => { const seat = seats[id].target; return Math.hypot(seat.x - studio.board!.x, seat.z - studio.board!.z); };- for (let i = 1; i < studio.members.length; i += 1) expect(from(studio.members[i])).toBeGreaterThanOrEqual(from(studio.members[i - 1]) - 0.11);- for (const seat of Object.values(seats)) expect(places.some((p) => p.id === seat.spotId && p.x === seat.target.x && p.z === seat.target.z)).toBe(true);- });-- it("leaves members beyond the places where they are, and has none for a studio without a board", () => {- const crowd = Array.from({ length: places.length + 3 }, (_, i) => `m${i}`);- expect(Object.keys(boardSeats(campus.layout, studio, crowd, campus.grid))).toHaveLength(places.length);- // Both argument orders name the same places.- expect(boardSeats(campus.layout, campus.grid, studio, studio.members)).toEqual(boardSeats(campus.layout, studio, studio.members, campus.grid));- expect(boardSeats(campus.layout, null, studio, studio.members)).toEqual(boardSeats(campus.layout, studio, studio.members));- expect(boardSeats(campus.layout, { ...studio, board: null }, studio.members, null)).toEqual({});- });-- it("stands a called member on its place at the board, facing it, and leaves a working one at its screen", () => {- const seats = boardSeats(campus.layout, studio, studio.members);- const book = new SpotBook();- const desks = campus.layout.departments.flatMap((d) => d.desks);- const plan = (id: string, state: "idle" | "working") => planFor({- agentId: id, state, desk: desks.find((d) => d.agentId === id) ?? null, layout: campus.layout, grid: campus.grid, rng: createRng(id), book,- previous: null, workingColleagues: [], calledTo: seats[id].target, calledSeat: seats[id].spotId,- });- const first = plan(studio.members[0], "idle");- const place = places.find((p) => p.id === seats[studio.members[0]].spotId)!;- expect(first).toMatchObject({ kind: "huddle", pose: "stand", dwellMs: Infinity, spotId: place.id, target: { x: place.x, z: place.z } });- expect(first.facing).toBeCloseTo(place.facing);- expect(plan(studio.members[1], "working").kind).toBe("work");- // The chairs at the team room's table stay free: this meeting is not there.- expect(campus.layout.spots.filter((s) => s.kind === "meeting").every((s) => book.isFree(s.id))).toBe(true);- });-});--describe("a board meeting of a team with a lead", () => {- const led = campusOf(12, [5], [3]);- const studio = studioOfTeam(led.layout, "team-0")!;- const places = huddlePlaces(led.layout, led.grid, studio);-- it("gives the lead the centre of the front arc, wherever it comes in the list, and everybody else a place of their own", () => {- const lead = studio.leadId!;- expect(lead).toBe(led.teams[0].members[3]);- const seats = boardSeats(led.layout, studio, studio.members);- expect(seats[lead].spotId).toBe(`fan:${studio.deptId}:0:0`);- const ids = Object.values(seats).map((s) => s.spotId);- expect(new Set(ids).size).toBe(studio.members.length);- expect(ids.every((id) => places.some((p) => p.id === id))).toBe(true);- });-- it("uses the lead's place for somebody else when the lead is not among those called", () => {- const withoutLead = studio.members.filter((id) => id !== studio.leadId);- const seats = boardSeats(led.layout, studio, withoutLead);- expect(Object.keys(seats)).toEqual(withoutLead);- expect(Object.values(seats).map((s) => s.spotId)).toContain(`fan:${studio.deptId}:0:0`);- });-- it("is the same seating as ever for a team without a lead", () => {- const plain = { ...studio, leadId: null };- const before = boardSeats(led.layout, plain, studio.members);- // The first member takes the first place of the front arc, as it always did.- expect(before[studio.members[0]].spotId).toBe(`fan:${studio.deptId}:0:0`);- expect(Object.values(before).map((s) => s.spotId)).toEqual(places.slice(0, studio.members.length)- .map((p, i) => ({ p, i, from: Math.hypot(p.x - studio.board!.x, p.z - studio.board!.z) }))- .sort((a, b) => Math.round((a.from - b.from) * 10) || a.i - b.i).map((x) => x.p.id));- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/teamMeeting.ts b/dodaios/ui/web/frontend/src/components/society/office/teamMeeting.tsdeleted file mode 100644index 3acef3e81a..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/teamMeeting.ts+++ /dev/null@@ -1,116 +0,0 @@-/**- * Team meetings in the team room: which chair each member takes, and how far- * the meeting has got (who already sits at the table, who is still on the way,- * who keeps working at their desk). Pure, so the panel and tests share it.- */-import type { SocietyAgent } from "../data";-import type { OfficeLayout, Point, Studio } from "./officeLayout";-import { buildNavGrid, type NavGrid } from "./officeNav";-import { huddlePlaces, leadPlace } from "./officeTeams";-import type { Summon, TeamMeeting } from "./officeStore";--/** A meeting holds its members at the table this long unless it is ended earlier. */-export const MEETING_MS = 10 * 60_000;--/** How close to its chair a member must be to count as seated, in metres. */-const SEATED_WITHIN_M = 0.35;-/** The same for a member without a chair, who stops about a step (1.2 m) from its point. */-const STANDING_WITHIN_M = 1.6;--export interface MeetingSeat { target: Point; spotId?: string }--/**- * A chair for every member, middle chairs first and facing pairs together, so- * a small team sits across from each other. Members beyond the chairs stand at- * the table's short ends.- */-export function meetingSeats(layout: OfficeLayout, members: readonly string[]): Record<string, MeetingSeat> {- const table = layout.furniture.find((f) => f.kind === "meetingTable");- const centre = table ? { x: table.x, z: table.z } : layout.spawn;- const chairs = layout.spots.filter((s) => s.kind === "meeting")- .sort((a, b) => Math.abs(a.x - centre.x) - Math.abs(b.x - centre.x) || a.x - b.x || a.z - b.z);- const seats: Record<string, MeetingSeat> = {};- members.forEach((id, i) => {- const chair = chairs[i];- if (chair) { seats[id] = { target: { x: chair.x, z: chair.z }, spotId: chair.id }; return; }- const extra = i - chairs.length;- const side = extra % 2 === 0 ? 1 : -1;- seats[id] = { target: { x: centre.x + side * (2.4 + 0.5 * Math.floor(extra / 2)), z: centre.z } };- });- return seats;-}--const gridCache = new WeakMap<OfficeLayout, NavGrid>();--/**- * A place at a studio's own board for every member, the arc nearest the board- * first: what "Meet" started from that studio's board hands to- * `startMeeting` instead of the team room's chairs. Members beyond the places- * of the arcs get none and stay where they are. The team's lead, when it is- * among them, gets the centre of the front arc. Like every meeting, it never- * moves a working member. `grid` is the floor's navigation grid when the- * caller has it; without one it is built from the layout (once per layout).- */-export function boardSeats(layout: OfficeLayout, studio: Studio, members: readonly string[], grid?: NavGrid | null): Record<string, MeetingSeat>;-/** The same, with the grid named before the studio; both orders are kept so no caller breaks. */-export function boardSeats(layout: OfficeLayout, grid: NavGrid | null | undefined, studio: Studio, members: readonly string[]): Record<string, MeetingSeat>;-export function boardSeats(- layout: OfficeLayout, second: Studio | NavGrid | null | undefined, third: Studio | readonly string[], fourth?: NavGrid | null | readonly string[],-): Record<string, MeetingSeat> {- // (layout, studio, members, grid?) has the member list third; (layout, grid, studio, members) has it last.- const membersThird = Array.isArray(third);- const studio = (membersThird ? second : third) as Studio;- const members = (membersThird ? third : fourth) as readonly string[];- const grid = (membersThird ? fourth : second) as NavGrid | null | undefined;- const board = studio.board;- if (!board) return {};- let floor = grid ?? gridCache.get(layout);- if (!floor) { floor = buildNavGrid(layout); gridCache.set(layout, floor); }- const all = huddlePlaces(layout, floor, studio);- // A team's lead, when it is among those called, stands at the centre of the front arc.- const centre = studio.leadId && members.includes(studio.leadId) ? leadPlace(all, studio) : null;- const places = all.filter((p) => p.id !== centre?.id)- .map((p, i) => ({ p, i, from: Math.hypot(p.x - board.x, p.z - board.z) }))- .sort((a, b) => Math.round((a.from - b.from) * 10) || a.i - b.i);- const seats: Record<string, MeetingSeat> = {};- let next = 0;- for (const id of members) {- const place = centre && id === studio.leadId ? centre : places[next++]?.p;- if (place) seats[id] = { target: { x: place.x, z: place.z }, spotId: place.id };- }- return seats;-}--export interface MeetingProgress {- /** Members sitting (or standing) at their place at the table. */- seated: string[];- /** Members on their way to the table. */- arriving: string[];- /** Members that keep working at their desk: a meeting never interrupts real work. */- busy: string[];- /** Members no longer in the office (removed or retired agents). */- missing: string[];-}--export function meetingProgress(- meeting: TeamMeeting, agents: readonly SocietyAgent[], summons: Record<string, Summon>, positions: ReadonlyMap<string, Point>,-): MeetingProgress {- const progress: MeetingProgress = { seated: [], arriving: [], busy: [], missing: [] };- for (const id of meeting.members) {- const agent = agents.find((a) => a.agentId === id);- if (!agent) { progress.missing.push(id); continue; }- if (agent.state === "working") { progress.busy.push(id); continue; }- const where = positions.get(id);- const summon = summons[id];- // A chair is exact; a member standing at the table's end stops a step short of its point.- const within = summon?.spotId ? SEATED_WITHIN_M : STANDING_WITHIN_M;- if (where && summon && Math.hypot(where.x - summon.target.x, where.z - summon.target.z) <= within) progress.seated.push(id);- else progress.arriving.push(id);- }- return progress;-}--/** Minutes left in a meeting, rounded up; 0 once it is over. */-export function minutesLeft(meeting: TeamMeeting, nowMs: number): number {- return Math.max(0, Math.ceil((meeting.untilMs - nowMs) / 60_000));-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/teamRoom.css b/dodaios/ui/web/frontend/src/components/society/office/teamRoom.cssdeleted file mode 100644index beec4e8eaf..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/teamRoom.css+++ /dev/null@@ -1,24 +0,0 @@-/* Teams sheet: theme tokens only, so light and dark mode both work. */-/* Green is for a round that is really answering; a team the person merely called together gets a plain edge. */-.team-card[data-called] { border-color:hsl(var(--border-strong)); box-shadow:inset 3px 0 0 hsl(var(--border-strong)); }-.team-card[data-live] { border-color:hsl(var(--success) / .7); box-shadow:inset 3px 0 0 hsl(var(--success)); }-.team-live-mark { flex:none; display:inline-flex; align-items:center; gap:5px; padding:1px 8px; border-radius:999px; background:hsl(var(--success) / .12); color:hsl(var(--success)); font-size:11px; font-weight:600; }-.team-live-mark i { width:6px; height:6px; border-radius:50%; background:hsl(var(--success)); }-/* A team's members as overlapping faces; each carries its run state as a dot. */-.team-stack { display:inline-flex; align-items:center; padding-left:6px; }-/* The face brings its own tile (agentFace.css); here it only overlaps its neighbour, parted by a ring in the dialog's ground. */-.team-face { position:relative; display:inline-flex; margin-left:-6px; border-radius:50%; box-shadow:0 0 0 2px hsl(var(--background)); }-.team-face .office-dot { position:absolute; right:-1px; bottom:-1px; width:9px; height:9px; box-shadow:0 0 0 2px hsl(var(--background)); }-.team-face .office-dot[data-state="paused"] { background:hsl(var(--background)); box-shadow:0 0 0 2px hsl(var(--background)), inset 0 0 0 1.5px hsl(var(--muted-foreground)); }-.team-face-more { width:32px; height:32px; font-size:11px; font-weight:600; color:hsl(var(--muted-foreground)); box-shadow:0 0 0 2px hsl(var(--background)), inset 0 0 0 1px hsl(var(--border-strong) / .7); }-/* The member list scrolls on its own: up to 22 rem, less on a short window, so name, picks and buttons stay on screen with it. */-.team-picker-list { max-height:min(22rem, max(8rem, calc(90dvh - 29rem))); }-/* The new-team form's buttons stay at the sheet's lower edge while the form scrolls. The negative margins undo the- sheet body's 1.25 rem padding so the bar spans it edge to edge. */-.team-footer { position:sticky; bottom:0; z-index:1; display:flex; flex-wrap:wrap; align-items:center; gap:8px; margin:0 -1.25rem -1.25rem; padding:12px 1.25rem; border-top:1px solid hsl(var(--border)); background:hsl(var(--background)); }-/* The team the person called together: a banner in the sheet, a small card in the HUD. Neutral on purpose — it is a- gathering on the map, not a running round, so nothing here is green or pulses. */-.team-meeting { display:flex; flex-direction:column; gap:4px; padding:12px 14px; border-radius:12px; border:1px solid hsl(var(--border-strong)); background:hsl(var(--secondary) / .6); }-.team-meeting[data-compact] { width:100%; padding:9px 11px; border-color:hsl(var(--border)); background:hsl(var(--popover) / .92); }-.team-meeting-title { display:flex; align-items:center; gap:8px; margin:0; font-size:13px; font-weight:600; overflow-wrap:anywhere; }-.team-meeting-line { margin:0; font-size:12px; color:hsl(var(--muted-foreground)); }diff --git a/dodaios/ui/web/frontend/src/components/society/office/teamStatus.test.ts b/dodaios/ui/web/frontend/src/components/society/office/teamStatus.test.tsdeleted file mode 100644index 7e693a24b3..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/teamStatus.test.ts+++ /dev/null@@ -1,30 +0,0 @@-import { describe, expect, it } from "vitest";-import { teamMark } from "./teamStatus";--const NOW = 1_000_000;-const gathering = { groupId: "g1", untilMs: NOW + 60_000 };--describe("what a team's mark may claim", () => {- it("is live only while the backend reports a running round", () => {- expect(teamMark("g1", { g1: { running: true } }, null, NOW)).toBe("live");- expect(teamMark("g1", { g1: { running: false } }, null, NOW)).toBeNull();- expect(teamMark("g1", {}, null, NOW)).toBeNull();- // Another team's round says nothing about this one.- expect(teamMark("g1", { g2: { running: true } }, null, NOW)).toBeNull();- });-- it("never calls the person's own gathering live", () => {- expect(teamMark("g1", {}, gathering, NOW)).toBe("called");- expect(teamMark("g1", { g1: { running: false } }, gathering, NOW)).toBe("called");- expect(teamMark("g2", {}, gathering, NOW)).toBeNull();- });-- it("drops the gathering once its time is up", () => {- expect(teamMark("g1", {}, { groupId: "g1", untilMs: NOW }, NOW)).toBeNull();- expect(teamMark("g1", {}, { groupId: "g1", untilMs: NOW - 1 }, NOW)).toBeNull();- });-- it("shows the real round when a called team is also answering", () => {- expect(teamMark("g1", { g1: { running: true } }, gathering, NOW)).toBe("live");- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/teamStatus.ts b/dodaios/ui/web/frontend/src/components/society/office/teamStatus.tsdeleted file mode 100644index 231592b638..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/teamStatus.ts+++ /dev/null@@ -1,24 +0,0 @@-/**- * What may be said about a team at a glance, and where each claim comes from.- *- * "Live" means one thing only: a round of the team is answering right now,- * as the backend reports it (teamwork's `TeamRound.running`). "Called" is the- * person's own gathering on the map (officeStore's `meeting`): members walk- * to the table or to their board, nothing is posted to the team and no agent- * starts work. The two are never mixed, so a board or a card can never show- * a gathering as a running round. Pure and tested.- */--export type TeamMark = "live" | "called" | null;--export function teamMark(- groupId: string,- rounds: Readonly<Record<string, { running: boolean } | undefined>>,- gathering: { groupId: string; untilMs: number } | null,- now: number,-): TeamMark {- // A real round outranks the gathering: if the team answers while it stands at its board, that is the news.- if (rounds[groupId]?.running) return "live";- if (gathering && gathering.groupId === groupId && gathering.untilMs > now) return "called";- return null;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/useDprBudget.test.ts b/dodaios/ui/web/frontend/src/components/society/office/useDprBudget.test.tsdeleted file mode 100644index 45cedc558a..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/useDprBudget.test.ts+++ /dev/null@@ -1,26 +0,0 @@-import { describe, expect, it } from "vitest";-import { budgetDpr, MAX_DPR, PIXEL_BUDGET } from "./useDprBudget";--describe("office pixel budget", () => {- it("gives a narrow side panel the full ratio the screen offers", () => {- expect(budgetDpr(520, 1100, 1.5)).toBe(1.5);- expect(budgetDpr(520, 1100, 3)).toBe(MAX_DPR);- });-- it("holds a full-width 4K view near the budget instead of at the device ratio", () => {- const dpr = budgetDpr(2100, 1350, 1.5);- expect(dpr).toBe(1);- expect(2100 * 1350 * dpr * dpr).toBeLessThan(1.5 * 1.5 * 2100 * 1350);- });-- it("keeps a mid-size view inside the budget in quarter steps", () => {- const dpr = budgetDpr(1400, 800, 2);- expect(dpr * 4).toBe(Math.round(dpr * 4));- expect(1400 * 800 * dpr * dpr).toBeLessThanOrEqual(PIXEL_BUDGET);- });-- it("never drops below one and survives an unmeasured view", () => {- expect(budgetDpr(5000, 3000, 2)).toBe(1);- expect(budgetDpr(0, 0, 1.25)).toBe(1.25);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/useDprBudget.ts b/dodaios/ui/web/frontend/src/components/society/office/useDprBudget.tsdeleted file mode 100644index ef51226013..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/useDprBudget.ts+++ /dev/null@@ -1,43 +0,0 @@-/**- * The office canvas's pixel ratio under a fixed pixel budget.- *- * Full resolution is cheap in the narrow side panel and ruinous when the same- * scene fills a 4K window: shadows and MSAA are paid per pixel, so the frame- * rate falls with the area. Holding the drawn pixel count near a budget keeps a- * large view as smooth as a small one; a small view still gets the full ratio.- */-import { useEffect, useState, type RefObject } from "react";--/** Physical pixels the scene is drawn at, at most (about 2.5 x 1.3 k). */-export const PIXEL_BUDGET = 3_200_000;-/** Never above this ratio, whatever the screen offers. */-export const MAX_DPR = 1.75;-/** Never below one CSS pixel per drawn pixel: below that text on the monitors blurs. */-const MIN_DPR = 1;--/** The ratio for a `width` x `height` CSS-pixel view on a `device`-ratio screen. Pure. */-export function budgetDpr(width: number, height: number, device: number): number {- const top = Math.max(MIN_DPR, Math.min(MAX_DPR, device || 1));- const area = width * height;- if (area <= 0) return top;- const fit = Math.sqrt(PIXEL_BUDGET / area);- // Quarter steps: a window drag never reallocates the drawing buffer per frame.- const stepped = Math.floor(fit * 4) / 4;- return Math.max(MIN_DPR, Math.min(top, stepped));-}--export function useDprBudget(host: RefObject<HTMLElement | null>): number {- const device = typeof window === "undefined" ? 1 : window.devicePixelRatio;- const [dpr, setDpr] = useState(() => Math.min(MAX_DPR, Math.max(MIN_DPR, device)));- useEffect(() => {- const node = host.current;- if (!node || typeof ResizeObserver === "undefined") return;- const observer = new ResizeObserver(([entry]) => {- const { width, height } = entry.contentRect;- setDpr(budgetDpr(width, height, window.devicePixelRatio));- });- observer.observe(node);- return () => observer.disconnect();- }, [host]);- return dpr;-}diff --git a/dodaios/ui/web/frontend/src/components/society/office/walkerRegistry.test.ts b/dodaios/ui/web/frontend/src/components/society/office/walkerRegistry.test.tsdeleted file mode 100644index 9da803fc10..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/walkerRegistry.test.ts+++ /dev/null@@ -1,52 +0,0 @@-import { afterEach, describe, expect, it } from "vitest";-import { agentPositions, bodiesExcept, bodiesNear, companions, extraBodies, placeAgent } from "./walkerRegistry";--describe("bodiesExcept", () => {- afterEach(() => { agentPositions.clear(); extraBodies.clear(); });-- it("counts every agent, the hovering Gigi included, but never the caller itself", () => {- agentPositions.set("gigi", { x: 1, z: 1 });- agentPositions.set("walker", { x: 2, z: 2 });- expect(Array.from(bodiesExcept(null, null))).toEqual([{ x: 1, z: 1 }, { x: 2, z: 2 }]);- expect(Array.from(bodiesExcept("walker", { x: 5, z: 5 }))).toEqual([{ x: 1, z: 1 }, { x: 5, z: 5 }]);- });-- it("counts the office dog as a body for everyone but the dog itself", () => {- extraBodies.set("office-dog", { x: 3, z: 3 });- expect(Array.from(bodiesExcept(null, null))).toEqual([{ x: 3, z: 3 }]);- expect(Array.from(bodiesExcept("office-dog", { x: 5, z: 5 }))).toEqual([{ x: 5, z: 5 }]);- });-});--describe("bodiesNear", () => {- afterEach(() => { agentPositions.clear(); extraBodies.clear(); companions.clear(); });-- it("lists the same bodies as bodiesExcept within reach, into the caller's own array", () => {- agentPositions.set("near", { x: 1, z: 1 });- agentPositions.set("far", { x: 30, z: 1 });- agentPositions.set("self", { x: 0, z: 0 });- agentPositions.set("pet", { x: 0.5, z: 0.5 });- companions.add("pet");- extraBodies.set("office-dog", { x: -1, z: 2 });- const person = { x: 2, z: -2 };- const out: { x: number; z: number }[] = [{ x: 99, z: 99 }];- const got = bodiesNear("self", { x: 0, z: 0 }, 7, person, out);- expect(got).toBe(out);- expect(got).toEqual([{ x: 1, z: 1 }, { x: -1, z: 2 }, person]);- expect(new Set(bodiesNear("self", { x: 0, z: 0 }, Infinity, person))).toEqual(new Set(bodiesExcept("self", person)));- expect(bodiesNear("office-dog", { x: 0, z: 0 }, 7, null)).toEqual([{ x: 1, z: 1 }, { x: 0, z: 0 }]);- });-});--describe("placeAgent", () => {- afterEach(() => { agentPositions.clear(); });-- it("moves an agent's entry in place instead of making a new one every frame", () => {- placeAgent("a", 1, 2);- const entry = agentPositions.get("a");- expect(entry).toEqual({ x: 1, z: 2 });- placeAgent("a", 3, 4);- expect(agentPositions.get("a")).toBe(entry);- expect(entry).toEqual({ x: 3, z: 4 });- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/walkerRegistry.ts b/dodaios/ui/web/frontend/src/components/society/office/walkerRegistry.tsdeleted file mode 100644index 87b884d044..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/walkerRegistry.ts+++ /dev/null@@ -1,106 +0,0 @@-/**- * Where every agent stands right now, written by the walkers each frame and- * read by the player (who is nearby?) and the HUD (focus the camera on X).- * A plain module map: per-frame positions must never become React state.- */-import type { Point } from "./officeLayout";--export const agentPositions = new Map<string, Point>();--/** Agent ids the office has already seen; a newcomer arrives by the elevator. */-export const knownAgents = new Set<string>();--/** Agents sitting at their own desk right now — their monitor shows their chat. */-export const seatedAtDesk = new Set<string>();--/**- * Agents flying along at the person's shoulder right now (Gigi). They are no- * obstacle and no "nearby" target: they would always be the closest one.- */-export const companions = new Set<string>();--/** Other solid bodies on the floor that are not agents (the office dog), by id. */-export const extraBodies = new Map<string, Point>();--/**- * Every body except `selfId`: all agents, the extra bodies (the office dog) plus, optionally, the person's character.- * Gigi counts too — it hovers at chest height, so walking "under" it would pass- * through it — except while it follows the person as a companion.- */-export function* bodiesExcept(selfId: string | null, player: Point | null): Generator<Point> {- for (const [id, p] of agentPositions) if (id !== selfId && !companions.has(id)) yield p;- for (const [id, p] of extraBodies) if (id !== selfId) yield p;- if (player) yield player;-}--/**- * The person's pet (Jarvis) as drawn right now: ground position, the height- * of its body centre and of its top, and its size. Written by `GigiFlyer`- * each frame; the level system's cosmetics and celebrations follow it.- */-export const petBody = { x: 0, z: 0, y: 0, top: 0.5, sizeM: 0.5, active: false };--/**- * The bodies within `radius` of `at`, without `selfId`: what a walker steers round. Fills and returns `out`,- * so a walker reuses one array instead of allocating a list of the whole floor every frame.- */-export function bodiesNear(selfId: string | null, at: Point, radius: number, player: Point | null, out: Point[] = []): Point[] {- out.length = 0;- // The same bodies as `bodiesExcept`, walked in place: this runs for every walker on every frame.- for (const [id, p] of agentPositions) {- if (id !== selfId && !companions.has(id) && Math.abs(p.x - at.x) <= radius && Math.abs(p.z - at.z) <= radius) out.push(p);- }- for (const [id, p] of extraBodies) {- if (id !== selfId && Math.abs(p.x - at.x) <= radius && Math.abs(p.z - at.z) <= radius) out.push(p);- }- if (player && Math.abs(player.x - at.x) <= radius && Math.abs(player.z - at.z) <= radius) out.push(player);- return out;-}--/** Write where an agent stands; its entry is moved in place, so a frame of forty walkers allocates nothing. */-export function placeAgent(agentId: string, x: number, z: number): void {- const at = agentPositions.get(agentId);- if (at) { at.x = x; at.z = z; } else agentPositions.set(agentId, { x, z });-}--/** What one walker is doing right now, for the dev handle (`window.__officeLife`); written in development builds only. */-export interface WalkerDebug {- id: string;- name: string;- state: string;- /** The team whose studio the agent sits in; null = the pool, or a floor without studios. */- team: string | null;- studio: string | null;- /** Its part in a running round of its team: none, gather, speaker or busy. */- role: string;- plan: string | null;- phase: "travel" | "dwell";- target: Point | null;- spot: string | null;- with: string | null;- at: Point;- /** Waypoints and metres left on the current walk. */- pathLength: number;- remainingM: number;- /**- * The current walk by the walker's own clock (the frame time it was actually given, not wall time and not- * what a stepping script assumes): seconds walked so far and the average speed along the route in m/s.- * Both are 0 while it stands.- */- walkS: number;- speed: number;- /** Seconds without progress on the current walk (the stuck watch). */- stuckS: number;- /**- * Since the walker mounted: detours round a body, safe placements, route repairs, arrivals beside an occupied- * place, walks given up because the way stayed closed, targets a new floor plan walled off.- */- replans: number;- rescues: number;- repaths: number;- near: number;- blocked: number;- lost: number;-}--export const walkerDebug = new Map<string, WalkerDebug>();diff --git a/dodaios/ui/web/frontend/src/components/society/office/wallCutaway.test.ts b/dodaios/ui/web/frontend/src/components/society/office/wallCutaway.test.tsdeleted file mode 100644index 64a721e14b..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/wallCutaway.test.ts+++ /dev/null@@ -1,141 +0,0 @@-import { describe, expect, it } from "vitest";-import { roomAt, wallsOf, type Room } from "./officeLayout";-import { campusLimits, cornersInView } from "./officeCamera.testkit";-import { CAMERA_LIMITS, OVERVIEW_SPAN, cameraLimitsFor, campusOverview, followBlend, frameDistance } from "./officeCamera";-import { buildOfficeLayout } from "./officeLayout";-import { rosterOf } from "./officeFixtures";-import { CUTAWAY_SCALE, cutawayStep, cutawayWalls, walledRoomAt, wallKey } from "./wallCutaway";-import { campusOf } from "./officeFixtures";--// Two walled rooms side by side sharing a wall line, and an open lobby south of them.-const west: Room = { id: "lead", kind: "lead", walled: true, minX: 0, maxX: 8, minZ: 0, maxZ: 6, doors: [{ side: "south", at: 4, width: 1.6 }] };-const east: Room = { id: "team", kind: "team", walled: true, minX: 8, maxX: 16, minZ: 0, maxZ: 6, doors: [{ side: "south", at: 12, width: 1.8 }] };-const lobby: Room = { id: "reception", kind: "reception", walled: false, minX: 0, maxX: 16, minZ: 10, maxZ: 16, doors: [] };-const rooms = [west, east, lobby];-const walls = rooms.flatMap(wallsOf);-/** Keys of the wall runs matching `test`; two rooms' runs along one shared line have one key. */-const keysOn = (test: (w: (typeof walls)[number]) => boolean) => [...new Set(walls.filter(test).map(wallKey))].sort();--describe("which walls step aside", () => {- it("opens the sides of the person's room that the camera looks in through", () => {- // The home view: the camera stands south-east of the room.- const cut = cutawayWalls(rooms, walls, { x: 4, z: 3 }, { x: 20, z: 18 });- const south = keysOn((w) => w.z1 === 6 && w.z2 === 6 && Math.max(w.x1, w.x2) <= 8);- // The shared wall line x = 8 holds a run of each room: both step aside.- const shared = keysOn((w) => w.x1 === 8 && w.x2 === 8);- expect(walls.filter((w) => w.x1 === 8 && w.x2 === 8)).toHaveLength(2);- expect([...cut].sort()).toEqual([...south, ...shared].sort());- // The far sides stay up: they are the room's backdrop.- expect(cut.has(wallKey(walls.find((w) => w.z1 === 0 && w.x1 === 0)!))).toBe(false);- expect(cut.has(wallKey(walls.find((w) => w.x1 === 0 && w.x2 === 0)!))).toBe(false);- });-- it("leaves every wall standing while the person is on the open floor or in an open room", () => {- expect(cutawayWalls(rooms, walls, { x: 4, z: 8 }, { x: 20, z: 18 }).size).toBe(0);- expect(cutawayWalls(rooms, walls, { x: 4, z: 12 }, { x: 20, z: 18 }).size).toBe(0);- expect(walledRoomAt(rooms, { x: 4, z: 12 })).toBeNull();- expect(walledRoomAt(rooms, { x: 4, z: 3 })?.kind).toBe("lead");- });-- it("follows the camera round the room and never flickers while the person walks about inside", () => {- const fromNorthWest = cutawayWalls(rooms, walls, { x: 12, z: 3 }, { x: -6, z: -9 });- expect([...fromNorthWest].sort()).toEqual(keysOn((w) => (w.z1 === 0 && w.z2 === 0 && Math.min(w.x1, w.x2) >= 8) || (w.x1 === 8 && w.x2 === 8)));- const here = cutawayWalls(rooms, walls, { x: 9, z: 1 }, { x: 20, z: 18 });- const there = cutawayWalls(rooms, walls, { x: 15, z: 5.5 }, { x: 20, z: 18 });- expect([...here].sort()).toEqual([...there].sort());- // A camera straight above the room looks in through no side.- expect(cutawayWalls(rooms, walls, { x: 12, z: 3 }, { x: 12, z: 3 }).size).toBe(0);- });-- it("opens the rooms of the real campus for someone standing in them", () => {- const { layout } = campusOf(20, [6, 5]);- for (const room of layout.rooms.filter((r) => r.walled)) {- const inside = { x: (room.minX + room.maxX) / 2, z: (room.minZ + room.maxZ) / 2 };- expect(roomAt(layout, inside)?.kind).toBe(room.kind);- const camera = { x: inside.x + 14, z: inside.z + 17 };- const cut = cutawayWalls(layout.rooms, layout.walls, inside, camera);- expect(cut.size, room.kind).toBeGreaterThan(0);- // Only walls along this room's own sides are touched.- for (const wall of layout.walls.filter((w) => cut.has(wallKey(w)))) {- const onSide = Math.abs(wall.z1 - room.maxZ) < 0.2 || Math.abs(wall.x1 - room.maxX) < 0.2 || Math.abs(wall.z1 - room.minZ) < 0.2 || Math.abs(wall.x1 - room.minX) < 0.2;- expect(onSide, room.kind).toBe(true);- }- }- });-- it("glides a wall down to a kerb and back up, and places it at once for reduced motion", () => {- let h = 1;- for (let i = 0; i < 60; i += 1) h = cutawayStep(h, true, 1 / 60);- expect(h).toBe(CUTAWAY_SCALE);- const mid = cutawayStep(1, true, 1 / 60);- expect(mid).toBeLessThan(1);- expect(mid).toBeGreaterThan(CUTAWAY_SCALE);- for (let i = 0; i < 60; i += 1) h = cutawayStep(h, false, 1 / 60);- expect(h).toBe(1);- expect(cutawayStep(1, true, 1 / 60, true)).toBe(CUTAWAY_SCALE);- expect(cutawayStep(CUTAWAY_SCALE, false, 1 / 60, true)).toBe(1);- });-});--describe("the camera on a campus", () => {- it("fits the whole floor to the viewport in the overview, at any size and viewport shape", () => {- const floors = [- campusOf(4, []).layout.bounds, campusOf(14, [5, 4, 3]).layout.bounds,- // The tall plan: forty agents in eight teams.- campusOf(40, [5, 5, 5, 5, 5, 5, 5, 5]).layout.bounds, campusOf(90, [12, 11, 10, 9, 8, 8, 7, 7]).layout.bounds,- buildOfficeLayout(rosterOf(10), { variant: "coding" }).bounds,- ];- for (const bounds of floors) {- // A wide window, a squarer one, and the IDE's narrow side panel.- for (const aspect of [16 / 9, 4 / 3, 0.62]) {- const label = `${(bounds.maxX - bounds.minX).toFixed(0)} x ${(bounds.maxZ - bounds.minZ).toFixed(0)} m, aspect ${aspect.toFixed(2)}`;- const pose = campusOverview(bounds, aspect);- const { inside, box } = cornersInView(bounds, pose, aspect);- expect(inside, label).toBe(true);- // In the middle of the view, not in its lower half.- expect(Math.abs(box.minX + box.maxX) / 2, label).toBeLessThan(0.02);- expect(Math.abs(box.minY + box.maxY) / 2, label).toBeLessThan(0.02);- // As large as it goes: it spans 85 % of whichever axis binds.- const span = Math.max(box.maxX - box.minX, box.maxY - box.minY) / 2;- expect(span, label).toBeGreaterThan(OVERVIEW_SPAN - 0.01);- expect(span, label).toBeLessThan(OVERVIEW_SPAN + 0.01);- // The look-at point stays on the floor, and the wheel can reach this view.- expect(pose.target[1]).toBe(0);- const distance = Math.hypot(pose.position[0] - pose.target[0], pose.position[1], pose.position[2] - pose.target[2]);- expect(distance, label).toBeLessThanOrEqual(cameraLimitsFor(bounds, aspect).maxDistance);- }- }- });-- it("stands much closer than a view that merely holds every corner", () => {- const bounds = campusOf(14, [5, 4, 3]).layout.bounds;- const pose = campusOverview(bounds, 16 / 9);- const distance = Math.hypot(pose.position[0] - pose.target[0], pose.position[1], pose.position[2] - pose.target[2]);- expect(distance).toBeLessThan(frameDistance(bounds, 16 / 9) * 0.9);- });-- it("lets the wheel back away far enough for that overview, and never less than before", () => {- const small = campusOf(4, []).layout.bounds;- const large = campusOf(90, [12, 11, 10, 9, 8, 8, 7, 7]).layout.bounds;- for (const bounds of [small, large]) {- const limits = cameraLimitsFor(bounds, 16 / 9);- expect(limits.maxDistance).toBeGreaterThanOrEqual(CAMERA_LIMITS.maxDistance);- expect(limits.maxDistance).toBeGreaterThan(frameDistance(bounds, 16 / 9));- expect(limits).toMatchObject({ minDistance: CAMERA_LIMITS.minDistance, minPolar: CAMERA_LIMITS.minPolar, maxPolar: CAMERA_LIMITS.maxPolar });- }- // A portrait viewport needs more room than a wide one.- expect(frameDistance(large, 0.62)).toBeGreaterThan(frameDistance(large, 16 / 9));- expect(campusLimits(large).maxDistance).toBeGreaterThanOrEqual(cameraLimitsFor(large, 16 / 9).maxDistance);- });-- it("follows at the same pace whatever the frame rate, and eases out", () => {- // One 33 ms frame closes as much of the gap as two 16.5 ms frames.- const one = followBlend(0.033);- const two = 1 - (1 - followBlend(0.0165)) ** 2;- expect(one).toBeCloseTo(two, 9);- expect(followBlend(0)).toBe(0);- expect(followBlend(0.016)).toBeGreaterThan(0.1);- expect(followBlend(0.016)).toBeLessThan(0.15);- expect(followBlend(10)).toBeCloseTo(1, 6);- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/office/wallCutaway.ts b/dodaios/ui/web/frontend/src/components/society/office/wallCutaway.tsdeleted file mode 100644index 1d22da7b64..0000000000--- a/dodaios/ui/web/frontend/src/components/society/office/wallCutaway.ts+++ /dev/null@@ -1,65 +0,0 @@-/**- * Which walls step out of the way while the person stands inside a walled- * room: the sides of that room the camera looks in through. Like the open- * front of a doll's house, they drop to a low kerb so the room stays- * readable, and rise again when the person leaves or the camera turns.- *- * The rule is by side, not by sight line, so nothing flickers while the- * person walks about inside: only crossing a doorway or orbiting the camera- * changes the answer. Pure and tested; OfficeCameraRig applies it to every- * object tagged `userData.officeWall` (see `wallKey`).- */-import type { Point, Room, WallSegment } from "./officeLayout";--/** How close to a room's side line a wall run must lie to belong to that side. */-const ON_SIDE_M = 0.2;-/** The camera must stand this far beyond a side before that side is opened (no flicker when it is level with it). */-const BEYOND_M = 0.5;-/** A lowered wall keeps this share of its height: a kerb that still shows where the wall is. */-export const CUTAWAY_SCALE = 0.12;--/** The identity of a wall run, shared by the layout's segments and the tagged scene objects. */-export function wallKey(wall: Pick<WallSegment, "x1" | "z1" | "x2" | "z2">): string {- return `${wall.x1.toFixed(2)}:${wall.z1.toFixed(2)}:${wall.x2.toFixed(2)}:${wall.z2.toFixed(2)}`;-}--/** The walled room the person stands in, or null (open rooms and the open office have nothing to open). */-export function walledRoomAt(rooms: readonly Room[], p: Point): Room | null {- return rooms.find((r) => r.walled && p.x > r.minX && p.x < r.maxX && p.z > r.minZ && p.z < r.maxZ) ?? null;-}--/**- * Keys of the wall runs to lower for a person at `person` seen by a camera- * standing over `camera` (its position on the floor plane). Walls of the- * neighbouring room that run along the same line are opened with it, or half- * the side would stay up.- */-export function cutawayWalls(rooms: readonly Room[], walls: readonly WallSegment[], person: Point, camera: Point): Set<string> {- const cut = new Set<string>();- const room = walledRoomAt(rooms, person);- if (!room) return cut;- const open = {- north: camera.z < room.minZ - BEYOND_M, south: camera.z > room.maxZ + BEYOND_M,- west: camera.x < room.minX - BEYOND_M, east: camera.x > room.maxX + BEYOND_M,- };- for (const wall of walls) {- const horizontal = Math.abs(wall.z1 - wall.z2) < 1e-6;- if (horizontal) {- const overlaps = Math.min(Math.max(wall.x1, wall.x2), room.maxX) - Math.max(Math.min(wall.x1, wall.x2), room.minX) > 0.05;- if (!overlaps) continue;- if ((open.north && Math.abs(wall.z1 - room.minZ) < ON_SIDE_M) || (open.south && Math.abs(wall.z1 - room.maxZ) < ON_SIDE_M)) cut.add(wallKey(wall));- } else {- const overlaps = Math.min(Math.max(wall.z1, wall.z2), room.maxZ) - Math.max(Math.min(wall.z1, wall.z2), room.minZ) > 0.05;- if (!overlaps) continue;- if ((open.west && Math.abs(wall.x1 - room.minX) < ON_SIDE_M) || (open.east && Math.abs(wall.x1 - room.maxX) < ON_SIDE_M)) cut.add(wallKey(wall));- }- }- return cut;-}--/** One frame of a wall's height towards its goal (1 = standing, CUTAWAY_SCALE = lowered); `snap` skips the glide. */-export function cutawayStep(current: number, lowered: boolean, dt: number, snap = false): number {- const goal = lowered ? CUTAWAY_SCALE : 1;- if (snap || Math.abs(goal - current) < 0.004) return goal;- return goal + (current - goal) * Math.exp(-9 * dt);-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/LevelHud.tsx b/dodaios/ui/web/frontend/src/components/society/progression/LevelHud.tsxdeleted file mode 100644index 65c5cd611f..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/LevelHud.tsx+++ /dev/null@@ -1,171 +0,0 @@-/**- * The level system's HUD pieces over the Verse: the person's level card (the- * rank insignia in a ring that fills with XP, the rank, a bar with a trailing- * "ghost" that catches up after each gain), the pet's line under it, the rank- * chip worn on name plates, and the toasts for agents that were promoted.- */-import { useEffect, useRef, useState } from "react";-import { useT } from "@/i18n";-import { levelFraction } from "./cosmetics";-import { RANK_INFO, rankAt, rankOf, type RankId, type SubjectKind } from "./levelCatalog";-import { RankInsignia } from "./insignia/RankInsignia";-import { PERSON_SUBJECT, petSubject } from "./progressionApi";-import { useProgression, type Celebration } from "./progressionStore";-import { AgentSymbol } from "../AgentSymbol";-import { resolveCompanion, type CompanionAppearance } from "../companion/appearance";-import type { SocietyAgent } from "../data";-import { accessoryItem, type AccessoryChoice } from "../companion/accessories";--/** The accessory choice that puts one look on, in its own slot. */-function lookSlot(id: string): AccessoryChoice {- const item = accessoryItem(id);- return item ? { [item.slot]: id } : {};-}--const TOAST_MS = 6500;--/** The rank a subject kind holds at `level`, from the server's ladder. */-export function useRankAt(kind: SubjectKind, level: number): RankId {- const bands = useProgression((s) => s.snapshot?.titles[kind]);- return rankAt(bands, level);-}--/** The rank chip on a name plate: the insignia and the level number on a dark plate. */-export function LevelChip({ kind, level }: { kind: SubjectKind; level: number }) {- const t = useT();- const rank = useRankAt(kind, level);- return (- <span className="level-chip" data-tier={RANK_INFO[rank].tier}- title={`${t(`society.level.title.${rank}`)} · ${t("society.level.level_n").replace("{0}", String(level))}`}>- <RankInsignia rank={rank} size={14} className="level-chip-insignia" />- <b>{level}</b>- </span>- );-}--/** A bar whose gain lights up first and fills a beat later, so every gain reads as motion. */-export function XpBar({ fraction, kind, label }: { fraction: number; kind: SubjectKind; label: string }) {- const [ghost, setGhost] = useState(fraction);- const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);- useEffect(() => {- clearTimeout(timer.current);- // After a level-up the bar restarts below the ghost: the ghost resets with it.- if (fraction < ghost) { setGhost(fraction); return; }- timer.current = setTimeout(() => setGhost(fraction), 450);- return () => clearTimeout(timer.current);- }, [fraction, ghost]);- return (- <span className="level-bar" data-kind={kind} role="progressbar" aria-label={label} aria-valuemin={0} aria-valuemax={100}- aria-valuenow={Math.round(fraction * 100)}>- {/* The gain shows at once in a bright segment; the solid fill slides up to it a beat later. */}- <i className="level-bar-gain" style={{ width: `${fraction * 100}%` }} />- <i className="level-bar-fill" style={{ width: `${Math.min(fraction, ghost) * 100}%` }} />- </span>- );-}--/** The rank insignia on a dark medallion inside a ring that fills with XP; the level sits on a tab below. */-export function LevelRing({ kind, level, fraction, size = 44 }: { kind: SubjectKind; level: number; fraction: number; size?: number }) {- const rank = useRankAt(kind, level);- const r = 20, c = 2 * Math.PI * r;- return (- <span className="level-ring" style={{ width: size, height: size }} data-kind={kind} data-tier={RANK_INFO[rank].tier}>- <svg className="level-ring-gauge" viewBox="0 0 48 48" width={size} height={size} aria-hidden>- <circle cx="24" cy="24" r={r} className="level-ring-track" />- <circle cx="24" cy="24" r={r} className="level-ring-fill" strokeDasharray={`${c * fraction} ${c}`} transform="rotate(-90 24 24)" />- <circle cx="24" cy="24" r="16.5" className="level-ring-medal" />- </svg>- <RankInsignia rank={rank} size={size * 0.46} className="level-ring-insignia" />- <b>{level}</b>- </span>- );-}--export function LevelHud({ playerName, petName, compact }: { playerName: string; petName: string; compact: boolean }) {- const t = useT();- const person = useProgression((s) => s.subjects[PERSON_SUBJECT]);- const petId = useProgression((s) => s.petId);- const pet = useProgression((s) => s.subjects[petSubject(petId)]);- const loaded = useProgression((s) => !!s.snapshot);- const open = useProgression((s) => s.openPanel);- const openHall = () => open("overview", { subject: "person" });- if (!loaded) return null;- const level = person?.level ?? 1;- const fraction = levelFraction(person);- const petLevel = pet?.level ?? 1;- const xpText = person && person.xpForNext > 0- ? t("society.level.xp_of").replace("{0}", String(person.xpIntoLevel)).replace("{1}", String(person.xpForNext))- : person ? t("society.level.max") : t("society.level.xp_of").replace("{0}", "0").replace("{1}", "40");- return (- <button type="button" className="office-card level-hud" data-compact={compact || undefined} onClick={openHall}- aria-label={t("society.level.open_panel")} aria-keyshortcuts="L">- <LevelRing kind="person" level={level} fraction={fraction} size={compact ? 38 : 54} />- <span className="level-hud-body">- <span className="level-hud-name">- <strong>{playerName}</strong>- <em>{t(`society.level.title.${rankOf(person?.title)}`)}</em>- </span>- <XpBar fraction={fraction} kind="person" label={t("society.level.xp_label")} />- {!compact && <span className="level-hud-xp">{xpText}</span>}- {!compact && (- <span className="level-hud-pet">- <span>{t("society.level.pet_line").replace("{0}", petName).replace("{1}", String(petLevel))}</span>- <XpBar fraction={levelFraction(pet)} kind="pet" label={t("society.level.pet_xp_label").replace("{0}", petName)} />- </span>- )}- </span>- </button>- );-}--/** An agent's level-up: a quiet card in the corner, gone on its own. */-export function LevelToasts({ names, agents = [] }: { names: ReadonlyMap<string, string>; agents?: readonly SocietyAgent[] }) {- const t = useT();- const toasts = useProgression((s) => s.toasts);- const dismiss = useProgression((s) => s.dismissToast);- useEffect(() => {- if (toasts.length === 0) return;- // A new look gets a moment longer: it is the part worth looking at.- const timers = toasts.map((toast) => setTimeout(() => dismiss(toast.id), TOAST_MS + (toast.looks?.length ? 3000 : 0)));- return () => timers.forEach(clearTimeout);- }, [toasts, dismiss]);- if (toasts.length === 0) return null;- return (- <div className="level-toasts" role="status" aria-live="polite" data-office-ui>- {toasts.map((toast) => {- const agentId = toast.subjectId.slice("agent:".length);- const agent = agents.find((a) => a.agentId === agentId);- return <LevelToast key={toast.id} toast={toast} name={names.get(agentId) ?? agentId}- look={resolveCompanion(agentId, agent?.figure?.companion)} onClose={() => dismiss(toast.id)} label={t} />;- })}- </div>- );-}--function LevelToast({ toast, name, look, onClose, label }: { toast: Celebration; name: string; look: CompanionAppearance; onClose: () => void; label: (key: string) => string }) {- const looks = toast.looks ?? [];- return (- <button type="button" className="level-toast" onClick={onClose}>- <LevelChip kind="agent" level={toast.level} />- <span>- <strong>{label("society.level.agent_up").replace("{0}", name).replace("{1}", String(toast.level))}</strong>- <em>{toast.away ? label("society.level.while_away") : label(`society.level.title.${rankOf(toast.title)}`)}</em>- {looks.length > 0 && (- <span className="level-toast-looks" data-testid="level-toast-looks">- {/* The symbol shows the agent already wearing its new look. */}- {looks.map((id) => {- return (- <span key={id} className="level-toast-look">- {/* Looks dress the shape; an agent that wears a pet shows only the words. */}- {!look.pet && <AgentSymbol shape={look.shape} color={look.color} eyes={look.eyes} skin={look.skin} size={30}- accessories={{ ...look.accessories, ...lookSlot(id) }} />}- <span>{label("society.level.new_look").replace("{0}", label(`society.companion.items.${id}`))}</span>- </span>- );- })}- </span>- )}- </span>- </button>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/LevelUpBanner.tsx b/dodaios/ui/web/frontend/src/components/society/progression/LevelUpBanner.tsxdeleted file mode 100644index 869655272e..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/LevelUpBanner.tsx+++ /dev/null@@ -1,94 +0,0 @@-/**- * The promotion card for the person and their pet, styled like a citation:- * midnight blue, a fine double gold rule, no flashing. In four beats:- *- * 1. the card settles in and "Promoted" (or "Level up") is set (0–0.4 s);- * 2. on a promotion the old insignia stands for a moment, then steps aside- * and dims while the new one is laid on piece by piece — each chevron,- * rocker, bar or star in turn — and catches the light once (0.5–1.6 s);- * between two promotions the insignia stays and the level number rolls;- * 3. the rank name, its grade and the level are set below (from 1.2 s);- * 4. each uniform piece the promotion unlocked slides up after it.- *- * It stays about five seconds — longer with pieces to show — and a click or- * Escape closes it early. Several level-ups play one after another. Reduced- * motion shows the same card without motion.- */-import { useEffect } from "react";-import { useT } from "@/i18n";-import { RANK_INFO, rankAt, rankOf } from "./levelCatalog";-import { RankInsignia } from "./insignia/RankInsignia";-import { useProgression } from "./progressionStore";-import { RewardIcon } from "./RewardIcon";--const BASE_MS = 5200;-const PER_REWARD_MS = 800;--export function LevelUpBanner({ playerName, petName }: { playerName: string; petName: string }) {- const t = useT();- const banner = useProgression((s) => s.banners[0]);- const dismiss = useProgression((s) => s.dismissBanner);- const bands = useProgression((s) => (banner ? s.snapshot?.titles[banner.kind] : undefined));-- useEffect(() => {- if (!banner) return;- const timer = setTimeout(dismiss, BASE_MS + banner.unlocked.length * PER_REWARD_MS);- const onKey = (event: KeyboardEvent) => { if (event.key === "Escape") { event.stopPropagation(); dismiss(); } };- window.addEventListener("keydown", onKey, true);- return () => { clearTimeout(timer); window.removeEventListener("keydown", onKey, true); };- }, [banner, dismiss]);-- if (!banner) return null;- const pet = banner.kind === "pet";- const who = pet ? t("society.level.pet_up").replace("{0}", petName) : playerName;- const rank = rankAt(bands, banner.level);- const before = rankAt(bands, banner.previousLevel);- const promoted = before !== rank;- const info = RANK_INFO[rank];- const next = bands?.find((band) => band.level > banner.level);- return (- <div className="level-banner-layer" data-office-ui>- <button type="button" key={banner.id} className="promo" data-tier={info.tier} data-promoted={promoted || undefined} onClick={dismiss}- aria-label={(promoted ? t("society.level.promoted_aria") : t("society.level.banner_aria"))- .replace("{0}", who).replace("{1}", String(banner.level)).replace("{2}", t(`society.level.title.${rank}`))}>- <span className="promo-rule" aria-hidden />- {banner.away && <span className="promo-away">{t("society.level.while_away")}</span>}- <span className="promo-kicker">{promoted ? t("society.level.promoted") : t("society.level.level_up")}</span>- <span className="promo-who">{who}</span>- <span className="promo-stage" aria-hidden>- {promoted && <span className="promo-old"><RankInsignia rank={before} size={64} /></span>}- <span className="promo-new"><RankInsignia rank={rank} size={118} reveal={promoted} /></span>- </span>- <span className="promo-rank">{t(`society.level.title.${rank}`)}</span>- <span className="promo-grade">- <span>{info.grade}</span>- <span className="promo-dot" aria-hidden />- <span className="promo-level">- {t("society.level.lv").replace("{0}", "")}- <span className="promo-number">- <span className="promo-number-old">{banner.previousLevel}</span>- <span className="promo-number-new">{banner.level}</span>- </span>- </span>- </span>- {!promoted && next && (- <span className="promo-next">- {t("society.level.next_promotion").replace("{0}", t(`society.level.title.${rankOf(next.title)}`)).replace("{1}", String(next.level))}- </span>- )}- {banner.unlocked.length > 0 && (- <span className="promo-rewards">- <span className="promo-unlocked">{t("society.level.unlocked")}</span>- {banner.unlocked.map((reward, i) => (- <span key={reward} className="promo-reward" style={{ animationDelay: `${1.7 + i * 0.22}s` }}>- <RewardIcon reward={reward} size={40} />- <span>{t(`society.level.reward.${reward}`)}</span>- </span>- ))}- <span className="promo-hint">{t("society.level.equip_hint")}</span>- </span>- )}- </button>- </div>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/ProgressionLayer.tsx b/dodaios/ui/web/frontend/src/components/society/progression/ProgressionLayer.tsxdeleted file mode 100644index b6e7ddd9f9..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/ProgressionLayer.tsx+++ /dev/null@@ -1,85 +0,0 @@-/**- * What the level system draws inside the Verse's canvas besides the figures'- * own uniforms and insignia (those are worn on the body, `regalia/dress.tsx`):- * the moment of a level-up and the floating "+XP". It only reads the shared- * positions the walkers already publish (`player`, `agentPositions`,- * `petBody`); it never moves anyone.- */-import { useRef } from "react";-import { useFrame } from "@react-three/fiber";-import { OFFICE_FIGURE_HEIGHT_M } from "../office/OfficeAgents";-import { player } from "../office/officeStore";-import { agentPositions, petBody } from "../office/walkerRegistry";-import { LevelUpBurst, XpPopup, type FlairSource } from "./effects/LevelUpBurst";-import { isRankId, rankAt } from "./levelCatalog";-import { PERSON_SUBJECT, petSubject, reportWorldAction } from "./progressionApi";-import { useProgression } from "./progressionStore";--const personSource: FlairSource = () => ({ x: player.x, z: player.z, heading: player.heading });-const petSource: FlairSource = () => (petBody.active ? { x: petBody.x, z: petBody.z } : null);--/** Where a subject stands, for a burst or a "+XP", and how tall it is there. */-function locate(subjectId: string, petId: string): { source: FlairSource; height: number; scale: number } | null {- if (subjectId === PERSON_SUBJECT) return { source: personSource, height: OFFICE_FIGURE_HEIGHT_M, scale: 1 };- if (subjectId === petSubject(petId)) return petBody.active ? { source: petSource, height: petBody.top, scale: 0.6 } : null;- if (subjectId.startsWith("agent:")) {- const id = subjectId.slice("agent:".length);- if (!agentPositions.has(id)) return null;- return { source: () => agentPositions.get(id) ?? null, height: OFFICE_FIGURE_HEIGHT_M, scale: 1 };- }- return null;-}--/** Every this many metres walked with the pet at your side, the pet earns a little XP (metered on the server). */-export const WALK_REPORT_M = 50;--/** Counts the metres the person walks while their pet is drawn beside them. */-function useWalkTogether(awake: boolean) {- const state = useRef({ last: null as { x: number; z: number } | null, metres: 0 });- useFrame(() => {- const s = state.current;- if (!awake || !petBody.active) { s.last = null; return; }- if (s.last) {- const step = Math.hypot(player.x - s.last.x, player.z - s.last.z);- // An elevator ride or a floor switch is no walk.- if (step < 1) s.metres += step;- }- s.last = { x: player.x, z: player.z };- if (s.metres >= WALK_REPORT_M) {- s.metres = 0;- void reportWorldAction("walk_together");- }- });-}--export function ProgressionLayer({ awake, reduced }: { awake: boolean; reduced: boolean }) {- const titles = useProgression((s) => s.snapshot?.titles);- const petId = useProgression((s) => s.petId);- const bursts = useProgression((s) => s.bursts);- const popups = useProgression((s) => s.popups);-- // Popups and bursts expire on the scene's own clock.- useFrame(() => useProgression.getState().expire(performance.now()));- useWalkTogether(awake);-- return (- <group>- {bursts.map((burst) => {- const where = locate(burst.subjectId, petId);- if (!where) return null;- const bands = titles?.[burst.kind];- const rank = isRankId(burst.title) ? burst.title : rankAt(bands, burst.level);- const promoted = rankAt(bands, burst.previousLevel) !== rank;- return <LevelUpBurst key={burst.id} source={where.source} kind={burst.kind} level={burst.level} rank={rank} promoted={promoted}- height={where.height} scale={where.scale} reduced={reduced} />;- })}- {popups.map((popup) => {- const where = locate(popup.subjectId, petId);- const at = where?.source();- if (!where || !at) return null;- const kind = popup.subjectId === PERSON_SUBJECT ? "person" : popup.subjectId.startsWith("pet:") ? "pet" : "agent";- return <XpPopup key={popup.id} x={at.x} z={at.z} y={where.height + 0.3} xp={popup.xp} kind={kind} />;- })}- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/RewardIcon.tsx b/dodaios/ui/web/frontend/src/components/society/progression/RewardIcon.tsxdeleted file mode 100644index 17fa407590..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/RewardIcon.tsx+++ /dev/null@@ -1,170 +0,0 @@-/**- * A reward's picture for the HUD, the promotion card and the hall screen: the- * piece itself, drawn from the same colours and ribbons the 3D figure wears —- * the uniform's coat with its collar, tie and buttons, the cap, the ribbons- * or the medals — on a dark display tile. Decorative: the name always sits- * next to it.- */-import { createContext, useContext, useId } from "react";-import type { RewardId } from "./levelCatalog";-import { uniformStyle, type UniformId } from "./regalia/dress";-import { MEDAL_METALS, RIBBONS, ribbonSpans, type RibbonSpec } from "./regalia/ribbons";--const GOLD = "#d8ab47";-const GOLD_DARK = "#8f6518";--function Uniform({ id }: { id: UniformId }) {- const u = uniformStyle(id, "captain");- const open = u.cut === "service" || u.cut === "mess";- return (- <g strokeLinejoin="round">- {/* Sleeves, then the body. */}- <path d="M13 15 L7 35 L12 36.5 L16 24 Z M35 15 L41 35 L36 36.5 L32 24 Z" fill={u.coat} stroke="#00000055" strokeWidth={0.8} />- <path d={u.cut === "mess" ? "M14 13 L34 13 L36 33 L24 37 L12 33 Z" : "M14 13 L34 13 L35.5 41 L12.5 41 Z"} fill={u.coat} stroke="#00000055" strokeWidth={0.8} />- {u.cuffBraid && <path d="M7.6 33 L12.6 34.6 M40.4 33 L35.4 34.6" stroke={u.cuffBraid} strokeWidth={1.6} />}- {/* The opening: a shirt V with the tie, or a field jacket's stand collar. */}- {u.cut === "field" ? (- <>- <path d="M18 11 h12 v3.5 h-12 z" fill={u.coat} stroke="#00000055" strokeWidth={0.8} />- <path d="M24 14 V41" stroke="#00000066" strokeWidth={1} />- </>- ) : (- <>- <path d={open ? "M18.5 13 L24 27 L29.5 13 Z" : "M20.5 13 L24 19 L27.5 13 Z"} fill={u.shirt} />- {u.tieKind === "bow"- ? <path d="M21 15 L24 16.5 L27 15 L27 18 L24 16.5 L21 18 Z" fill={u.tie} />- : <path d={open ? "M23 14 L25 14 L25.6 24.5 L24 26.5 L22.4 24.5 Z" : "M23 14 L25 14 L25.6 30 L24 32 L22.4 30 Z"} fill={u.tie} />}- {open && <path d="M18.5 13 L24 27 M29.5 13 L24 27" stroke={u.lapels ?? "#00000055"} strokeWidth={u.lapels ? 2.4 : 1} />}- </>- )}- {u.pockets > 0 && [16.5, 27.5].map((x) => <rect key={x} x={x} y={20} width={4} height={1.8} rx={0.4} fill="#00000040" />)}- {u.pockets === 4 && [16.2, 27.8].map((x) => <rect key={`l${x}`} x={x} y={31} width={4} height={1.8} rx={0.4} fill="#00000040" />)}- {u.belt && <rect x={12.8} y={34} width={22.4} height={2.2} fill={u.belt} stroke="#00000044" strokeWidth={0.4} />}- {(open ? [29, 32.5] : [22, 26.5, 31]).map((y) => <circle key={y} cx={24} cy={y} r={0.9} fill={u.buttons} />)}- </g>- );-}--function Headwear({ id }: { id: RewardId }) {- if (id === "headwear_patrol_cap") {- return (- <g>- <path d="M13 16 L35 16 L36 30 L12 30 Z" fill="#5c6248" stroke="#00000055" strokeWidth={0.8} />- <path d="M11 29 L37 29 L39 33 Q24 36 9 33 Z" fill="#4d523b" stroke="#00000055" strokeWidth={0.8} />- <path d="M24 19.5 L28 22 L28 24 L24 21.5 L20 24 L20 22 Z" fill={GOLD} />- </g>- );- }- if (id === "headwear_garrison_cap") {- return (- <g>- <path d="M7 31 Q9 21 24 17 Q39 21 41 31 Z" fill="#1d2742" stroke="#00000066" strokeWidth={0.8} />- <path d="M8 30.5 Q24 26 40 30.5" stroke={GOLD} strokeWidth={1} fill="none" />- <path d="M24 17.5 Q33 20 40.5 30" stroke={GOLD} strokeWidth={0.8} fill="none" />- <circle cx={14} cy={27} r={1.8} fill={GOLD} />- </g>- );- }- if (id === "headwear_beret") {- return (- <g>- <path d="M9 28 Q8 17 22 15 Q38 14 41 24 Q41 29 33 29 L11 30 Z" fill="#141518" stroke="#ffffff22" strokeWidth={0.8} />- <rect x={10} y={28.5} width={26} height={3} rx={1.2} fill="#24252a" />- <path d="M14 18.5 h6 v4 q-3 3 -6 0 z" fill="#24386b" stroke={GOLD} strokeWidth={0.8} />- <circle cx={17} cy={21} r={1} fill={GOLD} />- </g>- );- }- return (- <g>- <ellipse cx={24} cy={17} rx={17} ry={4.5} fill="#1d2742" stroke="#00000066" strokeWidth={0.8} />- <path d="M11 18 L13 27 L35 27 L37 18 Z" fill="#1d2742" />- <rect x={13} y={24} width={22} height={5} fill="#0f1013" />- <path d="M13.5 28 h21" stroke={GOLD} strokeWidth={1.2} />- <path d="M12 29 Q24 37 36 29 Z" fill="#0b0c0f" stroke="#ffffff22" strokeWidth={0.6} />- <path d="M24 18.5 l2.4 1.6 -0.9 2.6 h-3 l-0.9 -2.6 z" fill={GOLD} />- </g>- );-}--function Ribbon({ spec, x, y, w, h }: { spec: RibbonSpec; x: number; y: number; w: number; h: number }) {- return (- <g>- {ribbonSpans(spec, w).map(([sx, sw, colour], i) => <rect key={i} x={x + sx} y={y} width={sw + 0.05} height={h} fill={colour} />)}- <rect x={x} y={y} width={w} height={h} fill="none" stroke="#00000066" strokeWidth={0.4} />- </g>- );-}--function Decoration({ id }: { id: RewardId }) {- const w = 10.5, h = 3.6;- if (id === "decoration_ribbon_bar") {- return <g>{[RIBBONS[4], RIBBONS[5], RIBBONS[6]].map((spec, i) => <Ribbon key={spec.id} spec={spec} x={8.25 + i * (w + 0.5)} y={22} w={w} h={h} />)}</g>;- }- if (id === "decoration_medals") {- return (- <g>- {RIBBONS.slice(0, 3).map((spec, i) => {- const x = 12 + i * 9;- const metal = MEDAL_METALS[spec.medal.metal];- return (- <g key={spec.id}>- <Ribbon spec={spec} x={x} y={10} w={7.5} h={11} />- <circle cx={x + 3.75} cy={27} r={4.6} fill={metal.face} stroke={metal.edge} strokeWidth={0.9} />- <circle cx={x + 3.75} cy={27} r={2.4} fill="none" stroke={metal.edge} strokeWidth={0.5} />- </g>- );- })}- </g>- );- }- const rack = RIBBONS.slice(0, 9);- const cords = id === "decoration_aiguillette";- return (- <g>- {rack.map((spec, i) => {- const row = Math.floor(i / 3), col = i % 3;- return <Ribbon key={spec.id} spec={spec} x={8.25 + col * (w + 0.5)} y={(cords ? 8 : 16) + row * (h + 0.6)} w={w} h={h} />;- })}- {cords && (- <g fill="none" stroke={GOLD} strokeWidth={1.3} strokeLinecap="round">- <path d="M10 25 Q24 42 38 25" />- <path d="M10 25 Q24 37 38 25" />- <path d="M18 30 V40 M29 30 V41" />- <path d="M18 40 l-1 2.6 h2 z M29 41 l-1 2.6 h2 z" fill={GOLD_DARK} stroke={GOLD_DARK} strokeWidth={0.6} />- </g>- )}- </g>- );-}--/** The tile a picture sits on: dark display velvet (HUD, promotion card) or light card stock (the white hall screen). */-export const RewardTileTone = createContext<"dark" | "light">("dark");--const TILES = {- dark: { top: "#2a3456", bottom: "#121831", edge: "#c9a24a55" },- light: { top: "#ffffff", bottom: "#ece7dc", edge: "#cfc7b5" },-} as const;--export function RewardIcon({ reward, locked = false, size = 30 }: { reward: RewardId; locked?: boolean; size?: number }) {- const id = useId().replace(/:/g, "");- const tile = TILES[useContext(RewardTileTone)];- return (- <span className="level-reward-icon" data-locked={locked || undefined} aria-hidden style={{ width: size, height: size }}>- <svg viewBox="0 0 48 48" width={size} height={size}>- <defs>- <radialGradient id={`${id}-tile`} cx="0.5" cy="0.3" r="0.8">- <stop offset="0" stopColor={tile.top} />- <stop offset="1" stopColor={tile.bottom} />- </radialGradient>- </defs>- <rect x={0.5} y={0.5} width={47} height={47} rx={9} fill={`url(#${id}-tile)`} stroke={tile.edge} strokeWidth={1} />- <g opacity={locked ? 0.6 : 1} style={locked ? { filter: "grayscale(.75)" } : undefined}>- {reward.startsWith("uniform_") && <Uniform id={reward as UniformId} />}- {reward.startsWith("headwear_") && <Headwear id={reward} />}- {reward.startsWith("decoration_") && <Decoration id={reward} />}- </g>- </svg>- </span>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/cosmetics.ts b/dodaios/ui/web/frontend/src/components/society/progression/cosmetics.tsindex 2cc1f9c3b3..d219c78494 100644--- a/dodaios/ui/web/frontend/src/components/society/progression/cosmetics.ts+++ b/dodaios/ui/web/frontend/src/components/society/progression/cosmetics.ts@@ -1,40 +1,31 @@/**- * Which cosmetics a subject wears. Pure: the level comes from the server,- * the unlock levels from the rulebook, and the person's own choice (for- * themself and their pet) from browser storage. Agents always wear the best- * they have unlocked; so does anyone who never chose.+ * What a level has opened, and which suit the captain wears. Pure: the level+ * comes from the server, the unlock levels from the rulebook, the captain's+ * choice of suit from browser storage. Destinations open here too, but which+ * one the helm has set is the ship store's (`starship/space/destinations.ts`).*/import type { RewardRow, SubjectLevel } from "./progressionApi";-import { SLOTS, type RewardId, type Slot, type SubjectKind } from "./levelCatalog";+import { SLOTS, type SubjectKind, type SuitId } from "./levelCatalog";-/** A slot left on "automatic" wears the latest unlock; "none" wears nothing. */-export type SlotChoice = RewardId | "none" | "auto";-export type Loadout = Partial<Record<Slot, RewardId>>;+/** "auto" wears the finest suit open, "none" the captain's own clothes. */+export type SuitChoice = SuitId | "none" | "auto";export function unlockedFor(rewards: readonly RewardRow[], kind: SubjectKind, level: number): RewardRow[] {return rewards.filter((r) => { const at = r.levels[kind]; return at !== null && level >= at; });}-export function equippedFor(rewards: readonly RewardRow[], kind: SubjectKind, level: number,- choices: Partial<Record<Slot, SlotChoice>> = {}): Loadout {- const open = unlockedFor(rewards, kind, level);- const loadout: Loadout = {};- for (const slot of SLOTS) {- const choice = choices[slot] ?? "auto";- if (choice === "none") continue;- const inSlot = open.filter((r) => r.slot === slot);- const picked = choice !== "auto" ? inSlot.find((r) => r.rewardId === choice) : undefined;- const best = inSlot.reduce<RewardRow | undefined>((top, r) => (!top || (r.levels[kind] ?? 0) >= (top.levels[kind] ?? 0) ? r : top), undefined);- const wear = picked ?? best;- if (wear) loadout[slot] = wear.rewardId;- }- return loadout;+/** The suit the captain wears at `level` with `choice`; null = own clothes. A chosen suit that is not open yet falls back to automatic. */+export function suitFor(rewards: readonly RewardRow[], level: number, choice: SuitChoice = "auto"): SuitId | null {+ if (choice === "none") return null;+ const open = unlockedFor(rewards, "person", level).filter((r) => r.slot === "suit");+ const picked = choice !== "auto" ? open.find((r) => r.rewardId === choice) : undefined;+ const best = open.reduce<RewardRow | undefined>((top, r) => (!top || (r.levels.person ?? 0) >= (top.levels.person ?? 0) ? r : top), undefined);+ return ((picked ?? best)?.rewardId as SuitId | undefined) ?? null;}/**- * The rewards a subject kind can ever wear, in the order they unlock (lowest- * level first; within one level in slot order). The Level Road's pedestals- * and the reward road on screen both read this order.+ * The rewards a subject kind can ever earn, in the order they open (lowest+ * level first; within one level in slot order).*/export function rewardRoad(rewards: readonly RewardRow[], kind: SubjectKind): RewardRow[] {return rewards@@ -42,11 +33,16 @@ export function rewardRoad(rewards: readonly RewardRow[], kind: SubjectKind): Re.sort((a, b) => (a.levels[kind] ?? 0) - (b.levels[kind] ?? 0) || SLOTS.indexOf(a.slot) - SLOTS.indexOf(b.slot));}-/** The first reward on the road the subject has not unlocked yet; undefined once everything is open. */+/** The first reward on the road the subject has not opened yet; undefined once everything is open. */export function nextUnlock(rewards: readonly RewardRow[], kind: SubjectKind, level: number): RewardRow | undefined {return rewardRoad(rewards, kind).find((r) => (r.levels[kind] ?? 0) > level);}+/** Rewards a climb from `before` to `after` opened, in road order. */+export function rewardsBetween(rewards: readonly RewardRow[], kind: SubjectKind, before: number, after: number): RewardRow[] {+ return rewardRoad(rewards, kind).filter((r) => { const at = r.levels[kind] ?? 0; return at > before && at <= after; });+}+/** XP gathered into the current level and the level's size, from the curve the server sent. */export function progressFor(levelXp: readonly number[], totalXp: number, level: number): { into: number; size: number } {const start = levelXp[level - 1] ?? 0;@@ -61,27 +57,23 @@ export function levelFraction(subject: Pick<SubjectLevel, "xpIntoLevel" | "xpForreturn Math.max(0, Math.min(1, subject.xpIntoLevel / subject.xpForNext));}-// v2: the rank uniforms replaced the trails, auras and gadgets of v1; old choices name ids that no longer exist.-const CHOICES_KEY = "jarvis.verse.cosmetics.v2";--export type ChoiceBook = Partial<Record<"person" | "pet", Partial<Record<Slot, SlotChoice>>>>;+const SUIT_KEY = "dodaios.ship.suit.v1";-export function loadChoices(): ChoiceBook {+export function loadSuitChoice(): SuitChoice {try {- const raw = typeof localStorage === "undefined" ? null : localStorage.getItem(CHOICES_KEY);- const parsed = raw ? (JSON.parse(raw) as unknown) : null;- return parsed && typeof parsed === "object" ? (parsed as ChoiceBook) : {};+ const raw = typeof localStorage === "undefined" ? null : localStorage.getItem(SUIT_KEY);+ return raw === "none" || (raw !== null && raw.startsWith("suit_")) ? (raw as SuitChoice) : "auto";} catch (error) {- // Blocked storage: everyone wears their best unlocks, which is the default anyway.- console.debug("Verse cosmetics choices unavailable", error);- return {};+ // Blocked storage: the captain wears the finest suit open, which is the default anyway.+ console.debug("Ship suit choice unavailable", error);+ return "auto";}}-export function saveChoices(book: ChoiceBook): void {+export function saveSuitChoice(choice: SuitChoice): void {try {- localStorage.setItem(CHOICES_KEY, JSON.stringify(book));+ localStorage.setItem(SUIT_KEY, choice);} catch (error) {- console.debug("Verse cosmetics choices not saved", error);+ console.debug("Ship suit choice not saved", error);}}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/effects/LevelUpBurst.tsx b/dodaios/ui/web/frontend/src/components/society/progression/effects/LevelUpBurst.tsxdeleted file mode 100644index a419d45591..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/effects/LevelUpBurst.tsx+++ /dev/null@@ -1,94 +0,0 @@-/**- * The level-up moment in the world, kept quiet the way a ceremony is: a- * single gold ring runs out across the floor under the figure and a soft- * light fades beneath it, while a plate rises over the head with the new- * insignia — "Promoted · Sergeant" on a promotion, "Level 7" between two.- * The ring and the plate follow the figure if it keeps walking. Reduced- * motion keeps the plate and drops the ring.- */-import { useEffect, useMemo, useRef } from "react";-import { Html } from "@react-three/drei";-import { useFrame } from "@react-three/fiber";-import { AdditiveBlending, DoubleSide, MeshBasicMaterial, type Group, type Mesh } from "three";-import { useT } from "@/i18n";-import { glowTexture } from "./flairTextures";-import type { RankId, SubjectKind } from "../levelCatalog";-import { RankInsignia } from "../insignia/RankInsignia";-import { BURST_MS } from "../progressionStore";--/** Where something stands this frame (and how high its top is), or null while it is not drawn. */-export type FlairSource = () => { x: number; z: number; y?: number; heading?: number } | null;--const GOLD = "#e3b94f";--/** 0..1 ease-out (cubic). */-const easeOut = (x: number) => 1 - Math.pow(1 - Math.min(1, Math.max(0, x)), 3);--export function LevelUpBurst({ source, kind, level, rank, promoted, height, scale = 1, reduced }: {- source: FlairSource; kind: SubjectKind; level: number; rank: RankId; promoted: boolean; height: number; scale?: number; reduced: boolean;-}) {- const t = useT();- const group = useRef<Group>(null);- const ring = useRef<Mesh>(null);- const glow = useRef<Mesh>(null);- const clock = useRef(0);- const materials = useMemo(() => ({- ring: new MeshBasicMaterial({ color: GOLD, transparent: true, opacity: 0.8, blending: AdditiveBlending, depthWrite: false, side: DoubleSide }),- glow: new MeshBasicMaterial({ map: glowTexture(), color: GOLD, transparent: true, opacity: 0.5, blending: AdditiveBlending, depthWrite: false }),- }), []);- useEffect(() => () => { materials.ring.dispose(); materials.glow.dispose(); }, [materials]);-- useFrame((_, rawDt) => {- const g = group.current;- if (!g) return;- const at = source();- if (at) g.position.set(at.x, 0, at.z);- clock.current += Math.min(rawDt, 0.1);- const s = clock.current;- if (reduced) return;- if (ring.current) {- const k = s / 1.2;- ring.current.visible = k < 1;- ring.current.scale.setScalar((0.35 + easeOut(k) * 1.5) * scale);- materials.ring.opacity = 0.8 * (1 - k);- }- if (glow.current) {- const k = s / 1.6;- glow.current.visible = k < 1;- materials.glow.opacity = 0.5 * (1 - easeOut(k));- }- });-- const flat: [number, number, number] = [-Math.PI / 2, 0, 0];- const word = promoted ? t("society.level.promoted") : t("society.level.level_n").replace("{0}", String(level));- return (- <group ref={group}>- {!reduced && <>- <mesh ref={glow} material={materials.glow} rotation={flat} position={[0, 0.03, 0]} scale={1.1 * scale} renderOrder={3}>- <circleGeometry args={[0.8, 32]} />- </mesh>- <mesh ref={ring} material={materials.ring} rotation={flat} position={[0, 0.035, 0]} visible={false} renderOrder={3}>- <ringGeometry args={[0.95, 1, 64]} />- </mesh>- </>}- <Html center position={[0, height + 0.6, 0]} zIndexRange={[45, 40]}>- <span className="promo-tag" data-kind={kind} style={{ animationDuration: `${BURST_MS}ms` }} aria-hidden>- <RankInsignia rank={rank} size={30} className="promo-tag-insignia" />- <span>- <small>{word}</small>- <b>{t(`society.level.title.${rank}`)}</b>- </span>- </span>- </Html>- </group>- );-}--/** "+5 XP", rising and fading over the wearer's head (CSS does the motion). */-export function XpPopup({ x, z, y, xp, kind }: { x: number; z: number; y: number; xp: number; kind: SubjectKind }) {- return (- <Html center position={[x, y, z]} zIndexRange={[44, 40]}>- <span className="level-xp-pop" data-kind={kind} aria-hidden>+{xp} XP</span>- </Html>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/effects/flairTextures.ts b/dodaios/ui/web/frontend/src/components/society/progression/effects/flairTextures.tsdeleted file mode 100644index d8c50b6e50..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/effects/flairTextures.ts+++ /dev/null@@ -1,36 +0,0 @@-/**- * The soft glow texture the level effects and the Level Hall share.- * Drawn once per page on first use; three.js re-uploads them from their- * canvas after a lost WebGL context, so they are never disposed.- */-import { CanvasTexture, SRGBColorSpace, type Texture } from "three";--type Draw = (ctx: CanvasRenderingContext2D, size: number) => void;--const cache = new Map<string, Texture>();--function canvasTexture(key: string, size: number, draw: Draw, height = size): Texture {- const hit = cache.get(key);- if (hit) return hit;- const canvas = document.createElement("canvas");- canvas.width = size;- canvas.height = height;- const ctx = canvas.getContext("2d");- if (ctx) draw(ctx, size);- const texture = new CanvasTexture(canvas);- texture.colorSpace = SRGBColorSpace;- cache.set(key, texture);- return texture;-}--export function glowTexture(): Texture {- return canvasTexture("glow", 64, (ctx) => {- const g = ctx.createRadialGradient(32, 32, 0, 32, 32, 32);- g.addColorStop(0, "rgba(255,255,255,1)");- g.addColorStop(0.3, "rgba(255,255,255,0.55)");- g.addColorStop(0.65, "rgba(255,255,255,0.14)");- g.addColorStop(1, "rgba(255,255,255,0)");- ctx.fillStyle = g;- ctx.fillRect(0, 0, 64, 64);- });-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/hall/LevelHallScreen.tsx b/dodaios/ui/web/frontend/src/components/society/progression/hall/LevelHallScreen.tsxdeleted file mode 100644index c2681c1075..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/hall/LevelHallScreen.tsx+++ /dev/null@@ -1,333 +0,0 @@-/**- * The Level Hall screen: the game menu behind the hall's checkpoints, the- * level card and `L`. Six pages for the person or their pet (the pet IS- * Jarvis in the Verse):- *- * - Overview: the rank, level and XP bar, the next promotion, the next- * uniform pieces and the quickest ways to earn.- * - Ranks: the whole rank ladder as one chart, from private to five stars.- * - Studio: the dressing room. Every slot's pieces as cards; an unlocked- * piece is put on with one click, a locked one is tried on in the live- * preview with the level it needs.- * - Rewards: the promotion road from level 1 to the cap, every step's rank- * and pieces, and the chosen step in the preview.- * - Guide: how levelling works — three steps, what the next levels cost, and- * every rule that pays XP for you, your pet and your agents.- * - Team: every agent's level, best first.- *- * The chrome uses theme tokens (light and dark); the stage and the insignia- * are the game's own and read in both modes.- */-import { useEffect, useMemo, useRef } from "react";-import { useT } from "@/i18n";-import { useRunLocale } from "@/components/runs/format";-import { useCompanionPet } from "../../companion/companionPetStore";-import type { SocietyAgent } from "../../data";-import type { ToyLook } from "../../office/toyFigureModel";-import { levelFraction, rewardRoad } from "../cosmetics";-import { RANK_INFO, rankAt, rankOf } from "../levelCatalog";-import { RankInsignia } from "../insignia/RankInsignia";-import { LevelChip, XpBar } from "../LevelHud";-import { RewardTileTone } from "../RewardIcon";-import { useLevelSound } from "../levelSounds";-import { agentSubject, PERSON_SUBJECT, petSubject, type RewardRow, type XpRuleRow } from "../progressionApi";-import { HALL_TABS, useProgression, type HallTab } from "../progressionStore";-import { groupRules, nextTitle, quickWins, upcomingLevelCosts, xpToReach } from "./hallModel";-import { LevelHero, RewardCard, RuleRow, Section, TabIcon, type HallWho } from "./hallParts";-import { RanksTab } from "./RanksTab";-import { RewardsTab } from "./RewardsTab";-import { StudioTab } from "./StudioTab";-import { AgentSymbol } from "../../AgentSymbol";-import { CompanionMark } from "../../companion/CompanionMark";-import { accessoryItem } from "../../companion/accessories";-import { resolveCompanion } from "../../companion/appearance";-import "./hall.css";--const NO_LOOKS: Readonly<Record<string, number>> = {};--/** Every agent look in unlock order, each worn by a sample agent symbol. */-function LooksRoad({ looks }: { looks: Readonly<Record<string, number>> }) {- const t = useT();- const road = Object.entries(looks).sort((a, b) => a[1] - b[1] || a[0].localeCompare(b[0]));- if (road.length === 0) return null;- return (- <ol className="hall-looks" data-testid="hall-looks">- {road.map(([id, level], i) => {- const item = accessoryItem(id);- if (!item) return null;- return (- <li key={id}>- <AgentSymbol shape={(["circle", "squircle", "hexagon", "drop", "pill"] as const)[i % 5]!}- color={["#7ab6ef", "#bba7ed", "#79c7c4", "#f2a65a", "#ed91aa"][i % 5]!} size={58} accessories={{ [item.slot]: id }} />- <strong>{t(`society.companion.items.${id}`)}</strong>- <em>{level <= 1 ? t("society.hall.look_start") : t("society.level.lv").replace("{0}", String(level))}</em>- </li>- );- })}- </ol>- );-}--/** The next look an agent at `level` opens, lowest first. */-function nextLookFor(looks: Readonly<Record<string, number>>, level: number): [string, number] | undefined {- return Object.entries(looks).filter(([, at]) => at > level).sort((a, b) => a[1] - b[1])[0];-}--const LEAD_AGENT_ID = "jarvis";-// Stable fallbacks: a selector that returns a fresh [] or {} re-renders forever.-const NO_RULES: XpRuleRow[] = [];-const NO_REWARDS: RewardRow[] = [];-const NO_CURVE: number[] = [0];-const NO_TITLES: { level: number; title: string }[] = [];--/** Stroke icons in a 24 × 24 box for the page tabs. */-const TAB_ICON: Record<HallTab, string> = {- overview: "M12 2.8l8 4.6v9.2l-8 4.6-8-4.6V7.4zM12 8v4l3 2",- ranks: "M5 10l7-4.5 7 4.5M5 15l7-4.5 7 4.5M5 20l7-4.5 7 4.5",- studio: "M10 3l1.6 5.4L17 10l-5.4 1.6L10 17l-1.6-5.4L3 10l5.4-1.6zM18 14l.8 2.2L21 17l-2.2.8L18 20l-.8-2.2L15 17l2.2-.8z",- rewards: "M4 10h16v10H4zM2.5 6.5h19V10h-19zM12 6.5V20M12 6.5C10 3 6.5 3 6.5 5s3 1.5 5.5 1.5M12 6.5C14 3 17.5 3 17.5 5s-3 1.5-5.5 1.5",- guide: "M4 4.5h6a2 2 0 0 1 2 2V20a2 2 0 0 0-2-2H4zM20 4.5h-6a2 2 0 0 0-2 2V20a2 2 0 0 1 2-2h6z",- team: "M9 11a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM3 20c0-3.3 2.7-5.5 6-5.5s6 2.2 6 5.5M16.5 11a2.5 2.5 0 1 0 0-5M18 14.5c2 .6 3.5 2.4 3.5 5",-};--function OverviewTab({ who }: { who: HallWho }) {- const t = useT();- const locale = useRunLocale();- const open = useProgression((s) => s.openPanel);- const rewards = useProgression((s) => s.snapshot?.rewards ?? NO_REWARDS);- const rules = useProgression((s) => s.snapshot?.rules ?? NO_RULES);- const curve = useProgression((s) => s.snapshot?.levelXp ?? NO_CURVE);- const titles = useProgression((s) => s.snapshot?.titles[who.kind] ?? NO_TITLES);- const subject = useProgression((s) => s.subjects[who.subjectId]);- const level = subject?.level ?? 1;- const promotion = nextTitle(titles, level);- const promoRank = promotion ? rankAt(titles, promotion.level) : null;- const road = useMemo(() => rewardRoad(rewards, who.kind), [rewards, who.kind]);- const upcoming = road.filter((r) => (r.levels[who.kind] ?? 0) > level).slice(0, 3);- // With everything open, the page shows the three best pieces instead.- const best = upcoming.length === 0 ? road.slice(-3).reverse() : [];- const wins = useMemo(() => quickWins(rules, who.kind, 4), [rules, who.kind]);- return (- <div className="hall-overview">- <LevelHero who={who} />- {who.kind === "pet" && <p className="hall-hint hall-wide">{t("society.level.pet_intro")}</p>}- <Section title={t("society.hall.next_promotion_title")} aside={- <button type="button" className="hall-link" onClick={() => open("ranks")}>{t("society.hall.ranks_all")}</button>}>- {promotion && promoRank ? (- <button type="button" className="hall-promotion" data-tier={RANK_INFO[promoRank].tier} onClick={() => open("ranks")}>- <RankInsignia rank={promoRank} size={64} />- <span>- <strong>{t(`society.level.title.${promoRank}`)}</strong>- <em>{RANK_INFO[promoRank].grade} · {t("society.level.locked_at").replace("{0}", String(promotion.level))}</em>- <span className="hall-promotion-xp">{t("society.hall.xp_needed").replace("{0}", xpToReach(curve, subject?.xp ?? 0, promotion.level).toLocaleString(locale))}</span>- </span>- </button>- ) : <p className="hall-hint">{t("society.hall.top_title")}</p>}- </Section>- {road.length > 0 && <Section title={t(upcoming.length > 0 ? "society.hall.next_rewards" : "society.hall.best_pieces")} aside={- <button type="button" className="hall-link" onClick={() => open("rewards")}>{t("society.hall.road_all")}</button>}>- {upcoming.length === 0 && <p className="hall-hint">{t("society.hall.all_unlocked")}</p>}- {upcoming.length + best.length > 0 && (- <div className="hall-cards">- {[...upcoming, ...best].map((reward) => (- <RewardCard key={reward.rewardId} reward={reward} kind={who.kind} level={level}- xpMissing={xpToReach(curve, subject?.xp ?? 0, reward.levels[who.kind] ?? 1)}- onClick={() => open("studio", { reward: reward.rewardId })} />- ))}- </div>- )}- {upcoming.length > 0 && <p className="hall-hint">{t("society.hall.try_hint")}</p>}- </Section>}- <Section title={t("society.hall.quick_title")} aside={- <button type="button" className="hall-link" onClick={() => open("guide")}>{t("society.hall.quick_all")}</button>}>- <ul className="hall-rules">{wins.map((rule) => <RuleRow key={rule.source} rule={rule} />)}</ul>- </Section>- </div>- );-}--function GuideTab({ who, petName }: { who: HallWho; petName: string }) {- const t = useT();- const rules = useProgression((s) => s.snapshot?.rules ?? NO_RULES);- const curve = useProgression((s) => s.snapshot?.levelXp ?? NO_CURVE);- const level = useProgression((s) => s.subjects[who.subjectId]?.level ?? 1);- const costs = upcomingLevelCosts(curve, level, 3);- const steps = [1, 2, 3] as const;- const sections = [- { kind: "person" as const, title: t("society.hall.section_you") },- { kind: "pet" as const, title: t("society.hall.section_pet").replace("{0}", petName) },- { kind: "agent" as const, title: t("society.hall.section_agents") },- ];- return (- <div className="hall-guide">- <ol className="hall-steps">- {steps.map((n) => (- <li key={n}>- <span className="hall-step-n">{n}</span>- <strong>{t(`society.hall.step${n}_title`)}</strong>- <p>{t(`society.hall.step${n}_body`)}</p>- {n === 2 && costs.length > 0 && (- <ul className="hall-costs">- {costs.map((c) => <li key={c.level}>{t("society.hall.cost_line").replace("{0}", String(c.level)).replace("{1}", String(c.xp))}</li>)}- </ul>- )}- </li>- ))}- </ol>- {sections.map((section) => (- <Section key={section.kind} title={section.title} className="hall-guide-section">- {groupRules(rules, section.kind).map((group) => (- <div key={group.id} className="hall-rule-group">- <h4>{t(`society.hall.group.${group.id}`).replace("{0}", petName)}</h4>- <ul className="hall-rules">{group.rules.map((rule) => <RuleRow key={rule.source} rule={rule} />)}</ul>- </div>- ))}- </Section>- ))}- <p className="hall-hint">{t("society.hall.limits_note")}</p>- </div>- );-}--function TeamTab({ agents }: { agents: readonly SocietyAgent[] }) {- const t = useT();- const subjects = useProgression((s) => s.subjects);- const looks = useProgression((s) => s.snapshot?.looks ?? NO_LOOKS);- const rows = useMemo(() => agents- .filter((a) => a.agentId !== LEAD_AGENT_ID && a.tier !== "lead")- .map((a) => ({ agent: a, subject: subjects[agentSubject(a.agentId)] }))- .sort((a, b) => (b.subject?.xp ?? 0) - (a.subject?.xp ?? 0) || a.agent.name.localeCompare(b.agent.name)), [agents, subjects]);- return (- <div className="hall-team">- {Object.keys(looks).length > 0 && (- <Section title={t("society.hall.looks_title")}>- <p className="hall-lead">{t("society.hall.looks_body")}</p>- <LooksRoad looks={looks} />- </Section>- )}- <Section title={t("society.level.team")}>- {rows.length === 0 ? <p className="hall-empty">{t("society.level.no_agents")}</p> : (- <ol className="hall-ranking">- {rows.map(({ agent, subject }, i) => {- const level = subject?.level ?? 1;- const look = resolveCompanion(agent.agentId, agent.figure?.companion);- const next = nextLookFor(looks, level);- const nextItem = next ? accessoryItem(next[0]) : undefined;- return (- <li key={agent.agentId} data-podium={i < 3 ? i + 1 : undefined}>- <span className="hall-rank">{i + 1}</span>- <CompanionMark appearance={look} size={34} />- <LevelChip kind="agent" level={level} />- <span className="hall-rank-body">- <span><strong>{agent.name}</strong> <em>{t(`society.level.title.${rankOf(subject?.title)}`)}</em></span>- <XpBar fraction={levelFraction(subject)} kind="agent" label={t("society.level.agent_xp_label").replace("{0}", agent.name)} />- {next && nextItem && (- <span className="hall-rank-next">- {!look.pet && <AgentSymbol shape={look.shape} color={look.color} eyes={look.eyes} skin={look.skin} size={22}- accessories={{ ...look.accessories, [nextItem.slot]: next[0] }} />}- {t("society.hall.next_look").replace("{0}", t(`society.companion.items.${next[0]}`)).replace("{1}", String(next[1]))}- </span>- )}- </span>- <span className="hall-rank-xp">{t("society.level.total").replace("{0}", String(subject?.xp ?? 0))}</span>- </li>- );- })}- </ol>- )}- </Section>- <p className="hall-hint">{t("society.hall.team_note")}</p>- </div>- );-}--export function LevelHallScreen({ agents, playerName, petName, playerLook }: {- agents: readonly SocietyAgent[]; playerName: string; petName: string; playerLook: ToyLook;-}) {- const t = useT();- const tab = useProgression((s) => s.panel);- const subjectChoice = useProgression((s) => s.hallSubject);- const openPanel = useProgression((s) => s.openPanel);- const setSubject = useProgression((s) => s.setHallSubject);- const petId = useProgression((s) => s.petId);- const loaded = useProgression((s) => !!s.snapshot);- const companion = useCompanionPet((s) => s.pet);- const sound = useLevelSound();- const panel = useRef<HTMLDivElement>(null);- const open = !!tab;- // Focus moves into the screen when it opens, not on every page change (that would pull it off the clicked tab).- useEffect(() => {- if (open) panel.current?.focus({ preventScroll: true });- }, [open]);- useEffect(() => {- if (!open) return;- const onKey = (event: KeyboardEvent) => {- if (event.key !== "Escape") return;- event.stopPropagation();- openPanel(null);- };- window.addEventListener("keydown", onKey, true);- return () => window.removeEventListener("keydown", onKey, true);- }, [open, openPanel]);- // The team page has no subject; the subject switch steps aside there.- const who: HallWho = useMemo(() => (subjectChoice === "pet"- ? { who: "pet", kind: "pet", subjectId: petSubject(petId), name: petName, preview: { kind: "pet", pet: companion } }- : { who: "person", kind: "person", subjectId: PERSON_SUBJECT, name: playerName, preview: { kind: "person", look: playerLook } }),- [subjectChoice, petId, petName, companion, playerName, playerLook]);- if (!tab) return null;- return (- <div className="hall-layer" data-office-ui onPointerDown={(e) => { if (e.target === e.currentTarget) openPanel(null); }}>- {/* data-state="open" marks a modal for the office's keyboard guard: no walking or E behind the screen. */}- <div ref={panel} className="hall" role="dialog" data-state="open" aria-modal="true" aria-labelledby="hall-title" tabIndex={-1}>- <header className="hall-head">- <div className="hall-brand">- <span className="hall-brand-mark" aria-hidden><TabIcon path={TAB_ICON.ranks} size={20} /></span>- <span>- <h2 id="hall-title">{t("society.hall.title")}</h2>- <small>{t("society.hall.subtitle")}</small>- </span>- </div>- {tab !== "team" && (- <div className="hall-subject" role="radiogroup" aria-label={t("society.hall.subject_label")}>- {(["person", "pet"] as const).map((id) => (- <button key={id} type="button" role="radio" aria-checked={subjectChoice === id} onClick={() => setSubject(id)}>- {id === "person" ? t("society.hall.subject_you") : petName}- </button>- ))}- </div>- )}- <button type="button" className="hall-close" onClick={() => openPanel(null)} aria-label={t("society.office.close")}>- <TabIcon path="M6 6l12 12M18 6L6 18" size={18} />- </button>- </header>- <nav className="hall-tabs" role="tablist" aria-label={t("society.hall.title")}>- {HALL_TABS.map((id) => (- <button key={id} type="button" role="tab" aria-selected={tab === id} className="hall-tab" onClick={() => openPanel(id)}>- <TabIcon path={TAB_ICON[id]} />- <span>{t(`society.hall.tab_${id}`)}</span>- </button>- ))}- </nav>- <RewardTileTone.Provider value="light">- <div className="hall-body" role="tabpanel" data-tab={tab}>- {!loaded ? <p className="hall-empty">{t("society.hall.loading")}</p> : <>- {tab === "overview" && <OverviewTab who={who} />}- {tab === "ranks" && <RanksTab who={who} />}- {tab === "studio" && <StudioTab key={who.who} who={who} />}- {tab === "rewards" && <RewardsTab key={who.who} who={who} />}- {tab === "guide" && <GuideTab who={who} petName={petName} />}- {tab === "team" && <TeamTab agents={agents} />}- </>}- </div>- </RewardTileTone.Provider>- <footer className="hall-foot">- <label className="hall-sound">- <input type="checkbox" checked={sound.on} onChange={(e) => sound.set(e.target.checked)} />- {t("society.level.sound")}- </label>- <span>{t("society.level.free_note")}</span>- </footer>- </div>- </div>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/hall/LoadoutPreview.tsx b/dodaios/ui/web/frontend/src/components/society/progression/hall/LoadoutPreview.tsxdeleted file mode 100644index dd80533d9e..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/hall/LoadoutPreview.tsx+++ /dev/null@@ -1,161 +0,0 @@-/**- * The studio's live preview: the person's own figure on the hall's stage in- * the uniform, cap and decorations of a loadout — the one they wear, or one- * with a locked piece put on to try — and the insignia of their rank; or the- * pet, which wears its rank on its name plate. The stage turns slowly; a- * drag turns it by hand.- *- * One canvas through `useWebglSurface` (AP-32: the context is handed back on- * unmount and rebuilt when the browser takes it), rendering only while on- * screen (`useCanvasAwake`). The stage is the game's own room, so it keeps- * the hall's midnight look in light and dark mode, like the world itself.- */-import { Component, Suspense, useLayoutEffect, useMemo, useRef, type ErrorInfo, type PointerEvent as ReactPointerEvent, type ReactNode } from "react";-import { Canvas, useFrame, useThree } from "@react-three/fiber";-import { useReducedMotion } from "framer-motion";-import type { Group } from "three";-import { useCanvasAwake } from "@/hooks/useCanvasAwake";-import { useWebglSurface } from "@/hooks/useWebglSurface";-import { useT } from "@/i18n";-import { CompanionModel } from "../../companion/AgentFollower";-import { defaultCompanion } from "../../companion/appearance";-import { companionFlies, type CompanionPet } from "../../companion/petCompanions";-import type { PetDrive } from "../../companion/PetModel";-import type { FigureDrive } from "../../figures/FigureRig";-import { CompanionBody, GIGI_OFFICE_SIZE_M, ModelBoundary } from "../../office/GigiFlyer";-import { StudioStage } from "../../office/LevelHall";-import { OFFICE_FIGURE_HEIGHT_M } from "../../office/OfficeAgents";-import { ToyFigure } from "../../office/ToyFigure";-import type { ToyLook } from "../../office/toyFigureModel";-import type { Loadout } from "../cosmetics";-import type { RankId } from "../levelCatalog";-import { dressedLook, regaliaFor, type UniformId } from "../regalia/dress";--/** How fast the stage turns, rad/s. */-const TURN_SPEED = 0.18;-/** Flying pets hover this high over the stage. */-const HOVER_M = 0.32;-/** A pet is drawn this tall on the stage, so a 0.3 m teapot reads as well as the person does. */-const PET_SHOWN_M = 0.78;--export type PreviewSubject = { kind: "person"; look: ToyLook } | { kind: "pet"; pet: CompanionPet };--function PreviewScene({ subject, loadout, rank, paused, reduced, spin }: {- subject: PreviewSubject; loadout: Loadout; rank: RankId; paused: boolean; reduced: boolean; spin: { current: number };-}) {- const clock = useRef(0);- const body = useRef<Group>(null);- const turntable = useRef<Group>(null);- const figureDrive = useRef<FigureDrive>({ mode: "idle", speed: 0 });- const petDrive = useRef<PetDrive>({ speed: 0, mood: "idle" });- const pet = subject.kind === "pet" ? subject.pet : null;- const flies = pet ? companionFlies(pet) : false;- // A pet stands on the same stage, drawn larger (its own group scales; the stage does not).- const grow = pet ? PET_SHOWN_M / pet.heightM : 1;- const lift = flies ? HOVER_M / grow : 0;- const gigi = useMemo(() => ({ ...defaultCompanion("jarvis"), sizeM: GIGI_OFFICE_SIZE_M }), []);- const person = subject.kind === "person" ? subject.look : null;- const dressed = useMemo(() => (person ? {- look: dressedLook(person, loadout.uniform as UniformId | undefined, rank), regalia: regaliaFor(rank, loadout),- } : null), [person, loadout, rank]);-- useFrame((_, rawDt) => {- const dt = paused ? 0 : Math.min(rawDt, 0.1);- clock.current += dt;- if (body.current) body.current.position.set(0, lift + (flies && !reduced ? Math.sin(clock.current * 2.2) * 0.04 : 0), 0);- // The stage turns slowly; a drag adds its own turn.- if (turntable.current) {- if (!reduced) spin.current += dt * TURN_SPEED;- turntable.current.rotation.y = spin.current;- }- });-- return (- <>- <hemisphereLight args={["#ffffff", "#d9d2c3", 1.25]} />- <directionalLight position={[2.2, 4, 3.2]} intensity={1.6} color="#fff6e8" />- <directionalLight position={[-3, 2.2, 1.5]} intensity={0.55} color="#e6eeff" />- <pointLight position={[0, 1.6, -2]} intensity={2.2} distance={6} decay={2} color="#ffffff" />- <group ref={turntable}>- <StudioStage />- <group scale={grow}>- <group ref={body}>- {pet ? (- <ModelBoundary key={pet.id}>- <Suspense fallback={null}>- <CompanionBody pet={pet} drive={petDrive} reduced={reduced} paused={paused} gigi={<CompanionModel appearance={gigi} lead />} />- </Suspense>- </ModelBoundary>- ) : dressed && (- <ToyFigure look={dressed.look} drive={figureDrive} paused={paused} heightM={OFFICE_FIGURE_HEIGHT_M} regalia={dressed.regalia} />- )}- </group>- </group>- </group>- <CameraFrame />- </>- );-}--/** Frames the figure from the knees up; a tall, narrow box stands further back. */-function CameraFrame() {- const camera = useThree((s) => s.camera);- const size = useThree((s) => s.size);- useLayoutEffect(() => {- const narrow = size.width / Math.max(1, size.height) < 0.9;- // Close on the figure: the insignia, ribbons and cap are what the studio shows off.- const distance = 4.1 * (narrow ? 1.2 : 1);- camera.position.set(0, 1.45, distance);- camera.lookAt(0, 0.62, 0);- camera.updateProjectionMatrix();- }, [camera, size]);- return null;-}--export function LoadoutPreview({ subject, loadout, rank, label }: {- subject: PreviewSubject; loadout: Loadout; rank: RankId; label: string;-}) {- const t = useT();- const host = useRef<HTMLDivElement>(null);- const { generation } = useWebglSurface(host);- const awake = useCanvasAwake(host);- const reduced = useReducedMotion() ?? false;- const spin = useRef(-0.3);- const drag = useRef<{ x: number; id: number } | null>(null);- const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {- if (e.button !== 0) return;- drag.current = { x: e.clientX, id: e.pointerId };- e.currentTarget.setPointerCapture(e.pointerId);- };- const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {- const d = drag.current;- if (!d || d.id !== e.pointerId) return;- spin.current += (e.clientX - d.x) * 0.012;- d.x = e.clientX;- };- const onPointerUp = (e: ReactPointerEvent<HTMLDivElement>) => { if (drag.current?.id === e.pointerId) drag.current = null; };- return (- <div ref={host} className="hall-preview" role="img" aria-label={label}- onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={onPointerUp} onPointerCancel={onPointerUp}>- <PreviewBoundary fallback={<p className="hall-preview-fallback">{t("society.figure.unavailable")}</p>}>- <Canvas key={generation} dpr={[1, 1.5]} frameloop={awake ? "always" : "never"}- gl={{ antialias: true, alpha: true, powerPreference: "low-power" }} camera={{ fov: 30, near: 0.1, far: 40, position: [0, 1.75, 4.1] }}- onCreated={({ gl }) => gl.setClearColor(0x000000, 0)}>- <Suspense fallback={null}>- <PreviewScene subject={subject} loadout={loadout} rank={rank} paused={!awake} reduced={reduced} spin={spin} />- </Suspense>- </Canvas>- </PreviewBoundary>- </div>- );-}--class PreviewBoundary extends Component<{ fallback: ReactNode; children: ReactNode }, { failed: boolean }> {- state = { failed: false };- static getDerivedStateFromError(): { failed: boolean } { return { failed: true }; }- componentDidCatch(error: Error, info: ErrorInfo): void {- // A WebGL that cannot be created is a stated fallback, not a silent one.- console.warn("[society] studio preview fell back to text:", error.message, info.componentStack);- }- render(): ReactNode { return this.state.failed ? this.props.fallback : this.props.children; }-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/hall/RanksTab.tsx b/dodaios/ui/web/frontend/src/components/society/progression/hall/RanksTab.tsxdeleted file mode 100644index 02277e0a89..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/hall/RanksTab.tsx+++ /dev/null@@ -1,75 +0,0 @@-/**- * The rank ladder as one chart: every rank's insignia, name, pay grade and- * the level it starts at, grouped by tier — enlisted, non-commissioned- * officers, officers, general officers. Ranks already held are drawn in- * full, the one held now is framed, the ones ahead are quiet silhouettes.- * Choosing a rank ahead shows how much XP is still missing.- */-import { useMemo } from "react";-import { useT } from "@/i18n";-import { useRunLocale } from "@/components/runs/format";-import type { RankTier } from "../levelCatalog";-import { rankAt } from "../levelCatalog";-import { RankInsignia } from "../insignia/RankInsignia";-import { useProgression } from "../progressionStore";-import { rankLadder, xpToReach } from "./hallModel";-import type { HallWho } from "./hallParts";--const NO_TITLES: { level: number; title: string }[] = [];-const NO_CURVE: number[] = [0];-const TIERS: readonly RankTier[] = ["enlisted", "nco", "officer", "general"];--export function RanksTab({ who }: { who: HallWho }) {- const t = useT();- const locale = useRunLocale();- const titles = useProgression((s) => s.snapshot?.titles[who.kind] ?? NO_TITLES);- const curve = useProgression((s) => s.snapshot?.levelXp ?? NO_CURVE);- const subject = useProgression((s) => s.subjects[who.subjectId]);- const level = subject?.level ?? 1;- const held = rankAt(titles, level);- const ladder = useMemo(() => rankLadder(titles), [titles]);- const position = Math.max(0, ladder.findIndex((rung) => rung.rank === held));- return (- <div className="hall-ranks">- <div className="hall-rank-summary">- <RankInsignia rank={held} size={84} />- <div>- <span className="hall-hero-name">{t("society.hall.rank_held")}</span>- <strong className="hall-hero-title">{t(`society.level.title.${held}`)}</strong>- <span className="hall-rank-track" aria-hidden><i style={{ width: `${(position / Math.max(1, ladder.length - 1)) * 100}%` }} /></span>- <span className="hall-hint">{t("society.hall.rank_position").replace("{0}", String(position + 1)).replace("{1}", String(ladder.length))}</span>- </div>- </div>- <p className="hall-lead">{t("society.hall.ranks_body")}</p>- {TIERS.map((tier) => {- const rungs = ladder.filter((rung) => rung.tier === tier);- if (rungs.length === 0) return null;- return (- <section key={tier} className="hall-rank-tier" data-tier={tier}>- <h3>{t(`society.hall.tier.${tier}`)}</h3>- <ol className="hall-rank-grid">- {rungs.map((rung) => {- const reached = level >= rung.level;- const current = rung.rank === held;- const missing = xpToReach(curve, subject?.xp ?? 0, rung.level);- return (- <li key={rung.rank} className="hall-rank-cell" data-reached={reached || undefined} data-current={current || undefined}>- {current && <span className="hall-rank-now">{t("society.hall.rank_held")}</span>}- <span className="hall-rank-art">- <RankInsignia rank={rung.rank} size={78} dim={!reached} />- {rung.rank === "private" && <span className="hall-rank-none">{t("society.level.no_insignia")}</span>}- </span>- <strong>{t(`society.level.title.${rung.rank}`)}</strong>- <span className="hall-rank-grade">{rung.grade}</span>- <em>{reached ? t("society.hall.rank_from").replace("{0}", String(rung.level))- : `${t("society.hall.rank_from").replace("{0}", String(rung.level))} · ${t("society.hall.xp_needed").replace("{0}", missing.toLocaleString(locale))}`}</em>- </li>- );- })}- </ol>- </section>- );- })}- </div>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/hall/RewardsTab.tsx b/dodaios/ui/web/frontend/src/components/society/progression/hall/RewardsTab.tsxdeleted file mode 100644index 14e28352b8..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/hall/RewardsTab.tsx+++ /dev/null@@ -1,157 +0,0 @@-/**- * The promotion road: every level that brings something — a new rank, a- * uniform piece, or both — from the first promotion to the cap, as one- * horizontal road with the subject's own position on it. Choosing a step- * shows it below: the figure in the preview as it will look at that rank- * wearing that piece, the rank's insignia, name and grade, the level it- * opens at and the XP still missing, and a button to put an open piece on.- */-import { useEffect, useMemo, useRef, useState } from "react";-import { useT } from "@/i18n";-import { useRunLocale } from "@/components/runs/format";-import { equippedFor, rewardRoad, type SlotChoice } from "../cosmetics";-import { RANK_INFO, rankAt, slotOf, type RankId, type RewardId, type Slot } from "../levelCatalog";-import { RankInsignia } from "../insignia/RankInsignia";-import type { RewardRow } from "../progressionApi";-import { useProgression } from "../progressionStore";-import { RewardIcon } from "../RewardIcon";-import { xpToReach } from "./hallModel";-import { LockGlyph, type HallWho } from "./hallParts";-import { LoadoutPreview } from "./LoadoutPreview";--const NO_REWARDS: RewardRow[] = [];-const NO_TITLES: { level: number; title: string }[] = [];-const NO_CURVE: number[] = [0];-const NO_CHOICES: Partial<Record<Slot, SlotChoice>> = {};--interface Step { level: number; rewards: RewardRow[]; title?: string }--/** The road's steps: each level with a reward or a new rank, lowest first. */-export function roadSteps(road: readonly RewardRow[], titles: readonly { level: number; title: string }[], kind: "person" | "pet"): Step[] {- const byLevel = new Map<number, Step>();- for (const reward of road) {- const at = reward.levels[kind] ?? 0;- const step = byLevel.get(at) ?? { level: at, rewards: [] };- step.rewards.push(reward);- byLevel.set(at, step);- }- for (const band of titles) {- if (band.level <= 1) continue;- const step = byLevel.get(band.level) ?? { level: band.level, rewards: [] };- step.title = band.title;- byLevel.set(band.level, step);- }- return [...byLevel.values()].sort((a, b) => a.level - b.level);-}--export function RewardsTab({ who }: { who: HallWho }) {- const t = useT();- const locale = useRunLocale();- const rewards = useProgression((s) => s.snapshot?.rewards ?? NO_REWARDS);- const titles = useProgression((s) => s.snapshot?.titles[who.kind] ?? NO_TITLES);- const curve = useProgression((s) => s.snapshot?.levelXp ?? NO_CURVE);- const subject = useProgression((s) => s.subjects[who.subjectId]);- const choices = useProgression((s) => s.choices[who.who] ?? NO_CHOICES);- const choose = useProgression((s) => s.choose);- const focus = useProgression((s) => s.focusReward);- const level = subject?.level ?? 1;- const road = useMemo(() => rewardRoad(rewards, who.kind), [rewards, who.kind]);- const steps = useMemo(() => roadSteps(road, titles, who.kind), [road, titles, who.kind]);- const nextStep = steps.find((s) => s.level > level);- const focusRow = focus ? road.find((r) => r.rewardId === focus) : undefined;- const [selected, setSelected] = useState<{ level: number; reward: RewardId | null }>(() => ({- level: focusRow?.levels[who.kind] ?? nextStep?.level ?? steps[steps.length - 1]?.level ?? 1,- reward: focusRow?.rewardId ?? nextStep?.rewards[0]?.rewardId ?? null,- }));- const step = steps.find((s) => s.level === selected.level) ?? nextStep ?? steps[0];- const reward = step?.rewards.find((r) => r.rewardId === selected.reward) ?? step?.rewards[0];- const equipped = useMemo(() => equippedFor(rewards, who.kind, level, choices), [rewards, who.kind, level, choices]);- const loadout = reward ? { ...equipped, [slotOf(reward.rewardId)]: reward.rewardId } : equipped;- const track = useRef<HTMLOListElement>(null);- // Open on the chosen step, not on the first one.- useEffect(() => {- track.current?.querySelector("[aria-pressed='true']")?.scrollIntoView({ block: "nearest", inline: "center" });- }, []);- if (!step) return <p className="hall-empty">{t("society.hall.all_unlocked")}</p>;- const open = level >= step.level;- const missing = xpToReach(curve, subject?.xp ?? 0, step.level);- const worn = reward ? equipped[reward.slot] === reward.rewardId : false;- const stepRank: RankId = rankAt(titles, step.level);- const info = RANK_INFO[stepRank];- return (- <div className="hall-rewards">- <p className="hall-lead">{t("society.hall.road_body")}</p>- <ol ref={track} className="hall-road">- {steps.map((s, i) => {- const done = level >= s.level;- const here = s === nextStep;- const rank = rankAt(titles, s.level);- return (- <li key={s.level} data-done={done || undefined} data-here={here || undefined}>- {here && <span className="hall-road-here">{t("society.hall.road_here").replace("{0}", String(level))}</span>}- <button type="button" className="hall-road-step" aria-pressed={s.level === step.level}- onClick={() => setSelected({ level: s.level, reward: s.rewards[0]?.rewardId ?? null })}>- <span className="hall-road-level">{t("society.level.lv").replace("{0}", String(s.level))}</span>- <span className="hall-road-icons">- {s.title && <RankInsignia rank={rank} size={30} dim={!done} />}- {s.rewards.map((r) => <RewardIcon key={r.rewardId} reward={r.rewardId} size={30} locked={!done} />)}- </span>- {s.title && <span className="hall-road-title">{t(`society.level.title.${rank}`)}</span>}- {!done && <LockGlyph />}- </button>- {i < steps.length - 1 && <span className="hall-road-link" aria-hidden />}- </li>- );- })}- </ol>-- <div className="hall-detail">- <div className="hall-stage hall-stage-small">- <LoadoutPreview subject={who.preview} loadout={loadout} rank={stepRank}- label={t("society.hall.preview_label").replace("{0}", who.name)} />- </div>- <div className="hall-detail-info">- <span className="hall-detail-kicker" data-open={open || undefined}>- {open ? t("society.hall.reward_open").replace("{0}", String(step.level)) : t("society.hall.reward_locked").replace("{0}", String(step.level))}- </span>- <div className="hall-detail-rank" data-tier={info.tier}>- <RankInsignia rank={stepRank} size={72} dim={!open} />- <span>- <strong>{t(`society.level.title.${stepRank}`)}</strong>- <em>{info.grade} · {t(`society.hall.tier.${info.tier}`)}</em>- </span>- </div>- {step.rewards.length > 1 && (- <div className="hall-detail-pick" role="group" aria-label={t("society.level.lv").replace("{0}", String(step.level))}>- {step.rewards.map((r) => (- <button key={r.rewardId} type="button" aria-pressed={r.rewardId === reward?.rewardId}- onClick={() => setSelected({ level: step.level, reward: r.rewardId })}>- <RewardIcon reward={r.rewardId} size={24} />- {t(`society.level.reward.${r.rewardId}`)}- </button>- ))}- </div>- )}- {reward && (- <div className="hall-detail-piece">- <RewardIcon reward={reward.rewardId} size={56} locked={!open} />- <span>- <h3>{t(`society.level.reward.${reward.rewardId}`)}</h3>- <span className="hall-card-meta">{t(`society.level.slot.${reward.slot}`)}</span>- <p>{t(`society.hall.slot_hint.${reward.slot}`)}</p>- </span>- </div>- )}- {!open && <p className="hall-detail-missing">{t("society.hall.reward_missing").replace("{0}", missing.toLocaleString(locale))}</p>}- {reward && open && (- worn- ? <span className="hall-detail-worn">{t("society.hall.wearing_now")}</span>- : <button type="button" className="hall-button hall-button-primary" onClick={() => choose(who.who, reward.slot, reward.rewardId)}>- {t("society.hall.put_on")}- </button>- )}- </div>- </div>- </div>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/hall/StudioTab.tsx b/dodaios/ui/web/frontend/src/components/society/progression/hall/StudioTab.tsxdeleted file mode 100644index bc73497728..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/hall/StudioTab.tsx+++ /dev/null@@ -1,154 +0,0 @@-/**- * The studio: the dressing room for the person's uniform.- *- * The live preview on the left wears the current loadout and the insignia of- * the person's rank. On the right, one slot at a time (uniform, headwear,- * decorations): "automatic" (always the finest unlocked piece), "own- * clothes" (nothing from the slot), and every piece as a card with the rank- * it comes with. An unlocked piece is put on with one click; a locked one is- * tried on in the preview, marked as a try-on with the level and XP it still- * needs. The pet wears no uniform: its page shows it with its rank.- */-import { useMemo, useState } from "react";-import { useT } from "@/i18n";-import { useRunLocale } from "@/components/runs/format";-import { equippedFor, rewardRoad, type SlotChoice } from "../cosmetics";-import { RANK_INFO, rankAt, SLOTS, slotOf, type RankId, type RewardId, type Slot } from "../levelCatalog";-import { RankInsignia } from "../insignia/RankInsignia";-import type { RewardRow } from "../progressionApi";-import { useProgression } from "../progressionStore";-import { RewardIcon } from "../RewardIcon";-import { xpToReach } from "./hallModel";-import { LevelHero, LockGlyph, RankTag, TabIcon, type HallWho } from "./hallParts";-import { LoadoutPreview } from "./LoadoutPreview";--const NO_REWARDS: RewardRow[] = [];-const NO_CURVE: number[] = [0];-const NO_CHOICES: Partial<Record<Slot, SlotChoice>> = {};-const NO_TITLES: { level: number; title: string }[] = [];--/** The name plate as it shows over the figure: the name and the rank chip. */-export function RankPlate({ name, level, rank }: { name: string; level: number; rank: RankId }) {- return (- <span className="hall-plate">- <span>{name}</span>- <span className="level-chip"><RankInsignia rank={rank} size={16} /><b>{level}</b></span>- </span>- );-}--export function StudioTab({ who }: { who: HallWho }) {- const t = useT();- const locale = useRunLocale();- const rewards = useProgression((s) => s.snapshot?.rewards ?? NO_REWARDS);- const curve = useProgression((s) => s.snapshot?.levelXp ?? NO_CURVE);- const titles = useProgression((s) => s.snapshot?.titles[who.kind] ?? NO_TITLES);- const subject = useProgression((s) => s.subjects[who.subjectId]);- const choices = useProgression((s) => s.choices[who.who] ?? NO_CHOICES);- const choose = useProgression((s) => s.choose);- const focus = useProgression((s) => s.focusReward);- const level = subject?.level ?? 1;- const rank = rankAt(titles, level);- const road = useMemo(() => rewardRoad(rewards, who.kind), [rewards, who.kind]);- const focusRow = focus ? road.find((r) => r.rewardId === focus) : undefined;- const [slot, setSlot] = useState<Slot>(focusRow?.slot ?? "uniform");- const [tryOn, setTryOn] = useState<RewardId | null>(focusRow && (focusRow.levels[who.kind] ?? 0) > level ? focusRow.rewardId : null);- const equipped = useMemo(() => equippedFor(rewards, who.kind, level, choices), [rewards, who.kind, level, choices]);- const loadout = tryOn ? { ...equipped, [slotOf(tryOn)]: tryOn } : equipped;- const slots = SLOTS.filter((s) => road.some((r) => r.slot === s));- const inSlot = road.filter((r) => r.slot === slot);- const current: SlotChoice = choices[slot] ?? "auto";- const tryRow = tryOn ? road.find((r) => r.rewardId === tryOn) : undefined;- const tryAt = tryRow?.levels[who.kind] ?? 0;-- const pick = (choice: SlotChoice) => { choose(who.who, slot, choice); setTryOn(null); };-- return (- <div className="hall-studio">- <div className="hall-stage">- <LoadoutPreview subject={who.preview} loadout={loadout} rank={rank}- label={t("society.hall.preview_label").replace("{0}", who.name)} />- <div className="hall-stage-bottom">- {tryRow ? (- <div className="hall-tryon" role="status">- <span className="hall-tryon-badge">{t("society.hall.try_on")}</span>- <span>- <strong>{t(`society.level.reward.${tryRow.rewardId}`)}</strong>- <em>{t("society.hall.try_on_line").replace("{0}", String(tryAt))- .replace("{1}", xpToReach(curve, subject?.xp ?? 0, tryAt).toLocaleString(locale))}</em>- </span>- <button type="button" className="hall-button" onClick={() => setTryOn(null)}>{t("society.hall.try_on_back")}</button>- </div>- ) : (- <RankPlate name={who.name} level={level} rank={rank} />- )}- <span className="hall-stage-hint">{t("society.hall.drag_hint")}</span>- </div>- {rank !== "private" && (- <div className="hall-stage-rank" aria-hidden>- <RankInsignia rank={rank} size={46} />- <span>{RANK_INFO[rank].grade}</span>- </div>- )}- </div>-- <div className="hall-wardrobe">- <LevelHero who={who} compact />- {slots.length === 0 ? (- <div className="hall-insignia-card">- <RankInsignia rank={rank} size={120} />- <strong>{t(`society.level.title.${rank}`)}</strong>- <p className="hall-hint">{t("society.hall.pet_rank_only").replace("{0}", who.name)}</p>- </div>- ) : <>- <p className="hall-lead">{t("society.hall.studio_body_you")}</p>- <div className="hall-slots" role="tablist" aria-label={t("society.hall.slots_label")}>- {slots.map((s) => {- const worn = loadout[s];- return (- <button key={s} type="button" role="tab" aria-selected={slot === s} className="hall-slot" onClick={() => setSlot(s)}>- {worn ? <RewardIcon reward={worn} size={34} /> : <span className="hall-slot-empty" aria-hidden />}- <span>{t(`society.level.slot.${s}`)}</span>- </button>- );- })}- </div>- <p className="hall-hint">{t(`society.hall.slot_hint.${slot}`)}</p>- <div className="hall-items" role="group" aria-label={t(`society.level.slot.${slot}`)}>- <button type="button" className="hall-item hall-item-plain" aria-pressed={current === "auto" && !tryOn} onClick={() => pick("auto")}>- <span className="hall-item-tile" aria-hidden><TabIcon path="M12 3v3M12 18v3M3 12h3M18 12h3M6 6l2 2M16 16l2 2M6 18l2-2M16 8l2-2" size={22} /></span>- <strong>{t("society.level.auto")}</strong>- <em>{t("society.hall.auto_hint")}</em>- </button>- <button type="button" className="hall-item hall-item-plain" aria-pressed={current === "none" && !tryOn} onClick={() => pick("none")}>- <span className="hall-item-tile" aria-hidden><TabIcon path="M5 5l14 14M12 3a9 9 0 1 1 0 18a9 9 0 1 1 0-18z" size={22} /></span>- <strong>{t("society.level.none")}</strong>- <em>{t("society.hall.none_hint")}</em>- </button>- {inSlot.map((reward) => {- const at = reward.levels[who.kind] ?? 0;- const open = level >= at;- const worn = equipped[slot] === reward.rewardId;- const pressed = tryOn ? tryOn === reward.rewardId : current === reward.rewardId;- return (- <button key={reward.rewardId} type="button" className="hall-item" data-open={open || undefined}- aria-pressed={pressed}- aria-label={open ? undefined : t("society.hall.locked_aria").replace("{0}", t(`society.level.reward.${reward.rewardId}`)).replace("{1}", String(at))}- onClick={() => (open ? pick(reward.rewardId) : setTryOn(reward.rewardId))}>- <RewardIcon reward={reward.rewardId} size={58} locked={!open} />- <strong>{t(`society.level.reward.${reward.rewardId}`)}</strong>- <RankTag rank={rankAt(titles, at)} />- <em data-open={open || undefined}>- {worn ? t("society.hall.equipped") : open ? t("society.hall.unlocked") : t("society.level.locked_at").replace("{0}", String(at))}- </em>- {!open && <LockGlyph />}- {worn && <span className="hall-item-check" aria-hidden><TabIcon path="M5 12.5l4.5 4.5L19 7.5" size={14} /></span>}- </button>- );- })}- </div>- </>}- </div>- </div>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/hall/hall.css b/dodaios/ui/web/frontend/src/components/society/progression/hall/hall.cssdeleted file mode 100644index e67d587f95..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/hall/hall.css+++ /dev/null@@ -1,263 +0,0 @@-/*- * The Level Hall screen, a ceremonial white: warm paper, navy ink, one- * restrained gold. It is the game's own surface — like the hall it belongs to,- * with its marble floor and brass — so it keeps this one look in light and- * dark mode; every colour comes from the --h-* tokens on `.hall`, never from- * the app theme. The insignia, the reward pictures and the stage read on it- * in both modes.- */--.hall-layer { position:absolute; inset:0; z-index:50; display:flex; align-items:center; justify-content:center; padding:16px; background:rgb(8 10 20 / .42); backdrop-filter:blur(3px); }-.hall {- --h-bg:#fbfaf6; --h-panel:#ffffff; --h-sunken:#f2efe7; --h-sunken-2:#e9e4d8;- --h-line:#e5e0d4; --h-line-strong:#cfc7b5;- --h-ink:#151a2b; --h-ink-2:#3a3f52; --h-muted:#76726a;- --h-navy:#1b2444; --h-navy-2:#26325c;- --h-gold:#b08a35; --h-gold-ink:#8a6a22; --h-gold-soft:#f4ecd6;- --h-ok:#2d7a4b; --h-ok-soft:#e3f1e8;- --h-focus:#2f5bd3;- display:flex; flex-direction:column; width:min(1200px, 100%); height:min(860px, 100%); overflow:hidden;- border:1px solid var(--h-line); border-radius:18px; background:var(--h-bg); color:var(--h-ink);- box-shadow:0 30px 80px rgb(8 10 20 / .35), 0 0 0 1px rgb(255 255 255 / .6) inset;- color-scheme:light; animation:hall-in .28s cubic-bezier(.2,.9,.3,1) both;-}-.hall:focus { outline:none; }-@keyframes hall-in { from { opacity:0; transform:translateY(12px) scale(.985); } to { opacity:1; transform:none; } }--/* ---------- head, tabs, foot ---------- */-.hall-head { display:flex; align-items:center; gap:14px; padding:18px 20px 12px 22px; background:var(--h-panel); }-.hall-brand { display:flex; align-items:center; gap:13px; flex:1; min-width:0; }-.hall-brand-mark { display:inline-flex; flex:none; align-items:center; justify-content:center; width:42px; height:42px; border-radius:11px; color:#e5c574; background:linear-gradient(180deg, var(--h-navy-2), var(--h-navy)); box-shadow:inset 0 0 0 1px rgb(201 162 74 / .7), 0 4px 12px rgb(27 36 68 / .25); }-.hall-brand h2 { margin:0; font-size:19px; font-weight:800; letter-spacing:-.015em; color:var(--h-ink); }-.hall-brand small { display:block; margin-top:2px; font-size:12.5px; color:var(--h-muted); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }-.hall-subject { display:inline-flex; flex:none; gap:2px; padding:3px; border-radius:10px; background:var(--h-sunken); box-shadow:inset 0 0 0 1px var(--h-line); }-.hall-subject button { border:0; border-radius:8px; padding:6px 14px; background:none; color:var(--h-muted); font:inherit; font-size:12.5px; font-weight:700; cursor:pointer; }-.hall-subject button[aria-checked="true"] { background:var(--h-panel); color:var(--h-ink); box-shadow:0 1px 3px rgb(21 26 43 / .12), 0 0 0 1px var(--h-line); }-.hall-subject button:focus-visible, .hall-close:focus-visible, .hall-tab:focus-visible { outline:2px solid var(--h-focus); outline-offset:1px; }-.hall-close { display:inline-flex; flex:none; align-items:center; justify-content:center; width:36px; height:36px; border:0; border-radius:10px; background:none; color:var(--h-muted); cursor:pointer; }-.hall-close:hover { background:var(--h-sunken); color:var(--h-ink); }-.hall-tabs { display:flex; gap:4px; padding:0 16px; background:var(--h-panel); border-bottom:1px solid var(--h-line); overflow-x:auto; scrollbar-width:none; }-.hall-tab { display:inline-flex; flex:none; align-items:center; gap:7px; padding:11px 12px 10px; border:0; border-bottom:2px solid transparent; background:none; color:var(--h-muted); font:inherit; font-size:13.5px; font-weight:650; cursor:pointer; }-.hall-tab:hover { color:var(--h-ink); }-.hall-tab[aria-selected="true"] { color:var(--h-ink); border-bottom-color:var(--h-gold); }-.hall-tab[aria-selected="true"] svg { color:var(--h-gold); }-.hall-body { flex:1; min-height:0; overflow:auto; padding:22px; font-size:13px; }-.hall-foot { display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; padding:10px 22px 12px; border-top:1px solid var(--h-line); background:var(--h-panel); font-size:12px; color:var(--h-muted); }-.hall-sound { display:inline-flex; align-items:center; gap:7px; color:var(--h-ink-2); cursor:pointer; }-.hall-sound input { accent-color:var(--h-navy); }--/* ---------- shared ---------- */-.hall-section { display:flex; flex-direction:column; gap:10px; min-width:0; }-.hall-section > header { display:flex; align-items:baseline; justify-content:space-between; gap:10px; }-.hall-section h3, .hall-rank-tier h3 { margin:0; font-size:11px; font-weight:800; letter-spacing:.12em; text-transform:uppercase; color:var(--h-muted); }-.hall-link { border:0; padding:0; background:none; color:var(--h-gold-ink); font:inherit; font-size:12.5px; font-weight:700; cursor:pointer; }-.hall-link:hover { text-decoration:underline; }-.hall-lead { margin:0; font-size:14px; line-height:1.5; color:var(--h-ink-2); }-.hall-hint { margin:0; font-size:12px; line-height:1.5; color:var(--h-muted); }-.hall-empty { margin:0; padding:24px; text-align:center; color:var(--h-muted); }-.hall-button { border:1px solid var(--h-line-strong); border-radius:10px; padding:8px 14px; background:var(--h-panel); color:var(--h-ink); font:inherit; font-size:13px; font-weight:700; cursor:pointer; white-space:nowrap; }-.hall-button:hover { background:var(--h-sunken); }-.hall-button:focus-visible, .hall-card:focus-visible, .hall-item:focus-visible, .hall-slot:focus-visible, .hall-road-step:focus-visible, .hall-promotion:focus-visible { outline:2px solid var(--h-focus); outline-offset:2px; }-.hall-button-primary { align-self:flex-start; border-color:var(--h-navy); background:var(--h-navy); color:#f6ecd2; padding:10px 18px; box-shadow:0 4px 12px rgb(27 36 68 / .22); }-.hall-button-primary:hover { background:var(--h-navy-2); }-.hall-rank-tag { display:inline-flex; align-items:center; gap:5px; padding:2px 8px 2px 4px; border-radius:6px; background:var(--h-sunken); box-shadow:inset 0 0 0 1px var(--h-line); color:var(--h-ink-2); font-size:11px; font-weight:700; white-space:nowrap; }-.hall-rank-tag svg { display:block; }-.hall-lock { position:absolute; top:10px; right:10px; color:var(--h-muted); }-.hall .level-bar { background:var(--h-sunken-2); }-.hall .level-bar-fill { background:linear-gradient(90deg, #a07a2a, #d6b25e); }-.hall .level-bar-gain { background:#f0dda8; box-shadow:none; }-.hall .level-ring-track { stroke:var(--h-sunken-2); }-.hall .level-ring-fill { stroke:var(--h-gold); }-.hall .level-reward-icon { border-radius:9px; }--/* ---------- level hero ---------- */-.hall-hero { display:flex; align-items:center; gap:24px; padding:20px 24px; border:1px solid var(--h-line); border-radius:16px; background:linear-gradient(180deg, var(--h-panel), var(--h-bg)); box-shadow:0 1px 2px rgb(21 26 43 / .05); }-.hall-hero[data-compact] { gap:14px; padding:10px 14px; }-.hall-hero-body { display:flex; flex-direction:column; gap:7px; flex:1; min-width:0; }-.hall-hero-name { font-size:13px; font-weight:700; letter-spacing:.04em; text-transform:uppercase; color:var(--h-muted); overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }-.hall-hero-title { display:inline-flex; align-items:baseline; gap:10px; font-size:26px; font-weight:800; letter-spacing:-.02em; color:var(--h-ink); }-.hall-hero-title small { padding:2px 7px; border-radius:6px; background:var(--h-gold-soft); color:var(--h-gold-ink); font-size:11.5px; font-weight:800; letter-spacing:.06em; }-.hall-hero[data-compact] .hall-hero-name { font-size:11px; }-.hall-hero[data-compact] .hall-hero-title { font-size:16px; }-.hall-hero .level-bar { height:8px; margin-top:2px; }-.hall-hero[data-compact] .level-bar { height:6px; }-.hall-hero-xp { display:flex; align-items:baseline; gap:12px; flex-wrap:wrap; font-size:13px; font-variant-numeric:tabular-nums; color:var(--h-ink); }-.hall-hero-xp span { color:var(--h-muted); }-.hall-hero[data-compact] .hall-hero-xp { font-size:11.5px; }-.hall-hero-meta { display:flex; gap:18px; flex-wrap:wrap; font-size:12px; color:var(--h-muted); }-.hall-hero .level-ring b { font-size:12px; line-height:17px; bottom:-7px; }-.hall-hero[data-compact] .level-ring b { font-size:10px; line-height:14px; bottom:-5px; }--/* ---------- overview ---------- */-.hall-overview { display:grid; grid-template-columns:minmax(0, 1.3fr) minmax(0, 1fr); gap:22px; align-items:start; }-.hall-overview > .hall-hero, .hall-overview > .hall-wide { grid-column:1 / -1; }-.hall-cards { display:grid; grid-template-columns:1fr; gap:8px; }-.hall-card { position:relative; display:flex; align-items:center; gap:14px; width:100%; padding:10px 36px 10px 10px; border:1px solid var(--h-line); border-radius:12px; background:var(--h-panel); color:inherit; font:inherit; text-align:left; cursor:pointer; transition:border-color .12s, box-shadow .12s, transform .12s; }-.hall-card:hover { border-color:var(--h-line-strong); box-shadow:0 4px 14px rgb(21 26 43 / .08); transform:translateY(-1px); }-.hall-card-text { display:flex; flex-direction:column; gap:4px; min-width:0; }-.hall-card-text strong { font-size:14px; color:var(--h-ink); }-.hall-card-meta { display:flex; align-items:center; gap:8px; flex-wrap:wrap; font-size:11.5px; color:var(--h-muted); }-.hall-card-state { font-size:11.5px; color:var(--h-muted); font-variant-numeric:tabular-nums; }-.hall-card-state[data-open] { color:var(--h-ok); font-weight:700; }-.hall-rules { display:grid; grid-template-columns:repeat(auto-fill, minmax(250px, 1fr)); gap:6px 10px; margin:0; padding:0; list-style:none; }-.hall-overview .hall-rules { grid-template-columns:1fr; }-.hall-rule { display:flex; align-items:flex-start; gap:10px; padding:9px 11px; border:1px solid var(--h-line); border-radius:10px; background:var(--h-panel); }-.hall-rule-xp { flex:none; min-width:42px; padding:2px 6px; border-radius:6px; background:var(--h-gold-soft); color:var(--h-gold-ink); font-size:12px; font-weight:800; text-align:center; font-variant-numeric:tabular-nums; }-.hall-rule-text { display:flex; flex-direction:column; gap:2px; font-size:13px; color:var(--h-ink); }-.hall-rule-text em { font-style:normal; font-size:11px; color:var(--h-muted); }-.hall-promotion { display:flex; align-items:center; gap:18px; width:100%; padding:16px 18px; border:1px solid var(--h-line); border-radius:14px; background:var(--h-panel); color:inherit; font:inherit; text-align:left; cursor:pointer; box-shadow:0 1px 2px rgb(21 26 43 / .05); }-.hall-promotion:hover { border-color:var(--h-gold); }-.hall-promotion > svg { padding:8px; border-radius:12px; background:var(--h-sunken); box-sizing:content-box; }-.hall-promotion > span { display:flex; flex-direction:column; gap:4px; min-width:0; }-.hall-promotion strong { font-size:18px; letter-spacing:-.01em; color:var(--h-ink); }-.hall-promotion em { font-style:normal; font-size:12px; color:var(--h-muted); }-.hall-promotion-xp { font-size:12.5px; font-weight:800; color:var(--h-gold-ink); font-variant-numeric:tabular-nums; }--/* ---------- the stage: a bright photo studio ---------- */-.hall-stage { position:relative; min-height:460px; overflow:hidden; border-radius:16px; color:var(--h-ink);- background:radial-gradient(70% 55% at 50% 38%, #ffffff 0%, #f3f0e9 55%, #e4dfd3 100%); box-shadow:inset 0 0 0 1px var(--h-line); }-.hall-stage::after { content:""; position:absolute; left:0; right:0; bottom:0; height:30%; background:linear-gradient(180deg, transparent, rgb(214 206 189 / .35)); pointer-events:none; }-.hall-stage-small { min-height:380px; }-.hall-preview { position:absolute; inset:0; z-index:1; cursor:grab; touch-action:none; }-.hall-preview:active { cursor:grabbing; }-.hall-preview-note { position:absolute; left:12px; right:12px; top:50%; margin:0; padding:6px 10px; border-radius:10px; background:rgb(255 255 255 / .9); color:var(--h-ink); font-size:12px; text-align:center; pointer-events:none; }-.hall-preview-fallback { position:absolute; inset:0; display:flex; align-items:center; justify-content:center; margin:0; padding:20px; text-align:center; color:var(--h-muted); }-.hall-stage-top { position:absolute; z-index:2; top:12px; left:12px; right:12px; pointer-events:none; }-.hall-stage .hall-hero { border-color:rgb(255 255 255 / .9); background:rgb(255 255 255 / .82); backdrop-filter:blur(8px); box-shadow:0 6px 18px rgb(21 26 43 / .08); }-.hall-stage-bottom { position:absolute; z-index:2; left:12px; right:12px; bottom:14px; display:flex; flex-direction:column; align-items:center; gap:8px; pointer-events:none; }-.hall-stage-bottom > * { pointer-events:auto; }-.hall-stage-hint { font-size:11px; color:var(--h-muted); pointer-events:none !important; }-.hall-plate { display:inline-flex; align-items:center; gap:8px; padding:4px 6px 4px 12px; border-radius:9px; background:var(--h-navy); color:#f6ecd2; font-size:13px; font-weight:700; box-shadow:0 4px 12px rgb(27 36 68 / .25); }-.hall-plate .level-chip { height:22px; font-size:12px; padding:0 7px 0 4px; }-.hall-tryon { display:flex; align-items:center; gap:12px; max-width:100%; padding:8px 8px 8px 10px; border:1px solid var(--h-gold); border-radius:12px; background:var(--h-panel); color:var(--h-ink); box-shadow:0 8px 24px rgb(21 26 43 / .14); }-.hall-tryon > span:nth-child(2) { display:flex; flex-direction:column; gap:1px; min-width:0; }-.hall-tryon strong { font-size:13px; }-.hall-tryon em { font-style:normal; font-size:11.5px; color:var(--h-muted); }-.hall-tryon-badge { flex:none; padding:3px 8px; border-radius:6px; background:var(--h-gold-soft); color:var(--h-gold-ink); font-size:10px; font-weight:900; letter-spacing:.1em; text-transform:uppercase; }-.hall-tryon .hall-button { font-size:12px; padding:6px 10px; }-.hall-stage-rank { position:absolute; z-index:2; right:14px; top:14px; display:flex; flex-direction:column; align-items:center; gap:4px; padding:10px 12px 8px; border-radius:12px; background:rgb(255 255 255 / .85); box-shadow:0 6px 18px rgb(21 26 43 / .1); pointer-events:none; }-.hall-stage-rank span { font-size:10.5px; font-weight:800; letter-spacing:.06em; color:var(--h-gold-ink); }--/* ---------- studio ---------- */-.hall-studio { display:grid; grid-template-columns:minmax(320px, 1fr) minmax(0, 1.05fr); gap:22px; align-items:start; }-/* A fixed frame that stays in view while the wardrobe scrolls, so the figure never stretches with the list. */-.hall-studio .hall-stage { position:sticky; top:0; height:min(580px, calc(100vh - 260px)); min-height:420px; }-.hall-detail .hall-stage { height:420px; min-height:0; }-.hall-wardrobe { display:flex; flex-direction:column; gap:14px; min-width:0; }-.hall-slots { display:grid; grid-template-columns:repeat(3, minmax(0, 1fr)); gap:8px; padding:4px; border-radius:14px; background:var(--h-sunken); box-shadow:inset 0 0 0 1px var(--h-line); }-.hall-slot { display:flex; align-items:center; gap:10px; padding:8px 10px; border:0; border-radius:10px; background:none; color:var(--h-muted); font:inherit; font-size:13px; font-weight:750; text-align:left; cursor:pointer; }-.hall-slot:hover { color:var(--h-ink); }-.hall-slot[aria-selected="true"] { background:var(--h-panel); color:var(--h-ink); box-shadow:0 1px 3px rgb(21 26 43 / .12), 0 0 0 1px var(--h-line); }-.hall-slot-empty { flex:none; width:34px; height:34px; border:1.5px dashed var(--h-line-strong); border-radius:9px; }-.hall-items { display:grid; grid-template-columns:repeat(auto-fill, minmax(150px, 1fr)); gap:10px; }-.hall-item { position:relative; display:flex; flex-direction:column; align-items:center; gap:7px; padding:16px 10px 12px; border:1px solid var(--h-line); border-radius:14px; background:var(--h-panel); color:var(--h-ink); font:inherit; text-align:center; cursor:pointer; transition:border-color .12s, box-shadow .12s, transform .12s; }-.hall-item:hover { border-color:var(--h-line-strong); box-shadow:0 6px 16px rgb(21 26 43 / .08); transform:translateY(-2px); }-.hall-item[aria-pressed="true"] { border-color:var(--h-navy); box-shadow:0 0 0 2px var(--h-navy), 0 6px 16px rgb(27 36 68 / .14); }-.hall-item strong { font-size:13px; line-height:1.25; }-.hall-item em { font-style:normal; font-size:11px; color:var(--h-muted); font-variant-numeric:tabular-nums; }-.hall-item em[data-open] { color:var(--h-ok); font-weight:700; }-.hall-item-tile { display:inline-flex; align-items:center; justify-content:center; width:58px; height:58px; border-radius:10px; background:var(--h-sunken); color:var(--h-muted); box-shadow:inset 0 0 0 1px var(--h-line); }-.hall-item-check { position:absolute; top:8px; left:8px; display:inline-flex; align-items:center; justify-content:center; width:20px; height:20px; border-radius:6px; background:var(--h-navy); color:#f6ecd2; }-.hall-insignia-card { display:flex; flex-direction:column; align-items:center; gap:12px; padding:40px 24px; border:1px solid var(--h-line); border-radius:16px; background:var(--h-panel); text-align:center; }-.hall-insignia-card strong { font-size:22px; letter-spacing:-.01em; }--/* ---------- promotion road ---------- */-.hall-rewards { display:flex; flex-direction:column; gap:16px; }-.hall-road { display:flex; align-items:center; margin:0; padding:30px 4px 12px; list-style:none; overflow-x:auto; scroll-snap-type:x proximity; }-.hall-road > li { position:relative; display:flex; flex:none; align-items:center; scroll-snap-align:center; }-.hall-road-step { position:relative; display:flex; flex-direction:column; align-items:center; gap:8px; min-width:112px; padding:12px 12px 12px; border:1px solid var(--h-line); border-radius:14px; background:var(--h-panel); color:var(--h-ink); font:inherit; cursor:pointer; transition:transform .12s, box-shadow .12s, border-color .12s; }-.hall-road-step:hover { border-color:var(--h-line-strong); }-.hall-road > li[data-done] .hall-road-step { border-top:3px solid var(--h-gold); }-.hall-road-step[aria-pressed="true"] { transform:translateY(-3px); border-color:var(--h-navy); box-shadow:0 0 0 2px var(--h-navy), 0 10px 22px rgb(21 26 43 / .12); }-.hall-road-level { font-size:12px; font-weight:800; letter-spacing:.04em; color:var(--h-muted); font-variant-numeric:tabular-nums; }-.hall-road-icons { display:flex; align-items:center; gap:6px; min-height:34px; }-.hall-road-title { max-width:130px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; font-size:11.5px; font-weight:750; color:var(--h-ink); }-.hall-road-step .hall-lock { top:7px; right:7px; }-.hall-road-link { width:24px; height:2px; background:var(--h-line-strong); }-.hall-road > li[data-done] .hall-road-link { background:var(--h-gold); }-.hall-road-here { position:absolute; top:-26px; left:0; padding:2px 9px; border-radius:6px; background:var(--h-navy); color:#f6ecd2; font-size:10.5px; font-weight:800; white-space:nowrap; }-.hall-detail { display:grid; grid-template-columns:minmax(300px, 1.1fr) minmax(0, 1fr); gap:22px; align-items:stretch; }-.hall-detail-info { display:flex; flex-direction:column; justify-content:center; gap:14px; min-width:0; padding:8px 4px; }-.hall-detail-info p { margin:0; color:var(--h-muted); line-height:1.5; }-.hall-detail-kicker { font-size:11px; font-weight:800; letter-spacing:.12em; text-transform:uppercase; color:var(--h-muted); }-.hall-detail-kicker[data-open] { color:var(--h-ok); }-.hall-detail-rank { display:flex; align-items:center; gap:18px; padding:16px 18px; border:1px solid var(--h-line); border-radius:14px; background:var(--h-panel); }-.hall-detail-rank > svg { padding:6px; border-radius:12px; background:var(--h-sunken); box-sizing:content-box; }-.hall-detail-rank[data-tier="general"] > svg { background:#111216; }-.hall-detail-rank > span { display:flex; flex-direction:column; gap:4px; }-.hall-detail-rank strong { font-size:24px; font-weight:800; letter-spacing:-.02em; }-.hall-detail-rank em { font-style:normal; font-size:12.5px; color:var(--h-muted); }-.hall-detail-pick { display:flex; gap:6px; flex-wrap:wrap; }-.hall-detail-pick button { display:inline-flex; align-items:center; gap:6px; padding:4px 10px 4px 4px; border:1px solid var(--h-line); border-radius:10px; background:var(--h-panel); color:var(--h-ink); font:inherit; font-size:12px; font-weight:700; cursor:pointer; }-.hall-detail-pick button[aria-pressed="true"] { border-color:var(--h-navy); box-shadow:0 0 0 1px var(--h-navy); }-.hall-detail-piece { display:flex; align-items:flex-start; gap:14px; padding:14px; border:1px solid var(--h-line); border-radius:14px; background:var(--h-panel); }-.hall-detail-piece h3 { margin:0 0 3px; font-size:16px; font-weight:800; color:var(--h-ink); }-.hall-detail-piece p { margin:6px 0 0; font-size:12.5px; }-.hall-detail-missing { font-size:15px; font-weight:800; color:var(--h-gold-ink) !important; }-.hall-detail-worn { align-self:flex-start; padding:6px 12px; border-radius:8px; background:var(--h-ok-soft); color:var(--h-ok); font-size:12.5px; font-weight:800; }--/* ---------- ranks chart ---------- */-.hall-ranks { display:flex; flex-direction:column; gap:22px; }-.hall-rank-summary { display:flex; align-items:center; gap:18px; padding:16px 20px; border:1px solid var(--h-line); border-radius:14px; background:var(--h-panel); }-.hall-rank-summary > div { display:flex; flex-direction:column; gap:6px; flex:1; min-width:0; }-.hall-rank-summary strong { font-size:15px; }-.hall-rank-summary .hall-rank-track { position:relative; height:6px; border-radius:3px; background:var(--h-sunken-2); overflow:hidden; }-.hall-rank-summary .hall-rank-track i { position:absolute; inset:0 auto 0 0; border-radius:inherit; background:linear-gradient(90deg, #a07a2a, #d6b25e); }-.hall-rank-tier { display:flex; flex-direction:column; gap:10px; }-.hall-rank-tier h3 { display:flex; align-items:center; gap:10px; }-.hall-rank-tier h3::after { content:""; flex:1; height:1px; background:var(--h-line); }-.hall-rank-grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(140px, 1fr)); gap:10px; margin:0; padding:0; list-style:none; }-.hall-rank-cell { position:relative; display:flex; flex-direction:column; align-items:center; gap:5px; padding:12px 10px 12px; border:1px solid var(--h-line); border-radius:14px; background:var(--h-panel); text-align:center; }-.hall-rank-cell[data-current] { border-color:var(--h-gold); box-shadow:0 0 0 2px var(--h-gold), 0 10px 22px rgb(176 138 53 / .18); }-.hall-rank-art { position:relative; display:flex; align-items:center; justify-content:center; width:100%; height:96px; border-radius:10px; background:radial-gradient(80% 80% at 50% 35%, #ffffff, var(--h-sunken)); box-shadow:inset 0 0 0 1px var(--h-line); }-.hall-rank-tier[data-tier="general"] .hall-rank-art { background:radial-gradient(80% 80% at 50% 35%, #2a2c33, #111216); box-shadow:inset 0 0 0 1px #c9a24a66; }-.hall-rank-none { position:absolute; inset:auto 6px 8px; font-size:10px; color:var(--h-muted); }-.hall-rank-cell strong { font-size:12.5px; line-height:1.25; color:var(--h-ink); }-.hall-rank-cell:not([data-reached]) strong { color:var(--h-muted); }-.hall-rank-grade { padding:1px 7px; border-radius:5px; background:var(--h-gold-soft); color:var(--h-gold-ink); font-size:10.5px; font-weight:800; letter-spacing:.06em; }-.hall-rank-cell:not([data-reached]) .hall-rank-grade { background:var(--h-sunken); color:var(--h-muted); }-.hall-rank-cell em { font-style:normal; font-size:10.5px; color:var(--h-muted); font-variant-numeric:tabular-nums; }-.hall-rank-now { position:absolute; top:-9px; left:50%; transform:translateX(-50%); padding:2px 9px; border-radius:6px; background:var(--h-navy); color:#f6ecd2; font-size:10px; font-weight:800; white-space:nowrap; }--/* ---------- guide ---------- */-.hall-guide { display:flex; flex-direction:column; gap:22px; }-.hall-steps { display:grid; grid-template-columns:repeat(3, minmax(0, 1fr)); gap:12px; margin:0; padding:0; list-style:none; }-.hall-steps > li { display:flex; flex-direction:column; gap:7px; padding:18px; border:1px solid var(--h-line); border-radius:14px; background:var(--h-panel); }-.hall-steps strong { font-size:15px; }-.hall-steps p { margin:0; color:var(--h-muted); line-height:1.5; }-.hall-step-n { display:inline-flex; align-items:center; justify-content:center; width:28px; height:28px; border-radius:8px; background:var(--h-navy); color:#f6ecd2; font-size:14px; font-weight:900; }-.hall-costs { display:flex; flex-direction:column; gap:2px; margin:4px 0 0; padding:0; list-style:none; font-size:12px; color:var(--h-ink-2); font-variant-numeric:tabular-nums; }-.hall-rule-group h4 { margin:2px 0 8px; font-size:13px; font-weight:800; color:var(--h-ink); }-.hall-guide-section { padding-top:4px; }--/* ---------- team ---------- */-.hall-team { display:flex; flex-direction:column; gap:12px; }-.hall-ranking { display:flex; flex-direction:column; gap:6px; margin:0; padding:0; list-style:none; }-.hall-ranking li { display:flex; align-items:center; gap:12px; padding:10px 12px; border:1px solid var(--h-line); border-radius:12px; background:var(--h-panel); }-.hall-rank { width:24px; text-align:center; font-size:13px; font-weight:800; color:var(--h-muted); }-.hall-ranking li[data-podium="1"] .hall-rank { color:var(--h-gold-ink); }-.hall-rank-body { display:flex; flex-direction:column; gap:6px; flex:1; min-width:0; }-.hall-rank-body em { font-style:normal; font-size:11.5px; color:var(--h-muted); }-.hall-rank-next { display:flex; align-items:center; gap:6px; font-size:11.5px; color:var(--h-muted); }-.hall-looks { display:grid; grid-template-columns:repeat(auto-fill, minmax(104px, 1fr)); gap:8px; margin:0; padding:0; list-style:none; }-.hall-looks li { display:flex; flex-direction:column; align-items:center; gap:4px; padding:12px 8px 10px; border:1px solid var(--h-line); border-radius:12px; background:var(--h-panel); text-align:center; }-.hall-looks strong { font-size:12px; line-height:1.2; }-.hall-looks em { font-style:normal; font-size:11px; color:var(--h-muted); }-.hall-rank-xp { font-size:12px; color:var(--h-muted); font-variant-numeric:tabular-nums; white-space:nowrap; }--@media (max-width:860px) {- .hall-overview, .hall-studio, .hall-detail { grid-template-columns:1fr; }- .hall-studio .hall-stage { min-height:380px; }- .hall-steps { grid-template-columns:1fr; }- .hall-brand small { display:none; }-}-@media (max-width:520px) {- .hall-layer { padding:0; }- .hall { border-radius:0; height:100%; }- .hall-hero { flex-direction:column; align-items:flex-start; }- .hall-slots { grid-template-columns:1fr; }-}-@media (prefers-reduced-motion: reduce) {- .hall, .hall-card, .hall-item, .hall-road-step { animation:none; transition:none; }- .hall-card:hover, .hall-item:hover, .hall-road-step[aria-pressed="true"] { transform:none; }-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/hall/hall.test.tsx b/dodaios/ui/web/frontend/src/components/society/progression/hall/hall.test.tsxdeleted file mode 100644index d50fd23ae6..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/hall/hall.test.tsx+++ /dev/null@@ -1,142 +0,0 @@-import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";-import { afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";-import { loadLocaleChunk } from "@/i18n";-import { nextUnlock, rewardRoad } from "../cosmetics";-import type { ProgressionSnapshot, RewardRow, XpRuleRow } from "../progressionApi";-import { useProgression } from "../progressionStore";-import type { ToyLook } from "../../office/toyFigureModel";-import { groupRules, nextTitle, quickWins, rankLadder, upcomingLevelCosts, xpToReach } from "./hallModel";-import { LevelHallScreen } from "./LevelHallScreen";-import { roadSteps } from "./RewardsTab";--const REWARDS: RewardRow[] = [- { rewardId: "headwear_patrol_cap", slot: "headwear", levels: { person: 10, agent: null, pet: null } },- { rewardId: "decoration_ribbon_bar", slot: "decoration", levels: { person: 3, agent: 3, pet: null } },- { rewardId: "uniform_field_jacket", slot: "uniform", levels: { person: 10, agent: null, pet: null } },- { rewardId: "uniform_service_shirt", slot: "uniform", levels: { person: 2, agent: null, pet: null } },- { rewardId: "decoration_medals", slot: "decoration", levels: { person: 40, agent: 44, pet: null } },-];-const BANDS = [{ level: 1, title: "private" }, { level: 5, title: "private_second_class" }, { level: 10, title: "sergeant" }];-const CURVE = [0, 40, 105, 195, 310, 450, 615, 805, 1020, 1260];-const rule = (source: XpRuleRow["source"], kind: XpRuleRow["kind"], xp: number): XpRuleRow =>- ({ source, kind, xp, trigger: "server", cooldownS: 0, dailyCap: 0 });-const RULES: XpRuleRow[] = [- rule("chat_turn", "person", 5), rule("agent_hired", "person", 50), rule("daily_visit", "person", 25),- rule("quest_completed", "person", 20), rule("walk_together", "pet", 3), rule("task_done", "agent", 40),-];--function snapshot(): ProgressionSnapshot {- return {- subjects: [{ subjectId: "person", kind: "person", xp: 130, level: 3, xpIntoLevel: 25, xpForNext: 90, title: "private" }],- petId: "gigi", recent: [], latestSeq: 0, maxLevel: 50, levelXp: CURVE, rules: RULES, rewards: REWARDS,- titles: { person: BANDS, agent: BANDS, pet: BANDS }, looks: { cap: 1, suit: 4, crown: 10 },- };-}--describe("hall model", () => {- it("reads the server's bands as the rank ladder, skipping unknown ranks", () => {- expect(rankLadder([...BANDS, { level: 12, title: "admiral" }]).map((r) => [r.level, r.rank, r.grade, r.tier]))- .toEqual([[1, "private", "E-1", "enlisted"], [5, "private_second_class", "E-2", "enlisted"], [10, "sergeant", "E-5", "nco"]]);- });-- it("measures what is missing on the server's curve", () => {- expect(xpToReach(CURVE, 130, 5)).toBe(180);- expect(xpToReach(CURVE, 999, 2)).toBe(0);- expect(xpToReach(CURVE, 0, 99)).toBe(0);- expect(upcomingLevelCosts(CURVE, 3, 3)).toEqual([{ level: 4, xp: 90 }, { level: 5, xp: 115 }, { level: 6, xp: 140 }]);- expect(upcomingLevelCosts(CURVE, 9, 3)).toEqual([{ level: 10, xp: 240 }]);- });-- it("orders the road by unlock level, slot order within a level, and skips what a kind never wears", () => {- expect(rewardRoad(REWARDS, "person").map((r) => r.rewardId))- .toEqual(["uniform_service_shirt", "decoration_ribbon_bar", "uniform_field_jacket", "headwear_patrol_cap", "decoration_medals"]);- expect(rewardRoad(REWARDS, "pet")).toEqual([]);- expect(nextUnlock(REWARDS, "person", 3)?.rewardId).toBe("uniform_field_jacket");- expect(nextUnlock(REWARDS, "person", 40)).toBeUndefined();- });-- it("builds road steps from rewards and promotions", () => {- const steps = roadSteps(rewardRoad(REWARDS, "person"), BANDS, "person");- expect(steps.map((s) => s.level)).toEqual([2, 3, 5, 10, 40]);- expect(steps.find((s) => s.level === 10)).toMatchObject({ title: "sergeant" });- expect(steps.find((s) => s.level === 10)!.rewards.map((r) => r.rewardId)).toEqual(["uniform_field_jacket", "headwear_patrol_cap"]);- expect(nextTitle([BANDS[1], BANDS[0]], 3)).toEqual(BANDS[1]);- expect(nextTitle([BANDS[1]], 5)).toBeUndefined();- });-- it("groups the rules for the guide and picks repeatable quick wins", () => {- const extra = { ...rule("chat_turn", "person", 1), source: "future_rule" as XpRuleRow["source"] };- expect(groupRules([...RULES, extra], "person").map((g) => [g.id, g.rules.map((r) => r.source)])).toEqual([- ["jarvis", ["chat_turn"]], ["team", ["quest_completed", "agent_hired"]], ["verse", ["daily_visit"]], ["other", ["future_rule"]],- ]);- expect(groupRules(RULES, "pet")).toEqual([{ id: "pet", rules: [RULES[4]] }]);- expect(quickWins(RULES, "person", 2).map((r) => r.source)).toEqual(["daily_visit", "quest_completed"]);- });-});--describe("Level Hall screen", () => {- beforeAll(async () => { await loadLocaleChunk("society"); });- beforeEach(() => {- useProgression.setState({ snapshot: null, subjects: {}, panel: null, hallSubject: "person", focusReward: null, choices: {} });- useProgression.getState().hydrate(snapshot(), []);- });- afterEach(() => { cleanup(); useProgression.getState().openPanel(null); });-- const look = {} as ToyLook;- const mount = () => render(<LevelHallScreen agents={[]} playerName="Ruby" petName="Gigi" playerLook={look} />);-- it("stays closed until a page is opened", () => {- mount();- expect(screen.queryByRole("dialog")).toBeNull();- });-- it("opens on the overview with six pages, the next promotion and the next unlocks", () => {- useProgression.getState().openPanel("overview");- mount();- const dialog = screen.getByRole("dialog");- const tabs = within(dialog).getAllByRole("tab");- expect(tabs).toHaveLength(6);- expect(tabs[0].getAttribute("aria-selected")).toBe("true");- expect(within(dialog).getByText("Ruby")).toBeTruthy();- expect(dialog.querySelector(".hall-promotion")).toBeTruthy();- // The next unlock (the field jacket at level 10) opens in the studio, ready to try on.- const cards = dialog.querySelectorAll(".hall-card");- expect(cards.length).toBe(3);- fireEvent.click(cards[0]);- expect(useProgression.getState()).toMatchObject({ panel: "studio", focusReward: "uniform_field_jacket" });- });-- it("charts every rank on the ranks page and marks the one held", () => {- useProgression.getState().openPanel("ranks");- mount();- const cells = document.querySelectorAll(".hall-rank-cell");- expect(cells).toHaveLength(BANDS.length);- expect(document.querySelectorAll(".hall-rank-cell[data-current]")).toHaveLength(1);- expect(cells[0].hasAttribute("data-current")).toBe(true);- });-- it("switches between the person and the pet, and lists every way to earn on the guide", () => {- useProgression.getState().openPanel("guide");- mount();- expect(screen.getAllByText("Gigi").length).toBeGreaterThan(0);- const radios = screen.getAllByRole("radio");- fireEvent.click(radios[1]);- expect(useProgression.getState().hallSubject).toBe("pet");- expect(document.querySelectorAll(".hall-rule")).toHaveLength(RULES.length);- });-- it("closes on Escape", () => {- useProgression.getState().openPanel("team");- mount();- fireEvent.keyDown(window, { key: "Escape" });- expect(useProgression.getState().panel).toBeNull();- });-- it("forgets a focused reward when another page opens without one", () => {- const store = useProgression.getState();- store.openPanel("rewards", { reward: "headwear_patrol_cap", subject: "pet" });- expect(useProgression.getState()).toMatchObject({ panel: "rewards", focusReward: "headwear_patrol_cap", hallSubject: "pet" });- useProgression.getState().openPanel("guide");- expect(useProgression.getState()).toMatchObject({ focusReward: null, hallSubject: "pet" });- });-});diff --git a/dodaios/ui/web/frontend/src/components/society/progression/hall/hallModel.ts b/dodaios/ui/web/frontend/src/components/society/progression/hall/hallModel.tsdeleted file mode 100644index 863c4bf965..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/hall/hallModel.ts+++ /dev/null@@ -1,72 +0,0 @@-/**- * What the Level Hall screen computes from the server's numbers. Pure: the- * curve, the rules and the reward levels all come from the snapshot; nothing- * here re-derives the rulebook.- */-import { isRankId, RANK_INFO, type RankId, type RankTier, type SubjectKind, type XpSource } from "../levelCatalog";-import type { XpRuleRow } from "../progressionApi";--/** One rung of the rank ladder: the rank, the level it starts at, its grade and tier. */-export interface Rung { level: number; rank: RankId; grade: string; tier: RankTier }--/** The server's title bands as the rank ladder, lowest first; a band naming no known rank is skipped. */-export function rankLadder(bands: readonly { level: number; title: string }[]): Rung[] {- return [...bands].sort((a, b) => a.level - b.level)- .filter((band): band is { level: number; title: RankId } => isRankId(band.title))- .map((band) => ({ level: band.level, rank: band.title, ...RANK_INFO[band.title] }));-}--/** XP still missing until `target` is reached (0 once it is); `levelXp[i]` is the total at which level i + 1 starts. */-export function xpToReach(levelXp: readonly number[], totalXp: number, target: number): number {- const start = levelXp[target - 1];- if (start === undefined) return 0;- return Math.max(0, start - totalXp);-}--/** The size of each of the next `count` levels after `level`, for "every level takes a little more". */-export function upcomingLevelCosts(levelXp: readonly number[], level: number, count: number): { level: number; xp: number }[] {- const out: { level: number; xp: number }[] = [];- for (let next = level + 1; next <= level + count; next += 1) {- const start = levelXp[next - 2], end = levelXp[next - 1];- if (start === undefined || end === undefined) break;- out.push({ level: next, xp: end - start });- }- return out;-}--/** The next title band above `level`, if any. */-export function nextTitle(bands: readonly { level: number; title: string }[], level: number): { level: number; title: string } | undefined {- return [...bands].sort((a, b) => a.level - b.level).find((band) => band.level > level);-}--/** How the guide groups the ways to earn XP, per subject kind; a source the rulebook adds later lands in "other". */-export const RULE_GROUPS: Record<SubjectKind, readonly { id: string; sources: readonly XpSource[] }[]> = {- person: [- { id: "jarvis", sources: ["chat_turn", "voice_turn"] },- { id: "team", sources: ["quest_posted", "quest_completed", "mission_completed", "agent_hired"] },- { id: "verse", sources: ["daily_visit", "floor_discovered", "dog_petted", "dog_treat", "arcade_round", "arcade_record", "team_meeting"] },- ],- pet: [{ id: "pet", sources: ["jarvis_answered", "delegated", "walk_together"] }],- agent: [{ id: "agent", sources: ["task_done", "quest_done", "answered_teammate", "task_blocked"] }],-};--/** A subject kind's rules sorted into the guide's groups, in the group's order; empty groups are dropped. */-export function groupRules(rules: readonly XpRuleRow[], kind: SubjectKind): { id: string; rules: XpRuleRow[] }[] {- const mine = rules.filter((r) => r.kind === kind);- const groups = RULE_GROUPS[kind].map((group) => ({- id: group.id,- rules: group.sources.map((source) => mine.find((r) => r.source === source)).filter((r): r is XpRuleRow => !!r),- }));- const known = new Set(RULE_GROUPS[kind].flatMap((g) => g.sources));- const other = mine.filter((r) => !known.has(r.source));- if (other.length > 0) groups.push({ id: "other", rules: other });- return groups.filter((g) => g.rules.length > 0);-}--/** The quickest everyday ways to earn: the highest-paying repeatable rules first. */-export function quickWins(rules: readonly XpRuleRow[], kind: SubjectKind, count: number): XpRuleRow[] {- return rules- .filter((r) => r.kind === kind && r.source !== "agent_hired" && r.source !== "floor_discovered")- .sort((a, b) => b.xp - a.xp || a.source.localeCompare(b.source))- .slice(0, count);-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/hall/hallParts.tsx b/dodaios/ui/web/frontend/src/components/society/progression/hall/hallParts.tsxdeleted file mode 100644index 2105a887d3..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/hall/hallParts.tsx+++ /dev/null@@ -1,146 +0,0 @@-/**- * Pieces the Level Hall screen's pages share: the tab icons, the level hero,- * reward cards, the rank tag, the padlock and the XP rule rows.- */-import type { ReactNode } from "react";-import { useT } from "@/i18n";-import { useRunLocale } from "@/components/runs/format";-import { levelFraction } from "../cosmetics";-import { LevelRing, XpBar } from "../LevelHud";-import { RANK_INFO, rankAt, rankOf, type RankId } from "../levelCatalog";-import { RankInsignia } from "../insignia/RankInsignia";-import type { RewardRow, XpRuleRow } from "../progressionApi";-import { useProgression } from "../progressionStore";-import { RewardIcon } from "../RewardIcon";-import { nextTitle } from "./hallModel";-import type { PreviewSubject } from "./LoadoutPreview";-import { ruleLimit } from "./ruleLimit";--const NO_TITLES: { level: number; title: string }[] = [];--export function TabIcon({ path, size = 16 }: { path: string; size?: number }) {- return (- <svg viewBox="0 0 24 24" width={size} height={size} aria-hidden fill="none" stroke="currentColor" strokeWidth={1.8} strokeLinecap="round" strokeLinejoin="round">- <path d={path} />- </svg>- );-}--/** Whose page this is, everything the pages need to know about them. */-export interface HallWho {- who: "person" | "pet";- kind: "person" | "pet";- subjectId: string;- name: string;- preview: PreviewSubject;-}--export function Section({ title, aside, children, className }: { title: string; aside?: ReactNode; children: ReactNode; className?: string }) {- return (- <section className={`hall-section${className ? ` ${className}` : ""}`}>- <header><h3>{title}</h3>{aside}</header>- {children}- </section>- );-}--/** The level hero: ring, name, title, bar and what is missing. */-export function LevelHero({ who, compact = false }: { who: HallWho; compact?: boolean }) {- const t = useT();- const subject = useProgression((s) => s.subjects[who.subjectId]);- const titles = useProgression((s) => s.snapshot?.titles[who.kind] ?? NO_TITLES);- const level = subject?.level ?? 1;- const fraction = levelFraction(subject);- const atCap = !!subject && subject.xpForNext <= 0;- const upcoming = nextTitle(titles, level);- return (- <div className="hall-hero" data-kind={who.kind} data-compact={compact || undefined}>- <LevelRing kind={who.kind} level={level} fraction={fraction} size={compact ? 76 : 120} />- <div className="hall-hero-body">- <span className="hall-hero-name">{who.name}</span>- <span className="hall-hero-title">- <span>{t(`society.level.title.${rankAt(titles, level)}`)}</span>- <small>{RANK_INFO[rankAt(titles, level)].grade}</small>- </span>- <XpBar fraction={fraction} kind={who.kind} label={t("society.level.xp_label")} />- <span className="hall-hero-xp">- <b>{atCap ? t("society.level.max") : t("society.level.xp_of").replace("{0}", String(subject?.xpIntoLevel ?? 0)).replace("{1}", String(subject?.xpForNext ?? 40))}</b>- {!atCap && <span>{t("society.level.to_next").replace("{0}", String(subject ? subject.xpForNext - subject.xpIntoLevel : 40)).replace("{1}", String(level + 1))}</span>}- </span>- {!compact && (- <span className="hall-hero-meta">- <span>{t("society.level.total").replace("{0}", String(subject?.xp ?? 0))}</span>- <span>{upcoming- ? t("society.hall.next_title").replace("{0}", t(`society.level.title.${rankOf(upcoming.title)}`)).replace("{1}", String(upcoming.level))- : t("society.hall.top_title")}</span>- </span>- )}- </div>- </div>- );-}--/** The rank a level brings, as a small tag: its insignia and name. */-export function RankTag({ rank }: { rank: RankId }) {- const t = useT();- return (- <span className="hall-rank-tag" data-tier={RANK_INFO[rank].tier}>- <RankInsignia rank={rank} size={13} />- {t(`society.level.title.${rank}`)}- </span>- );-}--/** A reward as a card: its picture, name, slot, the rank it comes with, and whether it is open. */-export function RewardCard({ reward, kind, level, onClick, pressed, badge, xpMissing }: {- reward: RewardRow; kind: "person" | "pet"; level: number; onClick?: () => void; pressed?: boolean; badge?: string; xpMissing?: number;-}) {- const t = useT();- const locale = useRunLocale();- const titles = useProgression((s) => s.snapshot?.titles[kind] ?? NO_TITLES);- const at = reward.levels[kind] ?? 0;- const open = level >= at;- const body = (- <>- <RewardIcon reward={reward.rewardId} size={48} locked={!open} />- <span className="hall-card-text">- <strong>{t(`society.level.reward.${reward.rewardId}`)}</strong>- <span className="hall-card-meta">- <span>{t(`society.level.slot.${reward.slot}`)}</span>- <RankTag rank={rankAt(titles, at)} />- </span>- <span className="hall-card-state" data-open={open || undefined}>- {badge ?? (open ? t("society.hall.unlocked") : xpMissing !== undefined- ? `${t("society.level.locked_at").replace("{0}", String(at))} · ${t("society.hall.xp_needed").replace("{0}", xpMissing.toLocaleString(locale))}`- : t("society.level.locked_at").replace("{0}", String(at)))}- </span>- </span>- {!open && <LockGlyph />}- </>- );- return onClick- ? <button type="button" className="hall-card" data-open={open || undefined} aria-pressed={pressed} onClick={onClick}>{body}</button>- : <div className="hall-card" data-open={open || undefined}>{body}</div>;-}--export function LockGlyph() {- return (- <svg className="hall-lock" viewBox="0 0 24 24" width={14} height={14} aria-hidden fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round">- <rect x="5" y="11" width="14" height="9" rx="2" /><path d="M8 11V8a4 4 0 0 1 8 0v3" />- </svg>- );-}--export function RuleRow({ rule }: { rule: XpRuleRow }) {- const t = useT();- const limit = ruleLimit(rule, t);- return (- <li className="hall-rule">- <span className="hall-rule-xp">+{rule.xp}</span>- <span className="hall-rule-text">- <span>{t(`society.level.source.${rule.source}`)}</span>- {limit && <em>{limit}</em>}- </span>- </li>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/hall/ruleLimit.ts b/dodaios/ui/web/frontend/src/components/society/progression/hall/ruleLimit.tsdeleted file mode 100644index 59cc138ab0..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/hall/ruleLimit.ts+++ /dev/null@@ -1,18 +0,0 @@-/** The limit line under an XP rule: once a day, once per floor, a cooldown, a daily cap. */-import type { XpRuleRow } from "../progressionApi";--function duration(seconds: number, t: (key: string) => string): string {- return seconds >= 60- ? t("society.level.minutes").replace("{0}", String(Math.round(seconds / 60)))- : t("society.level.seconds").replace("{0}", String(seconds));-}--export function ruleLimit(rule: XpRuleRow, t: (key: string) => string): string {- if (rule.source === "daily_visit") return t("society.level.limit_daily");- if (rule.source === "floor_discovered") return t("society.level.limit_floor");- if (rule.source === "agent_hired") return t("society.level.limit_agent");- const parts: string[] = [];- if (rule.cooldownS > 0) parts.push(t("society.level.limit_cooldown").replace("{0}", duration(rule.cooldownS, t)));- if (rule.dailyCap > 0) parts.push(t("society.level.limit_cap").replace("{0}", String(rule.dailyCap)));- return parts.join(" · ");-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/insignia/RankInsignia.tsx b/dodaios/ui/web/frontend/src/components/society/progression/insignia/RankInsignia.tsxdeleted file mode 100644index ed519321bc..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/insignia/RankInsignia.tsx+++ /dev/null@@ -1,66 +0,0 @@-/**- * A rank's insignia as an SVG: embroidered gold on navy for enlisted ranks,- * struck metal for officers, silver stars for generals. Drawn from the same- * polygons as the 3D pieces (`rankArt.ts`). Private (E-1) wears no insignia,- * so it shows an empty stitched outline. Decorative: the rank name always- * sits next to it.- */-import { useId, type CSSProperties } from "react";-import type { RankId } from "../levelCatalog";-import { FINISH_TONES, rankArt, svgPoints, type Finish } from "./rankArt";--const FINISHES: Finish[] = ["gold", "silver", "cloth"];--export function RankInsignia({ rank, size = 32, dim = false, reveal = false, className }: {- rank: RankId;- /** Height in px; the width follows the insignia's own shape. */- size?: number;- /** A rank not reached yet: drawn as a quiet silhouette. */- dim?: boolean;- /** Lay the pieces on one after another (CSS: `.rank-part` with `--i`, the piece's place in the stack). */- reveal?: boolean;- className?: string;-}) {- const id = useId().replace(/:/g, "");- const art = rankArt(rank);- const pad = 4;- const vbH = art.h + pad * 2;- const vbW = art.w + pad * 2;- const width = (size * vbW) / vbH;- if (art.parts.length === 0) {- return (- <svg className={className} viewBox={`0 0 ${vbW} ${vbH}`} width={width} height={size} aria-hidden data-rank={rank}>- <rect x={pad + 18} y={pad + 22} width={64} height={56} rx={10} fill="none" stroke="currentColor" strokeOpacity={0.45}- strokeWidth={3} strokeDasharray="6 5" />- </svg>- );- }- return (- <svg className={className} viewBox={`${-pad} ${-pad} ${vbW} ${vbH}`} width={width} height={size} aria-hidden data-rank={rank}- data-dim={dim || undefined}>- <defs>- {FINISHES.map((finish) => {- const tone = FINISH_TONES[finish];- return (- <linearGradient key={finish} id={`${id}-${finish}`} x1="0" y1="0" x2="0.35" y2="1">- <stop offset="0" stopColor={tone.light} />- <stop offset="0.45" stopColor={tone.mid} />- <stop offset="1" stopColor={tone.dark} />- </linearGradient>- );- })}- </defs>- <g opacity={dim ? 0.45 : 1} style={dim ? { filter: "grayscale(1)" } : undefined}>- {art.parts.map((part, i) => {- const tone = FINISH_TONES[part.finish];- const order = reveal ? { className: "rank-part", style: { "--i": i } as CSSProperties } : {};- if (part.detail) return <polygon key={i} points={svgPoints(part.pts)} fill={tone.dark} fillOpacity={0.55} {...order} />;- return (- <polygon key={i} points={svgPoints(part.pts)} fill={`url(#${id}-${part.finish})`} stroke={tone.edge}- strokeWidth={part.finish === "cloth" ? 1.6 : 1.1} strokeLinejoin="round" {...order} />- );- })}- </g>- </svg>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/insignia/rankArt.ts b/dodaios/ui/web/frontend/src/components/society/progression/insignia/rankArt.tsdeleted file mode 100644index 314c65117a..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/insignia/rankArt.ts+++ /dev/null@@ -1,363 +0,0 @@-/**- * The rank insignia as vector art: one source for every place a rank is- * drawn — the SVG icons in the HUD, the banner and the hall screen, the- * canvas of the Level Wall, and the extruded 3D pieces on a figure's sleeve- * or shoulder and in the hall's display cases. Because every surface reads- * these polygons, the insignia in a display case IS the one on the figure.- *- * Coordinates: a box 100 units wide, y pointing down (SVG convention); the- * height depends on the insignia. Enlisted ranks are gold chevrons, rockers- * and devices on a cut-to-shape navy backing worn on the upper sleeve;- * officers wear metal pins (bars, oak leaves, the eagle) and general officers- * silver stars on the shoulder. Private (E-1) wears no insignia.- *- * Pure geometry: no DOM, no three.js.- */-import type { RankId } from "../levelCatalog";--export type Pt = readonly [number, number];--/** What a part is made of: embroidered gold, polished silver, or the navy cloth it is sewn onto. */-export type Finish = "gold" | "silver" | "cloth";--export interface InsigniaPart {- pts: Pt[];- finish: Finish;- /** Raised detail (a leaf's veins, an eagle's feathers): drawn in a darker tone, extruded higher. */- detail?: boolean;-}--export interface InsigniaArt {- w: number;- h: number;- parts: InsigniaPart[];- /** Where a figure wears it. */- mount: "sleeve" | "shoulder" | "none";-}--// ----------------------------------------------------------------------------// Primitives--/** Chevron geometry: each band rises RISE over a half-span of SPAN, BAND thick, a new band every STEP. */-const SPAN = 46;-const RISE = 30;-const BAND = 9.5;-const STEP = 13;-const TOP = 6;-/** How far a rocker sags at its centre. */-const SAG = 15;-/** The navy backing's margin round the gold. */-const MARGIN = 3.2;--function chevron(y0: number): Pt[] {- return [- [50, y0], [50 + SPAN, y0 + RISE], [50 + SPAN, y0 + RISE + BAND],- [50, y0 + BAND], [50 - SPAN, y0 + RISE + BAND], [50 - SPAN, y0 + RISE],- ];-}--/** A rocker: a band that hangs between the two leg ends, sagging SAG at the middle. */-function rockerEdge(yEnds: number, sag: number, steps = 16): Pt[] {- const out: Pt[] = [];- for (let i = 0; i <= steps; i += 1) {- const u = -1 + (2 * i) / steps;- out.push([50 + u * SPAN, yEnds + sag * (1 - u * u)]);- }- return out;-}--function rocker(yEnds: number): Pt[] {- const top = rockerEdge(yEnds, SAG);- const bottom = rockerEdge(yEnds + BAND, SAG).reverse();- return [...top, ...bottom];-}--export function star(cx: number, cy: number, r: number, rotation = 0): Pt[] {- const out: Pt[] = [];- for (let i = 0; i < 10; i += 1) {- const a = rotation - Math.PI / 2 + (i * Math.PI) / 5;- const rr = i % 2 === 0 ? r : r * 0.4;- out.push([cx + Math.cos(a) * rr, cy + Math.sin(a) * rr]);- }- return out;-}--export function ellipse(cx: number, cy: number, rx: number, ry: number, steps = 24, rotation = 0): Pt[] {- const out: Pt[] = [];- const c = Math.cos(rotation), s = Math.sin(rotation);- for (let i = 0; i < steps; i += 1) {- const a = (i / steps) * Math.PI * 2;- const x = Math.cos(a) * rx, y = Math.sin(a) * ry;- out.push([cx + x * c - y * s, cy + x * s + y * c]);- }- return out;-}--function roundRect(x0: number, y0: number, x1: number, y1: number, r: number): Pt[] {- const out: Pt[] = [];- const corners: [number, number, number][] = [[x1 - r, y0 + r, -Math.PI / 2], [x1 - r, y1 - r, 0], [x0 + r, y1 - r, Math.PI / 2], [x0 + r, y0 + r, Math.PI]];- for (const [cx, cy, start] of corners) {- for (let i = 0; i <= 4; i += 1) {- const a = start + (i / 4) * (Math.PI / 2);- out.push([cx + Math.cos(a) * r, cy + Math.sin(a) * r]);- }- }- return out;-}--function diamond(cx: number, cy: number, rx: number, ry: number): Pt[] {- return [[cx, cy - ry], [cx + rx, cy], [cx, cy + ry], [cx - rx, cy]];-}--function transform(pts: readonly Pt[], cx: number, cy: number, s: number, flipX = false): Pt[] {- return pts.map(([x, y]) => [cx + (flipX ? -x : x) * s, cy + y * s] as Pt);-}--/**- * A heraldic eagle with spread wings, its head turned to the viewer's left,- * in a unit box (about -1..1). Wings are fans of feathers; a tail fan below.- */-function eagleUnit(): { body: Pt[][]; detail: Pt[][] } {- // Each wing is a fan of primary feathers raised from the shoulder, longest at the top.- const pivot: Pt = [-0.14, -0.04];- const feathers = 7;- const wing: Pt[] = [[-0.06, -0.2]];- for (let k = 0; k < feathers; k += 1) {- const t = k / (feathers - 1);- const angle = (-100 - t * 92) * (Math.PI / 180);- const reach = 0.96 - t * 0.42;- const tip: Pt = [pivot[0] + Math.cos(angle) * reach, pivot[1] + Math.sin(angle) * reach];- // A feather has a rounded tip: two points either side of the axis.- const across = angle + Math.PI / 2;- wing.push([tip[0] + Math.cos(across) * 0.045, tip[1] + Math.sin(across) * 0.045]);- wing.push([tip[0] + Math.cos(angle) * 0.03, tip[1] + Math.sin(angle) * 0.03]);- wing.push([tip[0] - Math.cos(across) * 0.045, tip[1] - Math.sin(across) * 0.045]);- if (k < feathers - 1) {- const mid = angle - (92 / (feathers - 1) / 2) * (Math.PI / 180);- const notch = reach * 0.8;- wing.push([pivot[0] + Math.cos(mid) * notch, pivot[1] + Math.sin(mid) * notch]);- }- }- wing.push([-0.12, 0.16]);- const rightWing = wing.map(([x, y]) => [-x, y] as Pt).reverse();- const body = ellipse(0, 0.06, 0.17, 0.34, 20);- const head = ellipse(-0.03, -0.36, 0.12, 0.12, 16);- const beak: Pt[] = [[-0.1, -0.4], [-0.27, -0.34], [-0.11, -0.29]];- const tail: Pt[] = [[-0.12, 0.3], [-0.24, 0.72], [-0.1, 0.64], [0, 0.8], [0.1, 0.64], [0.24, 0.72], [0.12, 0.3]];- // Raised feather lines on each wing and a breast shield.- const detail: Pt[][] = [];- for (const side of [-1, 1]) {- for (let k = 0; k < 3; k += 1) {- const angle = (-118 - k * 26) * (Math.PI / 180);- const x0 = side * -(pivot[0] + Math.cos(angle) * 0.18), y0 = pivot[1] + Math.sin(angle) * 0.18;- const x1 = side * -(pivot[0] + Math.cos(angle) * (0.66 - k * 0.08)), y1 = pivot[1] + Math.sin(angle) * (0.66 - k * 0.08);- const nx = -(y1 - y0), ny = x1 - x0;- const len = Math.hypot(nx, ny) || 1;- const w = 0.016;- detail.push([[x0 + (nx / len) * w, y0 + (ny / len) * w], [x1 + (nx / len) * w, y1 + (ny / len) * w],- [x1 - (nx / len) * w, y1 - (ny / len) * w], [x0 - (nx / len) * w, y0 - (ny / len) * w]]);- }- }- detail.push([[-0.1, -0.06], [0.1, -0.06], [0.1, 0.12], [0, 0.24], [-0.1, 0.12]]);- return { body: [wing, rightWing, body, head, beak, tail], detail };-}--const EAGLE = eagleUnit();--export function eagle(cx: number, cy: number, s: number, finish: Finish): InsigniaPart[] {- return [- ...EAGLE.body.map((pts) => ({ pts: transform(pts, cx, cy, s), finish })),- ...EAGLE.detail.map((pts) => ({ pts: transform(pts, cx, cy, s), finish, detail: true })),- ];-}--/** A lobed oak leaf, stem down, centred on (50, cy). */-function oakLeaf(cy: number, finish: Finish): InsigniaPart[] {- const length = 84, width = 30, top = cy - length / 2;- const steps = 48;- const right: Pt[] = [];- for (let i = 0; i <= steps; i += 1) {- const t = i / steps;- const body = Math.pow(Math.sin(Math.PI * Math.pow(t, 0.8)), 0.85);- const lobes = 0.74 + 0.26 * Math.cos(t * Math.PI * 2 * 3.5 + 0.6);- right.push([50 + (width / 2) * body * lobes, top + t * length * 0.9]);- }- const stem: Pt[] = [[52.2, top + length * 0.9], [52.2, top + length], [47.8, top + length], [47.8, top + length * 0.9]];- const left = right.map(([x, y]) => [100 - x, y] as Pt).reverse();- const outline = [...right, ...stem.slice(1, 3), ...left];- const veins: Pt[][] = [[[49.2, top + 6], [50.8, top + 6], [50.8, top + length * 0.9], [49.2, top + length * 0.9]]];- for (let k = 0; k < 3; k += 1) {- const y = top + 20 + k * 18;- for (const side of [-1, 1]) {- veins.push([[50, y], [50 + side * 10, y - 6], [50 + side * 10.6, y - 4.6], [50, y + 2]]);- }- }- return [{ pts: outline, finish }, ...veins.map((pts) => ({ pts, finish, detail: true }))];-}--// ----------------------------------------------------------------------------// Enlisted sets--interface ChevronSet { chevrons: number; rockers: number; device?: "diamond" | "star" | "wreath" | "sma" }--function chevronSet({ chevrons, rockers, device }: ChevronSet): InsigniaArt {- const parts: InsigniaPart[] = [];- const lastY = TOP + (chevrons - 1) * STEP;- const legEnd = lastY + RISE + BAND;- for (let i = 0; i < chevrons; i += 1) parts.push({ pts: chevron(TOP + i * STEP), finish: "gold" });- const rockerEnds: number[] = [];- for (let j = 0; j < rockers; j += 1) {- const y = legEnd + 3.5 + j * STEP;- rockerEnds.push(y);- parts.push({ pts: rocker(y), finish: "gold" });- }- // The device sits in the space between the lowest chevron and the first rocker.- const deviceY = (lastY + BAND + (rockerEnds[0] ?? legEnd) + SAG) / 2 + 2;- if (device === "diamond") parts.push({ pts: diamond(50, deviceY, 8, 11.5), finish: "gold" });- if (device === "star") parts.push({ pts: star(50, deviceY + 1, 12), finish: "gold" });- if (device === "wreath") {- parts.push({ pts: star(50, deviceY - 1, 9), finish: "gold" });- for (const side of [-1, 1]) {- for (let k = 0; k < 5; k += 1) {- const a = Math.PI / 2 + side * (0.55 + k * 0.42);- const r = 14;- parts.push({ pts: ellipse(50 + Math.cos(a) * r, deviceY + 1 + Math.sin(a) * r, 3.6, 1.7, 10, a + Math.PI / 2), finish: "gold", detail: true });- }- }- }- if (device === "sma") {- parts.push(...eagle(50, deviceY - 1, 11, "gold"));- parts.push({ pts: star(33, deviceY + 5, 5.5), finish: "gold" }, { pts: star(67, deviceY + 5, 5.5), finish: "gold" });- }- // The navy backing: the gold outline grown by a margin, cut along the lowest band.- const bottom = rockers > 0- ? rockerEdge(rockerEnds[rockers - 1] + BAND + MARGIN, SAG + 0.6).reverse()- : [[50 + SPAN + MARGIN, legEnd + MARGIN], [50, lastY + BAND + MARGIN * 1.6], [50 - SPAN - MARGIN, legEnd + MARGIN]] as Pt[];- const sideBottom = rockers > 0 ? rockerEnds[rockers - 1] + BAND + MARGIN : legEnd + MARGIN;- const backing: Pt[] = [- [50, TOP - MARGIN * 1.7],- [50 + SPAN + MARGIN, TOP + RISE - MARGIN * 0.3],- [50 + SPAN + MARGIN, sideBottom],- ...(rockers > 0 ? bottom : bottom.slice(1, 2)),- [50 - SPAN - MARGIN, sideBottom],- [50 - SPAN - MARGIN, TOP + RISE - MARGIN * 0.3],- ];- const h = Math.max(...backing.map(([, y]) => y)) + 2;- return { w: 100, h, parts: [{ pts: backing, finish: "cloth" }, ...parts], mount: "sleeve" };-}--function specialist(): InsigniaArt {- const shield = (inset: number): Pt[] => {- const out: Pt[] = [];- const r = 38 - inset;- for (let i = 0; i <= 18; i += 1) {- const a = Math.PI + (i / 18) * Math.PI;- out.push([50 + Math.cos(a) * r, 44 + Math.sin(a) * r]);- }- out.push([88 - inset, 66 - inset * 0.3], [50, 98 - inset * 1.5], [12 + inset, 66 - inset * 0.3]);- return out;- };- return {- w: 100, h: 100, mount: "sleeve",- parts: [{ pts: shield(0), finish: "gold" }, { pts: shield(5), finish: "cloth" }, ...eagle(50, 50, 30, "gold")],- };-}--// ----------------------------------------------------------------------------// Officers--function bar(x0: number, x1: number, finish: Finish): InsigniaPart[] {- return [- { pts: roundRect(x0, 10, x1, 90, 3), finish },- // A raised rim inside the bar, the way a pin is struck.- { pts: roundRect(x0 + 3.5, 14, x1 - 3.5, 86, 2), finish, detail: true },- ];-}--function stars(count: number): InsigniaArt {- const r = [0, 21, 17, 13.5, 11][count];- const gap = (100 - 12) / count;- const parts: InsigniaPart[] = [];- for (let i = 0; i < count; i += 1) parts.push({ pts: star(50, 6 + gap * (i + 0.5), r), finish: "silver" });- return { w: 100, h: 100, parts, mount: "shoulder" };-}--function fiveStars(): InsigniaArt {- const parts: InsigniaPart[] = [];- for (let i = 0; i < 5; i += 1) {- const a = -Math.PI / 2 + (i * 2 * Math.PI) / 5;- // Each star points out from the ring; their inner points meet in the middle.- parts.push({ pts: star(50 + Math.cos(a) * 27, 50 + Math.sin(a) * 27, 17, a + Math.PI / 2), finish: "silver" });- }- return { w: 100, h: 100, parts, mount: "shoulder" };-}--// -----------------------------------------------------------------------------const BUILD: Record<RankId, () => InsigniaArt> = {- private: () => ({ w: 100, h: 100, parts: [], mount: "none" }),- private_second_class: () => chevronSet({ chevrons: 1, rockers: 0 }),- private_first_class: () => chevronSet({ chevrons: 1, rockers: 1 }),- specialist,- corporal: () => chevronSet({ chevrons: 2, rockers: 0 }),- sergeant: () => chevronSet({ chevrons: 3, rockers: 0 }),- staff_sergeant: () => chevronSet({ chevrons: 3, rockers: 1 }),- sergeant_first_class: () => chevronSet({ chevrons: 3, rockers: 2 }),- master_sergeant: () => chevronSet({ chevrons: 3, rockers: 3 }),- first_sergeant: () => chevronSet({ chevrons: 3, rockers: 3, device: "diamond" }),- sergeant_major: () => chevronSet({ chevrons: 3, rockers: 3, device: "star" }),- command_sergeant_major: () => chevronSet({ chevrons: 3, rockers: 3, device: "wreath" }),- sergeant_major_of_the_army: () => chevronSet({ chevrons: 3, rockers: 3, device: "sma" }),- second_lieutenant: () => ({ w: 100, h: 100, parts: bar(38, 62, "gold"), mount: "shoulder" }),- first_lieutenant: () => ({ w: 100, h: 100, parts: bar(38, 62, "silver"), mount: "shoulder" }),- captain: () => ({- w: 100, h: 100, mount: "shoulder",- parts: [...bar(22, 43, "silver"), ...bar(57, 78, "silver"),- { pts: roundRect(42, 20, 58, 25, 1), finish: "silver" }, { pts: roundRect(42, 75, 58, 80, 1), finish: "silver" }],- }),- major: () => ({ w: 100, h: 100, parts: oakLeaf(50, "gold"), mount: "shoulder" }),- lieutenant_colonel: () => ({ w: 100, h: 100, parts: oakLeaf(50, "silver"), mount: "shoulder" }),- colonel: () => ({ w: 100, h: 100, parts: eagle(50, 52, 46, "silver"), mount: "shoulder" }),- brigadier_general: () => stars(1),- major_general: () => stars(2),- lieutenant_general: () => stars(3),- general: () => stars(4),- general_of_the_army: fiveStars,-};--const cache = new Map<RankId, InsigniaArt>();--/** The insignia of a rank, built once. */-export function rankArt(rank: RankId): InsigniaArt {- let art = cache.get(rank);- if (!art) {- art = BUILD[rank]();- cache.set(rank, art);- }- return art;-}--/** The officer's cap badge: the gold eagle. */-export const CAP_BADGE_ART: InsigniaArt = { w: 100, h: 100, parts: eagle(50, 52, 46, "gold"), mount: "none" };--/** A unit crest for enlisted headwear: a gold disc ringed in gold with a star. */-export const CREST_ART: InsigniaArt = {- w: 100, h: 100, mount: "none",- parts: [- { pts: ellipse(50, 50, 46, 46, 36), finish: "gold" },- { pts: ellipse(50, 50, 36, 36, 36), finish: "cloth" },- { pts: star(50, 52, 28), finish: "gold" },- ],-};--/** Polygon points as an SVG `points` attribute. */-export function svgPoints(pts: readonly Pt[]): string {- return pts.map(([x, y]) => `${x.toFixed(2)},${y.toFixed(2)}`).join(" ");-}--/** The colours each finish is drawn in: a light, a mid and a dark stop, plus the edge line. */-export const FINISH_TONES: Record<Finish, { light: string; mid: string; dark: string; edge: string }> = {- gold: { light: "#fbe7a1", mid: "#d8a93f", dark: "#8f6518", edge: "#5c3f0a" },- silver: { light: "#ffffff", mid: "#c9ced6", dark: "#7c8592", edge: "#3d434d" },- cloth: { light: "#2a3558", mid: "#1b2340", dark: "#111731", edge: "#0a0e1f" },-};diff --git a/dodaios/ui/web/frontend/src/components/society/progression/levelCatalog.ts b/dodaios/ui/web/frontend/src/components/society/progression/levelCatalog.tsindex 44fa865d27..879e30eebf 100644--- a/dodaios/ui/web/frontend/src/components/society/progression/levelCatalog.ts+++ b/dodaios/ui/web/frontend/src/components/society/progression/levelCatalog.ts@@ -1,96 +1,66 @@/**- * The Verse's copy of the level system's ids (dodaios/progression/rules.py):- * subject kinds, cosmetic slots, reward ids, title ids and XP sources. The- * server sends levels and amounts; this file only knows what each id LOOKS- * like. tests/unit/progression/test_frontend_parity.py pins every list here- * to the Python rulebook (AP-4): add an id in Python first, then here.+ * The ship's copy of the level system's ids (dodaios/progression/rules.py):+ * subject kinds, reward slots, reward ids, rank ids and XP sources. The+ * server sends levels and amounts; this file only knows the ids, so a+ * surface can name and draw them. tests/unit/progression/test_frontend_parity.py+ * pins every list here to the Python rulebook (AP-4): add an id in Python+ * first, then here. The rank ladder itself (levels, tiers, pips) lives in+ * `starship/levels/ranks.ts`.*/export const SUBJECT_KINDS = ["person", "agent", "pet"] as const;export type SubjectKind = (typeof SUBJECT_KINDS)[number];-export const SLOTS = ["uniform", "headwear", "decoration"] as const;+/** What a level opens: a suit for the captain's figure, a destination for the helm, a decoration. */+export const SLOTS = ["suit", "destination", "decoration"] as const;export type Slot = (typeof SLOTS)[number];export const REWARD_IDS = [- "uniform_service_shirt", "uniform_field_jacket", "uniform_service_greens", "uniform_dress_blues", "uniform_mess_dress",- "headwear_patrol_cap", "headwear_garrison_cap", "headwear_beret", "headwear_service_cap",- "decoration_ribbon_bar", "decoration_ribbon_rack", "decoration_aiguillette", "decoration_medals",+ "suit_field_armor", "suit_command_coat", "suit_dress_whites", "suit_admiral_coat",+ "destination_gas_giant", "destination_crimson_nebula", "destination_ice_moon", "destination_twin_suns",+ "destination_event_horizon", "destination_aurora_world", "destination_galactic_core",+ "decoration_service_ribbon", "decoration_commendation", "decoration_star_medal", "decoration_legion_of_merit",] as const;export type RewardId = (typeof REWARD_IDS)[number];+export type SuitId = Extract<RewardId, `suit_${string}`>;-/** The rank ladder, lowest first: every subject kind wears it as its title. */-export const TITLE_IDS = [- "private", "private_second_class", "private_first_class", "specialist", "corporal", "sergeant", "staff_sergeant",- "sergeant_first_class", "master_sergeant", "first_sergeant", "sergeant_major", "command_sergeant_major",- "sergeant_major_of_the_army", "second_lieutenant", "first_lieutenant", "captain", "major", "lieutenant_colonel",- "colonel", "brigadier_general", "major_general", "lieutenant_general", "general", "general_of_the_army",+/** The rank ladder, lowest first (the server's `RANKS`, the ship's `ranks.ts`). */+export const RANK_IDS = [+ "cadet", "crewman", "specialist", "petty_officer", "chief_petty_officer", "warrant_officer", "ensign",+ "lieutenant_junior_grade", "lieutenant", "lieutenant_commander", "commander", "captain", "commodore",+ "rear_admiral", "vice_admiral", "admiral",] as const;-export type RankId = (typeof TITLE_IDS)[number];--/** Where a rank sits: enlisted, non-commissioned officer, officer or general officer. */-export type RankTier = "enlisted" | "nco" | "officer" | "general";--/** Each rank's pay grade and tier. The level it starts at comes from the server (`titles`). */-export const RANK_INFO: Record<RankId, { grade: string; tier: RankTier }> = {- private: { grade: "E-1", tier: "enlisted" },- private_second_class: { grade: "E-2", tier: "enlisted" },- private_first_class: { grade: "E-3", tier: "enlisted" },- specialist: { grade: "E-4", tier: "enlisted" },- corporal: { grade: "E-4", tier: "nco" },- sergeant: { grade: "E-5", tier: "nco" },- staff_sergeant: { grade: "E-6", tier: "nco" },- sergeant_first_class: { grade: "E-7", tier: "nco" },- master_sergeant: { grade: "E-8", tier: "nco" },- first_sergeant: { grade: "E-8", tier: "nco" },- sergeant_major: { grade: "E-9", tier: "nco" },- command_sergeant_major: { grade: "E-9", tier: "nco" },- sergeant_major_of_the_army: { grade: "E-9", tier: "nco" },- second_lieutenant: { grade: "O-1", tier: "officer" },- first_lieutenant: { grade: "O-2", tier: "officer" },- captain: { grade: "O-3", tier: "officer" },- major: { grade: "O-4", tier: "officer" },- lieutenant_colonel: { grade: "O-5", tier: "officer" },- colonel: { grade: "O-6", tier: "officer" },- brigadier_general: { grade: "O-7", tier: "general" },- major_general: { grade: "O-8", tier: "general" },- lieutenant_general: { grade: "O-9", tier: "general" },- general: { grade: "O-10", tier: "general" },- general_of_the_army: { grade: "O-11", tier: "general" },-};--export function isRankId(value: unknown): value is RankId {- return typeof value === "string" && value in RANK_INFO;-}--/** A title from the server as a rank; an id this build does not know (an older backend's) reads as private. */-export function rankOf(title: string | undefined): RankId {- return isRankId(title) ? title : "private";-}--/** The rank held at `level`, from the server's bands (lowest first); private before the snapshot arrives. */-export function rankAt(bands: readonly { level: number; title: string }[] | undefined, level: number): RankId {- let rank: RankId = "private";- for (const band of bands ?? []) if (level >= band.level && isRankId(band.title)) rank = band.title;- return rank;-}+export type RankId = (typeof RANK_IDS)[number];export const XP_SOURCES = ["chat_turn", "voice_turn", "quest_posted", "quest_completed", "agent_hired", "mission_completed",- "daily_visit", "floor_discovered", "dog_petted", "dog_treat", "arcade_round", "arcade_record", "team_meeting",+ "daily_visit", "deck_discovered", "holodeck_round", "holodeck_record", "team_briefing", "warp_jump","task_done", "task_blocked", "quest_done", "answered_teammate","jarvis_answered", "delegated", "walk_together",] as const;export type XpSource = (typeof XP_SOURCES)[number];-/** The world actions the Verse itself reports (`trigger: "world"` in the rulebook). */-export type WorldAction = "daily_visit" | "floor_discovered" | "dog_petted" | "dog_treat" | "arcade_round"- | "arcade_record" | "team_meeting" | "walk_together";+/** The world actions the ship itself reports (`trigger: "world"` in the rulebook). */+export type WorldAction = "daily_visit" | "deck_discovered" | "holodeck_round" | "holodeck_record"+ | "team_briefing" | "warp_jump" | "walk_together";export function slotOf(reward: RewardId): Slot {return reward.slice(0, reward.indexOf("_")) as Slot;}+/** The reward's name inside its slot; for a destination, the helm's destination id. */+export function rewardKey(reward: RewardId): string {+ return reward.slice(reward.indexOf("_") + 1);+}+export function isRewardId(value: unknown): value is RewardId {return typeof value === "string" && (REWARD_IDS as readonly string[]).includes(value);}++export function isRankId(value: unknown): value is RankId {+ return typeof value === "string" && (RANK_IDS as readonly string[]).includes(value);+}++export function isXpSource(value: unknown): value is XpSource {+ return typeof value === "string" && (XP_SOURCES as readonly string[]).includes(value);+}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/progression.css b/dodaios/ui/web/frontend/src/components/society/progression/progression.cssdeleted file mode 100644index 7c8ed4a9e4..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/progression.css+++ /dev/null@@ -1,182 +0,0 @@-/*- * The Verse's level system. The level card, toasts and progress panel are- * app chrome over the canvas: theme tokens only, so light and dark mode both- * read. The rank chip, the ring's medallion, the "+XP" numbers, the world- * plate and the promotion card belong to the game itself and keep one- * midnight-and-gold look in both modes, like the name plates in the diorama.- */--/* ---------- level card (HUD, top left) ---------- */-.level-hud { display:flex; align-items:center; gap:10px; padding:8px 12px 8px 8px; min-width:236px; max-width:300px; text-align:left; font:inherit; color:hsl(var(--popover-foreground)); cursor:pointer; }-.level-hud:hover { background:hsl(var(--secondary) / .92); }-.level-hud:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:2px; }-.level-hud[data-compact] { min-width:0; padding:5px 10px 5px 5px; }-.level-hud-body { display:flex; flex-direction:column; gap:4px; min-width:0; flex:1; }-.level-hud-name { display:flex; align-items:baseline; gap:6px; min-width:0; }-.level-hud-name strong { font-size:13px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }-.level-hud-name em { font-style:normal; font-size:11px; font-weight:600; color:hsl(var(--warning)); white-space:nowrap; }-.level-hud-xp { font-size:10.5px; color:hsl(var(--muted-foreground)); font-variant-numeric:tabular-nums; }-.level-hud-pet { display:flex; flex-direction:column; gap:3px; margin-top:2px; padding-top:5px; border-top:1px solid hsl(var(--border)); font-size:11px; color:hsl(var(--muted-foreground)); }--/* ---------- ring and bar ---------- */-.level-ring { position:relative; display:inline-flex; flex:none; align-items:center; justify-content:center; }-.level-ring-gauge { position:absolute; inset:0; }-.level-ring-track { fill:none; stroke:hsl(var(--border)); stroke-width:3; }-.level-ring-fill { fill:none; stroke-width:3; stroke-linecap:round; stroke:#d9ab47; transition:stroke-dasharray .7s cubic-bezier(.2,.8,.2,1); }-.level-ring[data-kind="pet"] .level-ring-fill { stroke:#2dd4bf; }-.level-ring[data-kind="agent"] .level-ring-fill { stroke:#4ade80; }-.level-ring-medal { fill:#141b33; stroke:#c9a24a; stroke-width:1; }-.level-ring[data-tier="general"] .level-ring-medal { fill:#0d0e12; stroke:#e0b955; stroke-width:1.6; }-.level-ring-insignia { position:relative; filter:drop-shadow(0 1px 1px rgb(0 0 0 / .45)); }-.level-ring b { position:absolute; left:50%; bottom:-5px; transform:translateX(-50%); min-width:18px; padding:0 5px; border-radius:6px;- background:#141b33; box-shadow:inset 0 0 0 1px #c9a24a; color:#f6e7bd; font-size:10px; line-height:14px; font-weight:800; text-align:center;- font-variant-numeric:tabular-nums; }-.level-bar { position:relative; display:block; height:6px; border-radius:999px; overflow:hidden; background:hsl(var(--muted)); }-.level-bar i { position:absolute; left:0; top:0; bottom:0; border-radius:inherit; }-.level-bar-gain { background:#fff1b8; box-shadow:0 0 8px #ffd25e; transition:width .15s ease-out; }-.level-bar-fill { background:linear-gradient(90deg, #f0a92b, #ffd25e); transition:width .65s cubic-bezier(.2,.8,.2,1); }-.level-bar[data-kind="pet"] .level-bar-fill { background:linear-gradient(90deg, #14b8a6, #5eead4); }-.level-bar[data-kind="pet"] .level-bar-gain { background:#ccfbf1; box-shadow:0 0 8px #5eead4; }-.level-bar[data-kind="agent"] .level-bar-fill { background:linear-gradient(90deg, #22c55e, #86efac); }-.level-bar[data-kind="agent"] .level-bar-gain { background:#dcfce7; box-shadow:0 0 8px #86efac; }--/* ---------- rank chip on name plates (in-world, one look) ---------- */-.level-chip { display:inline-flex; flex:none; align-items:center; gap:3px; height:18px; padding:0 5px 0 3px; border-radius:5px; background:#141b33;- box-shadow:inset 0 0 0 1px #b8913c; color:#f6e7bd; font-size:10px; font-variant-numeric:tabular-nums; }-.level-chip b { font-weight:800; }-.level-chip[data-tier="officer"] { box-shadow:inset 0 0 0 1px #d9dde3; }-.level-chip[data-tier="general"] { background:#0d0e12; box-shadow:inset 0 0 0 1.5px #e0b955; }-.level-chip-insignia { display:block; }-.office-plate .level-chip { margin-left:1px; }--/* ---------- agent toasts (bottom left) ---------- */-.level-toasts { position:absolute; z-index:38; left:14px; bottom:14px; display:flex; flex-direction:column; gap:6px; max-width:min(320px, calc(100% - 28px)); }-.level-toast { display:flex; align-items:center; gap:9px; padding:8px 12px 8px 9px; border:1px solid hsl(var(--border)); border-radius:12px; background:hsl(var(--popover) / .95); color:hsl(var(--popover-foreground)); font:inherit; text-align:left; cursor:pointer; box-shadow:0 6px 20px rgb(0 0 0 / .25); animation:level-toast-in .45s cubic-bezier(.2,1.4,.4,1) both; }-.level-toast span { display:flex; flex-direction:column; gap:1px; min-width:0; }-.level-toast strong { font-size:12px; }-.level-toast em { font-style:normal; font-size:11px; color:hsl(var(--muted-foreground)); }-.level-toast .level-toast-looks { margin-top:5px; gap:4px; }-.level-toast .level-toast-look { flex-direction:row; align-items:center; gap:7px; font-size:11.5px; font-weight:600; color:hsl(var(--primary)); }-@keyframes level-toast-in { from { opacity:0; transform:translateX(-24px) scale(.96); } to { opacity:1; transform:none; } }--/* ---------- world plate and "+XP" (in-world, one look) ---------- */-.promo-tag { display:inline-flex; align-items:center; gap:9px; padding:6px 14px 6px 8px; border-radius:8px; background:rgb(16 22 44 / .94);- box-shadow:inset 0 0 0 1px #c9a24a, 0 8px 22px rgb(0 0 0 / .35); color:#f6e7bd; white-space:nowrap; pointer-events:none;- animation-name:promo-tag; animation-timing-function:cubic-bezier(.2,.7,.2,1); animation-fill-mode:both; }-.promo-tag > span { display:flex; flex-direction:column; gap:1px; }-.promo-tag small { font-size:9.5px; font-weight:700; letter-spacing:.18em; text-transform:uppercase; color:#d9ab47; }-.promo-tag b { font-size:14px; font-weight:800; letter-spacing:.01em; }-@keyframes promo-tag { 0% { opacity:0; transform:translateY(14px); } 12% { opacity:1; transform:translateY(0); } 82% { opacity:1; transform:translateY(-8px); } 100% { opacity:0; transform:translateY(-14px); } }-.level-xp-pop { display:inline-block; font-size:13px; font-weight:800; color:#ffe58a; text-shadow:0 1px 0 #6b4a00, 0 0 8px rgb(255 210 94 / .8); white-space:nowrap; pointer-events:none; animation:level-xp 1.6s ease-out both; }-.level-xp-pop[data-kind="pet"] { color:#99f6e4; text-shadow:0 1px 0 #0f4f47, 0 0 8px rgb(94 234 212 / .8); }-.level-xp-pop[data-kind="agent"] { color:#bbf7d0; text-shadow:0 1px 0 #14532d, 0 0 8px rgb(134 239 172 / .8); }-@keyframes level-xp { 0% { opacity:0; transform:translateY(8px) scale(.7); } 15% { opacity:1; transform:translateY(0) scale(1.1); } 30% { transform:scale(1); } 100% { opacity:0; transform:translateY(-34px); } }--/* ---------- promotion card (game overlay, one look) ---------- */-.level-banner-layer { position:absolute; inset:0; z-index:55; display:flex; align-items:center; justify-content:center; pointer-events:none; background:radial-gradient(60% 55% at 50% 50%, rgb(6 9 20 / .45), transparent 75%); }-.promo { position:relative; pointer-events:auto; display:flex; flex-direction:column; align-items:center; gap:2px; min-width:320px; max-width:min(440px, calc(100% - 32px));- padding:26px 40px 24px; border:0; border-radius:14px; font:inherit; color:#f3ead2; cursor:pointer;- background:linear-gradient(180deg, #1b2445 0%, #111833 60%, #0c1229 100%);- box-shadow:0 0 0 1px #c9a24a, 0 30px 70px rgb(0 0 0 / .55); animation:promo-in .45s cubic-bezier(.2,.8,.2,1) both; }-.promo[data-tier="general"] { background:linear-gradient(180deg, #17181f 0%, #0d0e13 100%); box-shadow:0 0 0 1.5px #e0b955, 0 30px 70px rgb(0 0 0 / .6); }-.promo:focus-visible { outline:2px solid #f3ead2; outline-offset:4px; }-.promo-rule { position:absolute; inset:6px; border:1px solid rgb(201 162 74 / .55); border-radius:9px; pointer-events:none; }-.promo > :not(.promo-rule) { position:relative; }-.promo-away { font-size:11px; font-weight:600; color:#c9b88f; margin-bottom:4px; }-.promo-kicker { font-size:12px; font-weight:800; letter-spacing:.42em; padding-left:.42em; text-transform:uppercase; color:#d9ab47; animation:promo-kicker .6s .1s cubic-bezier(.2,.8,.2,1) both; }-.promo-who { font-size:13px; font-weight:600; color:#c9c2ad; animation:promo-rise .4s .2s ease-out both; }-.promo-stage { position:relative; display:flex; align-items:center; justify-content:center; height:138px; margin:10px 0 6px; }-.promo-new { display:flex; filter:drop-shadow(0 6px 14px rgb(0 0 0 / .5)); animation:promo-glint .9s 1.45s ease-out both; }-.promo:not([data-promoted]) .promo-new { animation:promo-rise .5s .25s ease-out both, promo-glint .9s .9s ease-out both; }-.promo-old { position:absolute; display:flex; animation:promo-old 1.1s .35s cubic-bezier(.4,0,.2,1) both; }-.promo-new .rank-part { animation:promo-part .32s calc(.75s + var(--i) * 70ms) cubic-bezier(.2,.9,.3,1.15) both; transform-box:fill-box; transform-origin:center; }-.promo-rank { font-size:24px; font-weight:800; letter-spacing:.01em; color:#fff6dc; text-align:center; animation:promo-rise .45s 1.15s ease-out both; }-.promo:not([data-promoted]) .promo-rank { animation-delay:.45s; }-.promo-grade { display:inline-flex; align-items:center; gap:8px; font-size:12px; font-weight:700; letter-spacing:.08em; color:#c9b88f; animation:promo-rise .45s 1.25s ease-out both; }-.promo:not([data-promoted]) .promo-grade { animation-delay:.55s; }-.promo-dot { width:3px; height:3px; border-radius:50%; background:#c9a24a; }-.promo-level { display:inline-flex; align-items:center; gap:4px; }-.promo-number { display:inline-grid; height:16px; overflow:hidden; font-variant-numeric:tabular-nums; color:#f3ead2; }-.promo-number > span { grid-area:1 / 1; text-align:center; }-.promo-number-old { animation:promo-roll-out .4s 1.5s ease-in both; }-.promo-number-new { animation:promo-roll-in .45s 1.6s cubic-bezier(.2,.9,.3,1.1) both; }-.promo:not([data-promoted]) .promo-number-old { animation-delay:.7s; }-.promo:not([data-promoted]) .promo-number-new { animation-delay:.8s; }-.promo-next { margin-top:8px; font-size:12px; color:#a9a28d; animation:promo-rise .4s 1s ease-out both; }-.promo-rewards { display:flex; flex-direction:column; align-items:stretch; gap:6px; width:100%; margin-top:16px; padding-top:14px; border-top:1px solid rgb(201 162 74 / .3); }-.promo-unlocked { font-size:10px; font-weight:700; letter-spacing:.24em; text-transform:uppercase; color:#d9ab47; text-align:center; animation:promo-rise .4s 1.6s ease-out both; }-.promo-reward { display:flex; align-items:center; gap:12px; padding:5px 12px 5px 5px; border-radius:10px; background:rgb(255 255 255 / .05); box-shadow:inset 0 0 0 1px rgb(201 162 74 / .25); font-size:13px; font-weight:700; text-align:left; animation:promo-rise .45s ease-out both; }-.promo-hint { margin-top:2px; font-size:11px; color:#a9a28d; text-align:center; animation:promo-rise .4s 2.1s ease-out both; }-@keyframes promo-in { 0% { opacity:0; transform:translateY(12px) scale(.97); } 100% { opacity:1; transform:none; } }-@keyframes promo-kicker { 0% { opacity:0; letter-spacing:.8em; } 100% { opacity:1; letter-spacing:.42em; } }-@keyframes promo-rise { 0% { opacity:0; transform:translateY(10px); } 100% { opacity:1; transform:none; } }-@keyframes promo-old { 0% { opacity:0; transform:scale(.9); } 20% { opacity:1; transform:none; } 55% { opacity:1; transform:none; } 100% { opacity:0; transform:translateX(-120px) scale(.7); } }-@keyframes promo-part { 0% { opacity:0; transform:translateY(-10px) scale(1.12); } 100% { opacity:1; transform:none; } }-@keyframes promo-glint { 0% { filter:drop-shadow(0 6px 14px rgb(0 0 0 / .5)) brightness(1); } 35% { filter:drop-shadow(0 6px 14px rgb(0 0 0 / .5)) drop-shadow(0 0 14px rgb(255 214 120 / .55)) brightness(1.35); } 100% { filter:drop-shadow(0 6px 14px rgb(0 0 0 / .5)) brightness(1); } }-@keyframes promo-roll-out { to { opacity:0; transform:translateY(-16px); } }-@keyframes promo-roll-in { 0% { opacity:0; transform:translateY(16px); } 100% { opacity:1; transform:none; } }--/* ---------- reward icon ---------- */-.level-reward-icon { display:inline-flex; flex:none; align-items:center; justify-content:center; }-.level-reward-icon svg { display:block; }--/* ---------- progress panel ---------- */-.level-panel-layer { position:absolute; inset:0; z-index:50; display:flex; align-items:center; justify-content:center; padding:16px; background:rgb(0 0 0 / .25); }-.level-panel { display:flex; flex-direction:column; width:min(680px, 100%); max-height:min(720px, 100%); overflow:hidden; }-.level-panel:focus { outline:none; }-.level-panel-head { display:flex; align-items:center; gap:12px; padding:12px 14px 8px; border-bottom:1px solid hsl(var(--border)); }-.level-panel-head h2 { margin:0; font-size:15px; font-weight:800; }-.level-tabs { display:flex; gap:4px; flex:1; flex-wrap:wrap; }-.level-tab { border:1px solid transparent; border-radius:8px; padding:4px 10px; background:none; color:hsl(var(--muted-foreground)); font:inherit; font-size:12px; font-weight:600; cursor:pointer; }-.level-tab:hover { background:hsl(var(--secondary)); color:hsl(var(--foreground)); }-.level-tab[aria-selected="true"] { background:hsl(var(--secondary)); color:hsl(var(--foreground)); border-color:hsl(var(--border)); }-.level-tab:focus-visible { outline:2px solid hsl(var(--ring)); outline-offset:1px; }-.level-panel-body { display:flex; flex-direction:column; gap:14px; padding:12px 14px 14px; overflow:auto; font-size:12px; }-.level-panel-foot { display:flex; align-items:center; justify-content:space-between; gap:10px; flex-wrap:wrap; padding:8px 14px 10px; border-top:1px solid hsl(var(--border)); }-.level-sound { display:inline-flex; align-items:center; gap:6px; font-size:12px; cursor:pointer; }-.level-sound input { accent-color:hsl(var(--primary)); }-.level-subject { display:flex; align-items:center; gap:12px; }-.level-subject > div { display:flex; flex-direction:column; gap:4px; flex:1; min-width:0; }-.level-subject strong { font-size:15px; }-.level-subject em { font-style:normal; font-size:12px; font-weight:700; color:hsl(var(--warning)); }-.level-subject-xp { font-size:11px; color:hsl(var(--muted-foreground)); font-variant-numeric:tabular-nums; }-.level-section h3 { margin:0 0 6px; font-size:11px; font-weight:700; letter-spacing:.04em; text-transform:uppercase; color:hsl(var(--muted-foreground)); }-.level-slots { display:flex; flex-direction:column; gap:8px; }-.level-slot { display:grid; grid-template-columns:64px 1fr; gap:8px; align-items:start; }-.level-slot-name { padding-top:4px; font-weight:600; }-.level-wear-chip { display:inline-flex; align-items:center; gap:5px; padding-left:4px; }-.level-wear-chip:disabled { opacity:.55; cursor:not-allowed; }-.level-wear-chip small { font-size:10px; color:hsl(var(--muted-foreground)); }-.level-track { display:flex; gap:8px; margin:0; padding:2px 2px 8px; list-style:none; overflow-x:auto; scroll-snap-type:x proximity; }-.level-track li { flex:none; display:flex; flex-direction:column; gap:6px; min-width:118px; max-width:150px; padding:8px; border:1px solid hsl(var(--border)); border-radius:12px; background:hsl(var(--background)); scroll-snap-align:center; }-.level-track li[data-done] { border-color:hsl(var(--warning) / .55); background:hsl(var(--warning) / .08); }-.level-track li[data-next] { border-color:hsl(var(--primary)); box-shadow:0 0 0 2px hsl(var(--primary) / .25); }-.level-track-at { font-size:11px; font-weight:800; }-.level-track-items { display:flex; flex-direction:column; gap:5px; }-.level-track-item { display:flex; align-items:center; gap:6px; font-size:11px; line-height:1.25; }-.level-track-title { align-self:flex-start; padding:2px 7px; border-radius:999px; background:hsl(var(--secondary)); font-size:10.5px; font-weight:700; }-.level-rules { display:grid; grid-template-columns:repeat(auto-fill, minmax(250px, 1fr)); gap:4px 12px; margin:0; padding:0; list-style:none; }-.level-rules li { display:flex; align-items:flex-start; gap:8px; padding:5px 6px; border-radius:8px; }-.level-rules li:hover { background:hsl(var(--secondary) / .6); }-.level-rule-xp { flex:none; min-width:34px; padding:1px 5px; border-radius:6px; background:hsl(var(--warning) / .16); color:hsl(var(--foreground)); font-size:11px; font-weight:800; text-align:center; font-variant-numeric:tabular-nums; }-.level-rule-text { display:flex; flex-direction:column; gap:1px; }-.level-rule-text em { font-style:normal; font-size:10.5px; color:hsl(var(--muted-foreground)); }-.level-agents { display:flex; flex-direction:column; gap:4px; margin:0; padding:0; list-style:none; }-.level-agents li { display:flex; align-items:center; gap:8px; padding:5px 6px; border-radius:8px; }-.level-agents li:hover { background:hsl(var(--secondary) / .6); }-.level-agent-rank { width:18px; text-align:right; font-size:11px; font-weight:700; color:hsl(var(--muted-foreground)); }-.level-agent-body { display:flex; flex-direction:column; gap:4px; flex:1; min-width:0; }-.level-agent-body em { font-style:normal; font-size:11px; color:hsl(var(--muted-foreground)); }--@media (max-width:600px) {- .level-hud { min-width:0; }- .level-slot { grid-template-columns:1fr; }- .promo { min-width:0; padding:22px 20px 20px; }- .promo-rank { font-size:20px; }-}--@media (prefers-reduced-motion: reduce) {- .promo, .promo *, .level-toast, .promo-tag, .level-xp-pop { animation-duration:.01ms !important; animation-delay:0s !important; }- .promo-old, .promo-number-old { display:none; }- .level-bar i, .level-ring-fill { transition:none; }-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/progression.test.ts b/dodaios/ui/web/frontend/src/components/society/progression/progression.test.tsindex 0ecafd89fe..47a9820222 100644--- a/dodaios/ui/web/frontend/src/components/society/progression/progression.test.ts+++ b/dodaios/ui/web/frontend/src/components/society/progression/progression.test.ts@@ -1,253 +1,127 @@+/**+ * The ship's level data layer: the API parses forgivingly (old ledger+ * sources, unknown rewards, the new rank list), the store applies awards+ * once and celebrates the right way per kind, and the cosmetics pick the+ * captain's suit.+ */import { beforeEach, describe, expect, it } from "vitest";-import { equippedFor, levelFraction, progressFor, unlockedFor } from "./cosmetics";+import { levelFraction, progressFor, rewardRoad, rewardsBetween, suitFor, unlockedFor } from "./cosmetics";+import { REWARD_IDS, slotOf } from "./levelCatalog";import { parseAwardEvent, parseSnapshot, type ProgressionSnapshot, type RewardRow } from "./progressionApi";import { awayCelebrations, looksBetween, useProgression } from "./progressionStore";-import { RANK_INFO, rankAt, REWARD_IDS, slotOf, TITLE_IDS } from "./levelCatalog";-import { rankArt } from "./insignia/rankArt";-import { rackRows, ribbonsFor } from "./regalia/decorations3d";-import { dressedLook, regaliaFor, uniformStyle } from "./regalia/dress";-import type { ToyLook } from "../office/toyFigureModel";+const CURVE = [0, 40, 105, 195, 310, 450, 615, 805, 1020, 1260];+const row = (rewardId: RewardRow["rewardId"], person: number | null, agent: number | null = null): RewardRow =>+ ({ rewardId, slot: slotOf(rewardId), levels: { person, agent, pet: null } });const REWARDS: RewardRow[] = [- { rewardId: "decoration_ribbon_bar", slot: "decoration", levels: { person: 3, agent: 3, pet: null } },- { rewardId: "decoration_ribbon_rack", slot: "decoration", levels: { person: 10, agent: 10, pet: null } },- { rewardId: "uniform_service_shirt", slot: "uniform", levels: { person: 2, agent: null, pet: null } },- { rewardId: "uniform_field_jacket", slot: "uniform", levels: { person: 5, agent: null, pet: null } },- { rewardId: "headwear_patrol_cap", slot: "headwear", levels: { person: 7, agent: null, pet: null } },+ row("suit_field_armor", 6), row("suit_command_coat", 16), row("destination_gas_giant", 5),+ row("decoration_service_ribbon", 8, 3),];-const BANDS = [{ level: 1, title: "private" }, { level: 2, title: "private_second_class" }, { level: 4, title: "private_first_class" }];--/** Total XP at which each level starts, the server's `level_xp` for the first few levels. */-const CURVE = [0, 40, 105, 195, 310, 450];--function snapshot(overrides: Partial<ProgressionSnapshot> = {}): ProgressionSnapshot {+function snapshot(over: Partial<ProgressionSnapshot> = {}): ProgressionSnapshot {return {- subjects: [], petId: "ember", recent: [], latestSeq: 0, maxLevel: 50, levelXp: CURVE, rules: [], rewards: REWARDS,- titles: { person: BANDS, agent: BANDS, pet: BANDS }, looks: { cap: 1, suit: 4, crown: 10 },- ...overrides,+ subjects: [], petId: "gigi", recent: [], latestSeq: 0, maxLevel: 50, levelXp: CURVE, rules: [], rewards: REWARDS,+ ranks: [], titles: { person: [], agent: [], pet: [] }, looks: {}, ...over,};}-describe("cosmetics", () => {- it("unlocks by the subject kind's own level", () => {- expect(unlockedFor(REWARDS, "person", 2).map((r) => r.rewardId)).toEqual(["uniform_service_shirt"]);- expect(unlockedFor(REWARDS, "pet", 50)).toEqual([]);- expect(unlockedFor(REWARDS, "agent", 4).map((r) => r.rewardId)).toEqual(["decoration_ribbon_bar"]);- });-- it("wears the latest unlock per slot unless the person chose", () => {- expect(equippedFor(REWARDS, "person", 7))- .toEqual({ decoration: "decoration_ribbon_bar", uniform: "uniform_field_jacket", headwear: "headwear_patrol_cap" });- expect(equippedFor(REWARDS, "person", 7, { uniform: "uniform_service_shirt", headwear: "none" }))- .toEqual({ decoration: "decoration_ribbon_bar", uniform: "uniform_service_shirt" });- });-- it("ignores a chosen piece that is not unlocked (any more)", () => {- expect(equippedFor(REWARDS, "person", 4, { decoration: "decoration_ribbon_rack" }))- .toEqual({ decoration: "decoration_ribbon_bar", uniform: "uniform_service_shirt" });- });-- it("measures progress inside a level from the server's curve", () => {- expect(progressFor(CURVE, 120, 3)).toEqual({ into: 15, size: 90 });- expect(progressFor([0, 40], 999, 2)).toEqual({ into: 959, size: 0 });- expect(levelFraction({ xpIntoLevel: 15, xpForNext: 60 })).toBe(0.25);- expect(levelFraction({ xpIntoLevel: 0, xpForNext: 0 })).toBe(1);- expect(levelFraction(undefined)).toBe(0);- });-});-describe("progressionApi", () => {- it("parses the snapshot and drops unknown rewards", () => {+ it("parses the snapshot with the ship's ranks, keeps old sources and drops unknown rewards", () => {const parsed = parseSnapshot({- subjects: [{ subject_id: "person", kind: "person", xp: 50, level: 2, xp_into_level: 10, xp_for_next: 65, title: "newcomer" }],- pet_id: "miso", recent: [], latest_seq: 7, max_level: 50, level_xp: [0, 40],- rules: [{ source: "chat_turn", kind: "person", xp: 5, trigger: "server", cooldown_s: 0, daily_cap: 100 }],- rewards: [{ reward_id: "headwear_beret", slot: "headwear", levels: { person: 24, agent: null, pet: null } }, { reward_id: "trail_rainbow", slot: "trail", levels: {} }],- titles: { person: [{ level: 1, title: "newcomer" }] },+ subjects: [{ subject_id: "person", kind: "person", xp: 120, level: 3, xp_into_level: 15, xp_for_next: 90, title: "crewman" }],+ recent: [{ seq: 4, subject_id: "person", kind: "person", source: "dog_petted", xp: 3, level_before: 3, level_after: 3, ref: "", ts_ms: 9 }],+ rewards: [{ reward_id: "suit_field_armor", slot: "suit", levels: { person: 6, agent: null, pet: null } },+ { reward_id: "uniform_dress_blues", slot: "uniform", levels: { person: 26 } }],+ ranks: [{ id: "cadet", level: 1, tier: "enlisted" }, { id: "admiral", level: 50, tier: "flag" }, { id: "", level: 2 }],+ rules: [{ source: "arcade_round", kind: "person", xp: 8, trigger: "world", cooldown_s: 45, daily_cap: 80 }],+ level_xp: CURVE, max_level: 50, pet_id: "miso", latest_seq: 4,});- expect(parsed.subjects[0]).toMatchObject({ subjectId: "person", level: 2, xpIntoLevel: 10, xpForNext: 65 });+ expect(parsed.recent[0]).toMatchObject({ source: "dog_petted", ref: "" });+ expect(parsed.rewards.map((r) => r.rewardId)).toEqual(["suit_field_armor"]);+ expect(parsed.ranks).toEqual([{ id: "cadet", level: 1, tier: "enlisted" }, { id: "admiral", level: 50, tier: "flag" }]);+ expect(parsed.rules[0].source).toBe("arcade_round");expect(parsed.petId).toBe("miso");- expect(parsed.rewards.map((r) => r.rewardId)).toEqual(["headwear_beret"]);- expect(parsed.rewards[0].levels.pet).toBeNull();- expect(parsed.rules[0]).toMatchObject({ source: "chat_turn", dailyCap: 100 });+ // A server older than the ship sends no ranks.+ expect(parseSnapshot({}).ranks).toEqual([]);});- it("parses an award push and refuses one without a subject", () => {- expect(parseAwardEvent({ subject_id: "agent:scout", subject_kind: "agent", xp: 40, total_xp: 108, level: 3, previous_level: 2, unlocked: ["decoration_ribbon_bar", "gadget_crown"] }))- .toMatchObject({ subjectId: "agent:scout", kind: "agent", level: 3, unlocked: ["decoration_ribbon_bar"] });- expect(parseAwardEvent({ xp: 5 })).toBeNull();- expect(parseAwardEvent(null)).toBeNull();+ it("parses a push and keeps only reward ids it knows", () => {+ const award = parseAwardEvent({ subject_id: "agent:scout", subject_kind: "agent", xp_source: "task_done", xp: 40, total_xp: 45,+ level: 2, previous_level: 1, title: "cadet", unlocked: ["decoration_service_ribbon", "decoration_medals"], seq: 7 });+ expect(award).toMatchObject({ kind: "agent", level: 2, unlocked: ["decoration_service_ribbon"] });+ expect(parseAwardEvent({})).toBeNull();});});-describe("progressionStore", () => {- beforeEach(() => {- useProgression.setState({ snapshot: null, subjects: {}, banners: [], toasts: [], popups: [], bursts: [], cheerUntil: 0, choices: {} });- useProgression.getState().hydrate(snapshot(), []);- });-- it("applies a gain as a popup without a celebration", () => {- useProgression.getState().apply({ seq: 1, subjectId: "person", kind: "person", source: "chat_turn", xp: 5, totalXp: 5, level: 1, previousLevel: 1, title: "newcomer", unlocked: [] }, 1000);- const s = useProgression.getState();- expect(s.subjects.person).toMatchObject({ xp: 5, xpIntoLevel: 5, xpForNext: 40 });- expect(s.popups).toHaveLength(1);- expect(s.banners).toHaveLength(0);- expect(s.bursts).toHaveLength(0);+describe("cosmetics", () => {+ it("opens rewards by level and orders the road", () => {+ expect(unlockedFor(REWARDS, "person", 6).map((r) => r.rewardId)).toEqual(["suit_field_armor", "destination_gas_giant"]);+ expect(rewardRoad(REWARDS, "agent").map((r) => r.rewardId)).toEqual(["decoration_service_ribbon"]);+ expect(rewardsBetween(REWARDS, "person", 5, 8).map((r) => r.rewardId)).toEqual(["suit_field_armor", "decoration_service_ribbon"]);});- it("celebrates the person with a banner, a burst and a cheer; an agent with a toast", () => {- useProgression.getState().apply({ seq: 2, subjectId: "person", kind: "person", source: "agent_hired", xp: 50, totalXp: 50, level: 2, previousLevel: 1, title: "newcomer", unlocked: ["uniform_service_shirt"] }, 1000);- useProgression.getState().apply({ seq: 3, subjectId: "agent:scout", kind: "agent", source: "task_done", xp: 40, totalXp: 40, level: 2, previousLevel: 1, title: "rookie", unlocked: [] }, 1000);- const s = useProgression.getState();- expect(s.banners.map((b) => b.subjectId)).toEqual(["person"]);- expect(s.toasts.map((b) => b.subjectId)).toEqual(["agent:scout"]);- expect(s.bursts).toHaveLength(2);- // The burst carries the climb, so the world can tell a promotion from a level.- expect(s.bursts[0]).toMatchObject({ level: 2, previousLevel: 1, title: "newcomer" });- expect(s.cheerUntil).toBeGreaterThan(1000);+ it("wears the finest open suit unless the captain chose", () => {+ expect(suitFor(REWARDS, 1)).toBeNull();+ expect(suitFor(REWARDS, 20)).toBe("suit_command_coat");+ expect(suitFor(REWARDS, 20, "suit_field_armor")).toBe("suit_field_armor");+ expect(suitFor(REWARDS, 10, "suit_command_coat")).toBe("suit_field_armor");+ expect(suitFor(REWARDS, 20, "none")).toBeNull();});- it("never rolls a subject back to a read older than a push", () => {- useProgression.getState().apply({ seq: 9, subjectId: "person", kind: "person", source: "agent_hired", xp: 50, totalXp: 50, level: 2, previousLevel: 1, title: "newcomer", unlocked: [] }, 0);- useProgression.getState().hydrate(snapshot({ subjects: [{ subjectId: "person", kind: "person", xp: 25, level: 1, xpIntoLevel: 25, xpForNext: 40, title: "newcomer" }] }), []);- expect(useProgression.getState().subjects.person.xp).toBe(50);+ it("measures the bar on the server's curve", () => {+ expect(progressFor(CURVE, 120, 3)).toEqual({ into: 15, size: 90 });+ expect(progressFor(CURVE, 2000, 10)).toEqual({ into: 740, size: 0 });+ expect(levelFraction({ xpIntoLevel: 45, xpForNext: 90 })).toBe(0.5);+ expect(levelFraction({ xpIntoLevel: 0, xpForNext: 0 })).toBe(1);});- it("measures a push that arrived before the first read once the curve is there", () => {- useProgression.setState({ snapshot: null, subjects: {} });- // No curve yet: the level is known, the distance to the next one is not.- useProgression.getState().apply({ seq: 6, subjectId: "person", kind: "person", source: "daily_visit", xp: 25, totalXp: 130, level: 3, previousLevel: 3, title: "private_second_class", unlocked: [] }, 0);- expect(useProgression.getState().subjects.person.xpForNext).toBe(0);- // The read is older than the push (105 XP), so the push stays — measured on the curve now.- useProgression.getState().hydrate(snapshot({ subjects: [{ subjectId: "person", kind: "person", xp: 105, level: 3, xpIntoLevel: 0, xpForNext: 90, title: "private_second_class" }] }), []);- expect(useProgression.getState().subjects.person).toMatchObject({ xp: 130, xpIntoLevel: 25, xpForNext: 90 });+ it("names every reward by a slot the catalog knows", () => {+ for (const id of REWARD_IDS) expect(["suit", "destination", "decoration"]).toContain(slotOf(id));});+});- it("ignores a late duplicate push", () => {- const award = { seq: 4, subjectId: "person", kind: "person" as const, source: "chat_turn", xp: 5, totalXp: 5, level: 1, previousLevel: 1, title: "newcomer", unlocked: [] };- useProgression.getState().apply(award, 1000);- useProgression.getState().apply(award, 1000);- expect(useProgression.getState().popups).toHaveLength(1);+describe("progressionStore", () => {+ beforeEach(() => {+ useProgression.setState({ snapshot: null, subjects: {}, banners: [], toasts: [], popups: [], cheerUntil: 0, record: null });});- it("expires popups and bursts on the scene clock", () => {- useProgression.getState().apply({ seq: 5, subjectId: "person", kind: "person", source: "agent_hired", xp: 50, totalXp: 50, level: 2, previousLevel: 1, title: "newcomer", unlocked: [] }, 0);- useProgression.getState().expire(100_000);- expect(useProgression.getState().popups).toHaveLength(0);- expect(useProgression.getState().bursts).toHaveLength(0);+ it("applies an award once, logs it and celebrates per kind", () => {+ useProgression.getState().hydrate(snapshot(), []);+ const push = { seq: 1, subjectId: "person", kind: "person" as const, source: "chat_turn", xp: 5, totalXp: 45, level: 2, previousLevel: 1, title: "cadet", unlocked: [] };+ useProgression.getState().apply(push, 100);+ useProgression.getState().apply(push, 200);+ const s = useProgression.getState();+ expect(s.subjects.person).toMatchObject({ xp: 45, level: 2, xpIntoLevel: 5, xpForNext: 65 });+ expect(s.banners).toHaveLength(1);+ expect(s.popups).toHaveLength(1);+ expect(s.cheerUntil).toBeGreaterThan(100);+ expect(s.snapshot?.recent.map((r) => r.source)).toEqual(["chat_turn"]);+ useProgression.getState().apply({ ...push, seq: 2, subjectId: "agent:scout", kind: "agent", totalXp: 45 }, 300);+ expect(useProgression.getState().toasts).toHaveLength(1);+ expect(useProgression.getState().banners).toHaveLength(1);});- it("tells each subject's missed level-ups once, and nothing on a first visit", () => {- const missed = snapshot({- subjects: [{ subjectId: "agent:scout", kind: "agent", xp: 200, level: 4, xpIntoLevel: 5, xpForNext: 115, title: "rookie" }],+ it("tells the level-ups missed while away once per subject, with what opened", () => {+ const snap = snapshot({+ subjects: [{ subjectId: "person", kind: "person", xp: 700, level: 7, xpIntoLevel: 85, xpForNext: 190, title: "petty_officer" }],recent: [- { seq: 3, subjectId: "agent:scout", kind: "agent", source: "task_done", xp: 40, levelBefore: 1, levelAfter: 2, tsMs: 0 },- { seq: 4, subjectId: "agent:scout", kind: "agent", source: "quest_done", xp: 60, levelBefore: 2, levelAfter: 4, tsMs: 0 },- { seq: 5, subjectId: "person", kind: "person", source: "chat_turn", xp: 5, levelBefore: 1, levelAfter: 1, tsMs: 0 },+ { seq: 3, subjectId: "person", kind: "person", source: "chat_turn", xp: 5, levelBefore: 4, levelAfter: 5, ref: "", tsMs: 1 },+ { seq: 4, subjectId: "person", kind: "person", source: "chat_turn", xp: 5, levelBefore: 6, levelAfter: 7, ref: "", tsMs: 2 },],});- const away = awayCelebrations(missed, 2);+ expect(awayCelebrations(snap, null)).toEqual([]);+ const away = awayCelebrations(snap, 2);expect(away).toHaveLength(1);- expect(away[0]).toMatchObject({ subjectId: "agent:scout", level: 4, previousLevel: 1, away: true, unlocked: ["decoration_ribbon_bar"] });- expect(awayCelebrations(missed, null)).toEqual([]);- expect(awayCelebrations(missed, 4)).toEqual([]);- });-});--describe("rank insignia", () => {- it("climbs from no insignia to five stars, sleeve first, shoulder for officers", () => {- expect(rankArt("private").parts).toEqual([]);- expect(rankArt("private").mount).toBe("none");- expect(rankArt("sergeant").mount).toBe("sleeve");- expect(rankArt("second_lieutenant").mount).toBe("shoulder");- expect(rankArt("general_of_the_army").mount).toBe("shoulder");- // Chevrons and rockers count up: one chevron, then three, then three with three rockers.- const gold = (rank: Parameters<typeof rankArt>[0]) => rankArt(rank).parts.filter((p) => p.finish === "gold" && !p.detail).length;- expect(gold("private_second_class")).toBe(1);- expect(gold("sergeant")).toBe(3);- expect(gold("master_sergeant")).toBe(6);- expect(gold("first_sergeant")).toBe(7);- // Generals: one star per grade, five at the cap.- expect(rankArt("brigadier_general").parts).toHaveLength(1);- expect(rankArt("general").parts).toHaveLength(4);- expect(rankArt("general_of_the_army").parts).toHaveLength(5);- });-- it("draws every polygon inside its own box", () => {- for (const rank of TITLE_IDS) {- const art = rankArt(rank);- for (const part of art.parts) {- for (const [x, y] of part.pts) {- expect(x).toBeGreaterThanOrEqual(-1);- expect(x).toBeLessThanOrEqual(art.w + 1);- expect(y).toBeGreaterThanOrEqual(-1);- expect(y).toBeLessThanOrEqual(art.h + 1);- }- }- }+ expect(away[0]).toMatchObject({ level: 7, previousLevel: 4, away: true, unlocked: ["destination_gas_giant", "suit_field_armor"] });+ expect(looksBetween({ cap: 1, crown: 10 }, 1, 10)).toEqual(["crown"]);});- it("reads the rank off the server's bands, private before any arrive", () => {- expect(rankAt(BANDS, 3)).toBe("private_second_class");- expect(rankAt(BANDS, 50)).toBe("private_first_class");- expect(rankAt(undefined, 30)).toBe("private");- expect(RANK_INFO.colonel).toEqual({ grade: "O-6", tier: "officer" });- });-});--describe("regalia", () => {- const look = { skin: "#f1c4a0", hair: "#2a1d15", hairStyle: "short", shirt: "#3f7fd6", shirtAccent: "#e5674f", inner: "#ffffff",- pants: "#2f4a7a", shoes: "#f4f4f2", blush: false, outfit: "hoodie", eyewear: "none" } as ToyLook;-- it("dresses the figure in the uniform's colours and keeps its own face", () => {- expect(dressedLook(look, undefined, "sergeant")).toBe(look);- const blues = dressedLook(look, "uniform_dress_blues", "captain");- expect(blues).toMatchObject({ skin: look.skin, hair: look.hair, shirt: "#1c2541", outfit: "suit" });- // Officers wear gold braid on the cuffs; a private's blues have no trouser stripe.- expect(blues.uniform?.cuffBraid).toBeTruthy();- expect(uniformStyle("uniform_dress_blues", "private").stripe).toBeUndefined();- expect(uniformStyle("uniform_mess_dress", "private").tieKind).toBe("bow");- });-- it("wears enlisted rank on the sleeves, officer rank on the shoulders, and nothing else unworn", () => {- expect(regaliaFor("sergeant", {})).toMatchObject({ shoulder: undefined, chest: undefined, hat: undefined });- expect(regaliaFor("sergeant", {}).sleeve).toBeTruthy();- expect(regaliaFor("colonel", {}).sleeve).toBeUndefined();- expect(regaliaFor("colonel", {}).shoulder).toBeTruthy();- expect(regaliaFor("private", {}).sleeve).toBeUndefined();- const full = regaliaFor("major", { headwear: "headwear_service_cap", decoration: "decoration_medals" });- expect(full.hat).toBeTruthy();- expect(full.chest).toBeTruthy();- });-- it("grows the ribbon rack with the decoration, rows of three", () => {- expect(ribbonsFor("decoration_ribbon_bar")).toHaveLength(3);- expect(ribbonsFor("decoration_ribbon_rack")).toHaveLength(9);- expect(ribbonsFor("decoration_medals")).toHaveLength(5);- expect(rackRows(9)).toEqual([3, 3, 3]);- expect(rackRows(5)).toEqual([2, 3]);- });-});--describe("level catalog", () => {- it("names every reward after its slot", () => {- for (const id of REWARD_IDS) expect(["uniform", "headwear", "decoration"]).toContain(slotOf(id));- });-});--describe("agent looks as level rewards", () => {- it("names the looks an agent climb opened, lowest first", () => {- expect(looksBetween({ cap: 1, suit: 4, crown: 10 }, 1, 4)).toEqual(["suit"]);- expect(looksBetween({ cap: 1, suit: 4, crown: 10 }, 3, 12)).toEqual(["suit", "crown"]);- expect(looksBetween({ cap: 1 }, 1, 1)).toEqual([]);- });- it("tells an away agent level-up with the looks it opened", () => {- const snap = snapshot({- subjects: [{ subjectId: "agent:scout", kind: "agent", xp: 200, level: 4, xpIntoLevel: 5, xpForNext: 115, title: "private_first_class" }],- recent: [{ seq: 7, subjectId: "agent:scout", kind: "agent", source: "task_done", xp: 40, levelBefore: 3, levelAfter: 4, tsMs: 1 }],- });- const [party] = awayCelebrations(snap, 1);- expect(party?.looks).toEqual(["suit"]);+ it("opens and closes the service record and remembers the suit", () => {+ useProgression.getState().openRecord("ranks");+ expect(useProgression.getState().record).toBe("ranks");+ useProgression.getState().openRecord(null);+ expect(useProgression.getState().record).toBeNull();+ useProgression.getState().chooseSuit("none");+ expect(useProgression.getState().suit).toBe("none");});});diff --git a/dodaios/ui/web/frontend/src/components/society/progression/progressionApi.ts b/dodaios/ui/web/frontend/src/components/society/progression/progressionApi.tsindex 0c9b593778..ba28cff1cb 100644--- a/dodaios/ui/web/frontend/src/components/society/progression/progressionApi.ts+++ b/dodaios/ui/web/frontend/src/components/society/progression/progressionApi.ts@@ -1,8 +1,13 @@/*** The typed client of `/api/progression` (dodaios/ui/web/progression_routes.py)* and the shape of the `ProgressionAwarded` push the WebSocket forwards.+ *+ * Parsing is forgiving: a ledger row may carry a source this build no longer+ * knows (the office tower's `dog_petted`, `floor_discovered`, …); it is kept as+ * a plain string, never dropped and never fatal.*/-import type { RewardId, Slot, SubjectKind, WorldAction, XpSource } from "./levelCatalog";+import type { RankTier } from "../starship/levels/ranks";+import type { RewardId, Slot, SubjectKind, WorldAction } from "./levelCatalog";import { isRewardId } from "./levelCatalog";export interface SubjectLevel {@@ -16,7 +21,8 @@ export interface SubjectLevel {}export interface XpRuleRow {- source: XpSource;+ /** A rulebook source; a string, so a newer server's rule still reads. */+ source: string;kind: SubjectKind;xp: number;trigger: "server" | "world";@@ -30,6 +36,12 @@ export interface RewardRow {levels: Record<SubjectKind, number | null>;}+export interface RankRow {+ id: string;+ level: number;+ tier: RankTier;+}+export interface AwardRow {seq: number;subjectId: string;@@ -38,6 +50,8 @@ export interface AwardRow {xp: number;levelBefore: number;levelAfter: number;+ /** What the award was for: a deck, `<destination>@<ms>` for a warp jump, a quest id, … */+ ref: string;tsMs: number;}@@ -51,6 +65,8 @@ export interface ProgressionSnapshot {levelXp: number[];rules: XpRuleRow[];rewards: RewardRow[];+ /** The rank ladder as the server has it (empty from a server older than the ship). */+ ranks: RankRow[];titles: Record<SubjectKind, { level: number; title: string }[]>;/** The agent level each wearable look opens at (companion accessory ids). */looks: Record<string, number>;@@ -76,9 +92,10 @@ type Raw = Record<string, unknown>;const num = (value: unknown, fallback = 0): number => (typeof value === "number" && Number.isFinite(value) ? value : fallback);const str = (value: unknown): string => (typeof value === "string" ? value : "");const kindOf = (value: unknown): SubjectKind => (value === "agent" || value === "pet" ? value : "person");+const tierOf = (value: unknown): RankTier => (value === "warrant" || value === "officer" || value === "flag" ? value : "enlisted");+const list = (value: unknown): Raw[] => (Array.isArray(value) ? value.filter((v): v is Raw => !!v && typeof v === "object") : []);export function parseSnapshot(body: Raw): ProgressionSnapshot {- const list = (value: unknown): Raw[] => (Array.isArray(value) ? value.filter((v): v is Raw => !!v && typeof v === "object") : []);const titles = (body.titles && typeof body.titles === "object" ? body.titles : {}) as Record<string, unknown>;const bands = (kind: SubjectKind) => list(titles[kind]).map((b) => ({ level: num(b.level, 1), title: str(b.title) }));return {@@ -89,20 +106,22 @@ export function parseSnapshot(body: Raw): ProgressionSnapshot {petId: str(body.pet_id) || "gigi",recent: list(body.recent).map((row) => ({seq: num(row.seq), subjectId: str(row.subject_id), kind: kindOf(row.kind), source: str(row.source), xp: num(row.xp),- levelBefore: num(row.level_before, 1), levelAfter: num(row.level_after, 1), tsMs: num(row.ts_ms),+ levelBefore: num(row.level_before, 1), levelAfter: num(row.level_after, 1), ref: str(row.ref), tsMs: num(row.ts_ms),})),latestSeq: num(body.latest_seq),maxLevel: num(body.max_level, 50),levelXp: Array.isArray(body.level_xp) ? body.level_xp.map((v) => num(v)) : [0],rules: list(body.rules).map((row) => ({- source: str(row.source) as XpSource, kind: kindOf(row.kind), xp: num(row.xp),+ source: str(row.source), kind: kindOf(row.kind), xp: num(row.xp),trigger: row.trigger === "world" ? "world" : "server", cooldownS: num(row.cooldown_s), dailyCap: num(row.daily_cap),})),+ // A reward id this build does not know (an older or newer server's) is left out: nothing could draw it.rewards: list(body.rewards).filter((row) => isRewardId(row.reward_id)).map((row) => {const levels = (row.levels && typeof row.levels === "object" ? row.levels : {}) as Raw;const at = (kind: SubjectKind) => (typeof levels[kind] === "number" ? (levels[kind] as number) : null);return { rewardId: row.reward_id as RewardId, slot: str(row.slot) as Slot, levels: { person: at("person"), agent: at("agent"), pet: at("pet") } };}),+ ranks: list(body.ranks).filter((row) => str(row.id)).map((row) => ({ id: str(row.id), level: num(row.level, 1), tier: tierOf(row.tier) })),titles: { person: bands("person"), agent: bands("agent"), pet: bands("pet") },looks: Object.fromEntries(list(body.looks).filter((row) => str(row.look_id)).map((row) => [str(row.look_id), num(row.agent, 1)])),};@@ -127,19 +146,27 @@ export async function fetchProgression(afterSeq = 0): Promise<ProgressionSnapshoreturn parseSnapshot((await res.json()) as Raw);}+/**+ * The office tower's arcade names, still sent by the shared retro games:+ * they are the holodeck's rounds now.+ */+const RENAMED_ACTIONS = { arcade_round: "holodeck_round", arcade_record: "holodeck_record" } as const satisfies Record<string, WorldAction>;+export type RenamedAction = keyof typeof RENAMED_ACTIONS;+/** Report a world action; the server decides whether it pays. Never throws; a report the server refuses is logged. */-export async function reportWorldAction(action: WorldAction, ref = ""): Promise<void> {+export async function reportWorldAction(action: WorldAction | RenamedAction, ref = ""): Promise<void> {+ const name: WorldAction = action in RENAMED_ACTIONS ? RENAMED_ACTIONS[action as RenamedAction] : (action as WorldAction);try {const res = await fetch("/api/progression/actions", {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ action, ref }),+ body: JSON.stringify({ action: name, ref }),});- // A refusal means this client and the server disagree about an action or a floor: say so, play on.- if (!res.ok) console.warn("Level action refused", action, ref, res.status);+ // A refusal means this client and the server disagree about an action or a deck: say so, play on.+ if (!res.ok) console.warn("Level action refused", name, ref, res.status);} catch (error) {- // XP is a garnish: an unreachable backend never disturbs the Verse.- console.debug("Level action not reported", action, error);+ // XP is a garnish: an unreachable backend never disturbs the ship.+ console.debug("Level action not reported", name, error);}}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/progressionStore.ts b/dodaios/ui/web/frontend/src/components/society/progression/progressionStore.tsindex 61e92a6d01..00566cc25f 100644--- a/dodaios/ui/web/frontend/src/components/society/progression/progressionStore.ts+++ b/dodaios/ui/web/frontend/src/components/society/progression/progressionStore.ts@@ -1,16 +1,18 @@/**- * The Verse's level state, shared by the HUD (DOM) and the effects (canvas).+ * The ship's level state, shared by the HUD, the service record and the+ * promotion layer.** The first read hydrates it; every `ProgressionAwarded` push applies one* award, queues a floating "+XP" over whoever earned it and, on a level-up,- * a celebration: the promotion card for the person and their pet, a toast for- * an agent, and the moment in the world for all three.+ * a celebration: the promotion ceremony for the captain and the pet, a quiet+ * toast for an android. Level-ups that happened while the ship was closed are+ * told once per subject.*/import { create } from "zustand";import type { AwardEvent, ProgressionSnapshot, SubjectLevel } from "./progressionApi";import { PERSON_SUBJECT } from "./progressionApi";-import type { RewardId, Slot, SubjectKind } from "./levelCatalog";-import { loadChoices, progressFor, saveChoices, type ChoiceBook, type SlotChoice } from "./cosmetics";+import type { RewardId, SubjectKind } from "./levelCatalog";+import { loadSuitChoice, progressFor, rewardsBetween, saveSuitChoice, type SuitChoice } from "./cosmetics";export interface Celebration {id: number;@@ -22,59 +24,44 @@ export interface Celebration {unlocked: RewardId[];/** Agent looks the level-up opened (agents only). */looks: string[];- /** Earned while the Verse was closed: told, not staged in the world. */+ /** Earned while the ship was closed: told, not staged. */away: boolean;}export interface XpPopup { id: number; subjectId: string; xp: number; bornMs: number }-/** A level-up shown in the world; `title` is the rank held after it, `previousLevel` tells a promotion from a level. */-export interface Burst { id: number; subjectId: string; kind: SubjectKind; level: number; previousLevel: number; title: string; bornMs: number }-/** How long a floating "+XP" and a level-up burst live, in ms. */+/** How long a floating "+XP" lives, in ms. */export const POPUP_MS = 1600;-export const BURST_MS = 3200;-/** How long the person's figure cheers after their own level-up. */+/** How long the captain's figure cheers after their own level-up. */export const CHEER_MS = 2200;const MAX_POPUPS = 12;const MAX_TOASTS = 4;-/**- * The Level Hall screen's pages: where you stand, the rank ladder, the studio- * (the uniform you wear, with a live preview), the promotion road, how XP is- * earned, and the team ranking. The hall's checkpoints, the level card and- * `L` open it.- */-export type HallTab = "overview" | "ranks" | "studio" | "rewards" | "guide" | "team";-export const HALL_TABS: readonly HallTab[] = ["overview", "ranks", "studio", "rewards", "guide", "team"];-/** Whose level the screen shows: the person's own, or their pet's (the pet IS Jarvis in the Verse). */-export type HallSubject = "person" | "pet";+/** The service record's pages. */+export type ServiceTab = "record" | "ranks" | "rewards" | "earn" | "crew";+export const SERVICE_TABS: readonly ServiceTab[] = ["record", "ranks", "rewards", "earn", "crew"];interface ProgressionState {snapshot: ProgressionSnapshot | null;subjects: Record<string, SubjectLevel>;petId: string;- /** Person and pet level-ups waiting for the banner, oldest first. */+ /** Captain and pet level-ups waiting for the ceremony, oldest first. */banners: Celebration[];- /** Agent level-ups, newest last. */+ /** Android level-ups, newest last. */toasts: Celebration[];popups: XpPopup[];- bursts: Burst[];cheerUntil: number;- panel: HallTab | null;- hallSubject: HallSubject;- /** A reward to show on the reward road (a pedestal in the hall was clicked); null = the next unlock. */- focusReward: RewardId | null;- choices: ChoiceBook;+ /** The service record's open page; null = closed. */+ record: ServiceTab | null;+ suit: SuitChoice;hydrate: (snapshot: ProgressionSnapshot, away: Celebration[]) => void;apply: (award: AwardEvent, nowMs?: number) => void;setPetId: (petId: string) => void;dismissBanner: () => void;dismissToast: (id: number) => void;expire: (nowMs: number) => void;- /** Open the Level Hall screen on a page (null closes it), optionally for a subject and a reward. */- openPanel: (tab: HallTab | null, options?: { subject?: HallSubject; reward?: RewardId | null }) => void;- setHallSubject: (subject: HallSubject) => void;- choose: (who: "person" | "pet", slot: Slot, choice: SlotChoice) => void;+ openRecord: (tab: ServiceTab | null) => void;+ chooseSuit: (choice: SuitChoice) => void;}let nextId = 1;@@ -98,12 +85,9 @@ export const useProgression = create<ProgressionState>((set, get) => ({banners: [],toasts: [],popups: [],- bursts: [],cheerUntil: 0,- panel: null,- hallSubject: "person",- focusReward: null,- choices: loadChoices(),+ record: null,+ suit: loadSuitChoice(),hydrate: (snapshot, away) => set((s) => {// A push can land before the read that was already on its way: never roll a subject back.const subjects: Record<string, SubjectLevel> = { ...s.subjects };@@ -132,14 +116,23 @@ export const useProgression = create<ProgressionState>((set, get) => ({subjectId: award.subjectId, kind: award.kind, xp: award.totalXp, level: award.level,xpIntoLevel: atCap ? 0 : into, xpForNext: atCap ? 0 : size, title: award.title,};+ const subjects = { ...s.subjects, [award.subjectId]: subject };const popups = [...s.popups, { id: nextId++, subjectId: award.subjectId, xp: award.xp, bornMs: nowMs }].slice(-MAX_POPUPS);- if (award.level <= award.previousLevel) return { subjects: { ...s.subjects, [award.subjectId]: subject }, popups };+ // The award went to the ledger too: keep the snapshot's log current for the service record.+ const snapshot = s.snapshot && award.seq > s.snapshot.latestSeq ? {+ ...s.snapshot,+ latestSeq: award.seq,+ recent: [...s.snapshot.recent, {+ seq: award.seq, subjectId: award.subjectId, kind: award.kind, source: award.source, xp: award.xp,+ levelBefore: award.previousLevel, levelAfter: award.level, ref: "", tsMs: Date.now(),+ }].slice(-50),+ } : s.snapshot;+ if (award.level <= award.previousLevel) return { subjects, popups, snapshot };const party = celebrationOf(award);- const bursts = [...s.bursts, { id: nextId++, subjectId: award.subjectId, kind: award.kind, level: award.level, previousLevel: award.previousLevel, title: award.title, bornMs: nowMs }];return {- subjects: { ...s.subjects, [award.subjectId]: subject },+ subjects,popups,- bursts,+ snapshot,banners: award.kind === "agent" ? s.banners : [...s.banners, party],toasts: award.kind === "agent" ? [...s.toasts, party].slice(-MAX_TOASTS) : s.toasts,cheerUntil: award.subjectId === PERSON_SUBJECT ? nowMs + CHEER_MS : s.cheerUntil,@@ -151,21 +144,13 @@ export const useProgression = create<ProgressionState>((set, get) => ({expire: (nowMs) => {const s = get();const popups = s.popups.filter((p) => nowMs - p.bornMs < POPUP_MS);- const bursts = s.bursts.filter((b) => nowMs - b.bornMs < BURST_MS);- if (popups.length !== s.popups.length || bursts.length !== s.bursts.length) set({ popups, bursts });+ if (popups.length !== s.popups.length) set({ popups });+ },+ openRecord: (record) => set({ record }),+ chooseSuit: (suit) => {+ saveSuitChoice(suit);+ set({ suit });},- openPanel: (panel, options = {}) => set((s) => ({- panel,- hallSubject: options.subject ?? s.hallSubject,- focusReward: options.reward !== undefined ? options.reward : panel === "rewards" ? s.focusReward : null,- })),- // A reward focused for one subject means nothing for the other: switching forgets it.- setHallSubject: (hallSubject) => set((s) => (s.hallSubject === hallSubject ? s : { hallSubject, focusReward: null })),- choose: (who, slot, choice) => set((s) => {- const choices: ChoiceBook = { ...s.choices, [who]: { ...(s.choices[who] ?? {}), [slot]: choice } };- saveChoices(choices);- return { choices };- }),}));const SEEN_KEY = "jarvis.verse.levels.seen.v1";@@ -177,7 +162,7 @@ export function readSeenSeq(): number | null {const value = raw === null ? NaN : Number(raw);return Number.isFinite(value) ? value : null;} catch (error) {- console.debug("Verse level marker unavailable", error);+ console.debug("Ship level marker unavailable", error);return null;}}@@ -186,13 +171,13 @@ export function writeSeenSeq(seq: number): void {try {localStorage.setItem(SEEN_KEY, String(seq));} catch (error) {- console.debug("Verse level marker not saved", error);+ console.debug("Ship level marker not saved", error);}}/**- * Level-ups that happened while the Verse was closed: the latest one per- * subject, so a busy agent that climbed three levels is told once.+ * Level-ups that happened while the ship was closed: the latest one per+ * subject, so a busy android that climbed three levels is told once.*/export function awayCelebrations(snapshot: ProgressionSnapshot, seenSeq: number | null): Celebration[] {if (seenSeq === null) return [];@@ -200,14 +185,12 @@ export function awayCelebrations(snapshot: ProgressionSnapshot, seenSeq: numberfor (const row of snapshot.recent) {if (row.seq <= seenSeq || row.levelAfter <= row.levelBefore) continue;const prior = latest.get(row.subjectId);- const subject = snapshot.subjects.find((s) => s.subjectId === row.subjectId);- const unlocked = snapshot.rewards- .filter((r) => { const at = r.levels[row.kind]; return at !== null && at > (prior?.previousLevel ?? row.levelBefore) && at <= row.levelAfter; })- .map((r) => r.rewardId);const from = prior?.previousLevel ?? row.levelBefore;+ const subject = snapshot.subjects.find((s) => s.subjectId === row.subjectId);latest.set(row.subjectId, celebrationOf({subjectId: row.subjectId, kind: row.kind, level: row.levelAfter, previousLevel: from,- title: subject?.title ?? "", unlocked,+ title: subject?.title ?? "",+ unlocked: rewardsBetween(snapshot.rewards, row.kind, from, row.levelAfter).map((r) => r.rewardId),unlockedLooks: row.kind === "agent" ? looksBetween(snapshot.looks, from, row.levelAfter) : [],}, true));}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/regalia/decorations3d.tsx b/dodaios/ui/web/frontend/src/components/society/progression/regalia/decorations3d.tsxdeleted file mode 100644index d71b5053be..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/regalia/decorations3d.tsx+++ /dev/null@@ -1,173 +0,0 @@-/**- * Decorations in 3D: the ribbon rack over the left breast, full-size medals- * on their drapes, and the gold aiguillette from the right shoulder. Each- * piece is built round its own anchor so the same component sits on a- * figure's chest and on the velvet board of a display case.- *- * - Ribbons and medals: origin at the centre of the rack, lying in the x/y- * plane, facing +z.- * - Aiguillette: origin where it hangs from the shoulder; its loops fall in- * the x/y plane towards +x (the chest's centre when worn on the right).- */-import { useMemo } from "react";-import { ExtrudeGeometry, MeshStandardMaterial, Shape, Vector2 } from "three";-import { cachedCanvasTexture } from "../../office/canvasMaterials";-import type { RewardId } from "../levelCatalog";-import { ellipse, star, type Pt } from "../insignia/rankArt";-import { MEDAL_COUNT, MEDAL_METALS, paintRibbon, RIBBONS, type RibbonSpec } from "./ribbons";-import { REGALIA_MATERIALS } from "./insignia3d";--/** A ribbon bar's size in metres (a real one is 35 × 10 mm; the toy wears it larger). */-export const RIBBON = { w: 0.03, h: 0.0095, gap: 0.0008 };--const ribbonMaterials = new Map<string, MeshStandardMaterial>();-function ribbonMaterial(spec: RibbonSpec): MeshStandardMaterial {- let material = ribbonMaterials.get(spec.id);- if (!material) {- const map = cachedCanvasTexture(`ribbon:${spec.id}`, 128, 40, (ctx, w, h) => paintRibbon(ctx, spec, w, h));- material = new MeshStandardMaterial({ map, color: map ? "#ffffff" : spec.stripes[0][0], roughness: 0.55 });- ribbonMaterials.set(spec.id, material);- }- return material;-}--/** Which ribbons a decoration wears, in rack order (highest first). */-export function ribbonsFor(decoration: RewardId): RibbonSpec[] {- if (decoration === "decoration_ribbon_bar") return [RIBBONS[4], RIBBONS[5], RIBBONS[6]];- if (decoration === "decoration_medals") return RIBBONS.slice(0, MEDAL_COUNT);- return [...RIBBONS];-}--/** Rows of three, the short row on top and centred, the way a rack is mounted. */-export function rackRows(count: number): number[] {- const rows: number[] = [];- let left = count;- while (left > 0) { const n = left % 3 || 3; rows.push(n); left -= n; }- return rows;-}--export function RibbonRack({ ribbons }: { ribbons: readonly RibbonSpec[] }) {- const rows = rackRows(ribbons.length);- const { w, h, gap } = RIBBON;- const height = rows.length * (h + gap);- let index = 0;- return (- <group>- {rows.map((n, row) => {- const y = height / 2 - (row + 0.5) * (h + gap);- return Array.from({ length: n }, (_, i) => {- const spec = ribbons[index++];- const x = (i - (n - 1) / 2) * (w + gap);- return (- <mesh key={spec.id} material={ribbonMaterial(spec)} position={[x, y, 0.0025]}>- <boxGeometry args={[w, h, 0.005]} />- </mesh>- );- });- })}- </group>- );-}--function shape(pts: readonly Pt[], s: number): Shape {- return new Shape(pts.map(([x, y]) => new Vector2((x - 50) * s, (50 - y) * s)));-}--const medalGeometry = new Map<string, ExtrudeGeometry>();-function medalShape(kind: RibbonSpec["medal"]["shape"], size: number): ExtrudeGeometry {- const key = `${kind}:${size}`;- let geometry = medalGeometry.get(key);- if (!geometry) {- const s = size / 100;- const outline = kind === "star" ? star(50, 52, 50) : kind === "cross"- ? [[38, 4], [62, 4], [58, 38], [96, 38], [96, 62], [58, 62], [62, 96], [38, 96], [42, 62], [4, 62], [4, 38], [42, 38]] as Pt[]- : ellipse(50, 50, 48, 48, 32);- geometry = new ExtrudeGeometry(shape(outline, s), { depth: size * 0.06, bevelEnabled: true, bevelThickness: size * 0.03, bevelSize: size * 0.03, bevelSegments: 2 });- geometry.computeVertexNormals();- medalGeometry.set(key, geometry);- }- return geometry;-}--const medalMaterials = new Map<string, MeshStandardMaterial>();-function medalMaterial(metal: RibbonSpec["medal"]["metal"]): MeshStandardMaterial {- let material = medalMaterials.get(metal);- if (!material) {- const tone = MEDAL_METALS[metal];- material = new MeshStandardMaterial({ color: tone.face, metalness: 0.65, roughness: 0.3, emissive: tone.edge, emissiveIntensity: 0.25 });- medalMaterials.set(metal, material);- }- return material;-}--/** Full-size medals in a row: each on its own short drape of ribbon, slightly overlapping like a court mount. */-export function MedalRow({ ribbons }: { ribbons: readonly RibbonSpec[] }) {- const step = 0.019, drape = 0.024, size = 0.02;- return (- <group>- {ribbons.map((spec, i) => {- const x = (i - (ribbons.length - 1) / 2) * step;- return (- <group key={spec.id} position={[x, 0, 0.003 + i * 0.0006]}>- <mesh material={ribbonMaterial(spec)} position={[0, -drape / 2, 0]}>- <boxGeometry args={[step * 0.95, drape, 0.003]} />- </mesh>- <mesh geometry={medalShape(spec.medal.shape, size)} material={medalMaterial(spec.medal.metal)} position={[0, -drape - size * 0.42, 0.001]} castShadow />- </group>- );- })}- {/* The brass bar the drapes hang from. */}- <mesh material={REGALIA_MATERIALS.gold} position={[0, 0.002, 0.004]}>- <boxGeometry args={[step * ribbons.length + 0.004, 0.004, 0.004]} />- </mesh>- </group>- );-}--/** Height of a decoration on the chest, so the anchor can sit it above a pocket. */-export function decorationSize(decoration: RewardId): { w: number; h: number } {- if (decoration === "decoration_medals") return { w: 0.019 * MEDAL_COUNT, h: 0.024 + 0.02 };- const rows = rackRows(ribbonsFor(decoration).length).length;- return { w: 3 * (RIBBON.w + RIBBON.gap), h: rows * (RIBBON.h + RIBBON.gap) };-}--/** The decoration over the left breast: a rack, or the medals. Origin: the top centre of the piece. */-export function BreastDecoration({ decoration }: { decoration: RewardId }) {- const ribbons = useMemo(() => ribbonsFor(decoration), [decoration]);- if (decoration === "decoration_medals") return <MedalRow ribbons={ribbons} />;- const { h } = decorationSize(decoration);- return <group position={[0, -h / 2, 0]}><RibbonRack ribbons={ribbons} /></group>;-}--/**- * The aiguillette: braided gold cords looping from the shoulder across the- * chest, two of them ending in pointed metal tips.- */-export function Aiguillette({ span = 0.11 }: { span?: number }) {- const loops = [0.05, 0.075, 0.1];- return (- <group>- {loops.map((sag, i) => (- <mesh key={i} material={REGALIA_MATERIALS.braid} position={[span / 2, 0, i * 0.003]} rotation={[0, 0, Math.PI]} scale={[1, sag / (span / 2), 1]}>- <torusGeometry args={[span / 2, 0.0042, 6, 28, Math.PI]} />- </mesh>- ))}- {[0.32, 0.55].map((k, i) => {- const x = span * k, top = -0.02, length = 0.07 + i * 0.015;- return (- <group key={k} position={[x, top, 0.008]}>- <mesh material={REGALIA_MATERIALS.braid} position={[0, -length / 2, 0]}>- <cylinderGeometry args={[0.0038, 0.0038, length, 6]} />- </mesh>- <mesh material={REGALIA_MATERIALS.gold} position={[0, -length - 0.008, 0]} rotation={[Math.PI, 0, 0]}>- <coneGeometry args={[0.0055, 0.018, 10]} />- </mesh>- </group>- );- })}- <mesh material={REGALIA_MATERIALS.gold} position={[span, 0, 0.004]}>- <sphereGeometry args={[0.006, 10, 8]} />- </mesh>- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/regalia/dress.tsx b/dodaios/ui/web/frontend/src/components/society/progression/regalia/dress.tsxdeleted file mode 100644index c61d0b5379..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/regalia/dress.tsx+++ /dev/null@@ -1,97 +0,0 @@-/**- * How a figure is dressed for its rank and loadout: the uniform it wears over- * its own look, the insignia on its sleeves or shoulders, the decoration on- * its chest and the hat on its head. The figure in the office, the studio- * preview and the mannequins in the hall's display cases all dress through- * here, so every surface shows the same pieces.- */-import { useMemo } from "react";-import type { FigureRegalia } from "../../office/ToyFigure";-import { TOY, type ToyLook, type UniformStyle } from "../../office/toyFigureModel";-import { equippedFor, type Loadout } from "../cosmetics";-import { RANK_INFO, rankAt, type RankId, type RewardId } from "../levelCatalog";-import { rankArt } from "../insignia/rankArt";-import { useProgression } from "../progressionStore";-import { Aiguillette, BreastDecoration } from "./decorations3d";-import { Headwear, type HeadwearId } from "./headwear3d";-import { ShoulderBoard, SleevePatch } from "./insignia3d";--export type UniformId = Extract<RewardId, `uniform_${string}`>;--const GOLD = "#d2a33f";--/** Each uniform as the figure draws it; `officer` and `nco` add the trims those grades wear. */-export function uniformStyle(id: UniformId, rank: RankId): UniformStyle {- const tier = RANK_INFO[rank].tier;- const officer = tier === "officer" || tier === "general";- const nco = tier !== "enlisted";- switch (id) {- case "uniform_service_shirt":- return { cut: "shirt", coat: "#c8b38c", shirt: "#c8b38c", tie: "#433a28", tieKind: "long", trousers: "#8d7a6b", shoes: "#4b311d",- buttons: "#7a6a4a", pockets: 2, belt: "#2f2418" };- case "uniform_field_jacket":- return { cut: "field", coat: "#5a613f", shirt: "#5a613f", tie: "#5a613f", tieKind: "long", trousers: "#5d6248", shoes: "#3b2f24",- buttons: "#2b2b25", pockets: 4, tapes: "#2c3023" };- case "uniform_service_greens":- return { cut: "service", coat: "#3d4632", shirt: "#cbb892", tie: "#39331f", tieKind: "long", trousers: "#a08a7b", shoes: "#4a2e1a",- buttons: "#c9a24a", pockets: 4, belt: "#3d4632" };- case "uniform_dress_blues":- return { cut: "service", coat: "#1c2541", shirt: "#f3f3ef", tie: "#121317", tieKind: "long", trousers: "#4a6a9e", shoes: "#0e0e10",- buttons: "#d4a845", pockets: 4, stripe: nco ? GOLD : undefined, cuffBraid: officer ? GOLD : undefined };- case "uniform_mess_dress":- default:- return { cut: "mess", coat: "#151e37", shirt: "#f7f7f3", tie: "#0f1013", tieKind: "bow", trousers: "#151e37", shoes: "#0e0e10",- buttons: "#d4a845", pockets: 0, stripe: GOLD, cuffBraid: GOLD, lapels: "#22305a" };- }-}--/** The look a figure shows with a uniform on: the uniform's colours over its own skin, hair and face. */-export function dressedLook(look: ToyLook, uniform: UniformId | undefined, rank: RankId): ToyLook {- if (!uniform) return look;- const u = uniformStyle(uniform, rank);- return { ...look, outfit: "suit", shirt: u.coat, inner: u.shirt, shirtAccent: u.tie, pants: u.trousers, shoes: u.shoes, uniform: u };-}--/** Where the breast decoration hangs: over the left pocket, its top just under the shoulder line. */-const BREAST = { x: 0.075, y: 0.207, z: TOY.torso.d / 2 + 0.002 };-/** Where the aiguillette hangs from: the front of the right shoulder. */-const CORD = { x: -0.168, y: 0.252, z: TOY.torso.d / 2 - 0.012 };--/** The pieces a figure of `rank` wears with `loadout`; empty slots stay undefined. */-export function regaliaFor(rank: RankId, loadout: Loadout): FigureRegalia {- const mount = rankArt(rank).mount;- const decoration = loadout.decoration;- const corded = decoration === "decoration_aiguillette" || decoration === "decoration_medals";- return {- sleeve: mount === "sleeve" ? <SleevePatch rank={rank} armRadius={TOY.armRadius} /> : undefined,- shoulder: mount === "shoulder" ? <ShoulderBoard rank={rank} /> : undefined,- chest: decoration ? (- <>- <group position={[BREAST.x, BREAST.y, BREAST.z]}><BreastDecoration decoration={decoration} /></group>- {corded && <group position={[CORD.x, CORD.y, CORD.z]}><Aiguillette /></group>}- </>- ) : undefined,- hat: loadout.headwear ? <Headwear kind={loadout.headwear as HeadwearId} rank={rank} /> : undefined,- };-}--/** A figure's rank and loadout from the store: the person's own choices, an agent's best unlocks. */-export function useDress(kind: "person" | "agent", subjectId: string): { rank: RankId; loadout: Loadout } {- const level = useProgression((s) => s.subjects[subjectId]?.level ?? 1);- const rewards = useProgression((s) => s.snapshot?.rewards);- const bands = useProgression((s) => s.snapshot?.titles[kind]);- const choices = useProgression((s) => (kind === "person" ? s.choices.person : undefined));- return useMemo(() => ({- rank: rankAt(bands, level),- loadout: rewards ? equippedFor(rewards, kind, level, choices) : {},- }), [bands, level, rewards, kind, choices]);-}--/** The look and regalia a figure renders with, from its rank and loadout. */-export function useDressedFigure(kind: "person" | "agent", subjectId: string, look: ToyLook): { look: ToyLook; regalia: FigureRegalia } {- const { rank, loadout } = useDress(kind, subjectId);- return useMemo(() => ({- look: dressedLook(look, loadout.uniform as UniformId | undefined, rank),- regalia: regaliaFor(rank, loadout),- }), [look, loadout, rank]);-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/regalia/headwear3d.tsx b/dodaios/ui/web/frontend/src/components/society/progression/regalia/headwear3d.tsxdeleted file mode 100644index bd4c925a31..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/regalia/headwear3d.tsx+++ /dev/null@@ -1,175 +0,0 @@-/**- * Military headwear for the toy figure, built in its head group's space- * (head centre `TOY.head.y` above the neck pivot, the face towards +z):- *- * - patrol cap: a soft flat-topped field cap with a short bill and the rank- * sewn on the front;- * - garrison cap: the folded side cap in Army blue with gold piping, worn- * tilted to the right, the rank pinned at the left front (a unit crest for- * enlisted ranks);- * - beret: black wool pulled down over the right ear, a shield-shaped flash- * over the left eye carrying the officer's rank or the unit crest;- * - service cap: the peaked dress cap with a black band, a glossy visor, a- * gold chin strap and the gold eagle; field-grade officers get one row of- * gold oak leaves on the visor, general officers two.- *- * The figure hides its hair under a hat except for the band at the nape.- */-import { CylinderGeometry, MeshStandardMaterial, SphereGeometry } from "three";-import { RoundedBoxGeometry } from "three-stdlib";-import { TOY } from "../../office/toyFigureModel";-import { RANK_INFO, type RankId, type RewardId } from "../levelCatalog";-import { CAP_BADGE_ART, CREST_ART, rankArt } from "../insignia/rankArt";-import { ArtPiece3D, RankInsignia3D, REGALIA_MATERIALS } from "./insignia3d";--const HD = TOY.head;--export type HeadwearId = Extract<RewardId, `headwear_${string}`>;--const GEO = {- cyl: new CylinderGeometry(1, 1, 1, 48),- crown: new CylinderGeometry(1.12, 1, 1, 48),- sphere: new SphereGeometry(1, 40, 24),- bill: new RoundedBoxGeometry(1, 1, 1, 3, 0.2),- /** The front half of a disc: a visor. */- visor: new CylinderGeometry(1, 1, 1, 40, 1, false, -Math.PI / 2, Math.PI),- prism: new CylinderGeometry(1, 1, 1, 3),-};--const cloth = new Map<string, MeshStandardMaterial>();-function fabric(colour: string, roughness = 0.92): MeshStandardMaterial {- const key = `${colour}|${roughness}`;- let m = cloth.get(key);- if (!m) { m = new MeshStandardMaterial({ color: colour, roughness }); cloth.set(key, m); }- return m;-}-const PATENT = new MeshStandardMaterial({ color: "#0c0d10", roughness: 0.12, metalness: 0.2 });--/** The rank pinned on a cap: officers wear their pin, enlisted ranks the unit crest (or their sewn rank on the patrol cap). */-function CapPin({ rank, width }: { rank: RankId; width: number }) {- const officer = RANK_INFO[rank].tier === "officer" || RANK_INFO[rank].tier === "general";- if (officer) {- const art = rankArt(rank);- // Stars stacked for the shoulder are pinned side by side on a cap.- const sideways = RANK_INFO[rank].tier === "general" && rank !== "general_of_the_army";- return <group rotation={[0, 0, sideways ? Math.PI / 2 : 0]}><RankInsignia3D rank={rank} width={sideways ? (width * art.w) / art.h * 2.2 : width} /></group>;- }- return <ArtPiece3D id="crest" art={CREST_ART} width={width * 0.9} />;-}--function PatrolCap({ rank }: { rank: RankId }) {- const shell = fabric("#5c6248");- const sewn = rankArt(rank).mount === "sleeve";- return (- <group position={[0, HD.y + 0.14, 0]} rotation={[-0.1, 0, 0]}>- <mesh geometry={GEO.crown} material={shell} position={[0, 0.07, 0]} scale={[HD.rx + 0.02, 0.17, HD.rz + 0.03]} castShadow />- <mesh geometry={GEO.cyl} material={fabric("#4d523b")} position={[0, -0.005, 0]} scale={[HD.rx + 0.026, 0.035, HD.rz + 0.036]} />- <mesh geometry={GEO.bill} material={shell} position={[0, -0.01, HD.rz + 0.08]} rotation={[0.22, 0, 0]} scale={[0.3, 0.022, 0.13]} castShadow />- <group position={[0, 0.07, HD.rz + 0.034]}>- {sewn ? <RankInsignia3D rank={rank} width={0.085} wrapRadius={0.3} /> : <CapPin rank={rank} width={0.06} />}- </group>- </group>- );-}--function GarrisonCap({ rank }: { rank: RankId }) {- const blue = fabric("#1d2742");- return (- <group position={[-0.02, HD.y + HD.ry - 0.06, 0]} rotation={[0, 0, 0.16]}>- {/* The folded body: a wedge lying front to back, its ridge on top. */}- <mesh geometry={GEO.prism} material={blue} rotation={[Math.PI / 2, 0, Math.PI]} position={[0, 0.045, 0]} scale={[0.16, 0.52, 0.095]} castShadow />- <mesh geometry={GEO.cyl} material={blue} position={[0, 0, 0]} scale={[0.21, 0.04, HD.rz + 0.02]} />- {/* Gold piping along the ridge and the curtain's edge. */}- <mesh material={REGALIA_MATERIALS.braid} position={[0, 0.095, 0]}>- <boxGeometry args={[0.01, 0.008, 0.5]} />- </mesh>- {[-1, 1].map((sx) => (- <mesh key={sx} material={REGALIA_MATERIALS.braid} position={[sx * 0.135, 0.022, 0]} rotation={[0, 0, sx * 0.55]}>- <boxGeometry args={[0.006, 0.006, 0.48]} />- </mesh>- ))}- <group position={[0.11, 0.035, 0.17]} rotation={[0, 0.5, 0.5]}>- <CapPin rank={rank} width={0.045} />- </group>- </group>- );-}--function Beret({ rank }: { rank: RankId }) {- const wool = fabric("#121316", 0.98);- return (- <group position={[0, HD.y + 0.1, 0]}>- {/* Head band, then the crown pulled over the right side (-x). */}- <mesh geometry={GEO.cyl} material={fabric("#1b1c20", 0.85)} position={[0, 0.02, 0]} scale={[HD.rx + 0.022, 0.04, HD.rz + 0.026]} />- <mesh geometry={GEO.sphere} material={wool} position={[-0.05, 0.12, -0.01]} rotation={[0.05, 0, 0.32]}- scale={[HD.rx + 0.07, 0.1, HD.rz + 0.06]} castShadow />- {/* The flash over the left eye: a navy shield edged in gold. */}- <group position={[0.1, 0.09, HD.rz + 0.005]} rotation={[-0.15, 0.32, 0]}>- <mesh material={REGALIA_MATERIALS.braid} scale={[0.072, 0.082, 0.006]}>- <sphereGeometry args={[0.5, 20, 12]} />- </mesh>- <mesh material={fabric("#24386b", 0.8)} position={[0, 0, 0.002]} scale={[0.064, 0.074, 0.006]}>- <sphereGeometry args={[0.5, 20, 12]} />- </mesh>- <group position={[0, 0, 0.006]}><CapPin rank={rank} width={0.038} /></group>- </group>- </group>- );-}--/** Rows of gold oak leaves on the visor: none below major, one for field grade, two for general officers. */-function visorRows(rank: RankId): number {- const info = RANK_INFO[rank];- if (info.tier === "general") return 2;- if (rank === "major" || rank === "lieutenant_colonel" || rank === "colonel") return 1;- return 0;-}--function ServiceCap({ rank }: { rank: RankId }) {- const crown = fabric("#1d2742", 0.8);- const rows = visorRows(rank);- const vr = HD.rx + 0.03;- return (- <group position={[0, HD.y + 0.12, 0]} rotation={[-0.06, 0, 0]}>- <mesh geometry={GEO.cyl} material={fabric("#0f1013", 0.6)} position={[0, 0.04, 0]} scale={[HD.rx + 0.024, 0.085, HD.rz + 0.03]} castShadow />- <mesh geometry={GEO.crown} material={crown} position={[0, 0.12, -0.01]} scale={[HD.rx + 0.07, 0.075, HD.rz + 0.085]} castShadow />- <mesh geometry={GEO.cyl} material={crown} position={[0, 0.16, -0.012]} scale={[HD.rx + 0.085, 0.022, HD.rz + 0.1]} castShadow />- {/* The glossy visor, angled down over the brow. */}- <mesh geometry={GEO.visor} material={PATENT} position={[0, 0.0, 0.03]} rotation={[0.38, 0, 0]} scale={[vr, 0.012, HD.rz + 0.1]} castShadow />- {Array.from({ length: rows }, (_, row) => (- <group key={row} position={[0, 0.004 - row * 0.018, 0.03]} rotation={[0.38, 0, 0]}>- {Array.from({ length: 9 }, (_, i) => {- const a = -0.95 + (i / 8) * 1.9;- const r = HD.rz + 0.06 - row * 0.03;- return (- <mesh key={i} material={REGALIA_MATERIALS.gold} position={[Math.sin(a) * vr * (r / (HD.rz + 0.1)), 0.008, Math.cos(a) * r]}- rotation={[0, a + 0.6, 0]} scale={[0.02, 0.004, 0.009]}>- <sphereGeometry args={[1, 10, 6]} />- </mesh>- );- })}- </group>- ))}- {/* The gold chin strap across the band, buttoned at each side. */}- <mesh material={REGALIA_MATERIALS.braid} position={[0, 0.015, HD.rz + 0.034]}>- <boxGeometry args={[0.32, 0.016, 0.006]} />- </mesh>- {[-1, 1].map((sx) => (- <mesh key={sx} material={REGALIA_MATERIALS.gold} position={[sx * 0.17, 0.015, HD.rz - 0.02]}>- <sphereGeometry args={[0.012, 10, 8]} />- </mesh>- ))}- <group position={[0, 0.115, HD.rz + 0.09]} rotation={[-0.12, 0, 0]}>- <ArtPiece3D id="cap-badge" art={CAP_BADGE_ART} width={0.11} />- </group>- </group>- );-}--/** A headwear piece for a figure of the given rank, in head-group space. */-export function Headwear({ kind, rank }: { kind: HeadwearId; rank: RankId }) {- if (kind === "headwear_patrol_cap") return <PatrolCap rank={rank} />;- if (kind === "headwear_garrison_cap") return <GarrisonCap rank={rank} />;- if (kind === "headwear_beret") return <Beret rank={rank} />;- return <ServiceCap rank={rank} />;-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/regalia/insignia3d.tsx b/dodaios/ui/web/frontend/src/components/society/progression/regalia/insignia3d.tsxdeleted file mode 100644index 9b35c076a1..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/regalia/insignia3d.tsx+++ /dev/null@@ -1,185 +0,0 @@-/**- * The rank insignia in 3D, extruded from the same polygons as the SVG icons- * (`insignia/rankArt.ts`): navy cloth backing, raised gold embroidery, struck- * gold and silver pins with a bevelled edge. The piece a figure wears and- * the piece in a display case are the same geometry.- *- * Built in a local frame: the insignia lies in the x/y plane, its front- * facing +z, its back at z = 0, `width` metres wide. With `wrapRadius` the- * piece bends round a cylinder of that radius (an upper sleeve), so a flat- * patch never floats off a round arm.- */-import { useMemo } from "react";-import { BufferGeometry, ExtrudeGeometry, MeshStandardMaterial, Shape, Vector2 } from "three";-import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";-import type { RankId, RankTier } from "../levelCatalog";-import { RANK_INFO } from "../levelCatalog";-import { rankArt, type Finish, type InsigniaArt, type Pt } from "../insignia/rankArt";--/** Materials shared by every insignia: struck metal catches the light, cloth stays matte. */-export const REGALIA_MATERIALS = {- gold: new MeshStandardMaterial({ color: "#d9aa45", metalness: 0.62, roughness: 0.32, emissive: "#3b2906", emissiveIntensity: 0.35 }),- goldDetail: new MeshStandardMaterial({ color: "#9a6f1f", metalness: 0.55, roughness: 0.42 }),- silver: new MeshStandardMaterial({ color: "#dfe3ea", metalness: 0.66, roughness: 0.26, emissive: "#2a2e36", emissiveIntensity: 0.3 }),- silverDetail: new MeshStandardMaterial({ color: "#8e96a3", metalness: 0.6, roughness: 0.35 }),- cloth: new MeshStandardMaterial({ color: "#1b2340", roughness: 0.95 }),- boardNavy: new MeshStandardMaterial({ color: "#18213d", roughness: 0.85 }),- boardBlack: new MeshStandardMaterial({ color: "#121318", roughness: 0.7 }),- braid: new MeshStandardMaterial({ color: "#d2a33f", metalness: 0.5, roughness: 0.45, emissive: "#3b2906", emissiveIntensity: 0.3 }),- /** A rank not reached yet: the whole piece in one dark pewter, a silhouette that still shows its form. */- muted: new MeshStandardMaterial({ color: "#3a3f4c", metalness: 0.35, roughness: 0.6 }),-} as const;--type Layer = "cloth" | "gold" | "silver" | "goldDetail" | "silverDetail";--/** Depths in insignia units (the art is 100 units wide). */-const DEPTH = { cloth: 2.2, metal: 3.4, detail: 1.1 };--function shapeOf(pts: readonly Pt[], h: number): Shape {- // Art space: y down, origin top-left. Shape space: y up, centred.- return new Shape(pts.map(([x, y]) => new Vector2(x - 50, h / 2 - y)));-}--/** Bends a piece round a vertical cylinder of radius `r` (insignia units): x runs round it, z grows outward. */-function wrap(geometry: BufferGeometry, r: number): void {- const pos = geometry.attributes.position;- for (let i = 0; i < pos.count; i += 1) {- const x = pos.getX(i), z = pos.getZ(i);- const angle = x / r;- pos.setXYZ(i, (r + z) * Math.sin(angle), pos.getY(i), (r + z) * Math.cos(angle) - r);- }- pos.needsUpdate = true;- geometry.computeVertexNormals();-}--interface Built { layer: Layer; geometry: BufferGeometry }--const builtCache = new Map<string, Built[]>();--/** The merged geometry per material layer of a rank's insignia, in insignia units. */-function buildArt(id: string, art: InsigniaArt, wrapUnits: number | null): Built[] {- const key = `${id}|${wrapUnits ?? "flat"}`;- const cached = builtCache.get(key);- if (cached) return cached;- const hasCloth = art.parts.some((p) => p.finish === "cloth");- const metalBase = hasCloth ? DEPTH.cloth : 0;- const byLayer = new Map<Layer, BufferGeometry[]>();- for (const part of art.parts) {- const shape = shapeOf(part.pts, art.h);- let geometry: BufferGeometry;- let layer: Layer;- if (part.finish === "cloth") {- geometry = new ExtrudeGeometry(shape, { depth: DEPTH.cloth, bevelEnabled: false, curveSegments: 4 });- layer = "cloth";- } else if (part.detail) {- geometry = new ExtrudeGeometry(shape, { depth: DEPTH.detail, bevelEnabled: false, curveSegments: 4 });- geometry.translate(0, 0, metalBase + DEPTH.metal);- layer = part.finish === "gold" ? "goldDetail" : "silverDetail";- } else {- geometry = new ExtrudeGeometry(shape, {- depth: DEPTH.metal - 0.8, bevelEnabled: true, bevelThickness: 0.6, bevelSize: 0.55, bevelSegments: 2, curveSegments: 4,- });- geometry.translate(0, 0, metalBase + 0.6);- layer = part.finish as Finish as Layer;- }- // Merging needs one attribute layout; extrusions carry uv and normal alike.- const list = byLayer.get(layer) ?? [];- list.push(geometry.index ? geometry.toNonIndexed() : geometry);- byLayer.set(layer, list);- }- const built: Built[] = [];- for (const [layer, list] of byLayer) {- const merged = mergeGeometries(list, false);- if (!merged) continue;- if (wrapUnits) wrap(merged, wrapUnits);- else merged.computeVertexNormals();- built.push({ layer, geometry: merged });- }- builtCache.set(key, built);- return built;-}--/** Any piece of vector art (`rankArt.ts`) in 3D, `width` metres wide; `id` names it in the geometry cache. */-export function ArtPiece3D({ id, art, width, wrapRadius, cast = false, muted = false }: {- id: string; art: InsigniaArt; width: number;- /** Draw every layer in the muted pewter (a rank not reached yet). */- muted?: boolean;- /** Bend round a cylinder of this radius in metres (a sleeve, a cap's front). */- wrapRadius?: number;- cast?: boolean;-}) {- const s = width / art.w;- const parts = useMemo(() => buildArt(id, art, wrapRadius ? wrapRadius / s : null), [id, art, wrapRadius, s]);- if (parts.length === 0) return null;- return (- <group scale={s}>- {parts.map(({ layer, geometry }) => (- <mesh key={layer} geometry={geometry} material={muted ? REGALIA_MATERIALS.muted : REGALIA_MATERIALS[layer]} castShadow={cast} />- ))}- </group>- );-}--/** A rank's insignia, `width` metres wide; nothing for a private, who wears none. */-export function RankInsignia3D({ rank, width, wrapRadius, cast, muted }: {- rank: RankId; width: number; wrapRadius?: number; cast?: boolean; muted?: boolean;-}) {- return <ArtPiece3D id={`rank:${rank}`} art={rankArt(rank)} width={width} wrapRadius={wrapRadius} cast={cast} muted={muted} />;-}--/** The height of a rank's insignia at `width` metres wide. */-export function insigniaHeight(rank: RankId, width: number): number {- const art = rankArt(rank);- return (art.h / art.w) * width;-}--// ----------------------------------------------------------------------------// Where a figure wears it--/** Upper-sleeve patch of an enlisted rank: centred on the arm surface, bent round it. */-export function SleevePatch({ rank, armRadius, width = 0.07 }: { rank: RankId; armRadius: number; width?: number }) {- if (rankArt(rank).mount !== "sleeve") return null;- return <RankInsignia3D rank={rank} width={width} wrapRadius={armRadius} />;-}--/** The shoulder board of an officer or general: its length runs along local +x, its top faces +y. */-export const BOARD = { length: 0.135, width: 0.066, thick: 0.012 };--function boardLook(tier: RankTier): { base: MeshStandardMaterial; edge: number } {- return tier === "general" ? { base: REGALIA_MATERIALS.boardBlack, edge: 0.012 } : { base: REGALIA_MATERIALS.boardNavy, edge: 0.004 };-}--export function ShoulderBoard({ rank }: { rank: RankId }) {- const art = rankArt(rank);- if (art.mount !== "shoulder") return null;- const { base, edge } = boardLook(RANK_INFO[rank].tier);- const { length: L, width: W, thick: T } = BOARD;- // The insignia's long axis (art y) runs along the board, fitted inside the braid.- const fit = Math.min((W - edge * 2) * 0.92, ((L - edge * 2 - 0.02) * 0.92 * art.w) / art.h);- return (- <group>- <mesh material={base} position={[0, T / 2, 0]} castShadow>- <boxGeometry args={[L, T, W]} />- </mesh>- {/* The pointed inner end that buttons at the collar. */}- <mesh material={base} position={[-L / 2, T / 2, 0]} rotation={[0, Math.PI / 4, 0]}>- <boxGeometry args={[W / Math.SQRT2, T, W / Math.SQRT2]} />- </mesh>- {/* Gold braid round the edge: a fine line for officers, a broad band for generals. */}- {[-1, 1].map((sz) => (- <mesh key={sz} material={REGALIA_MATERIALS.braid} position={[0.004, T + 0.0012, sz * (W / 2 - edge / 2)]}>- <boxGeometry args={[L - 0.008, 0.0024, edge]} />- </mesh>- ))}- <mesh material={REGALIA_MATERIALS.braid} position={[L / 2 - edge / 2, T + 0.0012, 0]}>- <boxGeometry args={[edge, 0.0024, W]} />- </mesh>- <mesh material={REGALIA_MATERIALS.braid} position={[-L / 2 - W * 0.36, T + 0.002, 0]}>- <cylinderGeometry args={[0.009, 0.009, 0.004, 16]} />- </mesh>- <group position={[0.008, T + 0.0024, 0]} rotation={[-Math.PI / 2, 0, -Math.PI / 2]}>- <RankInsignia3D rank={rank} width={fit} />- </group>- </group>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/regalia/ribbons.ts b/dodaios/ui/web/frontend/src/components/society/progression/regalia/ribbons.tsdeleted file mode 100644index 579ca8d72d..0000000000--- a/dodaios/ui/web/frontend/src/components/society/progression/regalia/ribbons.ts+++ /dev/null@@ -1,69 +0,0 @@-/**- * Service ribbons and medals: the striped silk bars worn above the left- * breast pocket and the full-size medals hung from them. One table drives- * the SVG icons, the canvas textures on the 3D ribbons and the medal discs,- * so a ribbon reads the same in the studio, on a figure and in the hall.- *- * Stripes are listed left to right as [colour, width]; widths are relative.- */--export interface RibbonSpec {- id: string;- stripes: readonly (readonly [string, number])[];- /** The medal hung from this ribbon: its metal and shape. */- medal: { metal: "bronze" | "gold" | "silver"; shape: "disc" | "star" | "cross" };-}--const R = "#b3202a", W = "#f4f1e8", B = "#1f3b7a", Y = "#e9b928", G = "#1e6b3a", K = "#1a1a1a", L = "#5b9bd5", O = "#d8752b";--/** In order of precedence, highest first: the rack fills from the top left. */-export const RIBBONS: readonly RibbonSpec[] = [- { id: "distinguished", stripes: [[B, 3], [W, 1], [R, 6], [W, 1], [B, 3]], medal: { metal: "gold", shape: "star" } },- { id: "meritorious", stripes: [[R, 2], [W, 1], [R, 6], [W, 1], [R, 2]], medal: { metal: "bronze", shape: "star" } },- { id: "commendation", stripes: [[W, 1], [G, 3], [W, 1], [G, 2], [W, 1], [G, 3], [W, 1]], medal: { metal: "bronze", shape: "cross" } },- { id: "achievement", stripes: [[W, 1], [G, 2], [W, 1], [B, 2], [W, 1], [G, 2], [W, 1]], medal: { metal: "bronze", shape: "disc" } },- { id: "good_conduct", stripes: [[R, 2], [W, 0.6], [R, 2], [W, 0.6], [R, 2], [W, 0.6], [R, 2]], medal: { metal: "bronze", shape: "disc" } },- { id: "national_defense", stripes: [[R, 2], [W, 0.6], [B, 0.6], [W, 0.6], [R, 0.6], [Y, 3], [R, 0.6], [W, 0.6], [B, 0.6], [W, 0.6], [R, 2]], medal: { metal: "bronze", shape: "disc" } },- { id: "service", stripes: [[R, 1], [O, 1], [Y, 1], [G, 1], [L, 1], [B, 1], [K, 0.6], [B, 1], [L, 1], [G, 1], [Y, 1], [O, 1], [R, 1]], medal: { metal: "bronze", shape: "disc" } },- { id: "overseas", stripes: [[B, 1], [Y, 1], [G, 1], [Y, 2], [R, 1], [Y, 2], [G, 1], [Y, 1], [B, 1]], medal: { metal: "bronze", shape: "disc" } },- { id: "leadership", stripes: [[Y, 1], [B, 1], [W, 1], [R, 3], [W, 1], [B, 1], [Y, 1]], medal: { metal: "silver", shape: "disc" } },-];--/** A ribbon's stripes as [x, width, colour] spans across a bar `width` wide. */-export function ribbonSpans(spec: RibbonSpec, width: number): [number, number, string][] {- const total = spec.stripes.reduce((sum, [, w]) => sum + w, 0);- let x = 0;- return spec.stripes.map(([colour, w]) => {- const span: [number, number, string] = [x, (w / total) * width, colour];- x += (w / total) * width;- return span;- });-}--/** Paints a ribbon onto a canvas, with a soft silk sheen and a dark edge. */-export function paintRibbon(ctx: CanvasRenderingContext2D, spec: RibbonSpec, w: number, h: number): void {- for (const [x, sw, colour] of ribbonSpans(spec, w)) {- ctx.fillStyle = colour;- ctx.fillRect(Math.floor(x), 0, Math.ceil(sw) + 1, h);- }- const sheen = ctx.createLinearGradient(0, 0, 0, h);- sheen.addColorStop(0, "rgba(255,255,255,0.28)");- sheen.addColorStop(0.45, "rgba(255,255,255,0)");- sheen.addColorStop(1, "rgba(0,0,0,0.25)");- ctx.fillStyle = sheen;- ctx.fillRect(0, 0, w, h);- ctx.strokeStyle = "rgba(0,0,0,0.45)";- ctx.lineWidth = Math.max(1, h * 0.06);- ctx.strokeRect(0, 0, w, h);-}--export const MEDAL_METALS: Record<RibbonSpec["medal"]["metal"], { face: string; edge: string }> = {- bronze: { face: "#b9833f", edge: "#6d4a1e" },- gold: { face: "#e2b54e", edge: "#80601a" },- silver: { face: "#d6dbe2", edge: "#6f7784" },-};--/** How many ribbons each decoration wears, rows of three like a real rack. */-export const RACK_SIZE = { decoration_ribbon_bar: 3, decoration_ribbon_rack: 9, decoration_aiguillette: 9, decoration_medals: 9 } as const;-/** The full-size medals worn with the top decoration: the five highest. */-export const MEDAL_COUNT = 5;diff --git a/dodaios/ui/web/frontend/src/components/society/progression/useProgressionSync.ts b/dodaios/ui/web/frontend/src/components/society/progression/useProgressionSync.tsindex cfb649cc5d..b8448a2688 100644--- a/dodaios/ui/web/frontend/src/components/society/progression/useProgressionSync.ts+++ b/dodaios/ui/web/frontend/src/components/society/progression/useProgressionSync.ts@@ -1,19 +1,18 @@/**- * Keeps the Verse's level state in step with the server while the map is- * open, and reports the world actions the server meters.+ * Keeps the ship's level state in step with the server while the Verse is+ * open, and reports the world actions only the visit itself knows about.*- * - First read on mount (with the level-ups missed while the map was closed),- * then a slow jittered re-read as a safety net (AP-33); live awards arrive- * as `ProgressionAwarded` pushes over the existing WebSocket.- * - Daily visit and each floor discovered, a pet or a treat for the office- * dog, a team gathered at the table: reported once each, the server- * decides whether they pay.+ * - First read on mount (with the level-ups missed while the ship was+ * closed), then a slow jittered re-read as a safety net (AP-33); live awards+ * arrive as `ProgressionAwarded` pushes over the existing WebSocket.+ * - The day's first visit and each deck discovered are reported once each;+ * the server decides whether they pay. Holodeck rounds, briefings and warp+ * jumps are reported by the stations that see them (`ShipActions.reportAction`).*/import { useEffect, useRef } from "react";import { useEventStore } from "@/store/events";import { useCompanionPet } from "../companion/companionPetStore";-import { useOfficeDog } from "../office/dogLife";-import { useOfficeStore, type OfficeFloor } from "../office/officeStore";+import { DECKS } from "../starship/plan/types";import { fetchProgression, parseAwardEvent, reportWorldAction } from "./progressionApi";import { awayCelebrations, readSeenSeq, useProgression, writeSeenSeq } from "./progressionStore";import { playLevelUp, playXpTick } from "./levelSounds";@@ -23,21 +22,22 @@ const RESYNC_JITTER_MS = 15_000;/** Ticks for "+XP" closer together than this are one sound. */const TICK_GAP_MS = 400;/**- * The floors the server pays a first visit for (`VERSE_FLOORS` in dodaios/progression/service.py). A backend- * started before the Level Hall became a floor refuses "hall"; the report is best-effort, so that costs nothing- * but a line in the console. `verseFloors.test.ts` holds this list, the server's and the elevator's together.+ * The decks the server pays a first visit for (`VERSE_DECKS` in dodaios/progression/service.py).+ * `verseFloors.test.ts` holds this list, the server's and the ship's together.*/-export const METERED_FLOORS: ReadonlySet<OfficeFloor> = new Set<OfficeFloor>(["agents", "coding", "arcade", "hall"]);+export const METERED_DECKS: ReadonlySet<string> = new Set<string>(DECKS);-export function useProgressionSync(awake: boolean, floor: OfficeFloor): void {+/** `deck`: the deck the captain is on; a value that is not a deck id is simply not reported. */+export function useProgressionSync(awake: boolean, deck: string): void {const seen = useRef<number>(0);- // First read, then the slow safety net while the map is on screen.+ // First read, then the slow safety net while the ship is on screen.useEffect(() => {if (!awake) return;let cancelled = false;let timer: ReturnType<typeof setTimeout> | undefined;const load = async (first: boolean) => {+ let next = false;try {const snapshot = await fetchProgression();if (cancelled) return;@@ -46,10 +46,11 @@ export function useProgressionSync(awake: boolean, floor: OfficeFloor): void {seen.current = Math.max(seen.current, snapshot.latestSeq);writeSeenSeq(seen.current);} catch (error) {- // The Verse plays on without levels; the next read tries again.- console.debug("Verse levels unavailable", error);+ // The ship flies on without levels; the next read tries again (and is still the first that tells what happened away).+ console.debug("Ship levels unavailable", error);+ next = first;}- if (!cancelled) timer = setTimeout(() => void load(false), RESYNC_MS + Math.random() * RESYNC_JITTER_MS);+ if (!cancelled) timer = setTimeout(() => void load(next), RESYNC_MS + Math.random() * RESYNC_JITTER_MS);};void load(true);return () => { cancelled = true; clearTimeout(timer); };@@ -82,18 +83,7 @@ export function useProgressionSync(awake: boolean, floor: OfficeFloor): void {const petId = useCompanionPet((s) => s.pet.id);useEffect(() => { useProgression.getState().setPetId(petId); }, [petId]);- // The day's first visit and every floor discovered.+ // The day's first visit and every deck discovered.useEffect(() => { if (awake) void reportWorldAction("daily_visit"); }, [awake]);- useEffect(() => { if (awake && METERED_FLOORS.has(floor)) void reportWorldAction("floor_discovered", floor); }, [awake, floor]);-- // The office dog: a pat, a treat.- useEffect(() => useOfficeDog.subscribe((state, prev) => {- if (state.petSeq !== prev.petSeq) void reportWorldAction("dog_petted");- if (state.treatSeq !== prev.treatSeq) void reportWorldAction("dog_treat");- }), []);-- // A team gathered at the team-room table.- useEffect(() => useOfficeStore.subscribe((state, prev) => {- if (state.meeting && state.meeting.groupId !== prev.meeting?.groupId) void reportWorldAction("team_meeting");- }), []);+ useEffect(() => { if (awake && METERED_DECKS.has(deck)) void reportWorldAction("deck_discovered", deck); }, [awake, deck]);}diff --git a/dodaios/ui/web/frontend/src/components/society/progression/verseFloors.test.ts b/dodaios/ui/web/frontend/src/components/society/progression/verseFloors.test.tsindex ef201778bc..c7458bf69f 100644--- a/dodaios/ui/web/frontend/src/components/society/progression/verseFloors.test.ts+++ b/dodaios/ui/web/frontend/src/components/society/progression/verseFloors.test.ts@@ -1,35 +1,38 @@/**- * The Verse's floors are listed in three places: the server's `VERSE_FLOORS`- * (which floors a `floor_discovered` report may name), the client's- * `METERED_FLOORS` (which floors it reports) and the elevator's- * `OFFICE_FLOORS` (which floors exist). A floor missing from one of them is- * either never paid or refused by the server, so they are held together here.+ * The ship's decks are listed in three places: the server's `VERSE_DECKS`+ * (which decks a `deck_discovered` report may name), the client's+ * `METERED_DECKS` (which decks it reports) and the ship's `DECKS` (which decks+ * exist). A deck missing from one of them is either never paid or refused by+ * the server, so they are held together here.*/import { readFileSync } from "node:fs";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";-import { OFFICE_FLOORS } from "../office/officeStore";+import { DECKS } from "../starship/plan/types";import { reportWorldAction } from "./progressionApi";-import { METERED_FLOORS } from "./useProgressionSync";+import { METERED_DECKS } from "./useProgressionSync";const SRC = join(__dirname, "..", "..", "..");-/** `VERSE_FLOORS` as the backend declares it. */-function serverFloors(): string[] {+/** `VERSE_DECKS` as the backend declares it. */+function serverDecks(): string[] {const py = readFileSync(join(SRC, "..", "..", "..", "..", "progression", "service.py"), "utf8");- const block = /^VERSE_FLOORS\s*=\s*frozenset\(\{([^}]*)\}\)/m.exec(py);- if (!block) throw new Error("VERSE_FLOORS is no longer a frozenset literal in dodaios/progression/service.py");+ const block = /^VERSE_DECKS\s*=\s*frozenset\(\{([^}]*)\}\)/m.exec(py);+ if (!block) throw new Error("VERSE_DECKS is no longer a frozenset literal in dodaios/progression/service.py");return [...block[1].matchAll(/"([a-z_]+)"/g)].map((m) => m[1]);}-describe("the Verse's floors", () => {- it("are the same on the server, in the reports and in the elevator", () => {- const server = serverFloors().sort();- expect(server.length).toBeGreaterThan(0);- expect([...METERED_FLOORS].sort()).toEqual(server);- expect([...OFFICE_FLOORS].sort()).toEqual(server);- // No floor is listed twice in the elevator.- expect(new Set(OFFICE_FLOORS).size).toBe(OFFICE_FLOORS.length);+describe("the ship's decks", () => {+ it("are the same on the server, in the reports and on the ship", () => {+ const server = serverDecks().sort();+ expect(server).toEqual(["bridge", "engineering", "holodeck", "honors", "ops"]);+ expect([...METERED_DECKS].sort()).toEqual(server);+ expect([...DECKS].sort()).toEqual(server);+ expect(new Set(DECKS).size).toBe(DECKS.length);+ });++ it("do not include what is not a deck (the stage may pass anything)", () => {+ for (const notADeck of ["agents", "coding", "arcade", "hall", ""]) expect(METERED_DECKS.has(notADeck)).toBe(false);});});@@ -56,16 +59,23 @@ describe("reporting a world action", () => {it("says nothing when the server takes it", async () => {const server = serverAnswering(200);- await reportWorldAction("floor_discovered", "hall");- expect(server.requests).toEqual([{ url: "/api/progression/actions", body: { action: "floor_discovered", ref: "hall" } }]);+ await reportWorldAction("deck_discovered", "honors");+ expect(server.requests).toEqual([{ url: "/api/progression/actions", body: { action: "deck_discovered", ref: "honors" } }]);expect(server.warned).toEqual([]);});+ it("sends the retro games' arcade names as holodeck rounds", async () => {+ const server = serverAnswering(200);+ await reportWorldAction("arcade_round");+ await reportWorldAction("arcade_record");+ expect(server.requests.map((r) => (r.body as { action: string }).action)).toEqual(["holodeck_round", "holodeck_record"]);+ });+it("logs a report the server refuses instead of dropping it, and does not throw", async () => {- const server = serverAnswering(400);- await expect(reportWorldAction("floor_discovered", "attic")).resolves.toBeUndefined();+ const server = serverAnswering(422);+ await expect(reportWorldAction("warp_jump", "andromeda")).resolves.toBeUndefined();expect(server.warned).toHaveLength(1);- expect(server.warned[0]).toEqual(["Level action refused", "floor_discovered", "attic", 400]);+ expect(server.warned[0]).toEqual(["Level action refused", "warp_jump", "andromeda", 422]);});it("stays quiet about an unreachable backend, and does not throw", async () => {diff --git a/dodaios/ui/web/frontend/src/components/society/starship/ShipStage.tsx b/dodaios/ui/web/frontend/src/components/society/starship/ShipStage.tsxnew file mode 100644index 0000000000..fa602f92e3--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/ShipStage.tsx@@ -0,0 +1,576 @@+/**+ * Agents > Dodaios Verse: the starship. The captain (the person) walks the+ * decks; the agents are the crew, androids at their consoles who live their+ * day by their real run state. Stations turn the ship's places into the+ * app's actions: the transporter beams in a new agent, a division's+ * holo-table opens its team, the turbolift rides to another deck.+ */+import { Component, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { Canvas, useFrame, type ThreeEvent } from "@react-three/fiber";+import { useQueryClient } from "@tanstack/react-query";+import { useReducedMotion } from "framer-motion";+import { ArrowUpDown, Crosshair, Map as MapIcon, CircleHelp } from "lucide-react";+import { CanvasActivity, useCanvasAwake } from "@/hooks/useCanvasAwake";+import { useWebglSurface } from "@/hooks/useWebglSurface";+import { useWebglSupported } from "@/lib/graphDimension";+import { useLocaleChunk, useT } from "@/i18n";+import { useEventStore } from "@/store/events";+import { chatGroupsKnown, useSocietyChatGroups } from "@/lib/societyChatGroups";+import { useQuickCreateAgent, useSocietyRoster, type SocietyAgent } from "../data";+import { isCreateCancelled } from "../create/createAgentStore";+import { resolveCompanion } from "../companion/appearance";+import { useSyncCompanionPet } from "../companion/companionPetStore";+import { AgentSwatch } from "../AgentSwatch";+import { creatureFromShape } from "../companion/creature";+import { growsCreature, useCreatureDefault } from "../companion/creatureDefault";+import { useDeskChats } from "../crewFeeds/useDeskChats";+import { useTeamRounds } from "../crewFeeds/useTeamRounds";+import { useTeamwork } from "../crewFeeds/teamwork";+import { useProgression } from "../progression/progressionStore";+import { useProgressionSync } from "../progression/useProgressionSync";+import { suitFor } from "../progression/cosmetics";+import { ServiceRecord } from "./levels/ServiceRecord";+import { PromotionLayer } from "./levels/PromotionCeremony";+import { reportWorldAction } from "../progression/progressionApi";+import type { WorldAction } from "../progression/levelCatalog";+import { useCodingFloorOccupants } from "../crewFeeds/codingFloor";+import { openPaneSession } from "../crewFeeds/codingNavigate";+import { deckModule, type ShipActions } from "./decks/registry";+import "./decks";+import { buildNavGrid, nearestFree } from "./nav/shipNav";+import type { CrewInput, DeckId, DeckPlan, Prop, Station, TeamInput } from "./plan/types";+import { DECKS, deckNumber } from "./plan/types";+import { captain, useShip } from "./shipStore";+import { CameraRig, CAMERA_FOV, orbit } from "./render/CameraRig";+import { DeckLights, PostFx, RendererSetup, type Quality } from "./render/ShipRenderer";+import { ConsoleScreens, HoloTables, RoomSigns, SlidingDoors, StaticDeck, StationHalo, StationTargets, TransporterBeam } from "./render/deck/DeckScene";+import type { ScreenContent } from "./render/deck/screens";+import { SpaceBackdrop } from "./space/SpaceBackdrop";+import { destinationById } from "./space/destinations";+import { CrewLayer, crewPoses, type CrewView } from "./life/CrewLayer";+import { CaptainFigure, typesText, walkCaptainTo } from "./life/Captain";+import { ShipPet } from "./life/ShipPet";+import type { RoundView } from "./life/crewLife";+import { FaceAtlas, type FaceLook } from "./crew/faceAtlas";+import { faceMaterial } from "./crew/figure";+import { PlateDriver, PlateLayer } from "./hud/Plates";+import { rankFor } from "./levels/ranks";+import "./hud/ship.css";++export interface ShipStageProps {+ onOpenLedger?: () => void;+ onSelectAgent?: (id: string | null) => void;+ onCreateAgent?: () => void;+ onOpenGroup?: (groupId: string) => void;+ /** The deck to show on mount (the IDE tab opens on engineering). */+ initialDeck?: DeckId;+ compact?: boolean;+ /** A visited map keeps its renderer while its host shows something else. */+ active?: boolean;+}++class RenderBoundary extends Component<{ children: ReactNode; fallback: string }, { failed: boolean }> {+ state = { failed: false };+ static getDerivedStateFromError() { return { failed: true }; }+ componentDidCatch(error: Error) { console.warn("Ship renderer unavailable", error); }+ render() { return this.state.failed ? <div className="ship-fallback" role="status">{this.props.fallback}</div> : this.props.children; }+}++// Dev-only handles for runtime checks: the captain, the store, the camera orbit and the crew's poses.+if (import.meta.env.DEV && typeof window !== "undefined") Object.assign(window, { __ship: { captain, useShip, orbit, crewPoses } });++const REFRESH_MS = 5000;++function useRosterRefresh(awake: boolean) {+ const client = useQueryClient();+ useEffect(() => {+ if (!awake) return;+ let timer: ReturnType<typeof setTimeout>;+ const schedule = () => {+ timer = setTimeout(() => { void client.invalidateQueries({ queryKey: ["society", "roster"] }); schedule(); }, REFRESH_MS + Math.random() * 1500);+ };+ schedule();+ return () => clearTimeout(timer);+ }, [awake, client]);+}++export function faceLookOf(agent: Pick<SocietyAgent, "agentId" | "figure">, creaturesByDefault: boolean): FaceLook {+ const look = resolveCompanion(agent.agentId, agent.figure?.companion);+ const creature = look.creature ?? (growsCreature(look, creaturesByDefault) ? creatureFromShape(look) : undefined);+ return creature ? { kind: "creature", creature } : { kind: "shape", shape: look.shape, color: look.color };+}++/** How long a newcomer counts as one (it walks from the transporter, the pad glows). */+const NEWCOMER_MS = 12_000;++/**+ * Crew that joined while the ship was open, per deck: they beam in at the+ * transporter and walk to their place. The first crew a deck shows is simply+ * aboard, so riding to a deck never makes its whole crew arrive.+ */+function useNewcomers(deck: DeckId, ids: readonly string[], ready: boolean): ReadonlySet<string> {+ const known = useRef(new Map<DeckId, Set<string>>());+ const timers = useRef<ReturnType<typeof setTimeout>[]>([]);+ const [fresh, setFresh] = useState<{ deck: DeckId; ids: ReadonlySet<string> }>({ deck, ids: new Set() });+ useEffect(() => {+ if (!ready) return;+ const seen = known.current.get(deck);+ if (!seen) { known.current.set(deck, new Set(ids)); return; }+ const added = ids.filter((id) => !seen.has(id));+ for (const id of ids) seen.add(id);+ if (added.length === 0) return;+ setFresh((prev) => ({ deck, ids: new Set([...(prev.deck === deck ? prev.ids : []), ...added]) }));+ // Not cleared by the next change of `ids` (the roster refreshes every few seconds): only by unmounting.+ timers.current.push(setTimeout(() => setFresh((prev) => (prev.deck === deck ? { deck, ids: new Set([...prev.ids].filter((id) => !added.includes(id))) } : prev)), NEWCOMER_MS));+ }, [deck, ids, ready]);+ useEffect(() => () => { for (const t of timers.current) clearTimeout(t); }, []);+ return fresh.deck === deck ? fresh.ids : EMPTY_SET;+}+const EMPTY_SET: ReadonlySet<string> = new Set();++export function ShipStage({ onOpenLedger, onSelectAgent, onCreateAgent, onOpenGroup, initialDeck, compact = false, active: onScreen = true }: ShipStageProps) {+ const t = useT();+ const chunkReady = useLocaleChunk("ship");+ const hostRef = useRef<HTMLDivElement>(null);+ const visible = useCanvasAwake(hostRef);+ const awake = onScreen && visible;+ const reduced = useReducedMotion() ?? false;+ const { generation } = useWebglSurface(hostRef);+ const webgl = useWebglSupported();+ const [quality] = useState<Quality>(() => (typeof navigator !== "undefined" && (navigator.hardwareConcurrency ?? 8) < 4 ? "low" : "high"));++ // The deck store is shared by every mounted stage (the Agents view and the IDE tab): each host remembers+ // its own deck and takes it back when it comes on screen; the IDE tab always opens on engineering.+ const hostDeck = useRef<DeckId | null>(initialDeck ?? null);+ useEffect(() => {+ if (!awake) return;+ const want = initialDeck ?? hostDeck.current;+ if (want && useShip.getState().deck !== want) useShip.getState().setDeck(want);+ // On waking only.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [awake]);+ const deck = useShip((s) => s.deck);+ useEffect(() => { if (awake && !initialDeck) hostDeck.current = deck; }, [awake, deck, initialDeck]);+ const module = deckModule(deck) ?? deckModule("ops");+ const population = module?.population ?? "agents";++ const roster = useSocietyRoster(awake);+ // The captain's companion is the pet chosen in My Pets.+ useSyncCompanionPet();+ const coding = useCodingFloorOccupants(awake && population === "panes");+ const panes = coding.occupants;+ useRosterRefresh(awake && population === "agents");+ const groups = useSocietyChatGroups(awake && population === "agents");+ const teamsKnown = chatGroupsKnown(groups);+ const jarvisAgents = useMemo(() => (roster.data?.agents ?? []).filter((a) => a.lifecycle !== "archived"), [roster.data]);+ // Engineering's crew are the coding panes, each projected into a crew member.+ const agents = useMemo(() => (population === "panes" ? panes.map((o) => o.agent) : jarvisAgents), [population, panes, jarvisAgents]);+ const byId = useMemo(() => new Map(agents.map((a) => [a.agentId, a])), [agents]);+ const teams = useMemo<TeamInput[]>(() => (groups.data ?? []).map((g) => ({+ id: g.group_id, name: g.name, members: g.members, createdMs: g.created_ms, leadId: g.lead_agent_id ?? null,+ })), [groups.data]);+ const crewInputs = useMemo<CrewInput[]>(() => (population === "panes" || (population === "agents" && teamsKnown) ? agents : []).map((a) => ({+ agentId: a.agentId, name: a.name, tier: a.tier, state: a.state, createdMs: a.createdMs,+ })), [agents, population, teamsKnown]);+ const ready = population === "none" || (population === "panes" ? coding.loaded : !!roster.data && teamsKnown);++ // The plan depends on who belongs where, never on run state.+ const teamsKey = teams.map((tm) => `${tm.id}|${tm.name}|${tm.createdMs}|${tm.leadId ?? ""}|${tm.members.join("+")}`).join(",");+ const paneKey = population === "panes" ? panes.map((o) => `${o.agent.agentId}|${o.pane.workspace_id}`).join(",") : "";+ const seatingKey = `${paneKey}${deck}:${crewInputs.map((c) => `${c.agentId}|${c.tier}|${c.createdMs}`).join(",")}#${teamsKey}`;+ const plan = useMemo<DeckPlan | null>(() => {+ if (!module) return null;+ try { return module.build({ crew: crewInputs, teams, panes }); }+ catch (error) { console.warn("Deck plan failed", error); return null; }+ },+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [seatingKey]);+ const grid = useMemo(() => (plan ? buildNavGrid(plan) : null), [plan]);++ // Levels.+ useProgressionSync(awake, deck);+ const record = useProgression((s) => s.record);+ const suitChoice = useProgression((s) => s.suit);+ const rewards = useProgression((s) => s.snapshot?.rewards);+ const subjects = useProgression((s) => s.subjects);+ const levelOf = useCallback((agentId: string) => subjects[`agent:${agentId}`]?.level ?? 1, [subjects]);+ const captainLevel = subjects.person?.level ?? 1;++ // Faces.+ const creaturesByDefault = useCreatureDefault((s) => s.enabled);+ const atlas = useMemo(() => new FaceAtlas(), []);+ const faceMat = useMemo(() => faceMaterial(atlas.texture), [atlas]);+ useEffect(() => () => { faceMat.dispose(); atlas.texture.dispose(); }, [atlas, faceMat]);++ const divisionOf = useMemo(() => {+ const m = new Map<string, DeckPlan["divisions"][number]>();+ for (const d of plan?.divisions ?? []) for (const id of d.members) m.set(id, d);+ return m;+ }, [plan]);+ const crew = useMemo<CrewView[]>(() => crewInputs.filter((c) => plan?.seatOf.has(c.agentId) || plan?.unseated.includes(c.agentId)).map((c) => {+ const agent = byId.get(c.agentId);+ const d = divisionOf.get(c.agentId);+ const rank = rankFor(levelOf(c.agentId));+ return {+ agentId: c.agentId, name: c.name, state: c.state, division: d?.room ?? null,+ face: agent ? faceLookOf(agent, creaturesByDefault) : { kind: "shape", shape: "circle", color: "#5fd4ff" },+ accent: d?.colour ?? "#8aa4c8", pips: rank.pips, gold: rank.gold, lead: !!d && d.leadId === c.agentId,+ ribbons: (rewards ?? []).filter((r) => r.slot === "decoration" && r.levels.agent !== null && levelOf(c.agentId) >= (r.levels.agent ?? 99)).length,+ };+ }), [crewInputs, plan, byId, divisionOf, levelOf, creaturesByDefault, rewards]);+ const newcomers = useNewcomers(deck, useMemo(() => crew.map((c) => c.agentId), [crew]), ready && population !== "none" && !!plan);++ // Team rounds feed the holo-tables and the gatherings.+ const watchTeams = useMemo(() => (plan?.divisions ?? []).map((d) => ({ teamId: d.teamId, members: d.members })) as never, [plan]);+ useTeamRounds(watchTeams, byId, awake && population === "agents");+ const rawRounds = useTeamwork((s) => s.rounds);+ const rounds = useMemo(() => {+ const m = new Map<string, RoundView>();+ for (const d of plan?.divisions ?? []) {+ const r = d.teamId ? rawRounds[d.teamId] : undefined;+ if (r?.running) m.set(d.room, { running: true, speakerId: r.speakerId });+ }+ return m;+ }, [plan, rawRounds]);++ // Console screens: the tail of each agent's chat.+ const sessions = useMemo(() => new Map(agents.filter((a) => a.chatSessionId).map((a) => [a.agentId, a.chatSessionId as string])), [agents]);+ const chats = useDeskChats(sessions, awake && population === "agents");++ const gathering = useShip((s) => s.gathering);+ const called = useMemo(() => (gathering && gathering.untilMs > Date.now() ? { place: gathering.place, agentIds: gathering.agentIds } : null), [gathering]);+ useEffect(() => {+ if (!gathering) return;+ const timer = setTimeout(() => useShip.getState().gather(null), Math.max(0, gathering.untilMs - Date.now()));+ return () => clearTimeout(timer);+ }, [gathering]);++ const chosenLook = useShip((st) => st.captainLook);+ // The cut of the suit is the level system's: the finest open one, or the one the captain chose.+ const look = useMemo(() => ({ ...chosenLook, cut: suitFor(rewards ?? [], captainLevel, suitChoice)?.replace(/^suit_/, "") ?? null }),+ [chosenLook, rewards, captainLevel, suitChoice]);+ const destinationId = useShip((s) => s.destination);+ const destination = useMemo(() => destinationById(destinationId), [destinationId]);++ // Interaction.+ const selection = useShip((s) => s.selection);+ const following = useShip((s) => s.follow);+ const nearby = useShip((s) => s.nearby);+ const hovered = useShip((s) => s.hovered);+ const [lift, setLift] = useState(false);+ const [doors, setDoors] = useState(false);+ const [notice, setNotice] = useState<string | null>(null);+ const timers = useRef<ReturnType<typeof setTimeout>[]>([]);+ useEffect(() => () => { for (const timer of timers.current) clearTimeout(timer); }, []);+ const later = useCallback((fn: () => void, ms: number) => { timers.current.push(setTimeout(fn, ms)); }, []);+ const say = useCallback((text: string) => {+ setNotice(text);+ later(() => setNotice((n) => (n === text ? null : n)), 4200);+ }, [later]);+ const quickCreate = useQuickCreateAgent();+ const creating = useRef(false);+ const createAgent = useCallback(() => {+ if (onCreateAgent) { onCreateAgent(); return; }+ if (creating.current) return;+ creating.current = true;+ void quickCreate().catch((e) => { if (!isCreateCancelled(e)) console.warn("Agent creation failed", e); }).finally(() => { creating.current = false; });+ }, [onCreateAgent, quickCreate]);+ const openAgent = useCallback((id: string) => {+ const pane = panes.find((o) => o.agent.agentId === id);+ if (pane) { openPaneSession(pane.pane); return; }+ if (onSelectAgent) onSelectAgent(id);+ else useEventStore.getState().setActiveSection("agents");+ }, [onSelectAgent, panes]);++ const [panel, setPanel] = useState<string | null>(null);+ useEffect(() => setPanel(null), [deck]);+ const rideRef = useRef<(to: DeckId) => void>(() => undefined);+ const actions = useMemo<ShipActions>(() => ({+ t, say, openAgent, createAgent,+ openLedger: () => { if (onOpenLedger) onOpenLedger(); else useEventStore.getState().setActiveSection("agents"); },+ openGroup: (id) => { if (onOpenGroup) onOpenGroup(id); else useEventStore.getState().setActiveSection("agents"); },+ openSection: (section) => useEventStore.getState().setActiveSection(section as never),+ ride: (to) => rideRef.current(to),+ sit: (seat) => { captain.seated = seat; if (seat) captain.path = []; },+ openPanel: (id) => setPanel(id),+ closePanel: () => setPanel(null),+ reportAction: (action, ref = "") => { void reportWorldAction(action as WorldAction, ref); },+ }), [t, say, openAgent, createAgent, onOpenLedger, onOpenGroup]);++ const activateStation = useCallback((station: Station) => {+ if (!plan) return;+ const far = Math.hypot(captain.x - station.x, captain.z - station.z) > station.radius + 0.6;+ if (module?.useStation?.(station, plan, actions, far)) return;+ switch (station.kind) {+ case "transporter": createAgent(); return;+ case "lift":+ if (far) { useShip.getState().requestWalk({ x: station.x, z: station.z }); return; }+ setLift(true); return;+ case "division": {+ const division = plan.divisions.find((d) => `division:${d.room}` === station.id);+ if (division?.teamId && onOpenGroup) onOpenGroup(division.teamId);+ else if (onOpenLedger) onOpenLedger();+ return;+ }+ case "newDivision": if (onOpenLedger) onOpenLedger(); else useEventStore.getState().setActiveSection("agents"); return;+ case "mess": {+ const free = crew.filter((c) => c.state === "idle").map((c) => c.agentId);+ const store = useShip.getState();+ if (store.gathering?.place === "mess") { store.gather(null); say(t("ship.station.mess.ended")); return; }+ if (free.length === 0) { say(t("ship.station.mess.nobody")); return; }+ store.gather({ place: "mess", agentIds: free, untilMs: Date.now() + 90_000 });+ say(t("ship.station.mess.called").replace("{count}", String(free.length)));+ return;+ }+ case "rankWall": useProgression.getState().openRecord("ranks"); return;+ case "honorCase": useProgression.getState().openRecord("rewards"); return;+ default: return;+ }+ }, [plan, module, actions, createAgent, onOpenGroup, onOpenLedger, crew, say, t]);++ // E uses the station the captain stands at; O overview, F follow, Escape closes.+ useEffect(() => {+ if (!awake) return;+ const key = (e: KeyboardEvent) => {+ if (typesText(e.target) || e.ctrlKey || e.metaKey || e.altKey) return;+ const host = hostRef.current;+ const activeEl = document.activeElement;+ if (activeEl && activeEl !== document.body && !host?.contains(activeEl)) return;+ if (e.code === "KeyE" && plan) {+ const s = plan.stations.find((st) => st.id === useShip.getState().nearby);+ if (s) { e.preventDefault(); activateStation(s); }+ } else if (e.code === "KeyO") useShip.getState().overview();+ else if (e.code === "KeyF") useShip.getState().setFollow(true);+ else if (e.code === "Escape") { setLift(false); setPanel(null); useShip.getState().select(null); }+ };+ window.addEventListener("keydown", key);+ return () => window.removeEventListener("keydown", key);+ }, [awake, plan, activateStation]);++ const rideTo = useCallback((to: DeckId) => {+ setLift(false);+ if (to === deck) return;+ if (reduced) { useShip.getState().setDeck(to); return; }+ setDoors(true);+ later(() => {+ useShip.getState().setDeck(to);+ later(() => setDoors(false), 650);+ }, 600);+ }, [deck, reduced, later]);+ rideRef.current = rideTo;++ const counts = useMemo(() => {+ const c = { working: 0, waiting: 0, idle: 0, paused: 0 };+ for (const m of crew) c[m.state] += 1;+ return c;+ }, [crew]);++ const stationText = useCallback((s: Station) => ({+ action: t(`ship.station.${s.kind}.action`),+ name: module?.stationName?.(s, t)+ ?? (s.kind === "division" ? (plan?.divisions.find((d) => `division:${d.room}` === s.id)?.name || t("ship.division.pool")) : t(`ship.station.${s.kind}.name`)),+ }), [t, plan, module]);+ const promptStation = plan?.stations.find((s) => s.id === (hovered?.kind === "station" ? hovered.id : nearby));+ const selectedAgent = selection?.kind === "agent" ? crew.find((c) => c.agentId === selection.id) : undefined;++ const screenContent = useCallback((p: Prop): ScreenContent => {+ const owner = p.ref ? byId.get(p.ref) : undefined;+ if (!owner) return { title: t("ship.screen.vacant"), state: "vacant", accent: p.accent ?? "#5fd4ff", stateLabel: t("ship.screen.vacant"), standby: t("ship.screen.vacant") };+ const lines = chats.get(owner.agentId)?.lines;+ return {+ title: owner.name, state: owner.state, accent: p.accent ?? "#5fd4ff", lines: owner.state === "idle" && !lines?.length ? undefined : lines,+ stateLabel: t(`ship.state.${owner.state}`), standby: t("ship.screen.standby"),+ };+ }, [byId, chats, t]);+ const divisionLabel = useCallback((d: DeckPlan["divisions"][number]) => (d.teamId ? d.name : t("ship.division.pool")), [t]);+ const roomText = useCallback((room: DeckPlan["rooms"][number]) => !room.sign ? null : "text" in room.sign ? room.sign.text : t(room.sign.key), [t]);+ const memberState = useCallback((id: string) => byId.get(id)?.state ?? "idle", [byId]);+ const bodies = useCallback(function* () {+ yield { x: captain.x, z: captain.z };+ for (const p of crewPoses.values()) if (p.moving) yield p;+ }, []);++ const floorClick = useCallback((e: ThreeEvent<MouseEvent>) => {+ if (!grid || e.button !== 0) return;+ e.stopPropagation();+ useShip.getState().select(null);+ walkCaptainTo(grid, { x: e.point.x, z: e.point.z });+ }, [grid]);++ const plates = useMemo(() => crew.map((c) => ({+ agentId: c.agentId, name: c.name, state: c.state,+ rank: t(`ship.rank.${rankFor(levelOf(c.agentId)).id}`),+ })), [crew, t, levelOf]);++ const captainRank = rankFor(captainLevel);+ const person = subjects.person;+ const xpShare = person && person.xpForNext > 0 ? Math.min(1, person.xpIntoLevel / person.xpForNext) : 0;++ const fallback = t("ship.fallback");+ return (+ <div ref={hostRef} className="ship-stage" data-compact={compact} tabIndex={-1} aria-label={t("ship.title")}>+ {!webgl ? <div className="ship-fallback">{fallback}</div> : (+ <RenderBoundary fallback={fallback}>+ <CanvasActivity.Provider value={awake}>+ <Canvas key={generation} frameloop={awake ? "always" : "never"} shadows dpr={[1, 1.75]}+ gl={{ antialias: false, powerPreference: "high-performance", stencil: false }}+ camera={{ fov: CAMERA_FOV, near: 0.1, far: 9000, position: [0, 20, 20] }}+ onPointerMissed={() => useShip.getState().select(null)}>+ <RendererSetup quality={quality} />+ <SpaceBackdrop destination={destination} reduced={reduced} />+ {plan && grid && (+ <>+ <DeckLights plan={plan} quality={quality} sunDirection={destination.sun.direction} />+ <StaticDeck plan={plan} />+ <mesh rotation={[-Math.PI / 2, 0, 0]} position={[(plan.bounds.x0 + plan.bounds.x1) / 2, 0.02, (plan.bounds.z0 + plan.bounds.z1) / 2]} onClick={floorClick}>+ <planeGeometry args={[plan.bounds.x1 - plan.bounds.x0, plan.bounds.z1 - plan.bounds.z0]} />+ <meshBasicMaterial visible={false} />+ </mesh>+ {population === "agents" && <ConsoleScreens plan={plan} content={screenContent} onScreen={(p) => p.ref && openAgent(p.ref)} />}+ <HoloTables plan={plan} label={divisionLabel} memberState={memberState} reduced={reduced} />+ <RoomSigns plan={plan} text={roomText} />+ <SlidingDoors plan={plan} bodies={bodies} />+ {plan.props.some((p) => p.kind === "transporter") && <TransporterBeam at={plan.arrival} active={newcomers.size > 0} reduced={reduced} />}+ <StationTargets plan={plan} onStation={activateStation} onHover={(s) => useShip.getState().hover(s ? { kind: "station", id: s.id } : null)} />+ <StationHalo plan={plan} id={promptStation?.id ?? null} />+ {module?.Scene && <module.Scene plan={plan} reduced={reduced} quality={quality} awake={awake} agents={byId} panes={panes} actions={actions} />}+ <CrewLayer plan={plan} grid={grid} crew={crew} rounds={rounds} called={called} atlas={atlas} faceMaterial={faceMat}+ reduced={reduced} newcomers={newcomers}+ onPick={(id) => useShip.getState().select({ kind: "agent", id })}+ onHover={(id) => useShip.getState().hover(id ? { kind: "agent", id } : null)} />+ <CaptainFigure plan={plan} grid={grid} look={look} pips={captainRank.pips} awake={awake} reduced={reduced} keyHost={hostRef} />+ <ShipPet grid={grid} reduced={reduced} onWalked={() => actions.reportAction("walk_together")} />+ <StationProximity plan={plan} />+ <CameraRig plan={plan} compact={compact} />+ <PlateDriver />+ </>+ )}+ <PostFx quality={quality} />+ </Canvas>+ </CanvasActivity.Provider>+ </RenderBoundary>+ )}+ {chunkReady && plan && (+ <>+ <PlateLayer plates={plates} onPick={(id) => useShip.getState().select({ kind: "agent", id })} />+ <div className="ship-hud">+ <section className="ship-panel ship-deck" aria-live="polite">+ <div className="ship-deck-number">{deckNumber(deck)}</div>+ <div className="ship-eyebrow">{t("ship.deck.label").replace("{n}", String(deckNumber(deck)))}</div>+ <div className="ship-deck-name">{t(`ship.deck.${deck}`)}</div>+ {population !== "none" && (+ <div className="ship-crewline">+ <span><i className="ship-dot" data-state="working" />{t("ship.crew.working").replace("{count}", String(counts.working))}</span>+ <span><i className="ship-dot" data-state="waiting" />{t("ship.crew.waiting").replace("{count}", String(counts.waiting))}</span>+ <span><i className="ship-dot" data-state="idle" />{t("ship.crew.idle").replace("{count}", String(counts.idle + counts.paused))}</span>+ </div>+ )}+ </section>+ {!compact && (+ <button type="button" className="ship-panel ship-rank" onClick={() => useProgression.getState().openRecord("record")}>+ <RankBadge pips={captainRank.pips} gold={captainRank.gold} />+ <span>+ <span className="ship-rank-title">{t(`ship.rank.${captainRank.id}`)}</span>+ <span className="ship-rank-sub"> · {t("ship.level").replace("{n}", String(captainLevel))}</span>+ </span>+ <span className="ship-xp"><i style={{ width: `${Math.round(xpShare * 100)}%` }} /></span>+ </button>+ )}+ <nav className="ship-panel ship-tools" aria-label={t("ship.tools.label")}>+ <button type="button" className="ship-tool" aria-pressed={following} title={t("ship.tools.follow")} aria-label={t("ship.tools.follow")} onClick={() => useShip.getState().setFollow(true)}><Crosshair size={17} /></button>+ <button type="button" className="ship-tool" title={t("ship.tools.overview")} aria-label={t("ship.tools.overview")} onClick={() => useShip.getState().overview()}><MapIcon size={17} /></button>+ <button type="button" className="ship-tool" title={t("ship.tools.lift")} aria-label={t("ship.tools.lift")} onClick={() => setLift(true)}><ArrowUpDown size={17} /></button>+ <button type="button" className="ship-tool" title={t("ship.tools.help")} aria-label={t("ship.tools.help")} onClick={() => say(t("ship.help"))}><CircleHelp size={17} /></button>+ </nav>+ {promptStation && !lift && !panel && (+ <button type="button" className="ship-panel ship-prompt" onClick={() => activateStation(promptStation)}>+ <span className="ship-key">{hovered?.kind === "station" && hovered.id === promptStation.id && nearby !== promptStation.id ? t("ship.click") : "E"}</span>+ <span>{stationText(promptStation).action}</span>+ <small>{stationText(promptStation).name}</small>+ </button>+ )}+ {notice && <div className="ship-panel ship-notice" role="status">{notice}</div>}+ {selectedAgent && (+ <section className="ship-panel ship-agent" aria-label={selectedAgent.name}>+ <button type="button" className="ship-tool ship-close" aria-label={t("ship.close")} onClick={() => useShip.getState().select(null)}>✕</button>+ <div className="ship-agent-head">+ <span className="ship-agent-face" style={{ borderColor: selectedAgent.accent }}>+ {byId.get(selectedAgent.agentId) && <AgentSwatch agent={{ ...(byId.get(selectedAgent.agentId) as SocietyAgent), state: undefined }} size={38} />}+ </span>+ <div>+ <div className="ship-agent-name">{selectedAgent.name}</div>+ <div className="ship-agent-meta">+ <i className="ship-dot" data-state={selectedAgent.state} />+ {t(`ship.state.${selectedAgent.state}`)}+ <span>·</span>+ {t(`ship.rank.${rankFor(levelOf(selectedAgent.agentId)).id}`)}+ </div>+ <div className="ship-agent-meta">{plan.divisions.find((d) => d.room === selectedAgent.division)?.name || t("ship.division.pool")}</div>+ </div>+ </div>+ <div className="ship-agent-actions">+ <button type="button" className="ship-btn" data-primary="true" onClick={() => openAgent(selectedAgent.agentId)}>{t("ship.agent.open_chat")}</button>+ <button type="button" className="ship-btn" onClick={() => {+ const p = crewPoses.get(selectedAgent.agentId);+ if (p && grid) { const at = nearestFree(grid, { x: p.x + 0.9, z: p.z + 0.4 }); if (at) useShip.getState().requestWalk(at); }+ }}>{t("ship.agent.walk_there")}</button>+ <button type="button" className="ship-btn" onClick={() => {+ const p = crewPoses.get(selectedAgent.agentId);+ if (p) useShip.getState().focusOn({ x: p.x, z: p.z });+ }}>{t("ship.agent.show")}</button>+ </div>+ </section>+ )}+ </div>+ {lift && (+ <div className="ship-scrim" onClick={() => setLift(false)}>+ <section className="ship-panel ship-lift" role="dialog" aria-modal="true" aria-label={t("ship.lift.title")} onClick={(e) => e.stopPropagation()}>+ <h2>{t("ship.lift.title")}</h2>+ <div className="ship-lift-list">+ {DECKS.filter((d) => deckModule(d)).map((d) => (+ <button key={d} type="button" className="ship-lift-row" aria-current={d === deck} autoFocus={d === deck} onClick={() => rideTo(d)}>+ <b>{deckNumber(d)}</b>+ <span>{t(`ship.deck.${d}`)}<small>{t(`ship.deck.${d}_about`)}</small></span>+ {d === deck && <small className="ship-eyebrow">{t("ship.lift.here")}</small>}+ </button>+ ))}+ </div>+ </section>+ </div>+ )}+ {panel && module?.Panel && plan.stations.some((s) => s.id === panel) && (+ <module.Panel plan={plan} station={plan.stations.find((s) => s.id === panel) as Station} actions={actions} agents={byId} panes={panes} />+ )}+ {awake && record && <ServiceRecord initialTab={record} onClose={() => useProgression.getState().openRecord(null)} />}+ {awake && <PromotionLayer />}+ <div className="ship-doors" data-shut={doors}><i /><i /></div>+ </>+ )}+ </div>+ );+}++/** Collar pips as a small badge: silver for enlisted ranks, gold for officers. */+export function RankBadge({ pips, gold }: { pips: number; gold: boolean }) {+ const metal = gold ? "#e1b04f" : "#c9cdd3";+ return (+ <svg width="34" height="34" viewBox="0 0 34 34" aria-hidden="true">+ <rect x="1" y="1" width="32" height="32" rx="8" fill="rgba(217,164,65,0.08)" stroke="rgba(217,164,65,0.45)" />+ <rect x="6" y="14" width="22" height="6" rx="2" fill="#1a1f27" stroke="rgba(255,255,255,0.12)" />+ {Array.from({ length: pips }, (_, i) => <circle key={i} cx={9.5 + i * 5} cy={17} r={1.9} fill={metal} />)}+ </svg>+ );+}++/** Which station the captain stands at. */+function StationProximity({ plan }: { plan: DeckPlan }) {+ useFrame(() => {+ let best: string | null = null, bd = Infinity;+ for (const s of plan.stations) {+ const d = Math.hypot(captain.x - s.x, captain.z - s.z);+ if (d < s.radius && d < bd) { bd = d; best = s.id; }+ }+ useShip.getState().setNearby(best);+ });+ return null;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/crew/faceAtlas.ts b/dodaios/ui/web/frontend/src/components/society/starship/crew/faceAtlas.tsnew file mode 100644index 0000000000..4376b7b278--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/crew/faceAtlas.ts@@ -0,0 +1,181 @@+/**+ * The androids' faces. Every crew member's head carries a glass display that+ * shows its own profile face: its pixel creature (painted by the same code+ * as the profile picture) or its shape with eyes, on a dark screen. All faces+ * share one atlas texture, so a deck of figures costs one face material.+ * A face is redrawn only when its frame changes (blinks, glances, the+ * thinking sweep), at most ten times a second.+ */+import { CanvasTexture, SRGBColorSpace } from "three";+import { creatureBody, creaturePose, CREATURE_TICK_MS, STAGE_H, STAGE_W, type CreatureLook, type CreatureState } from "../../companion/creature";+import { paintCreature } from "../../companion/creaturePaint";+import type { SymbolShape } from "../../companion/appearance";++export const ATLAS_COLS = 16;+export const ATLAS_ROWS = 8;+export const CELL_PX = 64;++export type FaceLook =+ | { kind: "creature"; creature: CreatureLook }+ | { kind: "shape"; shape: SymbolShape; color: string };++export type FaceMood = "idle" | "working" | "waiting" | "paused" | "talking";++const MOOD_STATE: Record<FaceMood, CreatureState> = {+ idle: "idle", working: "working", waiting: "asking", paused: "sleeping", talking: "talking",+};++interface Slot { index: number; look: FaceLook; mood: FaceMood; frame: number; key: string }++export class FaceAtlas {+ readonly canvas: HTMLCanvasElement;+ readonly texture: CanvasTexture;+ private readonly ctx: CanvasRenderingContext2D;+ private readonly scratch: HTMLCanvasElement;+ private readonly sctx: CanvasRenderingContext2D;+ private readonly slots = new Map<string, Slot>();+ private readonly free: number[] = [];+ private dirty = false;++ constructor() {+ this.canvas = document.createElement("canvas");+ this.canvas.width = ATLAS_COLS * CELL_PX;+ this.canvas.height = ATLAS_ROWS * CELL_PX;+ const ctx = this.canvas.getContext("2d");+ if (!ctx) throw new Error("2d canvas unavailable");+ this.ctx = ctx;+ this.scratch = document.createElement("canvas");+ this.scratch.width = 52;+ this.scratch.height = Math.round((52 / STAGE_W) * STAGE_H);+ const sctx = this.scratch.getContext("2d");+ if (!sctx) throw new Error("2d canvas unavailable");+ this.sctx = sctx;+ // The last cell stays blank for anyone beyond the atlas.+ for (let i = ATLAS_COLS * ATLAS_ROWS - 2; i >= 0; i -= 1) this.free.push(i);+ this.texture = new CanvasTexture(this.canvas);+ this.texture.colorSpace = SRGBColorSpace;+ this.drawBlank(ATLAS_COLS * ATLAS_ROWS - 1);+ }++ /** The uv rectangle (u0, v0, u1, v1) of `id`'s cell, allocating it on first use. */+ cell(id: string, look: FaceLook): [number, number, number, number] {+ let slot = this.slots.get(id);+ if (!slot) {+ const index = this.free.pop() ?? ATLAS_COLS * ATLAS_ROWS - 1;+ slot = { index, look, mood: "idle", frame: -1, key: "" };+ this.slots.set(id, slot);+ }+ slot.look = look;+ const c = slot.index % ATLAS_COLS, r = Math.floor(slot.index / ATLAS_COLS);+ const inset = 1 / (CELL_PX * ATLAS_COLS);+ return [c / ATLAS_COLS + inset, 1 - (r + 1) / ATLAS_ROWS + inset, (c + 1) / ATLAS_COLS - inset, 1 - r / ATLAS_ROWS - inset];+ }++ release(id: string): void {+ const slot = this.slots.get(id);+ if (!slot) return;+ this.slots.delete(id);+ if (slot.index !== ATLAS_COLS * ATLAS_ROWS - 1) this.free.push(slot.index);+ }++ setMood(id: string, mood: FaceMood): void {+ const slot = this.slots.get(id);+ if (slot && slot.mood !== mood) { slot.mood = mood; slot.frame = -1; }+ }++ /** Redraw the faces whose frame changed; call once per rendered frame. */+ tick(nowMs: number, still: boolean): void {+ const frame = still ? 5 : Math.floor(nowMs / CREATURE_TICK_MS);+ for (const [id, slot] of this.slots) {+ // Each face runs on its own phase, so a row of androids does not blink in step.+ const own = frame + (hashId(id) % 97);+ const key = this.frameKey(slot, own);+ if (key === slot.key) continue;+ slot.key = key;+ this.draw(slot, own);+ this.dirty = true;+ }+ if (this.dirty) { this.texture.needsUpdate = true; this.dirty = false; }+ }++ private frameKey(slot: Slot, frame: number): string {+ const pose = creaturePose(MOOD_STATE[slot.mood], frame);+ const lookKey = slot.look.kind === "creature" ? `${slot.look.creature.seed}|${slot.look.creature.palette}|${slot.look.creature.eyes}` : `${slot.look.shape}|${slot.look.color}`;+ return `${lookKey}|${slot.mood}|${pose.eyes}|${pose.ex}|${pose.ey}|${pose.head}|${pose.sweep}|${pose.mouth}|${pose.bits.length}|${pose.dim}`;+ }++ private cellOrigin(index: number): [number, number] {+ return [(index % ATLAS_COLS) * CELL_PX, Math.floor(index / ATLAS_COLS) * CELL_PX];+ }++ private background(x: number, y: number, mood: FaceMood): void {+ const { ctx } = this;+ const g = ctx.createLinearGradient(x, y, x, y + CELL_PX);+ const tint = mood === "working" ? ["#06221a", "#020a08"] : mood === "waiting" ? ["#2a1c05", "#0b0702"] : mood === "paused" ? ["#0e0c1c", "#040308"] : ["#071824", "#02070c"];+ g.addColorStop(0, tint[0]); g.addColorStop(1, tint[1]);+ ctx.fillStyle = g;+ ctx.fillRect(x, y, CELL_PX, CELL_PX);+ // Scan lines.+ ctx.fillStyle = "rgba(255,255,255,0.035)";+ for (let k = 0; k < CELL_PX; k += 3) ctx.fillRect(x, y + k, CELL_PX, 1);+ }++ private drawBlank(index: number): void {+ const [x, y] = this.cellOrigin(index);+ this.background(x, y, "idle");+ }++ private draw(slot: Slot, frame: number): void {+ const [x, y] = this.cellOrigin(slot.index);+ const { ctx } = this;+ ctx.save();+ ctx.beginPath(); ctx.rect(x, y, CELL_PX, CELL_PX); ctx.clip();+ this.background(x, y, slot.mood);+ if (slot.look.kind === "creature") {+ const body = creatureBody(slot.look.creature);+ paintCreature(this.sctx, this.scratch.width, body, creaturePose(MOOD_STATE[slot.mood], frame), 0);+ const w = this.scratch.width, h = this.scratch.height;+ ctx.globalAlpha = slot.mood === "paused" ? 0.55 : 1;+ ctx.drawImage(this.scratch, x + (CELL_PX - w) / 2, y + (CELL_PX - h) / 2 + 2, w, h);+ ctx.globalAlpha = 1;+ } else {+ drawShapeFace(ctx, x, y, slot.look.shape, slot.look.color, slot.mood, frame);+ }+ ctx.restore();+ }+}++function hashId(id: string): number {+ let h = 0;+ for (let i = 0; i < id.length; i += 1) h = (h * 31 + id.charCodeAt(i)) | 0;+ return Math.abs(h);+}++function shapePath(ctx: CanvasRenderingContext2D, shape: SymbolShape, cx: number, cy: number, r: number): void {+ ctx.beginPath();+ switch (shape) {+ case "triangle": ctx.moveTo(cx, cy - r); ctx.lineTo(cx + r * 0.95, cy + r * 0.75); ctx.lineTo(cx - r * 0.95, cy + r * 0.75); ctx.closePath(); break;+ case "hexagon": for (let k = 0; k < 6; k += 1) { const a = (k / 6) * Math.PI * 2 - Math.PI / 2; ctx[k ? "lineTo" : "moveTo"](cx + Math.cos(a) * r, cy + Math.sin(a) * r); } ctx.closePath(); break;+ case "squircle": ctx.roundRect(cx - r, cy - r, r * 2, r * 2, r * 0.45); break;+ case "pill": ctx.roundRect(cx - r, cy - r * 0.72, r * 2, r * 1.44, r * 0.72); break;+ case "drop": ctx.moveTo(cx, cy - r); ctx.quadraticCurveTo(cx + r, cy, cx + r * 0.8, cy + r * 0.4); ctx.arc(cx, cy + r * 0.3, r * 0.8, 0.2, Math.PI - 0.2); ctx.quadraticCurveTo(cx - r, cy, cx, cy - r); break;+ case "cloud": ctx.arc(cx - r * 0.45, cy + r * 0.15, r * 0.5, 0, Math.PI * 2); ctx.arc(cx + r * 0.45, cy + r * 0.15, r * 0.5, 0, Math.PI * 2); ctx.arc(cx, cy - r * 0.25, r * 0.6, 0, Math.PI * 2); break;+ default: ctx.arc(cx, cy, r, 0, Math.PI * 2);+ }+}++function drawShapeFace(ctx: CanvasRenderingContext2D, x: number, y: number, shape: SymbolShape, color: string, mood: FaceMood, frame: number): void {+ const cx = x + CELL_PX / 2, cy = y + CELL_PX / 2 + 2, r = CELL_PX * 0.32;+ ctx.globalAlpha = mood === "paused" ? 0.5 : 1;+ ctx.fillStyle = color;+ shapePath(ctx, shape, cx, cy, r);+ ctx.fill();+ const blink = frame % 60 < 2 || mood === "paused";+ const look = mood === "working" ? 3 : frame % 60 > 30 && frame % 60 < 36 ? -3 : 0;+ ctx.fillStyle = "#0b0d12";+ for (const s of [-1, 1]) {+ if (blink) ctx.fillRect(cx + s * r * 0.36 - 4 + look, cy - 1, 8, 2);+ else ctx.fillRect(cx + s * r * 0.36 - 2.5 + look, cy - 6 + (mood === "working" ? 2 : 0), 5, 9);+ }+ ctx.globalAlpha = 1;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/crew/figure.ts b/dodaios/ui/web/frontend/src/components/society/starship/crew/figure.tsnew file mode 100644index 0000000000..83ecc5c56c--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/crew/figure.ts@@ -0,0 +1,347 @@+/**+ * Figures as one skinned mesh each (every part rigidly bound to its bone),+ * plus a face display on the head. `CrewFigure` is an imperative object the+ * crew system poses every frame; React only mounts it.+ *+ * Two bodies share the skeleton: the android crew (ceramic shell, graphite+ * joints, shoulder caps in the division's colour, rank pips at the collar)+ * and the captain (a charcoal flight suit with gold shoulders, a helmet with+ * a gold visor and a pack).+ */+import {+ Bone, BoxGeometry, BufferAttribute, BufferGeometry, Color, CylinderGeometry, Group, Matrix4, Mesh, MeshBasicMaterial,+ MeshStandardMaterial, Skeleton, SkinnedMesh, SphereGeometry, Uint16BufferAttribute, Float32BufferAttribute, Euler, Quaternion, Vector3,+ type Material,+} from "three";+import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";+import { BONES, blendPose, OFFSET, PARENT, pose, restPositions, type BoneName, type PoseFrame, type PoseInput } from "./rig";++type V3 = [number, number, number];++interface Part { bone: BoneName; geo: BufferGeometry; color: string }++const REST = restPositions();+const tmp = new Color();++function part(bone: BoneName, geo: BufferGeometry, color: string, at: V3 = [0, 0, 0], scale?: V3, rot?: V3): Part {+ const m = new Matrix4();+ const q = new Quaternion().setFromEuler(new Euler(...(rot ?? [0, 0, 0])));+ const p = REST[bone];+ m.compose(new Vector3(p[0] + at[0], p[1] + at[1], p[2] + at[2]), q, new Vector3(...(scale ?? [1, 1, 1])));+ const g = geo.index ? geo.toNonIndexed() : geo;+ if (g !== geo) geo.dispose();+ g.applyMatrix4(m);+ return { bone, geo: g, color };+}++/** A capsule-ish limb segment from y=top down to y=bottom (bone-local), radius r0 at the top and r1 at the bottom. */+function limb(bone: BoneName, top: number, bottom: number, r0: number, r1: number, color: string): Part {+ const h = top - bottom;+ const g = new CylinderGeometry(r0, r1, h, 12, 1);+ return part(bone, g, color, [0, (top + bottom) / 2, 0]);+}++function ball(bone: BoneName, r: number, color: string, at: V3 = [0, 0, 0], scale?: V3, seg = 12): Part {+ return part(bone, new SphereGeometry(r, seg, Math.max(6, seg * 0.66)), color, at, scale);+}++function block(bone: BoneName, w: number, h: number, d: number, color: string, at: V3 = [0, 0, 0], rot?: V3): Part {+ return part(bone, new BoxGeometry(w, h, d), color, at, undefined, rot);+}++export interface AndroidLook {+ /** Shoulder caps and wrist bands: the division's colour. */+ accent: string;+ /** Rank pips at the collar (0–4) and whether they are gold (officers) or silver. */+ pips: number;+ gold: boolean;+ /** A small gold bar for a division lead. */+ lead: boolean;+ /** Decorations earned (the level system's agent `decoration` rewards), worn as ribbon bars over the left breast. */+ ribbons?: number;+}++/** The ribbons' colours, in the order they are earned. */+const RIBBON_COLOURS = ["#3c7fd0", "#c0392b", "#e1b04f", "#2e8b57"] as const;++const SHELL = "#e9e8e4";+const JOINT = "#2b2f36";+const DARK = "#1c1f24";++export function androidParts(look: AndroidLook): Part[] {+ const a = look.accent;+ const parts: Part[] = [+ // Hips and abdomen.+ block("hips", 0.29, 0.13, 0.17, JOINT, [0, -0.05, 0]),+ ball("hips", 0.07, SHELL, [0, -0.06, 0.06], [1.6, 0.8, 0.6]),+ limb("chest", 0.16, 0.0, 0.1, 0.11, JOINT),+ // Torso shell, chest plate, collar and the back's spine.+ ball("chest", 1, SHELL, [0, 0.29, 0], [0.19, 0.23, 0.125], 18),+ ball("chest", 1, "#d9d7d2", [0, 0.31, 0.035], [0.15, 0.15, 0.1], 14),+ block("chest", 0.05, 0.3, 0.05, JOINT, [0, 0.26, -0.11]),+ part("chest", new CylinderGeometry(0.075, 0.09, 0.05, 16), JOINT, [0, 0.43, 0]),+ // Shoulder caps in the division colour.+ ball("chest", 0.078, a, [0.2, 0.37, -0.01], [1, 0.85, 1]),+ ball("chest", 0.078, a, [-0.2, 0.37, -0.01], [1, 0.85, 1]),+ // Neck and head.+ limb("neck", 0.09, 0.0, 0.034, 0.042, JOINT),+ ball("head", 1, SHELL, [0, 0.11, -0.005], [0.112, 0.132, 0.124], 20),+ part("head", new CylinderGeometry(0.03, 0.03, 0.02, 12), JOINT, [0.112, 0.1, -0.01], undefined, [0, 0, Math.PI / 2]),+ part("head", new CylinderGeometry(0.03, 0.03, 0.02, 12), JOINT, [-0.112, 0.1, -0.01], undefined, [0, 0, Math.PI / 2]),+ // Arms.+ ball("armL", 0.055, JOINT), ball("armR", 0.055, JOINT),+ limb("armL", -0.02, -0.27, 0.047, 0.04, SHELL), limb("armR", -0.02, -0.27, 0.047, 0.04, SHELL),+ ball("forearmL", 0.043, JOINT), ball("forearmR", 0.043, JOINT),+ limb("forearmL", -0.02, -0.24, 0.04, 0.033, SHELL), limb("forearmR", -0.02, -0.24, 0.04, 0.033, SHELL),+ limb("forearmL", -0.19, -0.23, 0.037, 0.037, a), limb("forearmR", -0.19, -0.23, 0.037, 0.037, a),+ block("handL", 0.035, 0.1, 0.07, JOINT, [0, -0.05, 0.005]), block("handR", 0.035, 0.1, 0.07, JOINT, [0, -0.05, 0.005]),+ // Legs.+ ball("thighL", 0.062, JOINT), ball("thighR", 0.062, JOINT),+ limb("thighL", -0.02, -0.42, 0.066, 0.052, SHELL), limb("thighR", -0.02, -0.42, 0.066, 0.052, SHELL),+ ball("shinL", 0.05, JOINT), ball("shinR", 0.05, JOINT),+ limb("shinL", -0.02, -0.41, 0.05, 0.038, SHELL), limb("shinR", -0.02, -0.41, 0.05, 0.038, SHELL),+ block("footL", 0.09, 0.06, 0.21, DARK, [0, -0.02, 0.045]), block("footR", 0.09, 0.06, 0.21, DARK, [0, -0.02, 0.045]),+ ];+ // Rank pips on the right of the collar.+ const pip = look.gold ? "#e1b04f" : "#c9cdd3";+ for (let k = 0; k < Math.min(4, look.pips); k += 1) {+ parts.push(ball("chest", 0.013, pip, [-0.05 - k * 0.032, 0.41, 0.095], [1, 1, 0.5], 8));+ }+ if (look.lead) parts.push(block("chest", 0.09, 0.018, 0.01, "#e1b04f", [0.06, 0.39, 0.1]));+ // Ribbon bars on the figure's left breast, two to a row.+ for (let k = 0; k < Math.min(4, look.ribbons ?? 0); k += 1) {+ parts.push(block("chest", 0.034, 0.014, 0.01, RIBBON_COLOURS[k], [0.045 + (k % 2) * 0.037, 0.33 - Math.floor(k / 2) * 0.018, 0.118]));+ }+ return parts;+}++/** `cut` is a suit unlocked by rank: null (the duty suit), field_armor, command_coat, dress_whites, admiral_coat. */+export interface CaptainLook { suit: string; trim: string; visor: string; pips: number; cut?: string | null }++export function captainParts(look: CaptainLook): Part[] {+ const cut = look.cut ?? null;+ // Dress whites recolour the suit; the trim stays the captain's choice.+ const s = cut === "dress_whites" ? "#e6e6e3" : look.suit, t = look.trim;+ const parts: Part[] = [+ block("hips", 0.32, 0.15, 0.2, s, [0, -0.05, 0]),+ block("hips", 0.33, 0.04, 0.21, t, [0, 0.01, 0]),+ limb("chest", 0.16, 0.0, 0.12, 0.125, s),+ ball("chest", 1, s, [0, 0.29, 0], [0.205, 0.24, 0.14], 18),+ // Chest plate with a gold rule, and the pack on the back.+ ball("chest", 1, "#3a4252", [0, 0.31, 0.045], [0.16, 0.16, 0.11], 14),+ block("chest", 0.2, 0.012, 0.01, t, [0, 0.25, 0.15]),+ block("chest", 0.25, 0.3, 0.1, "#3d4554", [0, 0.28, -0.15]),+ block("chest", 0.2, 0.02, 0.02, "#8fd6ff", [0, 0.2, -0.2]),+ ball("chest", 0.088, t, [0.21, 0.37, -0.01], [1, 0.8, 1]),+ ball("chest", 0.088, t, [-0.21, 0.37, -0.01], [1, 0.8, 1]),+ part("chest", new CylinderGeometry(0.09, 0.1, 0.06, 16), "#252a33", [0, 0.43, 0]),+ limb("neck", 0.09, 0.0, 0.045, 0.05, "#252a33"),+ // Helmet shell (the visor is its own mesh).+ ball("head", 1, "#e8e9ec", [0, 0.11, -0.01], [0.135, 0.15, 0.142], 20),+ part("head", new CylinderGeometry(0.035, 0.035, 0.03, 12), t, [0.135, 0.1, -0.02], undefined, [0, 0, Math.PI / 2]),+ part("head", new CylinderGeometry(0.035, 0.035, 0.03, 12), t, [-0.135, 0.1, -0.02], undefined, [0, 0, Math.PI / 2]),+ ball("armL", 0.062, s), ball("armR", 0.062, s),+ limb("armL", -0.02, -0.27, 0.055, 0.047, s), limb("armR", -0.02, -0.27, 0.055, 0.047, s),+ ball("forearmL", 0.048, "#252a33"), ball("forearmR", 0.048, "#252a33"),+ limb("forearmL", -0.02, -0.24, 0.047, 0.04, s), limb("forearmR", -0.02, -0.24, 0.047, 0.04, s),+ limb("forearmL", -0.17, -0.24, 0.05, 0.05, "#e8e9ec"), limb("forearmR", -0.17, -0.24, 0.05, 0.05, "#e8e9ec"),+ block("handL", 0.04, 0.1, 0.075, "#252a33", [0, -0.05, 0.005]), block("handR", 0.04, 0.1, 0.075, "#252a33", [0, -0.05, 0.005]),+ ball("thighL", 0.07, s), ball("thighR", 0.07, s),+ limb("thighL", -0.02, -0.42, 0.072, 0.058, s), limb("thighR", -0.02, -0.42, 0.072, 0.058, s),+ ball("shinL", 0.056, "#252a33"), ball("shinR", 0.056, "#252a33"),+ limb("shinL", -0.02, -0.33, 0.056, 0.05, s), limb("shinR", -0.02, -0.33, 0.056, 0.05, s),+ limb("shinL", -0.28, -0.42, 0.06, 0.058, "#e8e9ec"), limb("shinR", -0.28, -0.42, 0.06, 0.058, "#e8e9ec"),+ block("footL", 0.1, 0.07, 0.23, "#1b1e24", [0, -0.02, 0.045]), block("footR", 0.1, 0.07, 0.23, "#1b1e24", [0, -0.02, 0.045]),+ ];+ for (let k = 0; k < Math.min(4, look.pips); k += 1) parts.push(ball("chest", 0.014, "#f0c060", [-0.06 - k * 0.034, 0.41, 0.11], [1, 1, 0.5], 8));+ if (cut === "field_armor") {+ // Armour plates over the suit: chest, shoulders and knees.+ parts.push(ball("chest", 1, "#4a5363", [0, 0.3, 0.06], [0.19, 0.17, 0.11], 14));+ parts.push(ball("chest", 0.105, "#4a5363", [0.23, 0.38, 0], [1, 0.7, 1.1]), ball("chest", 0.105, "#4a5363", [-0.23, 0.38, 0], [1, 0.7, 1.1]));+ parts.push(ball("shinL", 0.07, "#4a5363", [0, -0.02, 0.03], [1, 1, 0.7]), ball("shinR", 0.07, "#4a5363", [0, -0.02, 0.03], [1, 1, 0.7]));+ } else if (cut === "command_coat" || cut === "admiral_coat") {+ // A coat skirt from the waist; the admiral's reaches the knees and carries gold epaulettes.+ const long = cut === "admiral_coat";+ const coat = cut === "admiral_coat" ? "#1a2030" : s;+ const g = new CylinderGeometry(0.17, long ? 0.25 : 0.21, long ? 0.62 : 0.36, 18, 1, true);+ parts.push(part("hips", g, coat, [0, long ? -0.29 : -0.16, -0.005]));+ parts.push(block("chest", 0.012, 0.42, 0.01, t, [0.05, 0.22, 0.14]));+ if (long) parts.push(block("chest", 0.13, 0.025, 0.11, t, [0.22, 0.44, -0.01]), block("chest", 0.13, 0.025, 0.11, t, [-0.22, 0.44, -0.01]));+ } else if (cut === "dress_whites") {+ parts.push(block("chest", 0.22, 0.03, 0.02, t, [0, 0.4, 0.13]), block("hips", 0.33, 0.05, 0.21, t, [0, 0.0, 0]));+ }+ return parts;+}++/** Merge the parts into one geometry bound rigidly to its bones. */+export function skinnedGeometry(parts: Part[]): BufferGeometry {+ const geos = parts.map(({ bone, geo, color }) => {+ for (const name of Object.keys(geo.attributes)) if (name !== "position" && name !== "normal") geo.deleteAttribute(name);+ const n = geo.attributes.position.count;+ const idx = BONES.indexOf(bone);+ const colors = new Float32Array(n * 3);+ tmp.set(color).convertSRGBToLinear();+ for (let i = 0; i < n; i += 1) { colors[i * 3] = tmp.r; colors[i * 3 + 1] = tmp.g; colors[i * 3 + 2] = tmp.b; }+ geo.setAttribute("color", new BufferAttribute(colors, 3));+ const si = new Uint16Array(n * 4), sw = new Float32Array(n * 4);+ for (let i = 0; i < n; i += 1) { si[i * 4] = idx; sw[i * 4] = 1; }+ geo.setAttribute("skinIndex", new Uint16BufferAttribute(si, 4));+ geo.setAttribute("skinWeight", new Float32BufferAttribute(sw, 4));+ return geo;+ });+ const merged = mergeGeometries(geos, false);+ for (const g of geos) g.dispose();+ if (!merged) throw new Error("figure geometry failed to merge");+ merged.computeBoundingSphere();+ if (merged.boundingSphere) merged.boundingSphere.radius = 1.4;+ return merged;+}++let bodyMaterial: MeshStandardMaterial | null = null;+export function figureMaterial(): MeshStandardMaterial {+ if (!bodyMaterial) bodyMaterial = new MeshStandardMaterial({ vertexColors: true, roughness: 0.42, metalness: 0.08, envMapIntensity: 0.9 });+ return bodyMaterial;+}++const visorMaterials = new Map<string, MeshStandardMaterial>();+function visorMat(colour: string): MeshStandardMaterial {+ let m = visorMaterials.get(colour);+ if (!m) {+ m = new MeshStandardMaterial({ color: colour, roughness: 0.12, metalness: 1, envMapIntensity: 1.8, emissive: new Color(colour).multiplyScalar(0.12) });+ visorMaterials.set(colour, m);+ }+ return m;+}++/** The face display: the front of the head, uv-mapped to one atlas cell. */+export function faceGeometry(uv: [number, number, number, number], captain = false): BufferGeometry {+ const r = captain ? 1.035 : 1.03;+ const g = new SphereGeometry(r, 18, 12, Math.PI / 2 - 0.95, 1.9, Math.PI / 2 - 0.62, 1.12);+ // phi runs round y from +x; the front (+z) is at phi = pi/2. Map the patch onto the cell.+ const uvs = g.attributes.uv as BufferAttribute;+ for (let i = 0; i < uvs.count; i += 1) {+ const u = uvs.getX(i), v = uvs.getY(i);+ // Sphere uvs over the patch run 0..1 in u (phi, from the figure's right = the viewer's left) and v (top = 1).+ uvs.setXY(i, uv[0] + u * (uv[2] - uv[0]), uv[1] + v * (uv[3] - uv[1]));+ }+ const s = captain ? [0.135, 0.15, 0.142] : [0.112, 0.132, 0.124];+ g.applyMatrix4(new Matrix4().compose(new Vector3(0, 0.11 + (captain ? 0.0 : -0.005), captain ? -0.01 : -0.005), new Quaternion(), new Vector3(s[0], s[1], s[2])));+ return g;+}++export interface FigureOptions {+ kind: "android" | "captain";+ android?: AndroidLook;+ captain?: CaptainLook;+ /** Face material (the shared atlas) and this figure's cell. */+ face?: { material: Material; uv: [number, number, number, number] };+}++const BLEND_S = 0.32;++/**+ * One figure: a group at the figure's feet (position and yaw set by the+ * owner), its skinned body and its face. `apply(input, dt)` poses it,+ * blending over a third of a second whenever the activity changes.+ */+export class CrewFigure {+ readonly group = new Group();+ readonly bones: Record<BoneName, Bone>;+ private readonly body: SkinnedMesh;+ private readonly face: Mesh | null;+ private readonly root: Group;+ private from: PoseFrame | null = null;+ private current: PoseFrame | null = null;+ private activity: PoseInput["activity"] | null = null;+ private blend = 1;++ constructor(opts: FigureOptions) {+ const parts = opts.kind === "captain" ? captainParts(opts.captain ?? { suit: "#2c3340", trim: "#d9a441", visor: "#d6a440", pips: 0 })+ : androidParts(opts.android ?? { accent: "#5fd4ff", pips: 0, gold: false, lead: false });+ const geometry = skinnedGeometry(parts);+ const bones = {} as Record<BoneName, Bone>;+ for (const name of BONES) {+ const bone = new Bone();+ bone.name = name;+ const o = OFFSET[name];+ bone.position.set(o[0], o[1], o[2]);+ bones[name] = bone;+ }+ for (const name of BONES) {+ const parent = PARENT[name];+ if (parent) bones[parent].add(bones[name]);+ }+ this.bones = bones;+ this.body = new SkinnedMesh(geometry, figureMaterial());+ this.body.castShadow = true;+ this.body.frustumCulled = false;+ // Picking uses a simple hit volume; a skinned raycast is far too costly.+ this.body.raycast = () => undefined;+ this.root = new Group();+ this.root.add(bones.hips);+ this.root.add(this.body);+ this.group.add(this.root);+ // The skeleton takes its inverse bind matrices from the bones' world matrices: update them first.+ this.group.updateMatrixWorld(true);+ const skeleton = new Skeleton(BONES.map((n) => bones[n]));+ this.body.bind(skeleton);+ if (opts.face) {+ this.face = new Mesh(faceGeometry(opts.face.uv, opts.kind === "captain"), opts.face.material);+ this.face.frustumCulled = false;+ // Built in the head bone's own frame, so it turns with the head.+ bones.head.add(this.face);+ } else if (opts.kind === "captain") {+ this.face = new Mesh(faceGeometry([0, 0, 1, 1], true), visorMat(opts.captain?.visor ?? "#d6a440"));+ this.face.castShadow = false;+ bones.head.add(this.face);+ } else {+ this.face = null;+ }+ if (this.face) this.face.raycast = () => undefined;+ }++ /** Re-point the face at another cell (a new look). */+ setFaceUv(uv: [number, number, number, number]): void {+ if (!this.face) return;+ const old = this.face.geometry;+ this.face.geometry = faceGeometry(uv);+ old.dispose();+ }++ apply(input: PoseInput, dt: number): void {+ const next = pose(input);+ if (this.activity !== input.activity) {+ this.from = this.current ?? next;+ this.activity = input.activity;+ this.blend = 0;+ }+ this.blend = Math.min(1, this.blend + dt / BLEND_S);+ const k = this.blend * this.blend * (3 - 2 * this.blend);+ const frame = this.from && this.blend < 1 ? blendPose(this.from, next, k) : next;+ this.current = frame;+ const hips = this.bones.hips;+ hips.position.set(frame.root[0], frame.root[1], frame.root[2]);+ this.root.rotation.set(frame.rootRot[0], frame.rootRot[1], frame.rootRot[2]);+ for (const name of BONES) {+ const r = frame.bones[name];+ if (r) this.bones[name].rotation.set(r[0], r[1], r[2]);+ else this.bones[name].rotation.set(0, 0, 0);+ }+ }++ /** World position of the head (for name plates and bubbles). */+ headWorld(out: Vector3): Vector3 {+ return this.bones.head.getWorldPosition(out);+ }++ dispose(): void {+ this.body.geometry.dispose();+ this.body.skeleton.dispose();+ this.face?.geometry.dispose();+ }+}++/** The shared face material for an atlas texture. */+export function faceMaterial(map: MeshBasicMaterial["map"]): MeshBasicMaterial {+ return new MeshBasicMaterial({ map, toneMapped: false, color: new Color(1.35, 1.35, 1.35) });+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/crew/rig.ts b/dodaios/ui/web/frontend/src/components/society/starship/crew/rig.tsnew file mode 100644index 0000000000..e3d8cce00a--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/crew/rig.ts@@ -0,0 +1,216 @@+/**+ * One skeleton for every figure on the ship (the android crew and the+ * captain), and the poses it takes. Poses are pure functions of time, so+ * they are tested without a GPU; the renderer copies them onto bones.+ *+ * Bones rotate in their parent's frame. A limb hangs along -y at rest; a+ * figure faces +z. Positive x rotation tips a part's forward direction down+ * (a nod) and swings a hanging limb backwards; negative swings it forwards.+ */++export const BONES = [+ "hips", "chest", "neck", "head",+ "armL", "forearmL", "handL", "armR", "forearmR", "handR",+ "thighL", "shinL", "footL", "thighR", "shinR", "footR",+] as const;+export type BoneName = typeof BONES[number];++export const PARENT: Record<BoneName, BoneName | null> = {+ hips: null, chest: "hips", neck: "chest", head: "neck",+ armL: "chest", forearmL: "armL", handL: "forearmL", armR: "chest", forearmR: "armR", handR: "forearmR",+ thighL: "hips", shinL: "thighL", footL: "shinL", thighR: "hips", shinR: "thighR", footR: "shinR",+};++/** Bone offsets from the parent at rest (metres). Left is +x (the figure's own left when it faces +z). */+export const OFFSET: Record<BoneName, [number, number, number]> = {+ hips: [0, 0.94, 0],+ chest: [0, 0.1, 0],+ neck: [0, 0.44, -0.01],+ head: [0, 0.08, 0.01],+ armL: [0.215, 0.38, -0.01], forearmL: [0, -0.29, 0], handL: [0, -0.26, 0.01],+ armR: [-0.215, 0.38, -0.01], forearmR: [0, -0.29, 0], handR: [0, -0.26, 0.01],+ thighL: [0.1, -0.03, 0], shinL: [0, -0.44, 0], footL: [0, -0.43, 0],+ thighR: [-0.1, -0.03, 0], shinR: [0, -0.44, 0], footR: [0, -0.43, 0],+};++/** Hip height above the floor when standing. */+export const HIP_Y = OFFSET.hips[1];++export type Euler3 = [number, number, number];++export interface PoseFrame {+ /** Hips position offset from the figure's origin (y absolute). */+ root: [number, number, number];+ /** Extra rotation of the whole body (lying down). */+ rootRot: Euler3;+ bones: Partial<Record<BoneName, Euler3>>;+}++export type Activity = "stand" | "walk" | "sit" | "type" | "wave" | "rest" | "talk" | "listen" | "lean";++export interface PoseInput {+ activity: Activity;+ /** Seconds, for loops. */+ t: number;+ /** Walk cycle phase in cycles (grows with distance walked). */+ phase?: number;+ /** Walking speed in m/s (sets the swing). */+ speed?: number;+ /** Seat height for sit/type, couch height for rest. */+ seatY?: number;+ /** 0..1 per figure, so a crowd is out of step. */+ seed?: number;+}++const R = (x = 0, y = 0, z = 0): Euler3 => [x, y, z];++function breathe(t: number, seed: number): number {+ return Math.sin((t + seed * 7) * 1.6) * 0.02;+}++export function pose(input: PoseInput): PoseFrame {+ const { activity, t } = input;+ const seed = input.seed ?? 0;+ const b = breathe(t, seed);+ const base: PoseFrame = {+ root: [0, HIP_Y, 0], rootRot: R(),+ bones: {+ chest: R(b, 0, 0), head: R(-b * 0.5, Math.sin((t + seed * 11) * 0.37) * 0.12, 0),+ armL: R(0.04, 0, 0.09), armR: R(0.04, 0, -0.09), forearmL: R(-0.12), forearmR: R(-0.12),+ },+ };+ switch (activity) {+ case "walk": {+ const speed = Math.min(2.6, Math.max(0.3, input.speed ?? 1.3));+ const amp = 0.28 + speed * 0.14;+ const w = (input.phase ?? 0) * Math.PI * 2;+ const s = Math.sin(w), c = Math.cos(w);+ base.root = [0, HIP_Y - 0.02 + Math.abs(c) * 0.03, 0];+ base.bones.thighL = R(-s * amp, 0, 0);+ base.bones.thighR = R(s * amp, 0, 0);+ base.bones.shinL = R(Math.max(0, -c) * amp * 1.4 + 0.05);+ base.bones.shinR = R(Math.max(0, c) * amp * 1.4 + 0.05);+ base.bones.footL = R(-0.1 + s * 0.2);+ base.bones.footR = R(-0.1 - s * 0.2);+ base.bones.armL = R(s * amp * 0.8, 0, 0.08);+ base.bones.armR = R(-s * amp * 0.8, 0, -0.08);+ base.bones.forearmL = R(-0.25 - Math.max(0, s) * 0.3);+ base.bones.forearmR = R(-0.25 - Math.max(0, -s) * 0.3);+ base.bones.chest = R(0.04 + speed * 0.02, s * 0.06, 0);+ base.bones.hips = R(0, -s * 0.06, 0);+ base.bones.head = R(-0.04, 0, 0);+ return base;+ }+ case "sit":+ case "type": {+ const seatY = input.seatY ?? 0.5;+ base.root = [0, seatY + 0.07, -0.04];+ base.bones.thighL = R(-1.52, 0, 0.04);+ base.bones.thighR = R(-1.52, 0, -0.04);+ base.bones.shinL = R(1.45);+ base.bones.shinR = R(1.45);+ base.bones.footL = R(0.05);+ base.bones.footR = R(0.05);+ if (activity === "type") {+ // Forearms on the desk, fingers working: small, fast, out of step.+ const k = (t + seed * 3) * 9;+ base.bones.chest = R(0.14 + b, 0, 0);+ base.bones.head = R(0.22, Math.sin((t + seed) * 0.5) * 0.1, 0);+ base.bones.armL = R(-0.62, 0, 0.16);+ base.bones.armR = R(-0.62, 0, -0.16);+ base.bones.forearmL = R(-0.95 + Math.sin(k) * 0.05, 0, -0.18);+ base.bones.forearmR = R(-0.95 + Math.sin(k * 1.13 + 1) * 0.05, 0, 0.18);+ base.bones.handL = R(0.2 + Math.max(0, Math.sin(k * 1.7)) * 0.25);+ base.bones.handR = R(0.2 + Math.max(0, Math.sin(k * 1.9 + 2)) * 0.25);+ } else {+ base.bones.chest = R(-0.06 + b, 0, 0);+ base.bones.armL = R(-0.35, 0, 0.12);+ base.bones.armR = R(-0.35, 0, -0.12);+ base.bones.forearmL = R(-0.9, 0, -0.1);+ base.bones.forearmR = R(-0.9, 0, 0.1);+ }+ return base;+ }+ case "wave": {+ const k = Math.sin((t + seed) * 7);+ base.bones.armR = R(0, 0, -2.55);+ base.bones.forearmR = R(0, 0, -0.3 + k * 0.4);+ base.bones.handR = R(0, 0, k * 0.2);+ base.bones.head = R(-0.1, 0, 0.08);+ base.bones.chest = R(-0.03, -0.1, 0);+ return base;+ }+ case "talk": {+ const k = (t + seed * 5) * 2.2;+ base.bones.armR = R(-0.35 + Math.sin(k) * 0.15, 0, -0.2);+ base.bones.forearmR = R(-1.0 + Math.sin(k * 1.3) * 0.25, 0.3, 0);+ base.bones.armL = R(-0.2 + Math.sin(k * 0.8 + 1) * 0.1, 0, 0.18);+ base.bones.forearmL = R(-0.7 + Math.sin(k * 1.1 + 2) * 0.2, -0.3, 0);+ base.bones.head = R(-0.05 + Math.sin(k * 0.7) * 0.05, Math.sin(k * 0.4) * 0.15, 0);+ return base;+ }+ case "listen": {+ base.bones.armL = R(-0.15, 0, 0.22);+ base.bones.armR = R(-0.15, 0, -0.22);+ base.bones.forearmL = R(-1.2, 0, -0.5);+ base.bones.forearmR = R(-1.2, 0, 0.5);+ base.bones.head = R(-0.06, Math.sin((t + seed * 9) * 0.6) * 0.1, Math.sin((t + seed) * 0.3) * 0.06);+ return base;+ }+ case "lean": {+ base.root = [0, HIP_Y - 0.03, 0];+ base.bones.chest = R(0.18 + b, 0, 0);+ base.bones.armL = R(-0.7, 0, 0.1);+ base.bones.armR = R(-0.7, 0, -0.1);+ base.bones.forearmL = R(-0.5);+ base.bones.forearmR = R(-0.5);+ base.bones.head = R(0.25, 0, 0);+ return base;+ }+ case "rest": {+ const seatY = input.seatY ?? 0.6;+ base.root = [0, seatY + 0.12, 0];+ base.rootRot = R(-Math.PI / 2, 0, 0);+ base.bones.chest = R(b * 0.5, 0, 0);+ base.bones.head = R(-0.15, 0.3, 0);+ base.bones.armL = R(0, 0, 0.18);+ base.bones.armR = R(0, 0, -0.18);+ base.bones.forearmL = R(-0.4, 0, -0.5);+ base.bones.forearmR = R(-0.4, 0, 0.5);+ base.bones.thighL = R(0, 0, 0.03);+ base.bones.thighR = R(0, 0, -0.03);+ base.bones.footL = R(-0.5);+ base.bones.footR = R(-0.5);+ return base;+ }+ default:+ return base;+ }+}++/** Blend two frames: `k` = 0 gives `a`, 1 gives `b`. */+export function blendPose(a: PoseFrame, b: PoseFrame, k: number): PoseFrame {+ const lerp = (x: number, y: number) => x + (y - x) * k;+ const bones: Partial<Record<BoneName, Euler3>> = {};+ for (const name of BONES) {+ const ra = a.bones[name] ?? [0, 0, 0], rb = b.bones[name] ?? [0, 0, 0];+ bones[name] = [lerp(ra[0], rb[0]), lerp(ra[1], rb[1]), lerp(ra[2], rb[2])];+ }+ return {+ root: [lerp(a.root[0], b.root[0]), lerp(a.root[1], b.root[1]), lerp(a.root[2], b.root[2])],+ rootRot: [lerp(a.rootRot[0], b.rootRot[0]), lerp(a.rootRot[1], b.rootRot[1]), lerp(a.rootRot[2], b.rootRot[2])],+ bones,+ };+}++/** World positions of every bone at rest (the bind pose). */+export function restPositions(): Record<BoneName, [number, number, number]> {+ const out = {} as Record<BoneName, [number, number, number]>;+ for (const name of BONES) {+ const parent = PARENT[name];+ const o = OFFSET[name];+ const p = parent ? out[parent] : [0, 0, 0];+ out[name] = [p[0] + o[0], p[1] + o[1], p[2] + o[2]];+ }+ return out;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/BridgeScene.tsx b/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/BridgeScene.tsxnew file mode 100644index 0000000000..bd27f8ceef--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/BridgeScene.tsx@@ -0,0 +1,507 @@+/**+ * What the bridge adds to the shared deck: the sunken-looking command well,+ * the live console screens (course, destination, crew, the service record:+ * real data only), the viewscreen's holographic overlay over the forward+ * window (the stage renders the sky itself), the star chart's turning galaxy+ * with the destinations the captain's level opens, and the warp jump: stars+ * streak past while `useShip().warpingTo` is set, a flash covers the change+ * of sky, then everything settles. With reduced motion nothing turns and+ * the jump is a cut.+ */+import { useFrame } from "@react-three/fiber";+import { useCallback, useEffect, useMemo, useRef } from "react";+import {+ AdditiveBlending, BufferAttribute, BufferGeometry, CircleGeometry, Color, CylinderGeometry, DoubleSide, Group, LineBasicMaterial,+ LineSegments, Matrix4, Mesh, MeshBasicMaterial, OctahedronGeometry, PlaneGeometry, Points, PointsMaterial, RingGeometry, ShaderMaterial,+ Vector3,+} from "three";+import { findLead, type SocietyAgent } from "../../../data";+import { useProgression } from "../../../progression/progressionStore";+import { rankFor } from "../../levels/ranks";+import type { DeckPlan, Prop } from "../../plan/types";+import { ConsoleScreens, textPlane } from "../../render/deck/DeckScene";+import type { ScreenContent, ScreenState } from "../../render/deck/screens";+import { annulus, GeoBatch } from "../../render/kit/geo";+import { castsShadow, finishMaterial, receivesShadow } from "../../render/kit/materials";+import { SHIP } from "../../render/kit/palette";+import { captain, useShip } from "../../shipStore";+import { DESTINATIONS, destinationById, openDestinations, type Destination } from "../../space/destinations";+import type { DeckSceneProps, ShipActions } from "../registry";+import { BOW, COMMAND, STAR_CHART, VIEWSCREEN_INSET, VIEWSCREEN_SPAN, WELL_R } from "./bridgeDeck";+import { bridgeRuntime, WARP_MS } from "./bridgeRuntime";++const TAU = Math.PI * 2;+const SCREEN_KINDS: readonly Prop["kind"][] = ["helmConsole", "console"];++export function BridgeScene({ plan, reduced, quality, agents, actions }: DeckSceneProps) {+ useEffect(() => {+ bridgeRuntime.leadId = findLead([...agents.values()])?.agentId ?? null;+ }, [agents]);+ useEffect(() => () => { bridgeRuntime.seatRequestedMs = 0; }, []);+ return (+ <>+ <CommandWell />+ <BridgeScreens plan={plan} agents={agents} actions={actions} />+ <ViewscreenHolo reduced={reduced} t={actions.t} />+ <StarChartHolo reduced={reduced} quality={quality} t={actions.t} />+ <SitOnArrival plan={plan} actions={actions} />+ {!reduced && <WarpJump plan={plan} />}+ </>+ );+}++function destinationName(t: ShipActions["t"], d: Destination): string {+ return t(`ship.bridge.destination.${d.id}.name`);+}++// ── the command well ─────────────────────────────────────────────────++/** A flat disc with uvs in world metres (so the carpet's weave keeps its scale). */+function disc(radius: number, at: { x: number; z: number }, y: number): BufferGeometry {+ const g = new CircleGeometry(radius, 72);+ g.rotateX(-Math.PI / 2);+ g.translate(at.x, y, at.z);+ const pos = g.attributes.position;+ const uv = g.attributes.uv as BufferAttribute;+ for (let i = 0; i < pos.count; i += 1) uv.setXY(i, pos.getX(i), pos.getZ(i));+ return g;+}++/**+ * The well round the captain's chair reads as a step down: a warm carpet, a+ * shadowed band at the riser's foot, a dark nosing with a light line on its+ * edge. The floor itself stays flat, so walking needs no ramps.+ */+function CommandWell() {+ const meshes = useMemo(() => {+ const batch = new GeoBatch();+ const root = batch.frame(new Matrix4());+ root.geo("carpet", disc(WELL_R, COMMAND, 0.014), "#e6c8a2");+ root.geo("carpet", annulus(WELL_R - 0.42, WELL_R, 0, TAU, 96), "#6e5a4c", { x: COMMAND.x, y: 0.016, z: COMMAND.z });+ root.geo("structure", annulus(WELL_R, WELL_R + 0.26, 0, TAU, 96), SHIP.panelDark, { x: COMMAND.x, y: 0.018, z: COMMAND.z });+ root.geo("glow", annulus(WELL_R + 0.005, WELL_R + 0.03, 0, TAU, 96), SHIP.lightWarm, { x: COMMAND.x, y: 0.021, z: COMMAND.z });+ // A gold inlay round the chair.+ root.geo("glowSoft", annulus(1.5, 1.52, 0, TAU, 72), SHIP.goldDeep, { x: COMMAND.x, y: 0.02, z: COMMAND.z + 0.4 });+ return batch.merged().map(({ finish, geometry }) => {+ const mesh = new Mesh(geometry, finishMaterial(finish));+ mesh.castShadow = castsShadow(finish);+ mesh.receiveShadow = receivesShadow(finish);+ mesh.raycast = () => undefined;+ return mesh;+ });+ }, []);+ useEffect(() => () => { for (const m of meshes) m.geometry.dispose(); }, [meshes]);+ return <>{meshes.map((m, i) => <primitive key={i} object={m} />)}</>;+}++// ── the console screens ──────────────────────────────────────────────++/** "LABEL value", in the screens' monospace rows. */+function row(label: string, value: string): string {+ return `${label.toUpperCase().padEnd(10)} ${value}`;+}++const STATE_ORDER: Record<SocietyAgent["state"], number> = { waiting: 0, working: 1, idle: 2, paused: 3 };++function BridgeScreens({ plan, agents, actions }: { plan: DeckPlan; agents: ReadonlyMap<string, SocietyAgent>; actions: ShipActions }) {+ const { t } = actions;+ const destinationId = useShip((s) => s.destination);+ const warpingTo = useShip((s) => s.warpingTo);+ const person = useProgression((s) => s.subjects.person);+ const level = person?.level ?? 1;+ const crew = useMemo(() => [...agents.values()].sort((a, b) => STATE_ORDER[a.state] - STATE_ORDER[b.state] || a.name.localeCompare(b.name)), [agents]);+ const lead = useMemo(() => findLead(crew), [crew]);++ const content = useCallback((p: Prop): ScreenContent => {+ const accent = p.accent ?? SHIP.cyan;+ const here = destinationById(destinationId);+ const base = (title: string, state: ScreenState, stateLabel: string, rows: string[]): ScreenContent => ({+ title, state, accent, rows, stateLabel, standby: t("ship.screen.standby"),+ });+ switch (p.id) {+ case "helm-console": {+ const to = warpingTo ? destinationById(warpingTo) : null;+ const next = DESTINATIONS.find((d) => d.level > level);+ return base(t("ship.bridge.screen.helm"), to ? "working" : "idle", to ? t("ship.bridge.screen.warp") : t("ship.bridge.screen.holding"), [+ row(t("ship.bridge.screen.course"), to ? `${destinationName(t, here)} → ${destinationName(t, to)}` : destinationName(t, here)),+ row(t("ship.bridge.screen.charted"), `${openDestinations(level).length} / ${DESTINATIONS.length}`),+ next ? row(t("ship.bridge.screen.next"), `${destinationName(t, next)} · L${next.level}`) : t("ship.bridge.screen.all_charted"),+ ]);+ }+ case "ops-console": {+ if (crew.length === 0) return base(t("ship.bridge.screen.ops"), "vacant", t("ship.state.vacant"), [t("ship.bridge.screen.no_crew")]);+ const n = { working: 0, waiting: 0, idle: 0, paused: 0 };+ for (const a of crew) n[a.state] += 1;+ const state: ScreenState = n.waiting ? "waiting" : n.working ? "working" : "idle";+ return base(t("ship.bridge.screen.ops"), state, t(`ship.state.${state}`), [+ t("ship.crew.working").replace("{count}", String(n.working)),+ t("ship.crew.waiting").replace("{count}", String(n.waiting)),+ t("ship.crew.idle").replace("{count}", String(n.idle + n.paused)),+ ...crew.filter((a) => a.state === "waiting").slice(0, 3).map((a) => `! ${a.name}`),+ ]);+ }+ case "personnel-console": {+ if (crew.length === 0) return base(t("ship.bridge.screen.personnel"), "vacant", t("ship.state.vacant"), [t("ship.bridge.screen.no_crew")]);+ const shown = crew.slice(0, crew.length > 7 ? 6 : 7).map((a) => `${a.name.slice(0, 20).padEnd(21)}${t(`ship.state.${a.state}`)}`);+ if (crew.length > 7) shown.push(t("ship.bridge.screen.more").replace("{count}", String(crew.length - 6)));+ return base(t("ship.bridge.screen.personnel"), "idle", String(crew.length), shown);+ }+ case "comms-console":+ if (!lead) return base(t("ship.bridge.screen.comms"), "vacant", t("ship.state.vacant"), [t("ship.bridge.screen.no_lead")]);+ return base(t("ship.bridge.screen.comms"), lead.state, t(`ship.state.${lead.state}`), [lead.name, lead.title, t("ship.bridge.screen.comms_hint")].filter(Boolean));+ case "science-console": {+ const facts = [+ destinationName(t, here),+ t(`ship.bridge.body.${here.planet.kind}`),+ here.sun.twin ? t("ship.bridge.screen.twin_suns") : t("ship.bridge.screen.one_sun"),+ here.planet.rings ? t("ship.bridge.screen.rings") : "",+ here.planet.cityLights ? t("ship.bridge.screen.cities") : "",+ here.singularity ? t("ship.bridge.screen.singularity") : "",+ ].filter(Boolean);+ return base(t("ship.bridge.screen.science"), "idle", t("ship.bridge.screen.live"), facts);+ }+ case "navigation-console": {+ const others = DESTINATIONS.filter((d) => d.id !== here.id).slice(0, 6);+ return base(t("ship.bridge.screen.navigation"), "idle", `${openDestinations(level).length} / ${DESTINATIONS.length}`, [+ `▸ ${destinationName(t, here)}`,+ ...others.map((d) => (d.level <= level ? ` ${destinationName(t, d)}` : ` ${destinationName(t, d).padEnd(22)}L${d.level}`)),+ ]);+ }+ case "ready-desk": {+ const rank = rankFor(level);+ return base(t("ship.bridge.screen.record"), "idle", t("ship.level").replace("{n}", String(level)), [+ t(`ship.rank.${rank.id}`),+ person ? `${person.xpIntoLevel} / ${person.xpForNext} XP` : "",+ ].filter(Boolean));+ }+ default:+ return base("", "vacant", t("ship.screen.vacant"), []);+ }+ }, [t, destinationId, warpingTo, level, person, crew, lead]);++ const onScreen = useCallback((p: Prop) => {+ if (p.id === "helm-console") actions.openPanel("helm");+ else if (p.id === "ops-console" || p.id === "personnel-console") actions.openLedger();+ else if (p.id === "comms-console" && lead) actions.openAgent(lead.agentId);+ }, [actions, lead]);++ return <ConsoleScreens plan={plan} content={content} onScreen={onScreen} kinds={SCREEN_KINDS} />;+}++// ── the viewscreen overlay ───────────────────────────────────────────++const GRID_VERT = /* glsl */ `varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`;+const GRID_FRAG = /* glsl */ `uniform float uTime; uniform float uWarp; uniform vec3 uColour; varying vec2 vUv;+ float line(float x, float w) { float d = abs(fract(x) - 0.5); return smoothstep(0.5 - w, 0.5, d); }+ void main() {+ vec2 g = vec2(vUv.x * 28.0 + uTime * 0.05, vUv.y * 5.0);+ float grid = max(line(g.x, 0.035), line(g.y, 0.05)) * 0.55;+ float horizon = smoothstep(0.012, 0.0, abs(vUv.y - 0.42));+ float sweep = smoothstep(0.06, 0.0, abs(fract(vUv.x - uTime * 0.03) - 0.5)) * 0.35;+ float ticks = step(0.5 - 0.06, abs(fract(vUv.x * 56.0) - 0.5)) * smoothstep(0.03, 0.0, abs(vUv.y - 0.42)) * 0.8;+ float edge = smoothstep(0.0, 0.08, vUv.x) * smoothstep(1.0, 0.92, vUv.x) * smoothstep(0.0, 0.12, vUv.y) * smoothstep(1.0, 0.85, vUv.y);+ float a = (grid + horizon * 0.8 + ticks + sweep * (0.4 + uWarp)) * edge * (0.22 + uWarp * 0.5);+ gl_FragColor = vec4(uColour * a, a);+ }`;++/**+ * A framed hologram over the middle of the bow window: a slow tactical grid+ * with a bearing line, the destination's name above it (the jump's target+ * while the ship is at warp). Hidden while the camera is out beyond the bow.+ */+function ViewscreenHolo({ reduced, t }: { reduced: boolean; t: ShipActions["t"] }) {+ const destinationId = useShip((s) => s.destination);+ const warpingTo = useShip((s) => s.warpingTo);+ const group = useRef<Group>(null);+ const radius = BOW.radius - VIEWSCREEN_INSET - 0.24;+ const grid = useMemo(() => {+ const geo = new CylinderGeometry(radius, radius, 1.12, 64, 1, true, -VIEWSCREEN_SPAN, VIEWSCREEN_SPAN * 2);+ const mat = new ShaderMaterial({+ vertexShader: GRID_VERT, fragmentShader: GRID_FRAG, transparent: true, blending: AdditiveBlending, depthWrite: false, side: DoubleSide,+ uniforms: { uTime: { value: 0 }, uWarp: { value: 0 }, uColour: { value: new Color(SHIP.cyan).multiplyScalar(1.5) } },+ });+ const mesh = new Mesh(geo, mat);+ mesh.position.set(BOW.centre.x, 1.58, BOW.centre.z);+ mesh.rotation.y = Math.PI;+ mesh.raycast = () => undefined;+ return mesh;+ }, [radius]);+ useEffect(() => () => { grid.geometry.dispose(); (grid.material as ShaderMaterial).dispose(); }, [grid]);++ const target = warpingTo ? destinationById(warpingTo) : destinationById(destinationId);+ const name = destinationName(t, target);+ const eyebrow = (warpingTo ? t("ship.bridge.viewscreen.warp") : t("ship.bridge.viewscreen.destination")).toUpperCase();+ const labels = useMemo(() => {+ const at = { x: BOW.centre.x, z: BOW.centre.z - radius + 0.05 };+ const title = textPlane(name, SHIP.cyan, { size: 0.28 });+ title.position.set(at.x, 1.86, at.z);+ const over = textPlane(eyebrow, SHIP.gold, { size: 0.13, font: "600 64px 'Space Grotesk', 'Inter Variable', sans-serif" });+ over.position.set(at.x, 2.07, at.z);+ return [title, over];+ }, [name, eyebrow, radius]);+ useEffect(() => () => {+ for (const m of labels) { m.geometry.dispose(); const mat = m.material as MeshBasicMaterial; mat.map?.dispose(); mat.dispose(); }+ }, [labels]);++ const warp = useRef(0);+ useFrame(({ camera, clock }, dt) => {+ const g = group.current;+ if (!g) return;+ // Beyond the bow the frame has sunk with the hull: no picture without its frame.+ g.visible = Math.hypot(camera.position.x - BOW.centre.x, camera.position.z - BOW.centre.z) < BOW.radius || camera.position.z > BOW.centre.z;+ const u = (grid.material as ShaderMaterial).uniforms;+ warp.current += ((useShip.getState().warpingTo ? 1 : 0) - warp.current) * Math.min(1, dt * 2.5);+ u.uTime.value = reduced ? 0 : clock.elapsedTime;+ u.uWarp.value = reduced ? 0 : warp.current;+ });+ return (+ <group ref={group}>+ <primitive object={grid} />+ {labels.map((m, i) => <primitive key={i} object={m} />)}+ </group>+ );+}++// ── the star chart ───────────────────────────────────────────────────++const GALAXY_R = 1.05;+const CHART_Y = 1.34;++function rng(seed: number): () => number {+ let s = seed >>> 0;+ return () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; };+}++/** Where a destination lies on the chart: home out on an arm, the galactic core at the heart. */+export function chartPosition(d: Destination, index: number): { x: number; y: number; z: number } {+ const r = GALAXY_R * Math.max(0.08, 0.92 - (d.level / 44) * 0.86);+ const a = index * 2.25 + 0.6;+ return { x: Math.sin(a) * r, y: 0.025, z: Math.cos(a) * r };+}++/**+ * The hologram over the star chart table: a two-armed galaxy of points+ * turning slowly, each destination a marker (gold where the ship is, cyan+ * when the captain's level opens it, dim when it is still locked), the+ * current one ringed and named.+ */+function StarChartHolo({ reduced, quality, t }: { reduced: boolean; quality: "high" | "low"; t: ShipActions["t"] }) {+ const level = useProgression((s) => s.subjects.person?.level ?? 1);+ const destinationId = useShip((s) => s.destination);+ const spin = useRef<Group>(null);+ const galaxy = useMemo(() => {+ const n = quality === "high" ? 2600 : 1200;+ const r = rng(11);+ const pos = new Float32Array(n * 3), col = new Float32Array(n * 3);+ const warm = new Color("#ffe2b8"), cool = new Color("#7fcfff"), deep = new Color("#3c6fd8"), c = new Color();+ for (let i = 0; i < n; i += 1) {+ const bulge = i < n * 0.18;+ const f = bulge ? Math.pow(r(), 2) * 0.22 : 0.12 + Math.pow(r(), 0.8) * 0.88;+ const arm = (i % 2) * Math.PI;+ const a = bulge ? r() * TAU : arm + f * 3.4 + (r() - 0.5) * (0.5 - f * 0.25);+ const rad = f * GALAXY_R;+ const thick = (r() - 0.5) * (bulge ? 0.16 : 0.05) * (1.2 - f);+ pos[i * 3] = Math.sin(a) * rad; pos[i * 3 + 1] = thick; pos[i * 3 + 2] = Math.cos(a) * rad;+ c.copy(warm).lerp(f < 0.35 ? cool : deep, Math.min(1, f * 1.3)).multiplyScalar(0.55 + r() * 0.6);+ col[i * 3] = c.r; col[i * 3 + 1] = c.g; col[i * 3 + 2] = c.b;+ }+ const g = new BufferGeometry();+ g.setAttribute("position", new BufferAttribute(pos, 3));+ g.setAttribute("color", new BufferAttribute(col, 3));+ const m = new PointsMaterial({ size: 0.03, sizeAttenuation: true, vertexColors: true, transparent: true, depthWrite: false, blending: AdditiveBlending, toneMapped: false });+ m.color.setScalar(1.7);+ const p = new Points(g, m);+ p.raycast = () => undefined;+ return p;+ }, [quality]);+ const markers = useMemo(() => DESTINATIONS.map((d, i) => {+ const mesh = new Mesh(new OctahedronGeometry(0.035, 0), new MeshBasicMaterial({ toneMapped: false, transparent: true, depthWrite: false }));+ const at = chartPosition(d, i);+ mesh.position.set(at.x, at.y + 0.02, at.z);+ mesh.raycast = () => undefined;+ return { d, mesh };+ }), []);+ const ring = useMemo(() => {+ const m = new Mesh(new RingGeometry(0.075, 0.09, 40), new MeshBasicMaterial({ color: new Color(SHIP.gold).multiplyScalar(2), toneMapped: false, transparent: true, depthWrite: false, side: DoubleSide }));+ m.rotation.x = -Math.PI / 2;+ m.raycast = () => undefined;+ return m;+ }, []);+ const cone = useMemo(() => {+ const m = new Mesh(new CylinderGeometry(GALAXY_R * 1.02, 0.62, CHART_Y - 0.93, 48, 1, true),+ new MeshBasicMaterial({ color: new Color(SHIP.cyan).multiplyScalar(0.5), transparent: true, opacity: 0.07, blending: AdditiveBlending, depthWrite: false, side: DoubleSide, toneMapped: false }));+ m.position.set(STAR_CHART.x, (CHART_Y + 0.93) / 2, STAR_CHART.z);+ m.raycast = () => undefined;+ return m;+ }, []);+ const here = destinationById(destinationId);+ const label = useMemo(() => {+ const m = textPlane(destinationName(t, here), SHIP.gold, { size: 0.14 });+ m.position.set(STAR_CHART.x, CHART_Y + 0.42, STAR_CHART.z);+ return m;+ }, [t, here]);++ useEffect(() => {+ for (const { d, mesh } of markers) {+ const mat = mesh.material as MeshBasicMaterial;+ const open = d.level <= Math.max(1, level);+ mat.color.set(d.id === here.id ? SHIP.gold : open ? SHIP.cyan : SHIP.steel).multiplyScalar(d.id === here.id ? 2.4 : open ? 1.8 : 0.5);+ mat.opacity = open ? 1 : 0.45;+ mesh.scale.setScalar(d.id === here.id ? 1.5 : open ? 1 : 0.75);+ if (d.id === here.id) ring.position.set(mesh.position.x, mesh.position.y, mesh.position.z);+ }+ }, [markers, ring, level, here]);++ useEffect(() => () => {+ galaxy.geometry.dispose(); (galaxy.material as PointsMaterial).dispose();+ for (const { mesh } of markers) { mesh.geometry.dispose(); (mesh.material as MeshBasicMaterial).dispose(); }+ ring.geometry.dispose(); (ring.material as MeshBasicMaterial).dispose();+ cone.geometry.dispose(); (cone.material as MeshBasicMaterial).dispose();+ }, [galaxy, markers, ring, cone]);+ useEffect(() => () => { label.geometry.dispose(); const m = label.material as MeshBasicMaterial; m.map?.dispose(); m.dispose(); }, [label]);++ const tmp = useMemo(() => new Vector3(), []);+ useFrame(({ camera, clock }, dt) => {+ const t2 = reduced ? 0 : clock.elapsedTime;+ if (spin.current && !reduced) spin.current.rotation.y += dt * 0.06;+ ring.scale.setScalar(1 + Math.sin(t2 * 2.4) * 0.15);+ for (const { mesh } of markers) mesh.rotation.y = t2 * 0.8;+ label.getWorldPosition(tmp);+ label.lookAt(camera.position.x, tmp.y, camera.position.z);+ });++ return (+ <>+ <primitive object={cone} />+ <group position={[STAR_CHART.x, CHART_Y, STAR_CHART.z]} rotation={[0.12, 0, 0]}>+ <group ref={spin}>+ <primitive object={galaxy} />+ {markers.map(({ d, mesh }) => <primitive key={d.id} object={mesh} />)}+ <primitive object={ring} />+ </group>+ </group>+ <primitive object={label} />+ </>+ );+}++// ── sitting down on arrival ──────────────────────────────────────────++/** A captain sent to the chair from afar sits down on arriving (any other stop cancels it). */+function SitOnArrival({ plan, actions }: { plan: DeckPlan; actions: ShipActions }) {+ useFrame(() => {+ const asked = bridgeRuntime.seatRequestedMs;+ if (!asked || performance.now() - asked < 400 || captain.moving || captain.path.length > 0) return;+ bridgeRuntime.seatRequestedMs = 0;+ const station = plan.stations.find((s) => s.kind === "captain");+ const seat = plan.places.find((p) => p.kind === "captain");+ if (!station || !seat || Math.hypot(captain.x - station.x, captain.z - station.z) > station.radius) return;+ actions.sit({ x: seat.x, z: seat.z, yaw: seat.yaw, seatY: seat.seatY });+ });+ return null;+}++// ── the warp jump ────────────────────────────────────────────────────++const STREAKS = 340;+const FIELD_LEN = 420;++const FLASH_VERT = /* glsl */ `void main() { gl_Position = vec4(position.xy, 0.0, 1.0); }`;+const FLASH_FRAG = /* glsl */ `uniform float uAmount; void main() { gl_FragColor = vec4(vec3(0.92, 0.96, 1.0) * (1.0 + uAmount), uAmount); }`;++/**+ * Stars streaking past the ship from bow to stern: a field of a few hundred+ * additive lines round the deck that grow longer and faster with the jump's+ * progress, then a flash that hides the change of sky, then the field fades+ * as the ship drops out at the new destination.+ */+function WarpJump({ plan }: { plan: DeckPlan }) {+ const warpingTo = useShip((s) => s.warpingTo);+ const clock = useRef({ start: 0, end: 0, peak: 0 });+ useEffect(() => {+ const now = performance.now();+ if (warpingTo) { clock.current.start = now; clock.current.end = 0; }+ else if (clock.current.start) { clock.current.end = now; }+ }, [warpingTo]);++ const field = useMemo(() => {+ const r = rng(29);+ const seeds = Array.from({ length: STREAKS }, () => {+ const a = r() * TAU, rad = 22 + Math.pow(r(), 0.7) * 150;+ return { x: Math.cos(a) * rad, y: Math.sin(a) * rad * 0.65, z: r() * FIELD_LEN, speed: 0.6 + r() * 0.8, tint: r() };+ });+ const g = new BufferGeometry();+ g.setAttribute("position", new BufferAttribute(new Float32Array(STREAKS * 6), 3));+ g.setAttribute("color", new BufferAttribute(new Float32Array(STREAKS * 6), 3));+ const m = new LineBasicMaterial({ vertexColors: true, transparent: true, blending: AdditiveBlending, depthWrite: false, toneMapped: false });+ const lines = new LineSegments(g, m);+ lines.frustumCulled = false;+ lines.visible = false;+ lines.raycast = () => undefined;+ return { lines, seeds, offset: 0 };+ }, []);+ const flash = useMemo(() => {+ const m = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({+ vertexShader: FLASH_VERT, fragmentShader: FLASH_FRAG, transparent: true, depthTest: false, depthWrite: false, toneMapped: false,+ uniforms: { uAmount: { value: 0 } },+ }));+ m.frustumCulled = false;+ m.renderOrder = 999;+ m.visible = false;+ m.raycast = () => undefined;+ return m;+ }, []);+ useEffect(() => () => {+ field.lines.geometry.dispose(); (field.lines.material as LineBasicMaterial).dispose();+ flash.geometry.dispose(); (flash.material as ShaderMaterial).dispose();+ }, [field, flash]);++ const cx = (plan.bounds.x0 + plan.bounds.x1) / 2, cz = (plan.bounds.z0 + plan.bounds.z1) / 2;+ const blue = useMemo(() => new Color("#9fd4ff"), []), white = useMemo(() => new Color("#f4f8ff"), []), c = useMemo(() => new Color(), []);+ useFrame((_, rawDt) => {+ const dt = Math.min(0.1, rawDt);+ const now = performance.now();+ const k = clock.current;+ let progress = 0, flashAmount = 0;+ if (k.start && !k.end) {+ const s = Math.min(1, (now - k.start) / WARP_MS);+ progress = s * s;+ k.peak = progress;+ flashAmount = Math.min(1, Math.max(0, (s - 0.86) / 0.11));+ } else if (k.end) {+ const out = (now - k.end) / 900;+ progress = k.peak * Math.max(0, 1 - out);+ flashAmount = Math.max(0, 1 - (now - k.end) / 650);+ if (out >= 1 && flashAmount <= 0) { k.start = 0; k.end = 0; k.peak = 0; }+ }+ const fm = flash.material as ShaderMaterial;+ fm.uniforms.uAmount.value = flashAmount;+ flash.visible = flashAmount > 0.001;+ const lines = field.lines;+ lines.visible = progress > 0.002;+ if (!lines.visible) return;+ field.offset += dt * (25 + 1500 * progress * progress);+ const len = 0.4 + 95 * Math.pow(progress, 1.5);+ const bright = Math.min(1, progress * 3) * 2.2;+ const pos = lines.geometry.attributes.position as BufferAttribute;+ const col = lines.geometry.attributes.color as BufferAttribute;+ field.seeds.forEach((s, i) => {+ // Bow to stern: the ship flies towards -z, so the stars run towards +z.+ const z = cz - FIELD_LEN / 2 + ((s.z + field.offset * s.speed) % FIELD_LEN);+ const x = cx + s.x, y = s.y;+ pos.setXYZ(i * 2, x, y, z);+ pos.setXYZ(i * 2 + 1, x, y, z - len * s.speed);+ c.copy(blue).lerp(white, s.tint).multiplyScalar(bright);+ col.setXYZ(i * 2, c.r, c.g, c.b);+ col.setXYZ(i * 2 + 1, 0, 0, 0);+ });+ pos.needsUpdate = true;+ col.needsUpdate = true;+ });+ return (+ <>+ <primitive object={field.lines} />+ <primitive object={flash} />+ </>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/HelmPanel.tsx b/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/HelmPanel.tsxnew file mode 100644index 0000000000..52e6e81a84--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/HelmPanel.tsx@@ -0,0 +1,120 @@+/**+ * The helm's panel: "Set a course". Every destination is a row with its name,+ * one line about it and the captain's level that opens it; the ones the+ * captain's level has opened can be chosen, the current one is marked.+ * Choosing one closes the panel and starts the warp jump. Keyboard: the+ * arrows move between rows, Enter engages, Escape closes; focus stays in the+ * dialog while it is open and returns where it was afterwards.+ */+import { useEffect, useId, useRef, type CSSProperties, type KeyboardEvent } from "react";+import { useReducedMotion } from "framer-motion";+import { useProgression } from "../../../progression/progressionStore";+import { useShip } from "../../shipStore";+import { DESTINATIONS, destinationById, type Destination } from "../../space/destinations";+import type { DeckPanelProps } from "../registry";+import { engageWarp } from "./bridgeRuntime";+import "./bridge.css";++export function BridgePanel(props: DeckPanelProps) {+ if (props.station.kind !== "helm") return null;+ return <HelmPanel {...props} />;+}++/** A small swatch of the place: its planet's day side, or the nebula where there is none. */+function swatch(d: Destination): CSSProperties {+ if (d.singularity) return { background: `radial-gradient(circle at 50% 50%, #000 0 34%, #ffcf8a 40%, ${d.sky.nebula[1]} 62%, #05070c 76%)` };+ if (d.planet.kind === "none") return { background: `radial-gradient(circle at 40% 40%, ${d.sky.nebula[1]}, ${d.sky.nebula[0]} 58%, #05070c 80%)` };+ const [deep, mid, bright] = d.planet.colours;+ return { background: `radial-gradient(circle at 34% 30%, ${bright}, ${mid} 42%, ${deep} 72%, #05070c 74%)` };+}++function HelmPanel({ actions }: DeckPanelProps) {+ const { t } = actions;+ const reduced = useReducedMotion() ?? false;+ const level = useProgression((s) => s.subjects.person?.level ?? 1);+ const hereId = useShip((s) => s.destination);+ const warping = useShip((s) => s.warpingTo);+ const here = destinationById(hereId);+ const titleId = useId();+ const dialog = useRef<HTMLElement>(null);+ const list = useRef<HTMLDivElement>(null);++ useEffect(() => {+ const before = document.activeElement;+ const first = list.current?.querySelector<HTMLButtonElement>("[aria-current='true']") ?? list.current?.querySelector<HTMLButtonElement>("button");+ first?.focus();+ return () => { if (before instanceof HTMLElement && before.isConnected) before.focus(); };+ }, []);++ const name = (d: Destination) => t(`ship.bridge.destination.${d.id}.name`);+ const choose = (d: Destination) => {+ if (warping) return;+ if (d.id === here.id) { actions.say(t("ship.bridge.helm.already").replace("{place}", name(d))); return; }+ if (d.level > level) { actions.say(t("ship.bridge.helm.locked_say").replace("{place}", name(d)).replace("{n}", String(d.level))); return; }+ actions.closePanel();+ if (engageWarp(d.id, reduced, actions)) actions.say(t("ship.bridge.helm.engaged").replace("{place}", name(d)));+ };++ const onKey = (e: KeyboardEvent<HTMLElement>) => {+ // The ship's own keys (walking, E, O, F) stay out while the dialog has focus.+ e.stopPropagation();+ if (e.key === "Escape") { e.preventDefault(); actions.closePanel(); return; }+ const rows = [...(list.current?.querySelectorAll<HTMLButtonElement>("button") ?? [])];+ const at = rows.indexOf(document.activeElement as HTMLButtonElement);+ const go = (i: number) => { e.preventDefault(); rows[(i + rows.length) % rows.length]?.focus(); };+ if (e.key === "ArrowDown") go(at + 1);+ else if (e.key === "ArrowUp") go(at < 0 ? rows.length - 1 : at - 1);+ else if (e.key === "Home") go(0);+ else if (e.key === "End") go(rows.length - 1);+ else if (e.key === "Tab") {+ const all = [...(dialog.current?.querySelectorAll<HTMLButtonElement>("button") ?? [])];+ if (all.length === 0) return;+ const first = all[0], last = all[all.length - 1];+ if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }+ else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }+ }+ };++ return (+ <div className="ship-scrim" onClick={() => actions.closePanel()}>+ <section ref={dialog} className="ship-panel bridge-helm" role="dialog" aria-modal="true" aria-labelledby={titleId}+ onClick={(e) => e.stopPropagation()} onKeyDown={onKey}>+ <header className="bridge-helm-head">+ <div>+ <div className="ship-eyebrow">{t("ship.bridge.helm.eyebrow")}</div>+ <h2 id={titleId}>{t("ship.bridge.helm.title")}</h2>+ <p>+ {t("ship.bridge.helm.holding").replace("{place}", name(here))}+ <span aria-hidden="true"> · </span>+ {t("ship.bridge.helm.captain_level").replace("{n}", String(level))}+ </p>+ </div>+ <button type="button" className="ship-tool bridge-helm-close" aria-label={t("ship.close")} onClick={() => actions.closePanel()}>✕</button>+ </header>+ {warping && <div className="bridge-helm-warping" role="status">{t("ship.bridge.helm.warping").replace("{place}", name(destinationById(warping)))}</div>}+ <div ref={list} className="bridge-helm-list">+ {DESTINATIONS.map((d) => {+ const current = d.id === here.id;+ const locked = d.level > level;+ const state = current ? "here" : locked ? "locked" : "open";+ return (+ <button key={d.id} type="button" className="bridge-helm-row" data-state={state} aria-current={current}+ aria-disabled={locked || !!warping || undefined} onClick={() => choose(d)}>+ <span className="bridge-helm-swatch" style={swatch(d)} aria-hidden="true" />+ <span className="bridge-helm-text">+ <b>{name(d)}</b>+ <small>{t(`ship.bridge.destination.${d.id}.about`)}</small>+ </span>+ <span className="bridge-helm-meta">+ <span className="bridge-helm-chip">{t(`ship.bridge.helm.${state}`)}</span>+ <small>{t("ship.bridge.helm.opens").replace("{n}", String(d.level))}</small>+ </span>+ </button>+ );+ })}+ </div>+ <p className="bridge-helm-hint">{t("ship.bridge.helm.hint")}</p>+ </section>+ </div>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/bridge.css b/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/bridge.cssnew file mode 100644index 0000000000..10b846bfd9--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/bridge.css@@ -0,0 +1,63 @@+/* The bridge's helm panel: the ship's dark glass, gold for command, cyan for what is open. */++.bridge-helm {+ width: min(480px, calc(100% - 32px));+ max-height: calc(100% - 48px);+ padding: 18px 18px 14px;+ display: flex;+ flex-direction: column;+ gap: 12px;+ background: var(--ship-glass-strong);+}++.bridge-helm-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }+.bridge-helm-head h2 { margin: 4px 0 4px; font: 600 17px "Space Grotesk", sans-serif; letter-spacing: 0.03em; color: var(--ship-text); }+.bridge-helm-head p { margin: 0; font-size: 12px; color: var(--ship-muted); }+.bridge-helm-close { flex: none; }++.bridge-helm-warping {+ padding: 8px 12px; border-radius: 8px; font-size: 12.5px; color: var(--ship-cyan);+ border: 1px solid rgba(95, 212, 255, 0.35); background: rgba(95, 212, 255, 0.07);+}++.bridge-helm-list { display: flex; flex-direction: column; gap: 6px; overflow-y: auto; min-height: 0; padding: 2px; margin: -2px; }++.bridge-helm-row {+ display: grid; grid-template-columns: 34px 1fr auto; align-items: center; gap: 12px; padding: 9px 12px; border-radius: 8px;+ border: 1px solid var(--ship-line); background: rgba(255, 255, 255, 0.025); color: var(--ship-text); text-align: left;+ font: inherit; cursor: pointer;+}+.bridge-helm-row:hover { border-color: rgba(95, 212, 255, 0.45); background: rgba(95, 212, 255, 0.05); }+.bridge-helm-row:focus-visible { outline: 2px solid var(--ship-gold); outline-offset: 1px; }+.bridge-helm-row[data-state="here"] { border-color: rgba(217, 164, 65, 0.55); background: rgba(217, 164, 65, 0.07); cursor: default; }+.bridge-helm-row[data-state="locked"] { cursor: not-allowed; }+.bridge-helm-row[data-state="locked"] .bridge-helm-text,+.bridge-helm-row[data-state="locked"] .bridge-helm-swatch { opacity: 0.45; }+.bridge-helm-row[data-state="locked"]:hover { border-color: var(--ship-line-strong); background: rgba(255, 255, 255, 0.025); }+.bridge-helm-row[aria-disabled="true"][data-state="open"] { cursor: progress; }++.bridge-helm-swatch {+ width: 34px; height: 34px; border-radius: 50%; display: block;+ box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.12), 0 0 12px rgba(0, 0, 0, 0.4);+}++.bridge-helm-text { min-width: 0; }+.bridge-helm-text b { display: block; font-weight: 600; font-size: 13.5px; }+.bridge-helm-text small { display: block; margin-top: 2px; font-size: 11.5px; line-height: 1.35; color: var(--ship-muted); }++.bridge-helm-meta { display: flex; flex-direction: column; align-items: flex-end; gap: 4px; white-space: nowrap; }+.bridge-helm-meta small { font: 500 10.5px "JetBrains Mono", monospace; color: var(--ship-muted); }+.bridge-helm-chip {+ font: 600 10px "Space Grotesk", sans-serif; letter-spacing: 0.14em; text-transform: uppercase;+ padding: 2px 7px; border-radius: 999px; border: 1px solid rgba(95, 212, 255, 0.4); color: var(--ship-cyan);+}+.bridge-helm-row[data-state="here"] .bridge-helm-chip { border-color: rgba(217, 164, 65, 0.6); color: var(--ship-gold); }+.bridge-helm-row[data-state="locked"] .bridge-helm-chip { border-color: var(--ship-line-strong); color: var(--ship-muted); }++.bridge-helm-hint { margin: 0; font-size: 11.5px; color: var(--ship-muted); }++@media (max-width: 520px) {+ .bridge-helm-row { grid-template-columns: 28px 1fr; }+ .bridge-helm-swatch { width: 28px; height: 28px; }+ .bridge-helm-meta { grid-column: 2; flex-direction: row; align-items: center; justify-content: flex-start; gap: 8px; }+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/bridgeDeck.test.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/bridgeDeck.test.tsnew file mode 100644index 0000000000..e9836f8e3d--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/bridgeDeck.test.ts@@ -0,0 +1,107 @@+import { readdirSync, readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { buildBridgeDeck, bridgeHull, COMMAND, RAIL_R, READY_ROOM } from "./bridgeDeck";+import { buildNavGrid, findPath, isFree, lineOfSight } from "../../nav/shipNav";+import { insidePolygon } from "../../plan/builder";+import { rectContains, type Vec2 } from "../../plan/types";+import { DESTINATION_IDS } from "../../space/destinations";++function cross(o: Vec2, a: Vec2, b: Vec2): number {+ return (a.x - o.x) * (b.z - o.z) - (a.z - o.z) * (b.x - o.x);+}++describe("bridge deck plan", () => {+ const plan = buildBridgeDeck();+ const grid = buildNavGrid(plan);++ it("has a convex hull with the bow at z = 0", () => {+ const hull = bridgeHull();+ const signs = hull.map((p, i) => Math.sign(cross(p, hull[(i + 1) % hull.length], hull[(i + 2) % hull.length])));+ expect(new Set(signs.filter((s) => s !== 0)).size).toBe(1);+ expect(Math.min(...hull.map((p) => p.z))).toBeCloseTo(0, 6);+ expect(plan.bounds.z0).toBeCloseTo(0, 6);+ });++ it("reaches every place and station from the turbolift", () => {+ const misses: string[] = [];+ for (const place of plan.places) if (!findPath(grid, plan.lift, place)) misses.push(place.id);+ for (const station of plan.stations) if (!findPath(grid, plan.lift, station)) misses.push(station.id);+ expect(misses).toEqual([]);+ expect(isFree(grid, plan.lift)).toBe(true);+ expect(isFree(grid, plan.arrival)).toBe(true);+ });++ it("keeps ids unique and everything inside the hull", () => {+ const ids = [+ ...plan.props.map((x) => `prop:${x.id}`), ...plan.places.map((x) => `place:${x.id}`),+ ...plan.stations.map((x) => `station:${x.id}`), ...plan.rooms.map((x) => `room:${x.id}`), ...plan.walls.map((x) => `wall:${x.id}`),+ ];+ expect(new Set(ids).size).toBe(ids.length);+ for (const p of [...plan.places, ...plan.stations, ...plan.props]) expect(insidePolygon(plan.hull, p)).toBe(true);+ });++ it("seats the captain inside the horseshoe rail", () => {+ const seat = plan.places.find((p) => p.kind === "captain");+ expect(seat).toBeDefined();+ if (!seat) return;+ expect(Math.hypot(seat.x - COMMAND.x, seat.z - COMMAND.z)).toBeLessThan(RAIL_R - 1);+ expect(isFree(grid, seat)).toBe(true);+ // The rail is real: straight back to the lift is blocked, the way round (through the bow-side gap) is not.+ expect(plan.walls.filter((w) => w.kind === "rail").length).toBeGreaterThan(6);+ expect(lineOfSight(grid, seat, plan.lift)).toBe(false);+ expect(findPath(grid, plan.lift, seat)).not.toBeNull();+ const chair = plan.props.find((p) => p.kind === "captainChair");+ expect(chair && Math.hypot(chair.x - seat.x, chair.z - seat.z)).toBeLessThan(0.01);+ expect(plan.stations.find((s) => s.kind === "captain")?.propId).toBe(chair?.id);+ });++ it("has the bridge's stations, the turbolift centred on the stern wall", () => {+ const kinds = plan.stations.map((s) => s.kind);+ for (const k of ["captain", "firstOfficer", "helm", "ops", "lift"] as const) expect(kinds).toContain(k);+ const lift = plan.stations.find((s) => s.kind === "lift");+ expect(lift?.x).toBeCloseTo(0, 6);+ expect(plan.doors.find((d) => d.id === "lift-door")?.at.x).toBeCloseTo(0, 6);+ expect(plan.lift.z).toBeGreaterThan(plan.bounds.z1 - 2.5);+ expect(plan.props.some((p) => p.kind === "starChart" && !p.ref)).toBe(true);+ expect(plan.props.filter((p) => p.kind === "viewscreen").length).toBeGreaterThan(3);+ });++ it("puts the ready room off the side with a desk, a window and a door", () => {+ const room = plan.rooms.find((r) => r.kind === "readyroom");+ expect(room?.rect).toEqual(READY_ROOM);+ const desk = plan.props.find((p) => p.ref === "desk" && p.kind === "helmConsole");+ expect(desk && rectContains(READY_ROOM, desk)).toBe(true);+ expect(plan.places.some((p) => p.kind === "window" && rectContains(READY_ROOM, p))).toBe(true);+ expect(plan.doors.some((d) => d.id === "ready-door")).toBe(true);+ expect(plan.walls.some((w) => w.kind === "hull" && w.windows && w.a.x === READY_ROOM.x1 && w.b.x === READY_ROOM.x1)).toBe(true);+ });++ it("invents no crew", () => {+ expect(plan.divisions).toEqual([]);+ expect(plan.seatOf.size).toBe(0);+ expect(plan.places.some((p) => p.owner)).toBe(false);+ });+});++describe("bridge strings", () => {+ const dir = join(__dirname, "..", "..", "..", "..", "..", "i18n", "locales", "ship");+ const files = readdirSync(dir).filter((f) => /^bridge\.[a-z]+\.json$/.test(f));+ const flatten = (obj: Record<string, unknown>, prefix = ""): string[] => Object.entries(obj).flatMap(([k, v]) =>+ v && typeof v === "object" ? flatten(v as Record<string, unknown>, `${prefix}${k}.`) : [`${prefix}${k}`]);+ const load = (f: string) => JSON.parse(readFileSync(join(dir, f), "utf8")) as Record<string, unknown>;++ it("ships the same keys in all five languages", () => {+ expect(files.sort()).toEqual(["bridge.de.json", "bridge.en.json", "bridge.es.json", "bridge.pt.json", "bridge.zh.json"]);+ const en = flatten(load("bridge.en.json")).sort();+ for (const f of files) expect(flatten(load(f)).sort()).toEqual(en);+ });++ it("names and describes every destination", () => {+ const en = new Set(flatten(load("bridge.en.json")));+ for (const id of DESTINATION_IDS) {+ expect(en.has(`ship.bridge.destination.${id}.name`)).toBe(true);+ expect(en.has(`ship.bridge.destination.${id}.about`)).toBe(true);+ }+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/bridgeDeck.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/bridgeDeck.tsnew file mode 100644index 0000000000..16c5f095ae--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/bridgeDeck.ts@@ -0,0 +1,211 @@+/**+ * The bridge: where the captain commands the ship.+ *+ * bow ── a curved forward window, the viewscreen in its middle+ * helm · ops (two consoles facing the window)+ * ╭── command well ──╮ the captain's chair between two seats,+ * │ ( chair ) │ inside a horseshoe rail open to the bow,+ * ╰── tactical ──────╯ the tactical console at its aft apex+ * science │ star chart │ ready room (starboard: desk, sofa, window)+ * stern ── aft stations either side of the turbolift+ *+ * Nobody is invented here: the deck's population is "none", so the only+ * people on it are the captain and the pet. The seats are real places the+ * captain uses; the screens show the ship's real state. The command well+ * reads as sunken (a lit step drawn by the scene) while the floor stays flat+ * for walking.+ */+import { arcPoints, COMMAND_GOLD, HOLO_CYAN, PlanBuilder, polygonBounds, yawTowards } from "../../plan/builder";+import type { DeckPlan, Vec2 } from "../../plan/types";+import { rect } from "../../plan/types";++/** Half the bridge's beam (x) and its length from the bow (z). */+export const BRIDGE_HALF_W = 15;+export const BRIDGE_END = 30;++/** The bow: an arc of short hull segments round `centre`, ±`span` from straight ahead. */+export const BOW = { centre: { x: 0, z: 15 } as Vec2, radius: 15, span: (60 / 180) * Math.PI, segments: 10 } as const;+/** The viewscreen fills the middle of the bow window, ±this angle. */+export const VIEWSCREEN_SPAN = (36 / 180) * Math.PI;+/** How far the viewscreen's frame stands in from the hull's centre line. */+export const VIEWSCREEN_INSET = 0.41;++/** The command well and the horseshoe rail round it. */+export const COMMAND: Vec2 = { x: 0, z: 13.5 };+export const RAIL_R = 4.6;+/** The rail's arc, centred on the stern side; the rest (towards the bow) is the way in. */+export const RAIL_SPAN = (236 / 180) * Math.PI;+const RAIL_SEGMENTS = 11;+/** The sunken-looking floor of the well (visual only). */+export const WELL_R = 3.45;++export const STAR_CHART = { x: 0, z: 23.4, r: 1.3 } as const;+/** The captain's ready room, off the starboard side. */+export const READY_ROOM = rect(9.5, 11.5, BRIDGE_HALF_W, 21.5);+const READY_DOOR_Z = 16.5;++const SIDE_Z = 11.5;++/** A point on the bow arc at angle `a` (0 = straight ahead, positive to starboard). */+export function bowPoint(a: number, radius: number = BOW.radius): Vec2 {+ return { x: BOW.centre.x + Math.sin(a) * radius, z: BOW.centre.z - Math.cos(a) * radius };+}++/** The bridge's hull, clockwise from the port end of the bow arc. Convex. */+export function bridgeHull(): Vec2[] {+ const out: Vec2[] = [];+ for (let k = 0; k <= BOW.segments; k += 1) out.push(bowPoint(-BOW.span + (2 * BOW.span * k) / BOW.segments));+ const W = BRIDGE_HALF_W, E = BRIDGE_END;+ out.push({ x: W, z: SIDE_Z }, { x: W, z: E - 3 }, { x: W - 3, z: E }, { x: -W + 3, z: E }, { x: -W, z: E - 3 }, { x: -W, z: SIDE_Z });+ return out;+}++export function buildBridgeDeck(): DeckPlan {+ const b = new PlanBuilder("bridge");+ const hull = bridgeHull();+ const bounds = polygonBounds(hull);+ const W = BRIDGE_HALF_W, E = BRIDGE_END;+ const C = COMMAND;++ // ── hull: the bow window, the side windows, the turbolift in the stern ──+ hull.forEach((p, i) => {+ const q = hull[(i + 1) % hull.length];+ if (p.z === E && q.z === E) {+ b.wallWithDoors(`hull-${i}`, "hull", p, q, [{ at: Math.abs(q.x - p.x) / 2, width: 3, slides: true, id: "lift-door" }], 0.5);+ } else {+ b.wall(`hull-${i}`, "hull", p, q, 0.5, true);+ }+ });++ // ── rooms ──────────────────────────────────────────────────────────+ // The open bridge is three rectangles round the ready room, so no floor is laid twice.+ b.room({ id: "bridge", kind: "bridge", rect: rect(-W, 0, READY_ROOM.x0, E), floor: "deck", accent: COMMAND_GOLD, sign: null });+ b.room({ id: "bridge-fore", kind: "bridge", rect: rect(READY_ROOM.x0, 0, W, READY_ROOM.z0), floor: "deck", accent: COMMAND_GOLD, sign: null });+ b.room({ id: "bridge-aft", kind: "bridge", rect: rect(READY_ROOM.x0, READY_ROOM.z1, W, E), floor: "deck", accent: COMMAND_GOLD, sign: null });++ // ── the viewscreen: a frame round the middle of the bow window ─────+ for (let k = 0; k < BOW.segments; k += 1) {+ const a0 = -BOW.span + (2 * BOW.span * k) / BOW.segments;+ const a1 = -BOW.span + (2 * BOW.span * (k + 1)) / BOW.segments;+ const mid = (a0 + a1) / 2;+ if (Math.abs(mid) > VIEWSCREEN_SPAN) continue;+ const p0 = bowPoint(a0), p1 = bowPoint(a1);+ const m = { x: (p0.x + p1.x) / 2, z: (p0.z + p1.z) / 2 };+ const len = Math.hypot(p1.x - p0.x, p1.z - p0.z);+ const inward = { x: C.x - m.x, z: BOW.centre.z - m.z };+ const n = Math.hypot(inward.x, inward.z);+ const at = { x: m.x + (inward.x / n) * VIEWSCREEN_INSET, z: m.z + (inward.z / n) * VIEWSCREEN_INSET };+ b.prop({ id: `viewscreen-${k}`, kind: "viewscreen", x: at.x, z: at.z, yaw: yawTowards(at, BOW.centre), w: len + 0.02, d: 0.34, h: 2.6, solid: true });+ }+ // Standing at the window, looking out.+ for (const [k, deg] of [-42, -21, 21, 42].entries()) {+ const a = (deg / 180) * Math.PI;+ const p = bowPoint(a, BOW.radius - 1.25);+ b.place({ id: `window-${k}`, kind: "window", x: p.x, z: p.z, yaw: yawTowards(p, bowPoint(a)), pose: "stand", seatY: 0 });+ }++ // ── helm and operations, facing the viewscreen ─────────────────────+ for (const [id, x] of [["helm", -2.5], ["ops", 2.5]] as const) {+ const z = 8.0;+ b.prop({ id: `${id}-console`, kind: "helmConsole", x, z, yaw: 0, w: 1.9, d: 0.85, h: 1.1, solid: true, ref: id, accent: COMMAND_GOLD });+ b.prop({ id: `${id}-chair`, kind: "consoleChair", x, z: z + 0.88, yaw: Math.PI, w: 0.55, d: 0.55, h: 1.0, solid: false, accent: COMMAND_GOLD });+ b.place({ id: `${id}-seat`, kind: "command", x, z: z + 0.88, yaw: Math.PI, pose: "sit", seatY: 0.5 });+ b.station({ id, kind: id, x, z: z + 1.3, radius: 1.3, propId: `${id}-console` });+ }++ // ── the command well: the captain's chair between two seats ────────+ const chair = { x: C.x, z: C.z + 0.4 };+ b.prop({ id: "captain-chair", kind: "captainChair", x: chair.x, z: chair.z, yaw: Math.PI, w: 0.92, d: 0.9, h: 1.32, solid: false });+ b.place({ id: "captain-seat", kind: "captain", x: chair.x, z: chair.z, yaw: Math.PI, pose: "sit", seatY: 0.5 });+ // The captain walks right up to the chair (it is not solid), so sitting down is a turn, not a jump.+ b.station({ id: "captain", kind: "captain", x: chair.x, z: chair.z - 0.3, radius: 1.4, propId: "captain-chair" });+ for (const [id, side] of [["first-officer", 1], ["port", -1]] as const) {+ const x = C.x + side * 2.05, z = C.z + 0.6;+ // Turned a little towards the captain.+ const yaw = Math.PI + side * 0.18;+ b.prop({ id: `${id}-seat`, kind: "commandSeat", x, z, yaw, w: 0.72, d: 0.72, h: 1.08, solid: false, ref: id === "port" ? "port" : "firstOfficer" });+ b.place({ id: `${id}-seat`, kind: "command", x, z, yaw, pose: "sit", seatY: 0.48 });+ }+ b.station({ id: "firstOfficer", kind: "firstOfficer", x: C.x + 2.05, z: C.z - 0.25, radius: 1.0, propId: "first-officer-seat" });++ // ── the horseshoe rail, open to the bow, tactical at its apex ──────+ const rail = arcPoints(C, RAIL_R, RAIL_SEGMENTS + 1, 0, RAIL_SPAN);+ const apex = (RAIL_SEGMENTS - 1) / 2;+ for (let i = 0; i < RAIL_SEGMENTS; i += 1) {+ const p = rail[i], q = rail[i + 1];+ const m = { x: (p.x + q.x) / 2, z: (p.z + q.z) / 2 };+ const len = Math.hypot(q.x - p.x, q.z - p.z);+ const inward = yawTowards(m, C);+ if (i === apex) {+ // The tactical console takes the apex; its officer stands outside the rail, looking forward over the well.+ b.prop({ id: "tactical", kind: "tacticalRail", x: m.x, z: m.z, yaw: inward + Math.PI, w: len + 0.08, d: 0.62, h: 1.08, solid: true, ref: "console", accent: COMMAND_GOLD });+ const out = { x: m.x + Math.sin(inward + Math.PI) * 0.95, z: m.z + Math.cos(inward + Math.PI) * 0.95 };+ b.place({ id: "tactical-stand", kind: "command", x: out.x, z: out.z, yaw: inward, pose: "stand", seatY: 0 });+ continue;+ }+ b.wall(`rail-${i}`, "rail", p, q);+ b.prop({ id: `rail-panel-${i}`, kind: "tacticalRail", x: m.x, z: m.z, yaw: inward, w: len, d: 0.16, h: 1.0, solid: false, ref: "panel" });+ }++ // ── science and navigation along the port side ─────────────────────+ for (const [id, z] of [["science", 15.0], ["navigation", 18.4]] as const) {+ const x = -W + 0.7;+ b.prop({ id: `${id}-console`, kind: "console", x, z, yaw: Math.PI / 2, w: 1.15, d: 0.72, h: 1.02, solid: true, accent: HOLO_CYAN });+ b.prop({ id: `${id}-chair`, kind: "consoleChair", x: x + 0.82, z, yaw: -Math.PI / 2, w: 0.55, d: 0.55, h: 1.0, solid: false, accent: HOLO_CYAN });+ b.place({ id: `${id}-seat`, kind: "command", x: x + 0.82, z, yaw: -Math.PI / 2, pose: "sit", seatY: 0.5 });+ }++ // ── the star chart, between the rail and the turbolift ─────────────+ const chart = STAR_CHART;+ b.prop({ id: "star-chart", kind: "starChart", x: chart.x, z: chart.z, yaw: 0, w: chart.r * 2, d: chart.r * 2, h: 0.95, solid: true, accent: HOLO_CYAN });+ arcPoints(chart, chart.r + 0.8, 6, 0, (Math.PI * 2 * 5) / 6).forEach((p, k) => {+ b.place({ id: `chart-${k}`, kind: "chart", x: p.x, z: p.z, yaw: p.yaw + Math.PI, pose: "stand", seatY: 0 });+ });+ // Course can be set from the chart too: it opens the helm's panel.+ b.station({ id: "chart", kind: "helm", x: chart.x, z: chart.z + chart.r + 0.65, radius: 1.1, propId: "star-chart" });++ // ── stern: the turbolift and an aft station either side ────────────+ b.room({ id: "lift-lobby", kind: "lift", rect: rect(-4, E - 3.5, 4, E), floor: "deck", accent: COMMAND_GOLD,+ sign: { key: "ship.room.lift" }, signAt: { x: 0, z: E - 0.35, yaw: Math.PI } });+ b.prop({ id: "lift-doors", kind: "liftDoors", x: 0, z: E - 0.3, yaw: Math.PI, w: 3.4, d: 0.5, h: 2.7, solid: true });+ b.station({ id: "lift", kind: "lift", x: 0, z: E - 1.4, radius: 1.6, propId: "lift-doors" });+ for (const [id, x] of [["personnel", -6.2], ["comms", 6.2]] as const) {+ const z = E - 0.7;+ b.prop({ id: `${id}-console`, kind: "console", x, z, yaw: Math.PI, w: 1.15, d: 0.72, h: 1.02, solid: true, accent: id === "comms" ? COMMAND_GOLD : HOLO_CYAN });+ b.prop({ id: `${id}-chair`, kind: "consoleChair", x, z: z - 0.82, yaw: 0, w: 0.55, d: 0.55, h: 1.0, solid: false, accent: id === "comms" ? COMMAND_GOLD : HOLO_CYAN });+ b.place({ id: `${id}-seat`, kind: "command", x, z: z - 0.82, yaw: 0, pose: "sit", seatY: 0.5 });+ }+ for (const [k, x] of [-10.2, 10.2].entries()) b.prop({ id: `aft-plant-${k}`, kind: "plant", x, z: E - 0.9, yaw: 0, w: 0.8, d: 0.8, h: 1.4, solid: true });+ for (const [k, x] of [-12.2, 12.2].entries()) b.prop({ id: `fore-plant-${k}`, kind: "plant", x, z: 10.4, yaw: 0, w: 0.8, d: 0.8, h: 1.4, solid: true });+ b.place({ id: "window-port", kind: "window", x: -W + 0.9, z: 23.2, yaw: -Math.PI / 2, pose: "stand", seatY: 0 });+ b.place({ id: "window-starboard", kind: "window", x: W - 0.9, z: 24.6, yaw: Math.PI / 2, pose: "stand", seatY: 0 });+ b.place({ id: "stroll-aft", kind: "stroll", x: -4.4, z: 25.6, yaw: Math.PI, pose: "stand", seatY: 0 });++ // ── the ready room ─────────────────────────────────────────────────+ const R = READY_ROOM;+ b.room({ id: "readyroom", kind: "readyroom", rect: R, floor: "carpet", accent: COMMAND_GOLD,+ sign: { key: "ship.bridge.room.readyroom" }, signAt: { x: R.x0 - 0.2, z: READY_DOOR_Z, yaw: -Math.PI / 2 } });+ b.wallWithDoors("ready-w", "bulkhead", { x: R.x0, z: R.z0 }, { x: R.x0, z: R.z1 }, [{ at: READY_DOOR_Z - R.z0, width: 1.8, id: "ready-door" }]);+ b.wall("ready-n", "bulkhead", { x: R.x0, z: R.z0 }, { x: R.x1, z: R.z0 });+ b.wall("ready-s", "bulkhead", { x: R.x0, z: R.z1 }, { x: R.x1, z: R.z1 });+ // The desk faces the door; the captain sits with the window behind.+ b.prop({ id: "ready-desk", kind: "helmConsole", x: 12.7, z: 14.6, yaw: Math.PI / 2, w: 1.8, d: 0.8, h: 1.1, solid: true, ref: "desk", accent: COMMAND_GOLD });+ b.prop({ id: "ready-chair", kind: "commandSeat", x: 13.65, z: 14.6, yaw: -Math.PI / 2, w: 0.7, d: 0.7, h: 1.1, solid: false, ref: "desk" });+ b.place({ id: "ready-chair", kind: "command", x: 13.65, z: 14.6, yaw: -Math.PI / 2, pose: "sit", seatY: 0.5 });+ const sofa = { x: 14.1, z: 19.4, yaw: -Math.PI / 2 };+ b.prop({ id: "ready-sofa", kind: "sofa", x: sofa.x, z: sofa.z, yaw: sofa.yaw, w: 2.2, d: 0.9, h: 0.8, solid: true });+ b.prop({ id: "ready-table", kind: "lowTable", x: sofa.x - 1.35, z: sofa.z, yaw: sofa.yaw, w: 1.2, d: 0.6, h: 0.38, solid: true });+ for (const k of [-1, 1]) {+ // Along the sofa (its own x runs along world z when turned to face port).+ b.place({ id: `ready-sofa-${k}`, kind: "lounge", x: sofa.x - 0.12, z: sofa.z + k * 0.6, yaw: sofa.yaw, pose: "sit", seatY: 0.44 });+ }+ b.place({ id: "ready-window", kind: "window", x: W - 0.85, z: 17.0, yaw: Math.PI / 2, pose: "stand", seatY: 0 });+ b.prop({ id: "ready-plant", kind: "plant", x: R.x0 + 0.7, z: R.z0 + 0.7, yaw: 0, w: 0.7, d: 0.7, h: 1.4, solid: true });+ b.prop({ id: "ready-model", kind: "starChart", x: R.x0 + 0.8, z: R.z1 - 0.8, yaw: Math.PI / 4, w: 0.7, d: 0.7, h: 1.5, solid: true, ref: "model" });++ return b.build({+ bounds, hull,+ arrival: { x: 0, z: E - 1.6 },+ lift: { x: 0, z: E - 1.6, yaw: Math.PI },+ });+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/bridgeRuntime.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/bridgeRuntime.tsnew file mode 100644index 0000000000..fd2e849383--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/bridgeRuntime.ts@@ -0,0 +1,46 @@+/**+ * What the bridge's stations, its panel and its scene share outside React:+ * who the first officer is (the scene learns it from the roster), a seat the+ * captain is walking to, and the warp jump itself, whose timer must outlive+ * the helm's panel (the panel closes as the jump begins).+ */+import type { ShipActions } from "../registry";+import { useShip } from "../../shipStore";+import type { DestinationId } from "../../space/destinations";++export const bridgeRuntime = {+ /** The lead agent (the person's own assistant): the ship's first officer. */+ leadId: null as string | null,+ /** The captain was sent to the chair and sits down on arrival; the time it was asked. */+ seatRequestedMs: 0,+};++/** How long the streaks run before the ship drops out at the new destination. */+export const WARP_MS = 2600;++let timer: ReturnType<typeof setTimeout> | null = null;++/**+ * Jump to `id`: the streaks run for `WARP_MS`, then the sky changes under the+ * flash. With reduced motion the ship is there at once. A second order while+ * a jump runs is ignored.+ */+export function engageWarp(id: DestinationId, reduced: boolean, actions: Pick<ShipActions, "reportAction">): boolean {+ const ship = useShip.getState();+ if (ship.warpingTo || id === ship.destination) return false;+ if (reduced) {+ ship.setDestination(id);+ actions.reportAction("warp_jump", id);+ return true;+ }+ ship.setWarping(id);+ if (timer) clearTimeout(timer);+ timer = setTimeout(() => {+ timer = null;+ const s = useShip.getState();+ s.setDestination(id);+ s.setWarping(null);+ actions.reportAction("warp_jump", id);+ }, WARP_MS);+ return true;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/index.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/index.tsnew file mode 100644index 0000000000..f3bc3bc5e2--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/index.ts@@ -0,0 +1,56 @@+/**+ * Deck 1, the bridge. Nobody is invented here (population "none"): the+ * captain and the pet walk it; the seats and consoles are the captain's.+ * The captain's chair seats the captain (any movement stands up again), the+ * first officer's seat opens the lead agent's chat, the helm (and the star+ * chart) sets a course, operations opens the crew directory.+ */+import { captain, useShip } from "../../shipStore";+import type { DeckPlan } from "../../plan/types";+import { registerDeck, type DeckModule } from "../registry";+import { buildBridgeDeck } from "./bridgeDeck";+import { bridgeRuntime } from "./bridgeRuntime";+import { BridgeScene } from "./BridgeScene";+import { BridgePanel } from "./HelmPanel";+import "./props";++// The plan never changes: one build per session keeps the navigation grid and the merged deck.+let plan: DeckPlan | null = null;++const handleStation: NonNullable<DeckModule["useStation"]> = (station, deck, actions, far) => {+ switch (station.kind) {+ case "captain": {+ const seat = deck.places.find((p) => p.kind === "captain");+ if (!seat) return false;+ if (captain.seated) { actions.sit(null); return true; }+ if (far) {+ bridgeRuntime.seatRequestedMs = performance.now();+ useShip.getState().requestWalk({ x: station.x, z: station.z });+ return true;+ }+ actions.sit({ x: seat.x, z: seat.z, yaw: seat.yaw, seatY: seat.seatY });+ return true;+ }+ case "firstOfficer":+ if (bridgeRuntime.leadId) actions.openAgent(bridgeRuntime.leadId);+ else actions.say(actions.t("ship.bridge.no_first_officer"));+ return true;+ case "helm":+ actions.openPanel(station.id);+ return true;+ case "ops":+ actions.openLedger();+ return true;+ default:+ return false;+ }+};++registerDeck({+ id: "bridge",+ population: "none",+ build: () => (plan ??= buildBridgeDeck()),+ Scene: BridgeScene,+ useStation: handleStation,+ Panel: BridgePanel,+});diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/props.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/props.tsnew file mode 100644index 0000000000..c325fbeb6d--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/bridge/props.ts@@ -0,0 +1,219 @@+/**+ * The bridge's furniture, registered into the shared prop builders: the+ * captain's chair, the command seats, the helm and operations consoles (and+ * the ready room's desk, which shares their screen mount), the horseshoe+ * rail's panels and its tactical console, the viewscreen's frame, the star+ * chart table and the ship model in the ready room. Each piece is drawn in+ * its own frame: centred on its footprint, its front (where a person uses+ * it) towards +z, its foot on the floor. `glow` is only ever a real light.+ */+import type { Prop } from "../../plan/types";+import type { Frame } from "../../render/kit/geo";+import { SHIP } from "../../render/kit/palette";+import { CONSOLE_SCREEN, registerPropBuilders, type PropBuilder } from "../../render/deck/props";++const TAU = Math.PI * 2;+/** A warm walnut-dark for the command furniture's tops. */+const WALNUT = "#43352c";+const GLASS_FIELD = "#1f5a7a";++/** The live screen's bezel, exactly where `ConsoleScreens` draws the face. */+function screenBezel(f: Frame, accent: string): void {+ const s = f.child({ y: CONSOLE_SCREEN.y, z: CONSOLE_SCREEN.z, pitch: CONSOLE_SCREEN.tilt });+ const bw = CONSOLE_SCREEN.w + 0.06, bh = CONSOLE_SCREEN.h + 0.06;+ s.box("structure", bw, bh, 0.035, SHIP.charcoal, { y: -bh / 2, z: -0.025 });+ s.box("structure", bw - 0.2, bh - 0.12, 0.05, SHIP.graphite, { y: -bh / 2 + 0.06, z: -0.07 });+ s.box("glow", bw, 0.01, 0.04, accent, { y: -bh / 2 - 0.01, z: -0.025 });+}++// ── seats ────────────────────────────────────────────────────────────++const captainChair: PropBuilder = (f) => {+ // A low round plinth, ringed with the command gold.+ f.cylinder("structure", 0.46, 0.5, 0.06, SHIP.charcoal, {}, 40);+ f.ring("glow", 0.475, 0.007, SHIP.gold, { y: 0.06 }, TAU, 56);+ f.cylinder("metal", 0.1, 0.15, 0.28, SHIP.steel, { y: 0.06 }, 20);+ // Seat shell and cushion.+ f.rounded("structure", 0.7, 0.1, 0.64, 0.12, SHIP.graphite, { y: 0.34 });+ f.rounded("fabric", 0.58, 0.09, 0.54, 0.1, SHIP.leather, { y: 0.43, z: 0.03 });+ // A tall back leaning back, its cushion, a headrest and the gold line along its crown.+ const back = f.child({ y: 0.42, z: -0.29, pitch: -0.14 });+ back.rounded("structure", 0.7, 0.86, 0.1, 0.12, SHIP.graphite, {});+ back.rounded("fabric", 0.54, 0.6, 0.06, 0.1, SHIP.leather, { y: 0.1, z: 0.07 });+ back.rounded("fabric", 0.38, 0.14, 0.08, 0.06, SHIP.leather, { y: 0.72, z: 0.07 });+ back.box("glow", 0.46, 0.012, 0.104, SHIP.gold, { y: 0.86 });+ // Armrests, each with a dark glass control pad and its lights.+ for (const s of [-1, 1]) {+ const arm = f.child({ x: s * 0.42, y: 0.4 });+ arm.rounded("structure", 0.1, 0.24, 0.46, 0.04, SHIP.graphite, { z: -0.04 });+ arm.rounded("panel", 0.15, 0.05, 0.62, 0.05, SHIP.panelCool, { y: 0.24, z: 0.02 });+ arm.box("structure", 0.1, 0.006, 0.24, SHIP.panelDark, { y: 0.29, z: 0.14 });+ arm.box("glowSoft", 0.07, 0.004, 0.1, GLASS_FIELD, { y: 0.296, z: 0.1 });+ arm.box("glow", 0.024, 0.006, 0.024, s > 0 ? SHIP.gold : SHIP.cyan, { y: 0.296, z: 0.21 });+ }+};++const commandSeat: PropBuilder = (f, p) => {+ if (p.ref === "desk") {+ // The ready room's desk chair: five feet on casters, a swivel column, a mid-height back.+ for (let k = 0; k < 5; k += 1) {+ const a = (k / 5) * TAU;+ f.box("metal", 0.05, 0.04, 0.3, SHIP.steel, { x: Math.sin(a) * 0.14, z: Math.cos(a) * 0.14, y: 0.04, yaw: a });+ f.sphere("structure", 0.03, SHIP.charcoal, { x: Math.sin(a) * 0.28, z: Math.cos(a) * 0.28, y: 0.03 }, 8);+ }+ f.cylinder("metal", 0.035, 0.045, 0.36, SHIP.steelLight, { y: 0.06 }, 12);+ f.rounded("fabric", 0.5, 0.08, 0.48, 0.1, SHIP.leather, { y: 0.42 });+ const back = f.child({ y: 0.5, z: -0.24, pitch: -0.12 });+ back.rounded("structure", 0.48, 0.5, 0.06, 0.1, SHIP.graphite, {});+ back.rounded("fabric", 0.4, 0.42, 0.04, 0.08, SHIP.leather, { y: 0.04, z: 0.04 });+ for (const s of [-1, 1]) f.rounded("structure", 0.05, 0.04, 0.3, 0.02, SHIP.graphite, { x: s * 0.26, y: 0.64, z: 0.02 });+ return;+ }+ // The first officer's and the port seat: the captain's chair's lines, lower and without the plinth's ring.+ f.cylinder("structure", 0.34, 0.38, 0.05, SHIP.charcoal, {}, 32);+ f.cylinder("metal", 0.08, 0.12, 0.3, SHIP.steel, { y: 0.05 }, 18);+ f.rounded("structure", 0.6, 0.09, 0.56, 0.1, SHIP.graphite, { y: 0.34 });+ f.rounded("fabric", 0.5, 0.08, 0.48, 0.09, SHIP.fabric, { y: 0.42, z: 0.03 });+ const back = f.child({ y: 0.42, z: -0.26, pitch: -0.12 });+ back.rounded("structure", 0.6, 0.62, 0.09, 0.1, SHIP.graphite, {});+ back.rounded("fabric", 0.46, 0.46, 0.05, 0.08, SHIP.fabric, { y: 0.08, z: 0.06 });+ back.box(p.ref === "firstOfficer" ? "glowSoft" : "structure", 0.36, 0.01, 0.094, p.ref === "firstOfficer" ? SHIP.gold : SHIP.steelLight, { y: 0.62 });+ for (const s of [-1, 1]) {+ const arm = f.child({ x: s * 0.36, y: 0.4 });+ arm.rounded("structure", 0.08, 0.2, 0.38, 0.03, SHIP.graphite, { z: -0.04 });+ arm.rounded("panel", 0.12, 0.04, 0.5, 0.04, SHIP.panelCool, { y: 0.2 });+ }+ // One small pad on the inner arm, towards the captain.+ const inner = p.ref === "firstOfficer" ? -1 : 1;+ f.box("glowSoft", 0.06, 0.004, 0.09, GLASS_FIELD, { x: inner * 0.36, y: 0.645, z: 0.12 });+};++// ── consoles ─────────────────────────────────────────────────────────++/** The helm and operations: a wedge desk with a sloped control surface and a live screen. */+function helmDesk(f: Frame, p: Prop): void {+ const accent = p.accent ?? SHIP.gold;+ const w = p.w, d = p.d;+ // A chamfered foot and a body that steps back from the knees.+ f.chamfer("structure", w - 0.3, 0.06, 0.62, 0.12, SHIP.charcoal, { z: -0.12 });+ f.chamfer("panel", w - 0.42, 0.62, 0.36, 0.1, SHIP.panelCool, { y: 0.06, z: -0.2 });+ f.box("structure", w - 0.4, 0.035, 0.37, SHIP.graphite, { y: 0.34, z: -0.2 });+ // Side wings carry the top.+ for (const side of [-1, 1]) f.chamfer("structure", 0.12, 0.72, d - 0.12, 0.04, SHIP.graphite, { x: side * (w / 2 - 0.08), z: -0.02 });+ // The sloped top: a ceramic rim round a dark glass control surface.+ const top = f.child({ y: 0.7, pitch: 0.2 });+ top.rounded("panel", w, 0.07, d, 0.12, SHIP.panel, {});+ top.rounded("structure", w - 0.14, 0.02, d - 0.16, 0.08, SHIP.panelDark, { y: 0.07 });+ // Two lit glass fields either side of the screen's foot, a row of keys at the front.+ for (const s of [-1, 1]) top.box("glowSoft", w * 0.3, 0.005, d * 0.34, GLASS_FIELD, { x: s * w * 0.27, y: 0.091, z: 0.02 });+ for (let k = 0; k < 7; k += 1) top.box("glow", 0.07, 0.006, 0.026, k === 3 ? accent : SHIP.cyan, { x: (k - 3) * 0.11, y: 0.092, z: d / 2 - 0.14 });+ top.box("glow", w - 0.18, 0.012, 0.012, accent, { y: 0.035, z: d / 2 + 0.002 });+ // The screen's neck and bezel.+ f.box("structure", 0.1, 0.36, 0.08, SHIP.graphite, { y: 0.74, z: CONSOLE_SCREEN.z - 0.08 });+ screenBezel(f, accent);+}++/** The ready room's desk: two pedestals, a walnut-dark top and a desk screen. */+function readyDesk(f: Frame, p: Prop): void {+ const w = p.w, d = p.d;+ for (const s of [-1, 1]) f.rounded("panel", 0.42, 0.68, d - 0.12, 0.05, SHIP.panel, { x: s * (w / 2 - 0.27) });+ f.box("structure", w - 0.96, 0.46, 0.04, SHIP.graphite, { y: 0.2, z: -d / 2 + 0.12 });+ f.rounded("structure", w, 0.06, d, 0.06, WALNUT, { y: 0.68 });+ f.rounded("fabric", w * 0.42, 0.006, d * 0.42, 0.04, SHIP.leather, { y: 0.74, z: 0.1 });+ f.box("glowSoft", w - 0.24, 0.012, 0.012, SHIP.lightWarm, { y: 0.67, z: d / 2 - 0.02 });+ // A data pad, a cup.+ f.rounded("structure", 0.18, 0.012, 0.26, 0.02, SHIP.panelDark, { x: w * 0.3, y: 0.742, z: 0.12, yaw: 0.25 });+ f.box("glowSoft", 0.14, 0.003, 0.2, GLASS_FIELD, { x: w * 0.3, y: 0.755, z: 0.12, yaw: 0.25 });+ f.cylinder("ceramic", 0.04, 0.035, 0.09, "#f2f2f0", { x: -w * 0.32, y: 0.74, z: 0.16 }, 16);+ // The screen on a slim neck.+ f.box("metal", 0.05, 0.22, 0.05, SHIP.steelLight, { y: 0.74, z: CONSOLE_SCREEN.z - 0.06 });+ f.rounded("metal", 0.26, 0.012, 0.16, 0.03, SHIP.steelLight, { y: 0.74, z: CONSOLE_SCREEN.z - 0.04 });+ screenBezel(f, p.accent ?? SHIP.gold);+}++const helmConsole: PropBuilder = (f, p) => (p.ref === "desk" ? readyDesk(f, p) : helmDesk(f, p));++// ── the rail ─────────────────────────────────────────────────────────++const tacticalRail: PropBuilder = (f, p) => {+ const w = p.w;+ if (p.ref === "console") {+ // Tactical: a long console set into the rail's apex, its officer standing behind it.+ const accent = p.accent ?? SHIP.gold;+ f.box("structure", w, 0.1, 0.5, SHIP.panelDark, { z: -0.04 });+ f.chamfer("panel", w - 0.06, 0.8, 0.4, 0.08, SHIP.panelCool, { y: 0.1, z: -0.08 });+ for (const s of [-1, 1]) f.chamfer("structure", 0.1, 0.9, 0.5, 0.03, SHIP.graphite, { x: s * (w / 2 - 0.05), z: -0.04 });+ const top = f.child({ y: 0.9, pitch: 0.26 });+ top.rounded("panel", w, 0.06, p.d, 0.08, SHIP.panel, {});+ top.rounded("structure", w - 0.12, 0.02, p.d - 0.12, 0.06, SHIP.panelDark, { y: 0.06 });+ top.box("glowSoft", w * 0.6, 0.005, p.d * 0.4, GLASS_FIELD, { y: 0.081, z: -0.06 });+ for (let k = 0; k < 9; k += 1) top.box("glow", 0.06, 0.006, 0.024, k === 4 ? accent : k % 2 ? SHIP.cyanDeep : SHIP.cyan, { x: (k - 4) * 0.13, y: 0.082, z: p.d / 2 - 0.12 });+ top.box("glow", w - 0.12, 0.012, 0.012, accent, { y: 0.03, z: p.d / 2 + 0.002 });+ return;+ }+ // A rail panel: the balustrade under the handrail, a warm wash on the floor inside the well.+ f.box("structure", w, 0.1, 0.2, SHIP.panelDark, {});+ f.box("panel", w, 0.8, 0.12, SHIP.panelCool, { y: 0.1 });+ f.box("structure", w, 0.05, 0.16, SHIP.graphite, { y: 0.88 });+ f.box("glowSoft", w - 0.08, 0.01, 0.01, SHIP.lightWarm, { y: 0.07, z: 0.105 });+};++// ── the viewscreen ───────────────────────────────────────────────────++/** One segment of the viewscreen's frame, standing against the bow window's inner face. */+const viewscreen: PropBuilder = (f, p) => {+ const w = p.w;+ // The header beam over the window, with the emitter strip that throws the picture.+ f.box("structure", w, 0.34, 0.3, SHIP.graphite, { y: 2.2, z: -0.02 });+ f.box("structure", w, 0.04, 0.34, SHIP.charcoal, { y: 2.18, z: -0.02 });+ f.box("glow", w - 0.04, 0.012, 0.02, SHIP.cyan, { y: 2.19, z: 0.14 });+ // The sill: a dark ledge with a quiet light line along its lip.+ f.box("structure", w, 0.12, 0.34, SHIP.panelDark, { y: 0.84 });+ f.box("glowSoft", w - 0.04, 0.01, 0.02, SHIP.cyan, { y: 0.9, z: 0.17 });+ // Posts at the joints (a neighbour's post overlaps, which reads as one).+ for (const s of [-1, 1]) f.chamfer("structure", 0.16, 1.42, 0.3, 0.05, SHIP.graphite, { x: (s * w) / 2, y: 0.84, z: -0.02 });+};++// ── the star chart and the model ─────────────────────────────────────++const starChart: PropBuilder = (f, p) => {+ if (p.ref === "model") {+ // The ready room's display: a plinth, a glass case and the Dodaios in miniature.+ f.chamfer("panel", 0.52, 1.0, 0.52, 0.08, SHIP.panel, {});+ f.chamfer("structure", 0.6, 0.05, 0.6, 0.09, SHIP.graphite, { y: 1.0 });+ f.box("glowSoft", 0.36, 0.006, 0.36, SHIP.lightWarm, { y: 1.05 });+ f.cylinder("metal", 0.008, 0.008, 0.14, SHIP.steel, { y: 1.05 }, 8);+ const m = f.child({ y: 1.22 });+ m.rounded("metal", 0.1, 0.045, 0.4, 0.04, SHIP.hullOuter, { z: -0.02 });+ m.box("structure", 0.34, 0.01, 0.06, SHIP.graphite, { y: 0.0, z: 0.06 });+ for (const s of [-1, 1]) {+ m.cylinder("metal", 0.024, 0.024, 0.3, SHIP.hullOuter, { x: s * 0.17, y: -0.01, z: -0.08, pitch: Math.PI / 2 }, 12);+ m.box("glow", 0.03, 0.01, 0.01, SHIP.cyan, { x: s * 0.17, y: 0.004, z: -0.085 });+ }+ f.box("glass", 0.46, 0.42, 0.46, "#cfe8ff", { y: 1.05 });+ return;+ }+ const r = p.w / 2;+ // An octagonal foot, a ribbed pedestal.+ f.chamfer("structure", r * 1.6, 0.08, r * 1.6, r * 0.46, SHIP.charcoal, {});+ f.cylinder("structure", r * 0.4, r * 0.56, 0.72, SHIP.graphite, { y: 0.08 }, 32);+ for (let k = 0; k < 8; k += 1) {+ const a = (k / 8) * TAU;+ f.box("structure", 0.06, 0.6, 0.2, SHIP.steel, { x: Math.sin(a) * r * 0.48, z: Math.cos(a) * r * 0.48, y: 0.12, yaw: a });+ }+ // The table: a ceramic ring round a dark glass disc with the projector's field in the middle.+ f.cylinder("panel", r, r * 0.9, 0.1, SHIP.panelCool, { y: 0.8 }, 64);+ f.cylinder("structure", r * 0.86, r * 0.86, 0.02, SHIP.panelDark, { y: 0.9 }, 64);+ f.ring("glow", r * 0.965, 0.012, SHIP.gold, { y: 0.9 }, TAU, 72);+ f.cylinder("glowSoft", r * 0.5, r * 0.5, 0.004, "#123a52", { y: 0.92 }, 48);+ f.ring("glow", r * 0.52, 0.007, p.accent ?? SHIP.cyan, { y: 0.922 }, TAU, 48);+ // A bearing scale round the rim: a gold mark every quarter.+ for (let k = 0; k < 36; k += 1) {+ const a = (k / 36) * TAU, major = k % 9 === 0;+ f.box(major ? "glow" : "glowSoft", 0.012, 0.004, major ? 0.09 : 0.04, major ? SHIP.gold : SHIP.cyanDeep,+ { x: Math.sin(a) * r * 0.76, z: Math.cos(a) * r * 0.76, y: 0.921, yaw: a });+ }+ f.ring("glowSoft", r * 0.62, 0.01, SHIP.cyan, { y: 0.02 }, TAU, 48);+};++registerPropBuilders({ captainChair, commandSeat, helmConsole, tacticalRail, viewscreen, starChart });diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/EngineeringPanel.tsx b/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/EngineeringPanel.tsxnew file mode 100644index 0000000000..5fa2d815fe--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/EngineeringPanel.tsx@@ -0,0 +1,252 @@+/**+ * The master systems display's panel: start new coding agents from the ship.+ *+ * The same contract Mission Control used on the old coding floor, nothing of+ * its own: panes open through the IDE's `POST /terminals` (workspace, CLI, how+ * many), and a first task waits for each pane to come up, then goes through+ * `/terminals/{name}/prompt`, the path voice and the grid use. A new pane+ * appears on the deck at a free console of its workspace's bay.+ */+import { BrandedSelect } from "@/components/ui/select";+import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";+import { Minus, Plus, X } from "lucide-react";+import {+ fetchIdeAgents, fetchIdeState, fetchWorkspacePanes, openTerminal, promptTerminal, startTerminal,+ type AgentStatus, type WorkspaceCard,+} from "@/lib/agenticIdeApi";+import { useWorkspacePanesStore } from "@/store/workspacePanes";+import { AgentMark } from "@/components/agentic/AgentMark";+import type { DeckPanelProps } from "../registry";+import "./engineering.css";++/** At most this many agents per launch. */+const MAX_LAUNCH = 4;+const START_TIMEOUT_MS = 30_000;+const START_POLL_MS = 600;+const START_JITTER_MS = 300;++type LaunchLine = { tone: "busy" | "ok" | "warn" | "error"; text: string };++/** Coding CLIs a new agent can run: installed, and not a plain shell. Pure. */+function launchableClis(agents: readonly AgentStatus[]): AgentStatus[] {+ return agents.filter((a) => a.installed && (a.kind ?? "cli") !== "shell");+}++/** Wait until pane `name` of `workspaceId` is live; false when it failed or the clock ran out. */+async function waitLive(workspaceId: string, name: string): Promise<boolean> {+ const deadline = Date.now() + START_TIMEOUT_MS;+ for (;;) {+ try {+ const { panes } = await fetchWorkspacePanes();+ const row = panes.find((p) => p.workspace_id === workspaceId && p.name === name);+ if (row?.status === "live") return true;+ if (row && row.status !== "pending") return false;+ } catch (err) {+ // One failed poll is not an answer; the next one decides.+ console.warn("Engineering launcher: pane poll failed", err);+ }+ if (Date.now() >= deadline) return false;+ await new Promise((resolve) => setTimeout(resolve, START_POLL_MS + Math.random() * START_JITTER_MS));+ }+}++function errorText(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}++const FOCUSABLE = "button:not([disabled]), select:not([disabled]), textarea:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex='-1'])";++export function EngineeringPanel({ actions, panes }: DeckPanelProps) {+ const { t, closePanel, say, openSection } = actions;+ const dialog = useRef<HTMLElement>(null);+ const [workspaces, setWorkspaces] = useState<WorkspaceCard[] | null>(null);+ const [clis, setClis] = useState<AgentStatus[] | null>(null);+ const [loadError, setLoadError] = useState<string | null>(null);+ const [workspaceId, setWorkspaceId] = useState("");+ const [cli, setCli] = useState("");+ const [count, setCount] = useState(1);+ const [task, setTask] = useState("");+ const [running, setRunning] = useState(false);+ const [lines, setLines] = useState<LaunchLine[]>([]);+ const alive = useRef(true);++ useEffect(() => {+ alive.current = true;+ Promise.all([fetchIdeState(), fetchIdeAgents(true)])+ .then(([state, list]) => {+ if (!alive.current) return;+ setWorkspaces(state.workspaces);+ setWorkspaceId((current) => current || state.active_id || state.workspaces[0]?.id || "");+ const usable = launchableClis(list.agents);+ setClis(usable);+ setCli((current) => current || usable[0]?.name || "");+ })+ .catch((err) => { if (alive.current) setLoadError(errorText(err)); });+ return () => { alive.current = false; };+ }, []);++ // Focus moves into the dialog and back to where it was on close.+ useEffect(() => {+ const before = document.activeElement as HTMLElement | null;+ dialog.current?.focus();+ return () => { if (before && document.contains(before)) before.focus(); };+ }, []);++ const counts = useMemo(() => {+ const c = { working: 0, waiting: 0, idle: 0 };+ for (const o of panes) c[o.dot === "working" ? "working" : o.dot === "idle" ? "idle" : "waiting"] += 1;+ return c;+ }, [panes]);++ const setLine = (index: number, line: LaunchLine) => {+ if (alive.current) setLines((prev) => { const next = [...prev]; next[index] = line; return next; });+ };+ const fill = (key: string, name: string) => t(key).replace("{pane}", name);++ /** Wait for one new pane, then hand it the task. */+ const settle = async (i: number, name: string, wsId: string, brief: string) => {+ if (!brief) { setLine(i, { tone: "ok", text: fill("ship.engineering.panel.done_open", name) }); return; }+ setLine(i, { tone: "busy", text: fill("ship.engineering.panel.waiting", name) });+ try {+ // A pane starts when a viewer first attaches, and nobody views it from here.+ await startTerminal(name, wsId);+ } catch (err) {+ console.warn("Engineering launcher: pane start request failed", err);+ }+ if (!(await waitLive(wsId, name))) { setLine(i, { tone: "warn", text: fill("ship.engineering.panel.not_started", name) }); return; }+ setLine(i, { tone: "busy", text: fill("ship.engineering.panel.briefing", name) });+ try {+ const result = await promptTerminal(name, brief, { workspaceId: wsId });+ setLine(i, result.submitted === true+ ? { tone: "ok", text: fill("ship.engineering.panel.done_briefed", name) }+ : { tone: "warn", text: result.detail || t("ship.engineering.panel.unconfirmed") });+ } catch (err) {+ setLine(i, { tone: "error", text: errorText(err) });+ }+ };++ const ready = Boolean(cli) && Boolean(workspaceId) && !running;++ const launch = async () => {+ if (!ready) return;+ setRunning(true);+ setLines([]);+ const brief = task.trim();+ let opened = 0;+ for (let i = 0; i < count; i += 1) {+ setLine(i, { tone: "busy", text: t("ship.engineering.panel.opening") });+ let name = "";+ try {+ name = (await openTerminal({ workspace_id: workspaceId, agent: cli })).name;+ } catch (err) {+ setLine(i, { tone: "error", text: t("ship.engineering.panel.failed").replace("{error}", errorText(err)) });+ break;+ }+ opened += 1;+ void useWorkspacePanesStore.getState().load();+ await settle(i, name, workspaceId, brief);+ }+ void useWorkspacePanesStore.getState().load();+ if (opened > 0) {+ say(t("ship.engineering.panel.launched").replace("{count}", String(opened)));+ if (brief && alive.current) setTask("");+ }+ if (alive.current) setRunning(false);+ };++ const onKeyDown = (e: KeyboardEvent<HTMLElement>) => {+ if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closePanel(); return; }+ if (e.key !== "Tab" || !dialog.current) return;+ // Keep Tab inside the dialog.+ const items = [...dialog.current.querySelectorAll<HTMLElement>(FOCUSABLE)];+ if (items.length === 0) return;+ const first = items[0], last = items[items.length - 1];+ if (e.shiftKey && (document.activeElement === first || document.activeElement === dialog.current)) { e.preventDefault(); last.focus(); }+ else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }+ };++ const openIde = useCallback(() => { closePanel(); openSection("agentic-ide"); }, [closePanel, openSection]);++ return (+ <div className="ship-scrim" onClick={closePanel}>+ <section ref={dialog} className="ship-panel eng-launch" role="dialog" aria-modal="true" aria-labelledby="eng-launch-title"+ tabIndex={-1} onClick={(e) => e.stopPropagation()} onKeyDown={onKeyDown}>+ <header className="eng-launch-head">+ <div>+ <div className="ship-eyebrow">{t("ship.station.systems.name")}</div>+ <h2 id="eng-launch-title">{t("ship.engineering.panel.title")}</h2>+ </div>+ <button type="button" className="ship-tool" aria-label={t("ship.close")} onClick={closePanel}><X size={16} aria-hidden /></button>+ </header>+ <p className="eng-launch-crew">+ <span><i className="ship-dot" data-state="working" />{t("ship.crew.working").replace("{count}", String(counts.working))}</span>+ <span><i className="ship-dot" data-state="waiting" />{t("ship.crew.waiting").replace("{count}", String(counts.waiting))}</span>+ <span><i className="ship-dot" data-state="idle" />{t("ship.crew.idle").replace("{count}", String(counts.idle))}</span>+ </p>++ {loadError ? <p className="eng-launch-note" role="alert">{t("ship.engineering.panel.load_failed").replace("{error}", loadError)}</p>+ : !workspaces || !clis ? <p className="eng-launch-note" role="status">{t("ship.engineering.panel.loading")}</p>+ : (+ <>+ <fieldset className="eng-launch-field">+ <legend className="ship-eyebrow">{t("ship.engineering.panel.cli")}</legend>+ {clis.length === 0 ? <p className="eng-launch-note">{t("ship.engineering.panel.no_clis")}</p> : (+ <div className="eng-launch-clis" role="radiogroup" aria-label={t("ship.engineering.panel.cli")}>+ {clis.map((a) => (+ <button key={a.name} type="button" role="radio" aria-checked={cli === a.name} disabled={running}+ title={a.description || a.display_name} onClick={() => setCli(a.name)}>+ <AgentMark agent={a.name} label={a.display_name} logoUrl={a.logo_url || undefined} size="sm" />+ <span>{a.display_name}</span>+ </button>+ ))}+ </div>+ )}+ </fieldset>++ <label className="eng-launch-field">+ <span className="ship-eyebrow">{t("ship.engineering.panel.workspace")}</span>+ {workspaces.length === 0 ? (+ <span className="eng-launch-note">+ {t("ship.engineering.panel.no_workspace")}{" "}+ <button type="button" className="eng-launch-link" onClick={openIde}>{t("ship.engineering.panel.open_ide")}</button>+ </span>+ ) : (+ <BrandedSelect className="eng-launch-input" value={workspaceId} disabled={running} onValueChange={setWorkspaceId}+ ariaLabel={t("ship.engineering.panel.workspace")}+ options={workspaces.map((w) => ({ value: w.id, label: w.name, hint: w.branch || undefined }))} />+ )}+ </label>++ <label className="eng-launch-field">+ <span className="ship-eyebrow">{t("ship.engineering.panel.task")}</span>+ <textarea className="eng-launch-input" rows={3} value={task} maxLength={8000} disabled={running}+ placeholder={t("ship.engineering.panel.task_placeholder")}+ onChange={(e) => setTask(e.target.value)}+ onKeyDown={(e) => { if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) { e.preventDefault(); void launch(); } }} />+ </label>++ <div className="eng-launch-go">+ <div className="eng-launch-stepper" role="group" aria-label={t("ship.engineering.panel.count")}>+ <button type="button" disabled={running || count <= 1} onClick={() => setCount((n) => n - 1)}+ aria-label={t("ship.engineering.panel.fewer")}><Minus size={14} aria-hidden /></button>+ <output aria-live="polite">{count}</output>+ <button type="button" disabled={running || count >= MAX_LAUNCH} onClick={() => setCount((n) => n + 1)}+ aria-label={t("ship.engineering.panel.more")}><Plus size={14} aria-hidden /></button>+ </div>+ <button type="button" className="ship-btn" data-primary="true" disabled={!ready} onClick={() => void launch()}>+ {count === 1 ? t("ship.engineering.panel.start_one") : t("ship.engineering.panel.start_many").replace("{count}", String(count))}+ </button>+ </div>+ <p className="eng-launch-hint">{t("ship.engineering.panel.hint")}</p>+ </>+ )}++ {lines.length > 0 && (+ <ul className="eng-launch-log" aria-live="polite">+ {lines.map((line, i) => <li key={i} data-tone={line.tone}><i aria-hidden />{line.text}</li>)}+ </ul>+ )}+ </section>+ </div>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/EngineeringScene.tsx b/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/EngineeringScene.tsxnew file mode 100644index 0000000000..a7b3c7e84b--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/EngineeringScene.tsx@@ -0,0 +1,363 @@+/**+ * Engineering's own scene: what moves or changes beyond the shared kit.+ *+ * The reactor's plasma column pulses with the work on the deck (slow and dim+ * when every pane is idle, quick and bright when they all work; still with+ * reduced motion). Energy runs down the floor feed of every bay with a+ * working pane, the master systems display shows each bay's load as a+ * hologram, and every seated pane's console shows its live terminal (polled+ * only while the stage is awake, only for the panes sitting at their+ * consoles). A click on a screen opens that pane in the IDE.+ */+import { useFrame } from "@react-three/fiber";+import { useCallback, useEffect, useMemo, useRef } from "react";+import {+ AdditiveBlending, BoxGeometry, BufferAttribute, BufferGeometry, Color, CylinderGeometry, DoubleSide, InstancedMesh, Mesh,+ Matrix4, MeshBasicMaterial, Object3D, PlaneGeometry, ShaderMaterial, TorusGeometry, type PointLight,+} from "three";+import type { PaneScreen } from "@/lib/paneScreensApi";+import type { AgentDotKind } from "@/components/agentic/sidePanel/agentStatus";+import type { PaneOccupant } from "../../../crewFeeds/codingFloor";+import { MAX_SCREEN_TARGETS, usePaneScreens, type PaneScreenTarget } from "../../../crewFeeds/usePaneScreens";+import { visibleRows } from "../../../crewFeeds/terminalScreen";+import { seatedCrew } from "../../../crewFeeds/seated";+import type { DeckSceneProps, ShipActions } from "../registry";+import { COMMAND_GOLD, HOLO_CYAN } from "../../plan/builder";+import type { DeckPlan, Prop, Vec2 } from "../../plan/types";+import { ConsoleScreens } from "../../render/deck/DeckScene";+import type { ScreenContent, ScreenState } from "../../render/deck/screens";+import { annulus, floorQuad, GeoBatch } from "../../render/kit/geo";+import { castsShadow, finishMaterial, receivesShadow } from "../../render/kit/materials";+import { STATE } from "../../render/kit/palette";+import { crewPoses } from "../../life/CrewLayer";+import { CORE_R, engineeringLayout, RAIL_R, ROW_R, TABLE_AT, type EngineeringLayout } from "./engineeringDeck";+import { PLASMA } from "./props";++const BAY_KINDS: readonly Prop["kind"][] = ["bayConsole"];+/** Rows a console screen shows (the screen atlas fits seven under its header). */+const SCREEN_FIT = 7;+/** Live terminals at once: this many polls of MAX_SCREEN_TARGETS panes each. */+const SCREEN_CHUNKS = 4;++interface Busy { working: number; waiting: number; total: number }++export function EngineeringScene({ plan, reduced, quality, awake, panes, actions }: DeckSceneProps) {+ const layout = engineeringLayout(plan);+ const dotOf = useMemo(() => new Map(panes.map((o) => [o.agent.agentId, o.dot])), [panes]);+ const busy = useMemo<Busy>(() => {+ let working = 0, waiting = 0;+ for (const o of panes) { if (o.dot === "working") working += 1; else if (o.dot === "waiting" || o.dot === "error") waiting += 1; }+ return { working, waiting, total: panes.length };+ }, [panes]);+ return (+ <>+ {layout && <FloorTrims plan={plan} layout={layout} />}+ {layout && <ReactorCore at={layout.centre} busy={busy} reduced={reduced} light={quality === "high"} />}+ {layout && <PowerFeeds plan={plan} layout={layout} dotOf={dotOf} reduced={reduced} />}+ <SystemsHolo plan={plan} dotOf={dotOf} reduced={reduced} />+ <BayScreens plan={plan} panes={panes} awake={awake} actions={actions} />+ <SeatWatch plan={plan} />+ </>+ );+}++// ── reactor ──────────────────────────────────────────────────────────++const PLASMA_VERT = /* glsl */ `varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`;+const PLASMA_FRAG = /* glsl */ `uniform float uPhase; uniform float uTime; uniform float uLevel; uniform vec3 uColour; uniform vec3 uHot; varying vec2 vUv;+ void main() {+ float y = vUv.y;+ float bands = pow(0.5 + 0.5 * sin(y * 24.0 - uPhase * 6.2831), 4.0);+ float swirl = 0.5 + 0.5 * sin(vUv.x * 18.85 + y * 9.0 - uTime * 0.9);+ float beat = 0.5 + 0.5 * sin(uPhase * 3.1416);+ float ends = smoothstep(0.0, 0.06, y) * (1.0 - smoothstep(0.94, 1.0, y));+ float g = (0.32 + 0.68 * bands * (0.55 + 0.45 * swirl)) * (0.8 + 0.2 * beat) * uLevel * ends;+ gl_FragColor = vec4(mix(uColour, uHot, bands * 0.7) * g, g);+ }`;++/** How fast and bright the core runs for the work on the deck. */+function coreDrive(busy: Busy): { speed: number; level: number } {+ if (busy.total === 0) return { speed: 0.25, level: 0.5 };+ const share = busy.working / busy.total;+ return { speed: 0.35 + 1.9 * share + Math.min(0.6, busy.working * 0.06), level: 0.7 + 0.6 * Math.min(1, busy.working / 4) };+}++function ReactorCore({ at, busy, reduced, light }: { at: Vec2; busy: Busy; reduced: boolean; light: boolean }) {+ const drive = useMemo(() => coreDrive(busy), [busy]);+ const height = PLASMA.y1 - PLASMA.y0;+ const parts = useMemo(() => {+ const plasma = new ShaderMaterial({+ vertexShader: PLASMA_VERT, fragmentShader: PLASMA_FRAG, transparent: true, blending: AdditiveBlending, depthWrite: false, side: DoubleSide,+ uniforms: {+ uPhase: { value: 0 }, uTime: { value: 0 }, uLevel: { value: 0.5 },+ uColour: { value: new Color(HOLO_CYAN).multiplyScalar(1.5) }, uHot: { value: new Color("#e6fbff").multiplyScalar(2.2) },+ },+ });+ const column = new CylinderGeometry(PLASMA.r, PLASMA.r, height, 32, 1, true);+ column.translate(0, PLASMA.y0 + height / 2, 0);+ const heart = new CylinderGeometry(0.16, 0.16, height - 0.2, 16, 1, false);+ heart.translate(0, PLASMA.y0 + height / 2, 0);+ const heartMat = new MeshBasicMaterial({ color: new Color("#d8f6ff"), toneMapped: false });+ const ringGeo = new TorusGeometry(0.78, 0.028, 6, 48);+ ringGeo.rotateX(Math.PI / 2);+ const ringMat = new MeshBasicMaterial({ color: new Color(HOLO_CYAN).multiplyScalar(2.2), toneMapped: false, transparent: true, depthWrite: false });+ const rings = [0, 1, 2].map(() => { const m = new Mesh(ringGeo, ringMat); m.raycast = () => undefined; return m; });+ const columnMesh = new Mesh(column, plasma);+ const heartMesh = new Mesh(heart, heartMat);+ columnMesh.raycast = heartMesh.raycast = () => undefined;+ return { plasma, column, heart, heartMat, ringGeo, ringMat, rings, columnMesh, heartMesh };+ }, [height]);+ useEffect(() => () => {+ parts.plasma.dispose(); parts.column.dispose(); parts.heart.dispose(); parts.heartMat.dispose(); parts.ringGeo.dispose(); parts.ringMat.dispose();+ }, [parts]);+ const state = useRef({ speed: drive.speed, level: drive.level, phase: 0 });+ const lamp = useRef<PointLight>(null);+ const base = useMemo(() => new Color("#bfefff"), []);+ useFrame(({ clock }, dt) => {+ const s = state.current;+ const k = Math.min(1, dt * 1.2);+ s.speed += (drive.speed - s.speed) * k;+ s.level += (drive.level - s.level) * k;+ if (!reduced) s.phase += dt * s.speed;+ const u = parts.plasma.uniforms;+ u.uPhase.value = s.phase;+ u.uTime.value = reduced ? 0 : clock.elapsedTime;+ u.uLevel.value = s.level;+ const beat = reduced ? 0.5 : 0.5 + 0.5 * Math.sin(s.phase * Math.PI);+ parts.heartMat.color.copy(base).multiplyScalar(s.level * (1.5 + 0.7 * beat));+ // Rings rise through the cage, quicker with the work.+ parts.rings.forEach((ring, i) => {+ const t = reduced ? (i + 0.5) / 3 : (s.phase * 0.35 + i / 3) % 1;+ ring.position.y = PLASMA.y0 + 0.25 + t * (height - 0.5);+ ring.scale.setScalar(1 - 0.12 * Math.sin(t * Math.PI));+ });+ parts.ringMat.opacity = 0.35 + 0.45 * Math.min(1, s.level);+ if (lamp.current) lamp.current.intensity = 9 * s.level * (0.85 + 0.3 * beat);+ });+ return (+ <group position={[at.x, 0, at.z]}>+ <primitive object={parts.columnMesh} />+ <primitive object={parts.heartMesh} />+ {parts.rings.map((r, i) => <primitive key={i} object={r} />)}+ {light && <pointLight ref={lamp} position={[0, 2.6, 0]} color={HOLO_CYAN} intensity={6} distance={16} decay={2} />}+ </group>+ );+}++// ── floor trims ──────────────────────────────────────────────────────++/** A flat ring on the floor with uvs in metres, for tiled finishes (the grating round the core). */+function tiledRing(inner: number, outer: number, segments = 64): BufferGeometry {+ const g = annulus(inner, outer, 0, Math.PI * 2, segments);+ const pos = g.attributes.position;+ const uv = new Float32Array(pos.count * 2);+ for (let i = 0; i < pos.count; i += 1) { uv[i * 2] = pos.getX(i); uv[i * 2 + 1] = pos.getZ(i); }+ g.setAttribute("uv", new BufferAttribute(uv, 2));+ return g;+}++/** The pit grating round the core, the walkway's edge with each bay's colour, and gold guide lines from the turbolift. */+function FloorTrims({ plan, layout }: { plan: DeckPlan; layout: EngineeringLayout }) {+ const meshes = useMemo(() => {+ const batch = new GeoBatch();+ const c = layout.centre;+ const f = batch.frame(new Matrix4().makeTranslation(c.x, 0, c.z));+ f.geo("grate", tiledRing(CORE_R - 0.05, RAIL_R - 0.04), "#ffffff", { y: 0.013 });+ f.geo("glowSoft", annulus(RAIL_R + 0.28, RAIL_R + 0.33), HOLO_CYAN, { y: 0.016 });+ const edge = ROW_R[0] - 0.95;+ f.geo("structure", annulus(edge - 0.08, edge + 0.08, 0, Math.PI * 2, 96), "#2b3038", { y: 0.014 });+ for (const bay of layout.bays) {+ const inset = 0.6 / edge;+ f.geo("glowSoft", annulus(edge - 0.025, edge + 0.025, bay.a0 + inset, Math.max(0.05, bay.a1 - bay.a0 - 2 * inset), 32), bay.accent, { y: 0.018 });+ }+ // Two gold lines lead from the turbolift to the systems display.+ const systems = plan.props.find((p) => p.id === "systems");+ const lift = plan.lift;+ if (systems) {+ const z0 = systems.z + systems.d / 2 + 1.0, z1 = lift.z - 0.6;+ if (z1 > z0) for (const s of [-1, 1]) {+ batch.frame(new Matrix4().makeTranslation(lift.x + s * 1.5, 0.016, (z0 + z1) / 2)).geo("glowSoft", floorQuad(0.05, z1 - z0), COMMAND_GOLD);+ }+ }+ return batch.merged().map(({ finish, geometry }) => {+ const mesh = new Mesh(geometry, finishMaterial(finish));+ mesh.castShadow = castsShadow(finish);+ mesh.receiveShadow = receivesShadow(finish);+ mesh.raycast = () => undefined;+ return mesh;+ });+ }, [plan, layout]);+ useEffect(() => () => { for (const m of meshes) m.geometry.dispose(); }, [meshes]);+ return <>{meshes.map((m, i) => <primitive key={i} object={m} />)}</>;+}++// ── power feeds ──────────────────────────────────────────────────────++const PULSES = 3;++/** Energy running from the core down each bay's floor feed while one of its panes works. */+function PowerFeeds({ plan, layout, dotOf, reduced }: { plan: DeckPlan; layout: EngineeringLayout; dotOf: ReadonlyMap<string, AgentDotKind>; reduced: boolean }) {+ const feeds = useMemo(() => layout.bays.map((bay) => ({+ bay,+ members: plan.divisions.find((d) => d.room === bay.room)?.members ?? [],+ colour: new Color(bay.accent).multiplyScalar(2.4),+ phase: 0,+ })), [plan, layout]);+ const mesh = useMemo(() => {+ const m = new InstancedMesh(new BoxGeometry(0.2, 0.02, 0.36), new MeshBasicMaterial({ toneMapped: false }), Math.max(1, feeds.length * PULSES));+ m.raycast = () => undefined;+ m.frustumCulled = false;+ return m;+ }, [feeds]);+ useEffect(() => () => { mesh.geometry.dispose(); (mesh.material as MeshBasicMaterial).dispose(); }, [mesh]);+ const tmp = useMemo(() => new Object3D(), []);+ const from = RAIL_R + 0.4, to = TABLE_AT - 1.1;+ useFrame((_, dt) => {+ const c = layout.centre;+ let i = 0;+ for (const feed of feeds) {+ const working = feed.members.reduce((n, id) => n + (dotOf.get(id) === "working" ? 1 : 0), 0);+ if (!reduced) feed.phase = (feed.phase + dt * (0.35 + 0.08 * working)) % 1;+ for (let k = 0; k < PULSES; k += 1) {+ const t = (feed.phase + k / PULSES) % 1;+ const r = from + (to - from) * t;+ tmp.position.set(c.x + Math.sin(feed.bay.mid) * r, 0.06, c.z + Math.cos(feed.bay.mid) * r);+ tmp.rotation.set(0, feed.bay.mid, 0);+ tmp.scale.setScalar(working > 0 ? 1 - 0.5 * t : 0.0001);+ tmp.updateMatrix();+ mesh.setMatrixAt(i, tmp.matrix);+ mesh.setColorAt(i, feed.colour);+ i += 1;+ }+ }+ mesh.count = i;+ mesh.instanceMatrix.needsUpdate = true;+ if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;+ });+ return <primitive object={mesh} />;+}++// ── master systems display ───────────────────────────────────────────++/** Each bay's load as a bar over the systems table: its colour, its height the share of its panes at work, a state cap. */+function SystemsHolo({ plan, dotOf, reduced }: { plan: DeckPlan; dotOf: ReadonlyMap<string, AgentDotKind>; reduced: boolean }) {+ const table = plan.props.find((p) => p.id === "systems");+ const divisions = plan.divisions;+ const parts = useMemo(() => {+ const n = Math.max(1, divisions.length);+ const bars = new InstancedMesh(new BoxGeometry(1, 1, 1), new MeshBasicMaterial({ toneMapped: false, transparent: true, opacity: 0.75, depthWrite: false }), n);+ const caps = new InstancedMesh(new BoxGeometry(1, 1, 1), new MeshBasicMaterial({ toneMapped: false }), n);+ const sheet = new Mesh(new PlaneGeometry(2.7, 0.8), new MeshBasicMaterial({+ color: new Color(HOLO_CYAN).multiplyScalar(0.5), transparent: true, opacity: 0.35, blending: AdditiveBlending, depthWrite: false, toneMapped: false, side: DoubleSide,+ }));+ sheet.rotation.x = -Math.PI / 2;+ for (const m of [bars, caps, sheet]) { m.raycast = () => undefined; m.frustumCulled = false; }+ return { bars, caps, sheet, colours: divisions.map((d) => new Color(d.colour).multiplyScalar(1.8)) };+ }, [divisions]);+ useEffect(() => () => {+ for (const m of [parts.bars, parts.caps, parts.sheet]) { m.geometry.dispose(); (m.material as MeshBasicMaterial).dispose(); }+ }, [parts]);+ const tmp = useMemo(() => new Object3D(), []);+ const cap = useMemo(() => new Color(), []);+ useFrame(({ clock }) => {+ const n = divisions.length;+ const width = Math.min(0.3, 2.3 / Math.max(1, n));+ const shimmer = reduced ? 1 : 0.94 + 0.06 * Math.sin(clock.elapsedTime * 2.2);+ divisions.forEach((d, i) => {+ let working = 0, waiting = 0;+ for (const id of d.members) { const dot = dotOf.get(id); if (dot === "working") working += 1; else if (dot === "waiting" || dot === "error") waiting += 1; }+ const share = d.members.length ? working / d.members.length : 0;+ const h = (0.08 + 0.62 * share) * shimmer;+ const x = (i - (n - 1) / 2) * (2.3 / Math.max(1, n));+ tmp.position.set(x, h / 2, 0);+ tmp.scale.set(width * 0.7, h, width * 0.7);+ tmp.updateMatrix();+ parts.bars.setMatrixAt(i, tmp.matrix);+ parts.bars.setColorAt(i, parts.colours[i]);+ tmp.position.set(x, h + 0.05, 0);+ tmp.scale.set(width * 0.7, 0.04, width * 0.7);+ tmp.updateMatrix();+ parts.caps.setMatrixAt(i, tmp.matrix);+ cap.set(waiting ? STATE.waiting : working ? STATE.working : STATE.idle).multiplyScalar(2);+ parts.caps.setColorAt(i, cap);+ });+ parts.bars.count = parts.caps.count = n;+ for (const m of [parts.bars, parts.caps]) {+ m.instanceMatrix.needsUpdate = true;+ if (m.instanceColor) m.instanceColor.needsUpdate = true;+ }+ });+ if (!table) return null;+ return (+ <group position={[table.x, 1.32, table.z - 0.15]} rotation={[0, table.yaw, 0]}>+ <primitive object={parts.sheet} />+ <primitive object={parts.bars} />+ <primitive object={parts.caps} />+ </group>+ );+}++// ── live terminals ───────────────────────────────────────────────────++function screenState(dot: AgentDotKind): ScreenState {+ return dot === "working" ? "working" : dot === "waiting" ? "waiting" : dot === "error" ? "error" : "idle";+}++/** Every bay console's screen: the seated pane's live terminal, a standby page, or "vacant". */+function BayScreens({ plan, panes, awake, actions }: { plan: DeckPlan; panes: readonly PaneOccupant[]; awake: boolean; actions: ShipActions }) {+ const { t, openAgent } = actions;+ const byId = useMemo(() => new Map(panes.map((o) => [o.agent.agentId, o])), [panes]);+ const chunks = useMemo(() => {+ const targets: PaneScreenTarget[] = [];+ for (const id of plan.seatOf.keys()) {+ const o = byId.get(id);+ if (o) targets.push({ agentId: id, workspaceId: o.pane.workspace_id, key: o.pane.key });+ }+ return Array.from({ length: SCREEN_CHUNKS }, (_, k) => targets.slice(k * MAX_SCREEN_TARGETS, (k + 1) * MAX_SCREEN_TARGETS));+ }, [plan, byId]);+ // A fixed number of polls, each for its own slice of the seated panes.+ const s0 = usePaneScreens(chunks[0], awake);+ const s1 = usePaneScreens(chunks[1], awake);+ const s2 = usePaneScreens(chunks[2], awake);+ const s3 = usePaneScreens(chunks[3], awake);+ const rowsOf = useMemo(() => {+ const m = new Map<string, string[]>();+ for (const screens of [s0, s1, s2, s3]) for (const [id, screen] of screens as ReadonlyMap<string, PaneScreen>) {+ m.set(id, visibleRows(screen.lines, SCREEN_FIT, screen.cursor).rows);+ }+ return m;+ }, [s0, s1, s2, s3]);+ const content = useCallback((p: Prop): ScreenContent => {+ const accent = p.accent ?? HOLO_CYAN;+ const o = p.ref ? byId.get(p.ref) : undefined;+ if (!o) return { title: t("ship.screen.vacant"), state: "vacant", accent, stateLabel: t("ship.screen.vacant"), standby: t("ship.screen.vacant") };+ const state = screenState(o.dot);+ const live = rowsOf.get(o.agent.agentId);+ const rows = live?.length ? live : state !== "idle" && o.pane.last_prompt ? [`> ${o.pane.last_prompt}`] : undefined;+ return { title: o.agent.title || o.agent.name, state, accent, rows, stateLabel: t(`ship.state.${state}`), standby: t("ship.screen.standby") };+ }, [byId, rowsOf, t]);+ const onScreen = useCallback((p: Prop) => { if (p.ref) openAgent(p.ref); }, [openAgent]);+ return <ConsoleScreens plan={plan} kinds={BAY_KINDS} content={content} onScreen={onScreen} />;+}++/**+ * The terminal feed polls only panes that sit at their console (the shared+ * `seatedCrew` set the office used); the crew layer knows who sits, so+ * this mirrors it every frame and takes its own entries back on the way out.+ */+function SeatWatch({ plan }: { plan: DeckPlan }) {+ const mine = useRef(new Set<string>());+ useFrame(() => {+ for (const [id, seat] of plan.seatOf) {+ const pose = crewPoses.get(id);+ const at = !!pose && !pose.moving && Math.hypot(pose.x - seat.x, pose.z - seat.z) < 0.6;+ if (at) { seatedCrew.add(id); mine.current.add(id); }+ else if (mine.current.has(id)) { seatedCrew.delete(id); mine.current.delete(id); }+ }+ });+ useEffect(() => {+ const own = mine.current;+ return () => { for (const id of own) seatedCrew.delete(id); own.clear(); };+ }, [plan]);+ return null;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/engineering.css b/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/engineering.cssnew file mode 100644index 0000000000..575fcad159--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/engineering.css@@ -0,0 +1,79 @@+/* Engineering's launcher panel, in the ship's dark glass (tokens from hud/ship.css on .ship-stage). */++.eng-launch {+ width: min(440px, calc(100% - 32px));+ max-height: calc(100% - 48px);+ overflow-y: auto;+ padding: 18px 18px 16px;+ display: flex;+ flex-direction: column;+ gap: 14px;+ background: var(--ship-glass-strong);+ outline: none;+}+.eng-launch:focus-visible { box-shadow: 0 0 0 2px rgba(217, 164, 65, 0.5), 0 10px 30px rgba(0, 0, 0, 0.35); }++.eng-launch-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }+.eng-launch-head h2 { margin: 4px 0 0; font: 600 16px "Space Grotesk", "Inter Variable", sans-serif; letter-spacing: 0.02em; color: var(--ship-text); }++.eng-launch-crew { margin: -4px 0 0; display: flex; flex-wrap: wrap; gap: 14px; font-size: 12px; color: var(--ship-muted); }+.eng-launch-crew span { display: inline-flex; align-items: center; gap: 6px; }++.eng-launch-field { margin: 0; padding: 0; border: 0; display: flex; flex-direction: column; gap: 7px; min-width: 0; }+.eng-launch-field legend { padding: 0; margin-bottom: 7px; }++.eng-launch-clis { display: flex; flex-wrap: wrap; gap: 6px; }+.eng-launch-clis button {+ display: inline-flex; align-items: center; gap: 8px; height: 34px; padding: 0 12px 0 6px; border-radius: 8px;+ border: 1px solid var(--ship-line-strong); background: rgba(255, 255, 255, 0.03); color: var(--ship-text);+ font: 500 12.5px "Inter Variable", sans-serif; cursor: pointer;+}+.eng-launch-clis button:hover { background: rgba(255, 255, 255, 0.07); }+.eng-launch-clis button[aria-checked="true"] { border-color: var(--ship-gold); background: rgba(217, 164, 65, 0.1); }+.eng-launch-clis button:focus-visible { outline: 2px solid var(--ship-cyan); outline-offset: 1px; }+.eng-launch-clis button:disabled { opacity: 0.55; cursor: default; }++.eng-launch-input {+ width: 100%; box-sizing: border-box; border-radius: 8px; border: 1px solid var(--ship-line-strong);+ background: rgba(2, 5, 10, 0.6); color: var(--ship-text); font: 13px "Inter Variable", sans-serif; padding: 8px 10px;+}+select.eng-launch-input { height: 36px; padding: 0 10px; color-scheme: dark; }+textarea.eng-launch-input { resize: vertical; min-height: 64px; line-height: 1.45; }+.eng-launch-input::placeholder { color: var(--ship-muted); }+.eng-launch-input:focus-visible { outline: 2px solid var(--ship-cyan); outline-offset: 0; border-color: transparent; }++.eng-launch-go { display: flex; align-items: center; justify-content: space-between; gap: 10px; }+.eng-launch-go .ship-btn { height: 36px; padding: 0 18px; font-size: 13px; }+.eng-launch-go .ship-btn:disabled { opacity: 0.5; cursor: default; filter: none; }++.eng-launch-stepper {+ display: inline-flex; align-items: center; height: 36px; border-radius: 8px; border: 1px solid var(--ship-line-strong);+ background: rgba(255, 255, 255, 0.03);+}+.eng-launch-stepper button {+ width: 34px; height: 100%; display: grid; place-items: center; border: 0; background: transparent; color: var(--ship-text); cursor: pointer;+}+.eng-launch-stepper button:disabled { color: var(--ship-muted); opacity: 0.5; cursor: default; }+.eng-launch-stepper button:focus-visible { outline: 2px solid var(--ship-cyan); outline-offset: -2px; border-radius: 7px; }+.eng-launch-stepper output { min-width: 22px; text-align: center; font: 600 14px "Space Grotesk", sans-serif; color: var(--ship-gold); }++.eng-launch-hint { margin: -6px 0 0; font-size: 11.5px; color: var(--ship-muted); }+.eng-launch-note { margin: 0; font-size: 12.5px; color: var(--ship-muted); line-height: 1.45; }+.eng-launch-link {+ border: 0; padding: 0; background: none; color: var(--ship-gold); font: inherit; text-decoration: underline; cursor: pointer;+}+.eng-launch-link:focus-visible { outline: 2px solid var(--ship-cyan); outline-offset: 2px; }++.eng-launch-log { list-style: none; margin: 0; padding: 10px 0 0; border-top: 1px solid var(--ship-line); display: flex; flex-direction: column; gap: 6px; }+.eng-launch-log li { display: flex; align-items: center; gap: 8px; font-size: 12.5px; color: var(--ship-text); }+.eng-launch-log li > i { width: 7px; height: 7px; border-radius: 50%; flex: none; background: var(--ship-idle); }+.eng-launch-log li[data-tone="busy"] > i { background: var(--ship-cyan); animation: eng-launch-pulse 1.1s ease-in-out infinite; }+.eng-launch-log li[data-tone="ok"] > i { background: var(--ship-working); }+.eng-launch-log li[data-tone="warn"] > i { background: var(--ship-waiting); }+.eng-launch-log li[data-tone="error"] > i { background: #ff4d5e; }++@keyframes eng-launch-pulse { 50% { opacity: 0.35; } }++@media (prefers-reduced-motion: reduce) {+ .eng-launch-log li[data-tone="busy"] > i { animation: none; }+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/engineeringDeck.test.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/engineeringDeck.test.tsnew file mode 100644index 0000000000..2fdd1ee74e--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/engineeringDeck.test.ts@@ -0,0 +1,122 @@+import { describe, expect, it } from "vitest";+import { buildEngineeringDeck, engineeringLayout, MAX_BAYS, MIN_BAYS, planBays, type EngineeringPane } from "./engineeringDeck";+import { buildNavGrid, findPath, isFree } from "../../nav/shipNav";+import { insidePolygon } from "../../plan/builder";+import type { DeckPlan } from "../../plan/types";++/** `n` panes spread round-robin over `workspaces` workspaces. */+function panes(n: number, workspaces: number): EngineeringPane[] {+ return Array.from({ length: n }, (_, i) => {+ const ws = i % Math.max(1, workspaces);+ return { agentId: `pane:w${ws}:h${i}`, workspaceId: `w${ws}`, workspace: `Workspace ${ws}` };+ });+}++function reachable(plan: DeckPlan) {+ const grid = buildNavGrid(plan);+ const misses: string[] = [];+ for (const place of plan.places) if (!findPath(grid, plan.lift, place)) misses.push(place.id);+ for (const station of plan.stations) if (!findPath(grid, plan.lift, station)) misses.push(station.id);+ return { grid, misses };+}++/** A clockwise convex polygon: every turn goes the same way. */+function convex(points: readonly { x: number; z: number }[]): boolean {+ let sign = 0;+ for (let i = 0; i < points.length; i += 1) {+ const a = points[i], b = points[(i + 1) % points.length], c = points[(i + 2) % points.length];+ const cross = (b.x - a.x) * (c.z - b.z) - (b.z - a.z) * (c.x - b.x);+ if (Math.abs(cross) < 1e-9) continue;+ if (sign === 0) sign = Math.sign(cross);+ else if (Math.sign(cross) !== sign) return false;+ }+ return true;+}++const CASES = [0, 3, 20].flatMap((n) => [1, 4, 8].map((ws) => [n, ws] as const));++describe("engineering deck plan", () => {+ it("gives every workspace a bay, at least four, at most six, the rest in Other", () => {+ expect(planBays([])).toHaveLength(MIN_BAYS);+ expect(planBays(panes(3, 1)).map((b) => b.kind)).toEqual(["workspace", "free", "free", "free"]);+ const many = planBays(panes(20, 8));+ expect(many).toHaveLength(MAX_BAYS);+ expect(many.map((b) => b.kind)).toEqual(["workspace", "workspace", "workspace", "workspace", "workspace", "other"]);+ expect(many[5].members).toHaveLength(panes(20, 8).filter((p) => ["w5", "w6", "w7"].includes(p.workspaceId)).length);+ expect(many[0].name).toBe("Workspace 0");+ });++ it.each(CASES)("seats every pane at its own console (%i panes over %i workspaces)", (n, ws) => {+ const plan = buildEngineeringDeck({ panes: panes(n, ws) });+ expect(plan.unseated).toEqual([]);+ for (const p of panes(n, ws)) {+ const seat = plan.seatOf.get(p.agentId);+ expect(seat?.owner).toBe(p.agentId);+ expect(seat?.kind).toBe("console");+ expect(plan.props.some((q) => q.kind === "bayConsole" && q.ref === p.agentId)).toBe(true);+ }+ // A pane sits in its own workspace's bay.+ const bays = planBays(panes(n, ws));+ for (const bay of bays) for (const id of bay.members) expect(plan.seatOf.get(id)?.division).toBe(bay.id);+ expect(plan.divisions.flatMap((d) => d.members).sort()).toEqual(panes(n, ws).map((p) => p.agentId).sort());+ });++ it.each(CASES)("reaches every place and station from the turbolift (%i panes over %i workspaces)", (n, ws) => {+ const plan = buildEngineeringDeck({ panes: panes(n, ws) });+ const { grid, misses } = reachable(plan);+ expect(misses).toEqual([]);+ expect(isFree(grid, plan.lift)).toBe(true);+ expect(isFree(grid, plan.arrival)).toBe(true);+ });++ it.each(CASES)("keeps ids unique and everything inside a convex hull (%i panes over %i workspaces)", (n, ws) => {+ const plan = buildEngineeringDeck({ panes: panes(n, ws) });+ expect(convex(plan.hull)).toBe(true);+ expect(plan.hull[0].z).toBe(0);+ const ids = [+ ...plan.props.map((x) => `prop:${x.id}`), ...plan.places.map((x) => `place:${x.id}`),+ ...plan.stations.map((x) => `station:${x.id}`), ...plan.rooms.map((x) => `room:${x.id}`), ...plan.walls.map((x) => `wall:${x.id}`),+ ];+ expect(new Set(ids).size).toBe(ids.length);+ for (const p of [...plan.places, ...plan.stations, ...plan.props]) expect(insidePolygon(plan.hull, p)).toBe(true);+ expect(plan.props.filter((p) => p.kind === "bayConsole").length).toBeLessThanOrEqual(64);+ });++ it("is deterministic", () => {+ const a = buildEngineeringDeck({ panes: panes(20, 4) });+ const b = buildEngineeringDeck({ panes: panes(20, 4) });+ expect(b.places.map((p) => [p.id, p.x, p.z, p.owner])).toEqual(a.places.map((p) => [p.id, p.x, p.z, p.owner]));+ expect(b.props.map((p) => [p.id, p.x, p.z, p.ref])).toEqual(a.props.map((p) => [p.id, p.x, p.z, p.ref]));+ });++ it("has the core, the systems display, the nook and the turbolift on the stern wall", () => {+ const plan = buildEngineeringDeck({ panes: panes(3, 1) });+ const layout = engineeringLayout(plan);+ expect(layout).toBeDefined();+ const reactor = plan.props.find((p) => p.kind === "reactor");+ expect(reactor && { x: reactor.x, z: reactor.z }).toEqual(layout?.centre);+ expect(plan.walls.filter((w) => w.kind === "rail").length).toBeGreaterThan(8);+ expect(plan.stations.find((s) => s.kind === "systems")?.propId).toBe("systems");+ expect(plan.props.find((p) => p.id === "systems")?.kind).toBe("systemsTable");+ expect(plan.places.some((p) => p.kind === "galley")).toBe(true);+ expect(plan.places.some((p) => p.kind === "window")).toBe(true);+ const lift = plan.props.find((p) => p.kind === "liftDoors");+ expect(lift?.x).toBe(0);+ expect(lift?.z).toBeCloseTo(plan.bounds.z1 - 0.3);+ expect(plan.stations.find((s) => s.kind === "lift")?.x).toBe(0);+ expect(plan.divisions).toHaveLength(1);+ expect(plan.divisions[0].colour).toMatch(/^#/);+ });++ it("widens a busy bay and opens a third row only when needed", () => {+ const small = buildEngineeringDeck({ panes: panes(6, 4) });+ const big = buildEngineeringDeck({ panes: panes(40, 1) });+ const span = (plan: DeckPlan, room: string) => {+ const arc = engineeringLayout(plan)?.bays.find((b) => b.room === room);+ return arc ? arc.a1 - arc.a0 : 0;+ };+ expect(span(big, "bay-ws-w0")).toBeGreaterThan(span(small, "bay-ws-w0"));+ expect(big.unseated).toEqual([]);+ expect(engineeringLayout(big)?.hullR).toBeGreaterThan(engineeringLayout(small)?.hullR ?? Infinity);+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/engineeringDeck.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/engineeringDeck.tsnew file mode 100644index 0000000000..714ee9a7ca--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/engineeringDeck.ts@@ -0,0 +1,381 @@+/**+ * The engineering deck: where the coding agents of the Agentic IDE work.+ *+ * bow ── crew rest nook: galley, mess table, benches at the windows+ * bays (port) ── reactor core in a railed ring ── bays (starboard)+ * stern ── master systems display, turbolift+ *+ * One round chamber (a twelve-sided hull) round a vertical reactor core you+ * can walk round. Every IDE workspace gets a bay: a sector of the ring with+ * arcs of consoles facing the core, one pane's seat behind each console, a+ * holo-table at the bay's inner edge and a power feed running to it from the+ * core. Bays share their side of the ring by how many consoles they need, so+ * a busy workspace gets a wide bay. Four bays at least (the empty ones stand+ * by), six at most; later workspaces share the last bay. Lanes between the+ * bays lead from the walkway to every row.+ */+import { COMMAND_GOLD, DIVISION_COLOURS, HOLO_CYAN, PlanBuilder, POOL_COLOUR, arcPoints, polygonBounds, slug, yawTowards } from "../../plan/builder";+import type { DeckPlan, Place, Rect, Vec2 } from "../../plan/types";+import { rect } from "../../plan/types";++/** One coding pane as the plan sees it. */+export interface EngineeringPane {+ /** The pane projected into a crew member (`paneAgentId`). */+ agentId: string;+ workspaceId: string;+ /** The workspace's label (its department name on the old coding floor). */+ workspace: string;+}++export interface EngineeringInput {+ panes: readonly EngineeringPane[];+}++export const MIN_BAYS = 4;+export const MAX_BAYS = 6;+const SIDES = 12;+const STEP = (Math.PI * 2) / SIDES;+/** The reactor's footprint and the rail round it. */+export const CORE_R = 2.4;+export const RAIL_R = 3.6;+/** Console rows, inner first; a third only when a bay needs it. */+export const ROW_R = [10.5, 13.1, 15.7] as const;+const SEAT_INSET = 0.82;+/** Room behind the last row's seats to the hull. */+const AFT_AISLE = 2.0;+const PITCH = 1.32;+/** From a bay's edge to the centre of its end console: half a walking lane plus the console. */+const LANE = 1.3;+/** The sectors that are not bays: the rest nook at the bow, the turbolift approach at the stern. */+const NOOK_HALF = (40 / 180) * Math.PI;+const LOBBY_HALF = (24 / 180) * Math.PI;+const SIDE_SPAN = Math.PI - NOOK_HALF - LOBBY_HALF;+export const TABLE_AT = 8.3;+const TABLE_R = 0.65;+/** Consoles an empty bay keeps ready. */+const FREE_CONSOLES = 3;+/** Every console screen of a deck lives in one atlas of this many cells. */+export const MAX_CONSOLES = 64;++export type BayKind = "workspace" | "other" | "free";++export interface BayPlan {+ id: string;+ kind: BayKind;+ /** The workspace (or "other") this bay stands for; null for an empty bay. */+ teamId: string | null;+ name: string;+ members: string[];+}++/** Where a bay lies on the ring, for the deck's own scene. */+export interface BayArc {+ room: string;+ kind: BayKind;+ /** From and to (yaw round the core), and the middle. */+ a0: number;+ a1: number;+ mid: number;+ accent: string;+}++export interface EngineeringLayout {+ centre: Vec2;+ /** The hull's inner radius (to the middle of its flat sides). */+ hullR: number;+ bays: BayArc[];+}++const layouts = new WeakMap<DeckPlan, EngineeringLayout>();++/** The ring geometry a plan was built with (the scene draws the floor trims and feeds from it). */+export function engineeringLayout(plan: DeckPlan): EngineeringLayout | undefined {+ return layouts.get(plan);+}++function polar(c: Vec2, r: number, a: number): Vec2 {+ return { x: c.x + Math.sin(a) * r, z: c.z + Math.cos(a) * r };+}++/** Distance from the centre to the hull wall in direction `a` (the hull is a regular twelve-gon with flat bow and stern). */+function wallDistance(hullR: number, a: number): { r: number; normal: number } {+ const normal = Math.round(a / STEP) * STEP;+ return { r: hullR / Math.cos(a - normal), normal };+}++/** Consoles that fit in one row of a bay `span` radians wide at radius `r`. */+export function rowCapacity(r: number, span: number): number {+ const room = span * r - 2 * LANE;+ return room < 0 ? 0 : Math.floor(room / PITCH) + 1;+}++/**+ * Which panes go to which bay: one bay per workspace in the order the panes+ * come (by workspace, then arrival), the workspaces past the sixth bay+ * folded into "Other", empty bays up to four.+ */+export function planBays(panes: readonly EngineeringPane[]): BayPlan[] {+ const order: string[] = [];+ const byWorkspace = new Map<string, EngineeringPane[]>();+ for (const p of panes) {+ let list = byWorkspace.get(p.workspaceId);+ if (!list) { list = []; byWorkspace.set(p.workspaceId, list); order.push(p.workspaceId); }+ list.push(p);+ }+ const own = order.length > MAX_BAYS ? order.slice(0, MAX_BAYS - 1) : order;+ const folded = order.length > MAX_BAYS ? order.slice(MAX_BAYS - 1) : [];+ const used = new Set<string>();+ const bays: BayPlan[] = own.map((ws) => {+ let id = `bay-ws-${slug(ws)}`;+ for (let k = 2; used.has(id); k += 1) id = `bay-ws-${slug(ws)}-${k}`;+ used.add(id);+ const list = byWorkspace.get(ws) ?? [];+ return { id, kind: "workspace", teamId: ws, name: list[0]?.workspace || ws, members: list.map((p) => p.agentId) };+ });+ if (folded.length) {+ const names = folded.map((ws) => byWorkspace.get(ws)?.[0]?.workspace || ws);+ bays.push({+ id: "bay-other", kind: "other", teamId: "other",+ name: names.slice(0, 2).join(" · ") + (names.length > 2 ? ` +${names.length - 2}` : ""),+ members: folded.flatMap((ws) => (byWorkspace.get(ws) ?? []).map((p) => p.agentId)),+ });+ }+ while (bays.length < MIN_BAYS) bays.push({ id: `bay-free-${bays.length}`, kind: "free", teamId: null, name: "", members: [] });+ return bays;+}++function need(bay: BayPlan): number {+ return bay.kind === "free" ? FREE_CONSOLES : bay.members.length + 1;+}++interface Sector { bay: BayPlan; a0: number; a1: number; mid: number; span: number }++/**+ * Split the two sides of the ring between the bays: each bay goes to the+ * lighter side, then every side is shared by weight (consoles needed, four+ * at least). Starboard runs from the stern towards the bow, port likewise.+ */+function sectors(bays: readonly BayPlan[]): Sector[] {+ const weight = (b: BayPlan) => Math.max(4, need(b));+ const sides: BayPlan[][] = [[], []];+ const load = [0, 0];+ for (const bay of bays) {+ const s = load[0] <= load[1] ? 0 : 1;+ sides[s].push(bay);+ load[s] += weight(bay);+ }+ const out: Sector[] = [];+ sides.forEach((list, s) => {+ const start = s === 0 ? LOBBY_HALF : Math.PI * 2 - LOBBY_HALF;+ const dir = s === 0 ? 1 : -1;+ let acc = 0;+ for (const bay of list) {+ const span = (SIDE_SPAN * weight(bay)) / load[s];+ const from = start + dir * acc, to = start + dir * (acc + span);+ out.push({ bay, a0: Math.min(from, to), a1: Math.max(from, to), mid: (from + to) / 2, span });+ acc += span;+ }+ });+ // Back in bay order.+ return bays.map((b) => out.find((o) => o.bay === b) as Sector);+}++function capacity(span: number, rows: number): number[] {+ return ROW_R.slice(0, rows).map((r) => rowCapacity(r, span));+}++/** The hull outline: a regular twelve-gon round `centre`, flat at the bow (z = 0) and the stern, clockwise from the bow. */+export function engineeringHull(hullR: number): Vec2[] {+ const rv = hullR / Math.cos(STEP / 2);+ const c = { x: 0, z: hullR };+ return Array.from({ length: SIDES }, (_, j) => {+ const p = polar(c, rv, Math.PI + STEP / 2 - STEP * j);+ // Snap the flat edges exactly onto their lines.+ return { x: Math.abs(p.x) < 1e-9 ? 0 : p.x, z: Math.abs(p.z) < 1e-9 ? 0 : Math.abs(p.z - 2 * hullR) < 1e-9 ? 2 * hullR : p.z };+ });+}++export function buildEngineeringDeck({ panes }: EngineeringInput): DeckPlan {+ const b = new PlanBuilder("engineering");+ const bays = planBays(panes);+ const sect = sectors(bays);++ // Two rows unless a bay needs a third.+ let rows = 2;+ if (sect.some((s) => s.bay.members.length > capacity(s.span, 2).reduce((x, y) => x + y, 0))) rows = 3;+ const caps = sect.map((s) => capacity(s.span, rows));+ const capTotal = caps.map((c) => c.reduce((x, y) => x + y, 0));++ // Seat members first (within the bay and the screen atlas), then spare consoles while there is room.+ let budget = MAX_CONSOLES;+ const seated = sect.map((s, i) => {+ const n = Math.min(s.bay.members.length, capTotal[i], budget);+ budget -= n;+ return n;+ });+ const consoles = sect.map((s, i) => {+ const extra = Math.max(0, Math.min(need(s.bay) - seated[i], capTotal[i] - seated[i], budget));+ budget -= extra;+ return seated[i] + extra;+ });+ const unseated = sect.flatMap((s, i) => s.bay.members.slice(seated[i]));++ const hullR = ROW_R[rows - 1] + SEAT_INSET + AFT_AISLE;+ const c: Vec2 = { x: 0, z: hullR };+ const zEnd = 2 * hullR;+ const hull = engineeringHull(hullR);+ const bounds = polygonBounds(hull);+ const clampRect = (r: Rect): Rect => rect(Math.max(bounds.x0, r.x0), Math.max(bounds.z0, r.z0), Math.min(bounds.x1, r.x1), Math.min(bounds.z1, r.z1));++ // ── hull ───────────────────────────────────────────────────────────+ // Edge j runs from vertex j to j + 1; edge 0 is the bow, 6 the stern, 1 and 11 the nook's windows.+ hull.forEach((p, i) => {+ const q = hull[(i + 1) % hull.length];+ if (i === SIDES / 2) {+ b.wallWithDoors(`hull-${i}`, "hull", p, q, [{ at: Math.abs(q.x - p.x) / 2, width: 3, slides: true, id: "lift-door" }], 0.5);+ } else {+ b.wall(`hull-${i}`, "hull", p, q, 0.5, i === 1 || i === SIDES - 1);+ }+ });++ // ── the core ───────────────────────────────────────────────────────+ b.room({ id: "core", kind: "core", rect: rect(c.x - RAIL_R, c.z - RAIL_R, c.x + RAIL_R, c.z + RAIL_R), floor: "deck", accent: HOLO_CYAN, sign: null });+ b.room({ id: "chamber", kind: "engineering", rect: clampRect(rect(c.x - ROW_R[0], c.z - ROW_R[0], c.x + ROW_R[0], c.z + ROW_R[0])), floor: "deck", accent: HOLO_CYAN, sign: null });+ b.prop({ id: "reactor", kind: "reactor", x: c.x, z: c.z, yaw: 0, w: CORE_R * 2, d: CORE_R * 2, h: 5.2, solid: true });+ const railN = 16;+ for (let k = 0; k < railN; k += 1) {+ b.wall(`core-rail-${k}`, "rail", polar(c, RAIL_R, (k / railN) * Math.PI * 2), polar(c, RAIL_R, ((k + 1) / railN) * Math.PI * 2));+ }++ // ── master systems display, between the core and the turbolift ───+ b.prop({ id: "systems", kind: "systemsTable", x: c.x, z: c.z + 6.2, yaw: 0, w: 3.2, d: 1.5, h: 1.05, solid: true, accent: COMMAND_GOLD });+ b.station({ id: "systems", kind: "systems", x: c.x, z: c.z + 7.6, radius: 1.6, propId: "systems" });++ // ── bays ───────────────────────────────────────────────────────────+ const seatOf = new Map<string, Place>();+ const arcs: BayArc[] = [];+ let colour = 0;+ const boundaries = new Set<number>();+ sect.forEach((s, i) => {+ const bay = s.bay;+ const room = bay.id;+ const accent = bay.kind === "free" ? POOL_COLOUR : DIVISION_COLOURS[colour++ % DIVISION_COLOURS.length];+ arcs.push({ room, kind: bay.kind, a0: s.a0, a1: s.a1, mid: s.mid, accent });+ boundaries.add(Math.round(s.a0 * 1e6) / 1e6);+ boundaries.add(Math.round(s.a1 * 1e6) / 1e6);++ // The bay's floor area (for the sign and the minimap; the floor itself is the chamber's).+ const corners = [s.a0, s.mid, s.a1].flatMap((a) => [polar(c, TABLE_AT - 1, a), polar(c, wallDistance(hullR, a).r, a)]);+ const box = polygonBounds(corners);+ const wall = wallDistance(hullR, s.mid);+ const signAt = polar(c, wall.r - 0.3, s.mid);+ b.room({ id: room, kind: "bay", rect: clampRect(box), floor: "deck", accent,+ sign: bay.kind === "workspace" ? { text: bay.name } : { key: bay.kind === "other" ? "ship.engineering.other" : "ship.engineering.bay_free" },+ signAt: { ...signAt, yaw: wall.normal + Math.PI } });++ // Consoles, inner row first, each row centred on the bay; seats behind them face the core.+ const members: string[] = [];+ let left = consoles[i];+ let seatIndex = 0;+ let lastRow = 0;+ caps[i].forEach((cap, row) => {+ const n = Math.min(cap, left);+ left -= n;+ if (n <= 0) return;+ lastRow = row;+ const r = ROW_R[row];+ arcPoints(c, r, n, s.mid, ((n - 1) * PITCH) / r).forEach((p, k) => {+ const owner = seatIndex < seated[i] ? bay.members[seatIndex] : undefined;+ seatIndex += 1;+ const seat = polar(c, r + SEAT_INSET, p.yaw);+ b.prop({ id: `bayconsole-${room}-${row}-${k}`, kind: "bayConsole", x: p.x, z: p.z, yaw: p.yaw, w: 1.15, d: 0.72, h: 1.5, solid: true, ref: owner, accent });+ b.prop({ id: `chair-${room}-${row}-${k}`, kind: "consoleChair", x: seat.x, z: seat.z, yaw: p.yaw + Math.PI, w: 0.55, d: 0.55, h: 1.0, solid: false, ref: owner, accent });+ if (owner) {+ const place = b.place({ id: `seat-${room}-${row}-${k}`, kind: "console", x: seat.x, z: seat.z, yaw: p.yaw + Math.PI, pose: "sit", seatY: 0.5, owner, division: room });+ seatOf.set(owner, place);+ members.push(owner);+ }+ });+ });++ // The power feed from the core to the bay, under a floor plate.+ const feedFrom = RAIL_R + 0.25, feedTo = TABLE_AT - TABLE_R - 0.3;+ const feedAt = polar(c, (feedFrom + feedTo) / 2, s.mid);+ b.prop({ id: `feed-${room}`, kind: "conduit", x: feedAt.x, z: feedAt.z, yaw: s.mid, w: 0.46, d: feedTo - feedFrom, h: 0.05, solid: false, ref: `floor:${room}`, accent });++ // A quiet place in the aisle behind the consoles.+ const stroll = polar(c, Math.min(ROW_R[lastRow] + SEAT_INSET + 0.85, wall.r - 1.0), s.mid);++ const tableAt = polar(c, TABLE_AT, s.mid);+ if (bay.kind === "free") {+ b.prop({ id: `crate-${room}-0`, kind: "crate", x: tableAt.x, z: tableAt.z, yaw: s.mid, w: 1.0, d: 0.9, h: 0.8, solid: true });+ const side = polar(c, TABLE_AT, s.mid + 1.25 / TABLE_AT);+ b.prop({ id: `crate-${room}-1`, kind: "crate", x: side.x, z: side.z, yaw: s.mid + 0.3, w: 0.8, d: 0.7, h: 0.6, solid: true });+ return;+ }+ b.place({ id: `bay-stroll-${room}`, kind: "stroll", x: stroll.x, z: stroll.z, yaw: s.mid + Math.PI, pose: "stand", seatY: 0, division: room });+ // The bay's holo-table at the walkway, its people gather on the core's side of it.+ b.prop({ id: `table-${room}`, kind: "holoTable", x: tableAt.x, z: tableAt.z, yaw: s.mid + Math.PI, w: TABLE_R * 2, d: TABLE_R * 2, h: 0.95, solid: true, ref: room, accent });+ const towardsCore = yawTowards(tableAt, c);+ const gather = arcPoints(tableAt, TABLE_R + 0.62, 3, towardsCore, 1.5).map((p, k) =>+ b.place({ id: `gather-${room}-${k}`, kind: "table", x: p.x, z: p.z, yaw: p.yaw + Math.PI, pose: "stand", seatY: 0, division: room }));+ b.divisions.push({ id: room, teamId: bay.teamId, name: bay.name, colour: accent, leadId: null, members, centre: tableAt, room, gather });+ });++ // Pipe risers on the hull wall where the bays meet each other, the nook and the lobby.+ [...boundaries].sort((x, y) => x - y).forEach((a, k) => {+ const wall = wallDistance(hullR, a);+ const at = polar(c, wall.r - 0.25 - 0.3, a);+ b.prop({ id: `riser-${k}`, kind: "conduit", x: at.x, z: at.z, yaw: wall.normal + Math.PI, w: 1.0, d: 0.6, h: 2.7, solid: true, ref: "wall" });+ });++ // ── bow: the crew rest nook ────────────────────────────────────────+ const nookDepth = Math.min(7.6, c.z - 8.4);+ b.room({ id: "nook", kind: "mess", rect: rect(-5.5, 0, 5.5, nookDepth), floor: "carpet", accent: COMMAND_GOLD,+ sign: { key: "ship.engineering.nook" }, signAt: { x: 0, z: 0.3, yaw: 0 } });+ b.prop({ id: "galley", kind: "galley", x: 0, z: 0.75, yaw: 0, w: 4.4, d: 0.9, h: 1.05, solid: true });+ for (let k = 0; k < 3; k += 1) b.place({ id: `galley-${k}`, kind: "galley", x: -1.6 + k * 1.6, z: 1.8, yaw: 0, pose: "stand", seatY: 0 });+ b.station({ id: "mess", kind: "mess", x: 0, z: 2.0, radius: 1.6, propId: "galley" });+ for (const [k, x] of [-3.2, 3.2].entries()) b.prop({ id: `nook-plant-${k}`, kind: "plant", x, z: 0.8, yaw: 0, w: 0.8, d: 0.8, h: 1.4, solid: true });+ const mess = { x: 0, z: Math.min(4.8, nookDepth - 1.6) };+ b.prop({ id: "mess-0", kind: "messTable", x: mess.x, z: mess.z, yaw: 0, w: 1.3, d: 1.3, h: 0.74, solid: true });+ for (let k = 0; k < 4; k += 1) {+ const a = (k / 4) * Math.PI * 2 + Math.PI / 4;+ const sx = mess.x + Math.sin(a) * 1.05, sz = mess.z + Math.cos(a) * 1.05;+ b.place({ id: `mess-0-${k}`, kind: "mess", x: sx, z: sz, yaw: yawTowards({ x: sx, z: sz }, mess), pose: "sit", seatY: 0.48 });+ b.prop({ id: `stool-0-${k}`, kind: "messStool", x: sx, z: sz, yaw: 0, w: 0.42, d: 0.42, h: 0.46, solid: false });+ }+ // Benches facing the two windowed sides of the bow, standing places at the glass.+ for (const [k, side] of [-1, 1].entries()) {+ const a = Math.PI + side * (22 / 180) * Math.PI;+ const at = polar(c, hullR - 2.6, a);+ b.prop({ id: `nook-bench-${k}`, kind: "bench", x: at.x, z: at.z, yaw: a, w: 2.4, d: 0.55, h: 0.45, solid: true });+ for (const s of [-1, 1]) {+ const p = { x: at.x + Math.cos(a) * 0.55 * s, z: at.z - Math.sin(a) * 0.55 * s };+ b.place({ id: `nook-bench-${k}-${s}`, kind: "lounge", x: p.x, z: p.z, yaw: a, pose: "sit", seatY: 0.45 });+ }+ for (const [w, deg] of [18, 28].entries()) {+ const wa = Math.PI + side * (deg / 180) * Math.PI;+ const wp = polar(c, wallDistance(hullR, wa).r - 1.0, wa);+ b.place({ id: `nook-window-${k}-${w}`, kind: "window", x: wp.x, z: wp.z, yaw: wa, pose: "stand", seatY: 0 });+ }+ }++ // ── stern: the turbolift ───────────────────────────────────────────+ b.room({ id: "lobby", kind: "lift", rect: rect(-3.8, zEnd - 6, 3.8, zEnd), floor: "deck", accent: COMMAND_GOLD,+ sign: { key: "ship.room.lift" }, signAt: { x: 0, z: zEnd - 0.56, yaw: Math.PI } });+ b.prop({ id: "lift-doors", kind: "liftDoors", x: 0, z: zEnd - 0.3, yaw: Math.PI, w: 3.4, d: 0.5, h: 2.7, solid: true });+ b.station({ id: "lift", kind: "lift", x: 0, z: zEnd - 1.4, radius: 1.6, propId: "lift-doors" });+ for (const [k, x] of [-3.2, 3.2].entries()) {+ b.prop({ id: `lobby-locker-${k}`, kind: "locker", x, z: zEnd - 0.6, yaw: Math.PI, w: 1.0, d: 0.6, h: 2.1, solid: true });+ b.place({ id: `lobby-stroll-${k}`, kind: "stroll", x: x * 0.6, z: zEnd - 4.2, yaw: x < 0 ? Math.PI / 2 : -Math.PI / 2, pose: "stand", seatY: 0 });+ }++ const plan = b.build({+ bounds, hull, seatOf, unseated,+ arrival: { x: 0, z: zEnd - 2.4 },+ lift: { x: 0, z: zEnd - 1.6, yaw: Math.PI },+ });+ layouts.set(plan, { centre: c, hullR, bays: arcs });+ return plan;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/index.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/index.tsnew file mode 100644index 0000000000..76de224d73--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/index.ts@@ -0,0 +1,25 @@+/**+ * Deck 3, engineering: the coding panes of the Agentic IDE at work round the+ * reactor. Its crew are the panes; the master systems display opens the+ * launcher for new coding agents.+ */+import { registerDeck } from "../registry";+import { buildEngineeringDeck } from "./engineeringDeck";+import { EngineeringPanel } from "./EngineeringPanel";+import { EngineeringScene } from "./EngineeringScene";+import "./props";++registerDeck({+ id: "engineering",+ population: "panes",+ build: (input) => buildEngineeringDeck({+ panes: input.panes.map((o) => ({ agentId: o.agent.agentId, workspaceId: o.pane.workspace_id, workspace: o.agent.providerLabel || o.pane.workspace_name })),+ }),+ Scene: EngineeringScene,+ useStation: (station, _plan, actions) => {+ if (station.kind !== "systems") return false;+ actions.openPanel(station.id);+ return true;+ },+ Panel: EngineeringPanel,+});diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/props.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/props.tsnew file mode 100644index 0000000000..6146553c01--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/engineering/props.ts@@ -0,0 +1,127 @@+/**+ * Engineering's machinery, built into the deck's merged batch: the bay+ * workstations, the master systems display, the reactor's housing and cage,+ * and the conduits (floor feeds and wall risers). Same conventions as the+ * shared builders: centred on the footprint, the front (where a person uses+ * it) towards +z, foot on the floor. The reactor's plasma and the screens+ * are drawn live by the deck's scene; `glow` is kept for real light sources.+ */+import { CONSOLE_SCREEN, registerPropBuilders, type PropBuilder } from "../../render/deck/props";+import { SHIP } from "../../render/kit/palette";++/** Where the plasma column runs inside the reactor (its own frame). */+export const PLASMA = { y0: 1.3, y1: 4.55, r: 0.62, sleeve: 0.92 } as const;++/** A bay workstation: a heavy pedestal, a sloped desk, the live screen and an equipment spine behind it. */+const bayConsole: PropBuilder = (f, p) => {+ const accent = p.accent ?? SHIP.cyan;+ f.chamfer("structure", p.w - 0.05, 0.1, 0.66, 0.1, SHIP.charcoal, { z: -0.03 });+ f.chamfer("structure", 0.84, 0.64, 0.44, 0.08, SHIP.graphite, { y: 0.1, z: -0.1 });+ // Vent slats on the pedestal's front and the kick light under them.+ for (let k = 0; k < 4; k += 1) f.box("structure", 0.56, 0.025, 0.02, SHIP.panelDark, { y: 0.26 + k * 0.08, z: 0.13 });+ f.box("glow", 0.6, 0.012, 0.012, accent, { y: 0.12, z: 0.13 });+ // Desk: ceramic rim round a dark sloped work surface.+ f.rounded("panel", p.w, 0.06, 0.6, 0.07, SHIP.panelCool, { y: 0.74, z: 0.04 });+ f.rounded("structure", p.w - 0.1, 0.02, 0.48, 0.05, SHIP.panelDark, { y: 0.8, z: 0.05, pitch: 0.06 });+ f.box("glowSoft", 0.5, 0.006, 0.15, "#24607f", { y: 0.825, z: 0.17 });+ for (const s of [-1, 1]) f.box("glowSoft", 0.12, 0.006, 0.1, s < 0 ? "#3a5a2c" : "#5c4a22", { x: s * 0.4, y: 0.825, z: 0.17 });+ f.box("glow", p.w - 0.12, 0.012, 0.012, accent, { y: 0.75, z: 0.34 });+ // Screen post and bezel (the face is drawn live in the same place as every console's).+ f.box("structure", 0.1, 0.34, 0.07, SHIP.graphite, { y: 0.8, z: CONSOLE_SCREEN.z - 0.07 });+ const s = f.child({ y: CONSOLE_SCREEN.y, z: CONSOLE_SCREEN.z, pitch: CONSOLE_SCREEN.tilt });+ s.box("structure", CONSOLE_SCREEN.w + 0.07, CONSOLE_SCREEN.h + 0.07, 0.04, SHIP.charcoal, { y: -(CONSOLE_SCREEN.h + 0.07) / 2, z: -0.028 });+ s.box("structure", CONSOLE_SCREEN.w + 0.07, 0.05, 0.08, SHIP.graphite, { y: (CONSOLE_SCREEN.h + 0.07) / 2 - 0.05, z: -0.05 });+ s.box("glow", CONSOLE_SCREEN.w + 0.06, 0.01, 0.045, accent, { y: -(CONSOLE_SCREEN.h + 0.07) / 2 - 0.01, z: -0.028 });+ // Equipment spine behind the screen: a dark box with module seams and two pilot lights.+ f.box("structure", p.w - 0.25, 0.5, 0.14, SHIP.graphite, { y: 0.8, z: -0.29 });+ for (let k = 0; k < 3; k += 1) f.box("structure", 0.012, 0.44, 0.15, SHIP.charcoal, { x: -0.3 + k * 0.3, y: 0.83, z: -0.29 });+ f.box("glow", 0.04, 0.04, 0.01, SHIP.cyan, { x: -(p.w - 0.25) / 2 + 0.1, y: 1.18, z: -0.36 });+ f.box("glow", 0.04, 0.04, 0.01, accent, { x: -(p.w - 0.25) / 2 + 0.18, y: 1.18, z: -0.36 });+ // Side cheeks.+ for (const side of [-1, 1]) f.chamfer("panel", 0.09, 0.26, 0.46, 0.03, SHIP.panel, { x: side * (p.w / 2 - 0.045), y: 0.77, z: 0.02 });+};++/** The master systems display: a long sloped table on two pedestals, framed by two uprights for the hologram above it. */+const systemsTable: PropBuilder = (f, p) => {+ const accent = p.accent ?? SHIP.gold;+ f.chamfer("structure", p.w - 0.2, 0.1, p.d - 0.2, 0.14, SHIP.charcoal, {});+ for (const s of [-1, 1]) {+ f.chamfer("structure", 0.7, 0.72, p.d - 0.5, 0.1, SHIP.graphite, { x: s * (p.w / 2 - 0.65), y: 0.1 });+ f.box("glow", 0.5, 0.012, 0.012, SHIP.cyan, { x: s * (p.w / 2 - 0.65), y: 0.14, z: (p.d - 0.5) / 2 + 0.005 });+ }+ f.box("structure", p.w - 1.6, 0.3, 0.3, SHIP.panelDark, { y: 0.5 });+ const top = f.child({ y: 0.84, pitch: 0.1 });+ top.rounded("panel", p.w, 0.08, p.d, 0.12, SHIP.panelCool, {});+ top.rounded("structure", p.w - 0.18, 0.02, p.d - 0.2, 0.08, SHIP.panelDark, { y: 0.08 });+ top.box("glowSoft", p.w - 0.36, 0.006, p.d - 0.42, "#12405c", { y: 0.1 });+ // A grid of status cells across the display.+ for (let k = 0; k < 8; k += 1) top.box("glowSoft", 0.24, 0.006, 0.08, k % 3 === 0 ? "#2f7fa8" : "#1c5574", { x: -1.05 + k * 0.3, y: 0.107, z: p.d / 2 - 0.36 });+ top.box("glow", p.w - 0.1, 0.014, 0.014, accent, { y: 0.02, z: p.d / 2 + 0.005 });+ // Uprights at the back with an emitter bar between them.+ for (const s of [-1, 1]) f.box("metal", 0.08, 1.1, 0.08, SHIP.steelLight, { x: s * (p.w / 2 - 0.12), y: 0.9, z: -p.d / 2 + 0.12 });+ f.box("structure", p.w - 0.2, 0.08, 0.12, SHIP.graphite, { y: 1.98, z: -p.d / 2 + 0.12 });+ f.box("glow", p.w - 0.4, 0.015, 0.03, SHIP.cyan, { y: 1.97, z: -p.d / 2 + 0.19 });+};++/** The reactor's fixed parts: plinth, housing, the glass sleeve, the cage with its constrictor coils, and the cap. */+const reactor: PropBuilder = (f, p) => {+ const r = p.w / 2;+ f.cylinder("structure", r, r + 0.05, 0.14, SHIP.charcoal, {}, 48);+ f.cylinder("structure", r - 0.55, r - 0.3, 0.95, SHIP.graphite, { y: 0.14 }, 12);+ // Housing panels: twelve inset faces with a seam light under each.+ for (let k = 0; k < 12; k += 1) {+ const a = (k / 12) * Math.PI * 2 + Math.PI / 12;+ f.box("panel", 0.62, 0.5, 0.05, SHIP.panelCool, { x: Math.sin(a) * (r - 0.42), z: Math.cos(a) * (r - 0.42), y: 0.36, yaw: a, pitch: -0.12 });+ if (k % 3 === 0) f.box("glowSoft", 0.4, 0.02, 0.02, SHIP.cyan, { x: Math.sin(a) * (r - 0.4), z: Math.cos(a) * (r - 0.4), y: 0.24, yaw: a });+ }+ // Feed pipes from the housing down into the deck.+ for (let k = 0; k < 8; k += 1) {+ const a = (k / 8) * Math.PI * 2;+ f.cylinder("metal", 0.08, 0.1, 0.62, SHIP.steel, { x: Math.sin(a) * (r - 0.18), z: Math.cos(a) * (r - 0.18), y: 0.14 }, 10);+ f.cylinder("structure", 0.13, 0.13, 0.06, SHIP.graphite, { x: Math.sin(a) * (r - 0.18), z: Math.cos(a) * (r - 0.18), y: 0.72 }, 10);+ }+ f.cylinder("panel", 1.55, 1.75, 0.2, SHIP.panel, { y: 1.09 }, 36);+ f.ring("glow", 1.58, 0.022, SHIP.cyan, { y: 1.3 }, Math.PI * 2, 64);+ // The sleeve the plasma runs in.+ f.cylinder("glass", PLASMA.sleeve, PLASMA.sleeve, PLASMA.y1 - PLASMA.y0, "#bfe8ff", { y: PLASMA.y0 }, 36, true);+ // Cage: six struts and the constrictor coils round the sleeve.+ for (let k = 0; k < 6; k += 1) {+ const a = (k / 6) * Math.PI * 2;+ f.box("metal", 0.09, PLASMA.y1 - PLASMA.y0, 0.16, SHIP.steelLight, { x: Math.sin(a) * 1.12, z: Math.cos(a) * 1.12, y: PLASMA.y0, yaw: a });+ }+ for (const y of [1.95, 2.85, 3.75]) {+ f.ring("structure", 1.06, 0.1, SHIP.graphite, { y }, Math.PI * 2, 40);+ f.ring("metal", 1.06, 0.035, SHIP.steelLight, { y: y + 0.11 }, Math.PI * 2, 40);+ }+ // Cap with its own collar and a ring of status lights.+ f.cylinder("panel", 1.7, 1.5, 0.18, SHIP.panel, { y: PLASMA.y1 }, 36);+ f.cylinder("structure", 1.2, 1.55, 0.42, SHIP.graphite, { y: PLASMA.y1 + 0.18 }, 12);+ f.ring("glow", 1.52, 0.02, SHIP.cyan, { y: PLASMA.y1 + 0.2 }, Math.PI * 2, 64);+ f.cylinder("metal", 0.5, 0.7, 0.05, SHIP.steel, { y: PLASMA.y1 + 0.6 }, 24);+};++/** A floor feed (`ref` "floor:…"): a ribbed duct under a plate. Otherwise a wall riser: a pipe bundle with brackets and a valve. */+const conduit: PropBuilder = (f, p) => {+ const accent = p.accent ?? SHIP.cyan;+ if (p.ref?.startsWith("floor")) {+ f.rounded("structure", p.w, 0.03, p.d, 0.08, SHIP.charcoal, {});+ f.box("metal", p.w - 0.12, 0.012, p.d - 0.12, SHIP.steel, { y: 0.03 });+ const n = Math.max(2, Math.floor(p.d / 0.6));+ for (let k = 0; k <= n; k += 1) f.box("structure", p.w - 0.06, 0.02, 0.05, SHIP.graphite, { y: 0.03, z: -p.d / 2 + 0.06 + ((p.d - 0.12) * k) / n });+ f.box("glowSoft", 0.05, 0.006, p.d - 0.2, accent, { y: 0.045 });+ return;+ }+ const h = p.h;+ f.chamfer("structure", p.w, 0.14, p.d, 0.08, SHIP.charcoal, {});+ f.box("structure", p.w, h - 0.1, 0.08, SHIP.graphite, { z: -p.d / 2 + 0.04, y: 0.1 });+ const xs = [-p.w / 2 + 0.2, 0, p.w / 2 - 0.2];+ xs.forEach((x, k) => f.cylinder("metal", k === 1 ? 0.11 : 0.075, k === 1 ? 0.11 : 0.075, h - 0.16, k === 1 ? SHIP.steelLight : SHIP.steel, { x, y: 0.14, z: 0.02 }, 14));+ for (const y of [0.55, 1.45, 2.3]) f.box("structure", p.w - 0.04, 0.07, p.d - 0.1, SHIP.panelDark, { y, z: 0.0 });+ // A lit band round the main pipe, and a hand valve on its front.+ f.ring("glow", 0.12, 0.012, SHIP.cyan, { y: 1.0, z: 0.02 }, Math.PI * 2, 20);+ f.ring("metal", 0.12, 0.018, SHIP.steelLight, { y: 1.2, z: 0.2, pitch: Math.PI / 2 }, Math.PI * 2, 20);+ f.box("metal", 0.03, 0.03, 0.1, SHIP.steel, { y: 1.185, z: 0.13 });+ f.box("glowSoft", 0.06, 0.12, 0.01, accent, { x: p.w / 2 - 0.08, y: 1.7, z: p.d / 2 - 0.02 });+};++registerPropBuilders({ bayConsole, systemsTable, reactor, conduit });diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/HolodeckPanel.tsx b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/HolodeckPanel.tsxnew file mode 100644index 0000000000..d8db6e8be6--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/HolodeckPanel.tsx@@ -0,0 +1,65 @@+/**+ * A holo cabinet's program: the game's player, loaded the first time it is+ * needed. The retro games open RetroArcadeOverlay with a metered loader;+ * Asteroid Run opens its 3D cabinet. Closing the game closes the panel.+ */+import { lazy, Suspense, useCallback, useEffect, useMemo, useRef } from "react";+import { useLocaleChunk } from "@/i18n";+import { arcadeGame, type RetroGameId } from "../../../arcade/arcadeGames";+import type { DeckPanelProps } from "../registry";+import { meteredLoader, readAsteroidBest } from "./holodeckMeter";+import "./holodeck.css";++const RetroArcadeOverlay = lazy(() => import("../../../arcade/RetroArcadeOverlay").then((m) => ({ default: m.RetroArcadeOverlay })));+const ArcadeCabinet = lazy(() => import("../../../arcade/ArcadeCabinet").then((m) => ({ default: m.ArcadeCabinet })));++export function HolodeckPanel({ station, actions }: DeckPanelProps) {+ // The players' own strings live in the society chunk.+ const ready = useLocaleChunk("society");+ const game = station.ref ? arcadeGame(station.ref) : null;+ // The stage's actions are rebuilt on every render; the game's callbacks must stay put.+ const actionsRef = useRef(actions);+ actionsRef.current = actions;+ const close = useCallback(() => actionsRef.current.closePanel(), []);+ const loader = useMemo(() => meteredLoader((action, ref) => actionsRef.current.reportAction(action, ref)), []);++ // Asteroid Run tells nobody about its rounds; a new best on leaving it counts as a record.+ const asteroids = game?.kind === "asteroid3d";+ useEffect(() => {+ if (!asteroids) return;+ const before = readAsteroidBest();+ return () => { if (readAsteroidBest() > before) actionsRef.current.reportAction("holodeck_record", "asteroid-run"); };+ }, [asteroids]);++ const t = actions.t;+ if (!game) {+ return (+ <div className="ship-scrim holo-scrim" onClick={close}>+ <section className="ship-panel holo-card" role="alertdialog" aria-modal="true" aria-label={t("ship.holodeck.room")} onClick={(e) => e.stopPropagation()}>+ <p>{t("ship.holodeck.missing")}</p>+ <button type="button" className="ship-btn" data-primary="true" autoFocus onClick={close}>{t("ship.close")}</button>+ </section>+ </div>+ );+ }+ const loading = (+ <div className="ship-scrim holo-scrim">+ <div className="ship-panel holo-card holo-loading" role="status" aria-live="polite">+ <span className="holo-loading-mark" aria-hidden />+ <span>+ <span className="ship-eyebrow">{t("ship.holodeck.program")}</span>+ <span className="holo-loading-title">{game.title}</span>+ <small>{t("ship.holodeck.loading")}</small>+ </span>+ </div>+ </div>+ );+ if (!ready) return loading;+ return (+ <Suspense fallback={loading}>+ {game.kind === "retro"+ ? <RetroArcadeOverlay gameId={game.id as RetroGameId} loadGame={loader} report={false} onClose={close} />+ : <ArcadeCabinet onClose={close} />}+ </Suspense>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/HolodeckScene.tsx b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/HolodeckScene.tsxnew file mode 100644index 0000000000..d18bb2fecf--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/HolodeckScene.tsx@@ -0,0 +1,279 @@+/**+ * The holodeck on screen, beyond the shared kit: the arch, a soft pulse that+ * runs through the gold grid from the program spot, and over every emitter a+ * hovering holographic cabinet (a translucent cyan body with gold edges,+ * scan lines, a flicker, the game's title and its two-frame attract loop).+ * Reduced motion holds everything still.+ */+import { useFrame } from "@react-three/fiber";+import { useEffect, useMemo } from "react";+import {+ AdditiveBlending, BoxGeometry, Color, CylinderGeometry, DoubleSide, EdgesGeometry, Group, LineBasicMaterial, LineSegments,+ Matrix4, Mesh, MeshBasicMaterial, PlaneGeometry, ShaderMaterial, Shape, ShapeGeometry, Vector3, type BufferGeometry, type Material,+} from "three";+import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";+import { arcadeGame, type ArcadeGameInfo } from "../../../arcade/arcadeGames";+import type { DeckSceneProps } from "../registry";+import type { DeckPlan, Prop, Vec2 } from "../../plan/types";+import { GeoBatch } from "../../render/kit/geo";+import { castsShadow, finishMaterial, receivesShadow } from "../../render/kit/materials";+import { SHIP } from "../../render/kit/palette";+import { textPlane } from "../../render/deck/DeckScene";+import { clipPolygon } from "../../render/deck/structure";+import { AttractAtlas } from "./attract";+import { buildArch, LENS_Y } from "./holodeckProps";+import { PROGRAM_SPOT } from "./holodeckPlan";++export function HolodeckScene({ plan, reduced }: DeckSceneProps) {+ return (+ <>+ <HolodeckFittings plan={plan} />+ <GridPulse plan={plan} reduced={reduced} />+ <HoloCabinets plan={plan} reduced={reduced} />+ </>+ );+}++/** The arch: static, merged like the rest of the deck. */+function HolodeckFittings({ plan }: { plan: DeckPlan }) {+ const meshes = useMemo(() => {+ const door = plan.doors.find((d) => d.id === "holo-arch");+ if (!door) return [];+ const batch = new GeoBatch();+ // The arch belongs to its bulkhead: it sinks with it in the cut-away.+ buildArch(batch.frame(new Matrix4().setPosition(door.at.x, 0, door.at.z), { ax: plan.bounds.x0, az: door.at.z, bx: plan.bounds.x1, bz: door.at.z, kind: 2 }));+ return batch.merged().map(({ finish, geometry }) => {+ const mesh = new Mesh(geometry, finishMaterial(finish));+ mesh.castShadow = castsShadow(finish);+ mesh.receiveShadow = receivesShadow(finish);+ mesh.raycast = () => undefined;+ return mesh;+ });+ }, [plan]);+ useEffect(() => () => { for (const m of meshes) m.geometry.dispose(); }, [meshes]);+ return <>{meshes.map((m, i) => <primitive key={i} object={m} />)}</>;+}++// ── the grid pulse ────────────────────────────────────────────────────++const WORLD_VERT = /* glsl */ `varying vec3 vWorld; varying vec2 vUv;+ void main() { vUv = uv; vec4 w = modelMatrix * vec4(position, 1.0); vWorld = w.xyz; gl_Position = projectionMatrix * viewMatrix * w; }`;++const PULSE_FRAG = /* glsl */ `uniform float uTime; uniform float uMotion; uniform vec2 uCentre; uniform vec3 uGold;+ varying vec3 vWorld;+ void main() {+ vec2 p = vWorld.xz;+ vec2 g = abs(fract(p + 0.5) - 0.5);+ vec2 w = fwidth(p) * 1.2 + 0.012;+ float line = max(1.0 - smoothstep(0.0, w.x, g.x), 1.0 - smoothstep(0.0, w.y, g.y));+ float d = length(p - uCentre);+ // A wide, slow ring that leaves the program spot every few seconds.+ float wave = exp(-pow(mod(d - uTime * 2.4, 16.0) - 2.0, 2.0) * 0.35) * uMotion;+ float spot = exp(-pow((d - 1.7) * 5.0, 2.0));+ float fall = 1.0 - smoothstep(4.0, 22.0, d) * 0.6;+ gl_FragColor = vec4(uGold * (line * (0.05 + wave * 0.5) * fall + spot * 0.22), 1.0);+ }`;++/** A flat polygon on the floor (y = 0), in world coordinates. */+function floorPolygon(points: readonly Vec2[]): BufferGeometry {+ const shape = new Shape(points.map((p) => ({ x: p.x, y: -p.z }) as never));+ const g = new ShapeGeometry(shape);+ g.rotateX(-Math.PI / 2);+ return g;+}++function GridPulse({ plan, reduced }: { plan: DeckPlan; reduced: boolean }) {+ const room = plan.rooms.find((r) => r.kind === "holodeck");+ const geometry = useMemo(() => {+ if (!room) return null;+ const r = room.rect;+ const poly = clipPolygon([{ x: r.x0, z: r.z0 }, { x: r.x1, z: r.z0 }, { x: r.x1, z: r.z1 }, { x: r.x0, z: r.z1 }], plan.hull);+ return poly.length >= 3 ? floorPolygon(poly) : null;+ }, [room, plan.hull]);+ const material = useMemo(() => new ShaderMaterial({+ vertexShader: WORLD_VERT, fragmentShader: PULSE_FRAG, transparent: true, blending: AdditiveBlending, depthWrite: false,+ uniforms: {+ uTime: { value: 0 }, uMotion: { value: 1 }, uCentre: { value: [PROGRAM_SPOT.x, PROGRAM_SPOT.z] },+ uGold: { value: new Color(SHIP.gold).multiplyScalar(1.6) },+ },+ }), []);+ useEffect(() => () => { geometry?.dispose(); }, [geometry]);+ useEffect(() => () => material.dispose(), [material]);+ useFrame(({ clock }) => {+ material.uniforms.uTime.value = reduced ? 0 : clock.elapsedTime;+ material.uniforms.uMotion.value = reduced ? 0 : 1;+ });+ if (!geometry) return null;+ return <mesh geometry={geometry} material={material} position={[0, 0.03, 0]} renderOrder={1} raycast={() => undefined} />;+}++// ── the holographic cabinets ──────────────────────────────────────────++const BODY_VERT = /* glsl */ `varying vec3 vWorld; varying vec3 vNormal; varying vec2 vUv;+ void main() {+ vUv = uv; vec4 w = modelMatrix * vec4(position, 1.0); vWorld = w.xyz;+ vNormal = normalize(mat3(modelMatrix) * normal);+ gl_Position = projectionMatrix * viewMatrix * w;+ }`;++const BODY_FRAG = /* glsl */ `uniform float uTime; uniform float uFlicker; uniform vec3 uColour;+ varying vec3 vWorld; varying vec3 vNormal; varying vec2 vUv;+ void main() {+ vec3 view = normalize(cameraPosition - vWorld);+ float rim = pow(1.0 - abs(dot(normalize(vNormal), view)), 2.0);+ vec2 e = abs(vUv * 2.0 - 1.0);+ float edge = smoothstep(0.86, 1.0, max(e.x, e.y));+ float scan = 0.7 + 0.3 * sin(vWorld.y * 110.0 - uTime * 6.0);+ float sweep = exp(-pow((fract(vWorld.y * 0.45 - uTime * 0.28) - 0.5) * 9.0, 2.0));+ vec3 c = uColour * (0.07 + rim * 0.35 + edge * 0.55 + sweep * 0.22) * scan * uFlicker;+ gl_FragColor = vec4(c, 1.0);+ }`;++const SCREEN_FRAG = /* glsl */ `uniform sampler2D uMap; uniform vec4 uCell; uniform float uFrame; uniform float uTime; uniform float uFlicker; uniform vec3 uTint;+ varying vec3 vWorld; varying vec2 vUv;+ void main() {+ vec2 uv = vec2(uCell.x + (vUv.x + uFrame) * uCell.z, uCell.y + vUv.y * uCell.w);+ vec3 px = texture2D(uMap, uv).rgb;+ float scan = 0.72 + 0.28 * sin(vUv.y * 140.0 - uTime * 4.0);+ vec2 e = abs(vUv * 2.0 - 1.0);+ float frame = smoothstep(0.9, 1.0, max(e.x, e.y));+ gl_FragColor = vec4((px * 1.7 * scan + uTint * (0.05 + frame * 0.6)) * uFlicker, 1.0);+ }`;++const BEAM_FRAG = /* glsl */ `uniform float uFlicker; uniform vec3 uColour; varying vec2 vUv;+ void main() {+ float fade = smoothstep(0.0, 0.25, vUv.y) * (1.0 - smoothstep(0.6, 1.0, vUv.y));+ gl_FragColor = vec4(uColour * fade * 0.28 * uFlicker, 1.0);+ }`;++/** The cabinet's silhouette in its own frame: foot at y = 0, the screen side towards +z. */+const SHAPE = [+ { w: 0.74, h: 0.86, d: 0.6, y: 0, z: -0.04, pitch: 0 },+ { w: 0.8, h: 0.07, d: 0.34, y: 0.86, z: 0.18, pitch: 0.2 },+ { w: 0.74, h: 0.8, d: 0.5, y: 0.93, z: -0.09, pitch: 0 },+ { w: 0.8, h: 0.22, d: 0.46, y: 1.73, z: -0.07, pitch: 0 },+] as const;+const SCREEN = { w: 0.58, h: 0.44, y: 1.34, z: 0.165, tilt: -0.1 } as const;+const HOVER = LENS_Y + 0.12;+const TITLE_Y = 2.28;++function silhouette(): { fill: BufferGeometry; edges: BufferGeometry } {+ const fills: BufferGeometry[] = [], edges: BufferGeometry[] = [];+ for (const s of SHAPE) {+ const box = new BoxGeometry(s.w, s.h, s.d);+ box.translate(0, s.h / 2, 0);+ const m = new Matrix4().makeRotationX(s.pitch).setPosition(0, s.y, s.z);+ box.applyMatrix4(m);+ fills.push(box);+ edges.push(new EdgesGeometry(box));+ }+ const fill = mergeGeometries(fills, false) as BufferGeometry;+ const edge = mergeGeometries(edges, false) as BufferGeometry;+ for (const g of [...fills, ...edges]) g.dispose();+ return { fill, edges: edge };+}++interface Cabinet {+ game: ArcadeGameInfo;+ group: Group;+ hover: Group;+ title: Mesh;+ body: ShaderMaterial;+ screen: ShaderMaterial;+ beam: ShaderMaterial;+ edges: LineBasicMaterial;+ seed: number;+}++/** Deterministic noise in [0, 1). */+function noise(n: number): number {+ const s = Math.sin(n * 127.1) * 43758.5453;+ return s - Math.floor(s);+}++function HoloCabinets({ plan, reduced }: { plan: DeckPlan; reduced: boolean }) {+ const atlas = useMemo(() => new AttractAtlas(), []);+ const shared = useMemo(() => ({ ...silhouette(), screen: new PlaneGeometry(SCREEN.w, SCREEN.h), beam: new CylinderGeometry(0.46, 0.21, HOVER - LENS_Y + 0.08, 28, 1, true) }), []);+ const cabinets = useMemo(() => plan.props+ .filter((p): p is Prop & { ref: string } => p.kind === "cabinet" && !!p.ref && !!arcadeGame(p.ref))+ .map((p, i): Cabinet => {+ const game = arcadeGame(p.ref) as ArcadeGameInfo;+ const group = new Group();+ group.position.set(p.x, 0, p.z);+ group.rotation.y = p.yaw;+ const hover = new Group();+ hover.position.y = HOVER;+ group.add(hover);+ const holo = { transparent: true, blending: AdditiveBlending, depthWrite: false, side: DoubleSide } as const;+ const body = new ShaderMaterial({ ...holo, vertexShader: BODY_VERT, fragmentShader: BODY_FRAG,+ uniforms: { uTime: { value: 0 }, uFlicker: { value: 1 }, uColour: { value: new Color(SHIP.cyan).multiplyScalar(0.42) } } });+ const fill = new Mesh(shared.fill, body);+ fill.renderOrder = 3;+ hover.add(fill);+ const edges = new LineBasicMaterial({ color: new Color(SHIP.gold).multiplyScalar(1.15), transparent: true, opacity: 0.85, blending: AdditiveBlending, depthWrite: false, toneMapped: false });+ const lines = new LineSegments(shared.edges, edges);+ lines.renderOrder = 3;+ hover.add(lines);+ const [u0, v0, du, dv] = atlas.cell(game.id);+ const screen = new ShaderMaterial({ ...holo, vertexShader: WORLD_VERT, fragmentShader: SCREEN_FRAG,+ uniforms: {+ uMap: { value: atlas.texture }, uCell: { value: [u0, v0, du, dv] }, uFrame: { value: 0 }, uTime: { value: 0 }, uFlicker: { value: 1 },+ uTint: { value: new Color(game.look.accent) },+ } });+ const face = new Mesh(shared.screen, screen);+ face.position.set(0, SCREEN.y, SCREEN.z);+ face.rotation.x = SCREEN.tilt;+ face.renderOrder = 4;+ hover.add(face);+ const beam = new ShaderMaterial({ ...holo, vertexShader: WORLD_VERT, fragmentShader: BEAM_FRAG,+ uniforms: { uFlicker: { value: 1 }, uColour: { value: new Color(SHIP.cyan).multiplyScalar(0.55) } } });+ const cone = new Mesh(shared.beam, beam);+ cone.position.y = LENS_Y + (HOVER - LENS_Y + 0.08) / 2;+ cone.renderOrder = 2;+ group.add(cone);+ const title = textPlane(game.title, game.look.marqueeText, { size: 0.24 });+ title.position.y = TITLE_Y;+ title.renderOrder = 5;+ group.add(title);+ for (const o of [fill, lines, face, cone]) o.raycast = () => undefined;+ return { game, group, hover, title, body, screen, beam, edges, seed: i * 1.37 + 0.4 };+ }), [plan, atlas, shared]);++ useEffect(() => () => {+ for (const c of cabinets) {+ for (const m of [c.body, c.screen, c.beam, c.edges] as Material[]) m.dispose();+ const tm = c.title.material as MeshBasicMaterial;+ tm.map?.dispose(); tm.dispose(); c.title.geometry.dispose();+ }+ }, [cabinets]);+ useEffect(() => () => {+ shared.fill.dispose(); shared.edges.dispose(); shared.screen.dispose(); shared.beam.dispose();+ atlas.dispose();+ }, [shared, atlas]);++ const at = useMemo(() => new Vector3(), []);+ useFrame(({ camera, clock }) => {+ const t = reduced ? 0 : clock.elapsedTime;+ for (const c of cabinets) {+ // A steady shimmer with a rare drop-out, each cabinet on its own beat.+ let flicker = 1;+ if (!reduced) {+ flicker = 0.92 + 0.08 * Math.sin(t * 13 + c.seed * 5) * Math.sin(t * 7.3 + c.seed);+ if (noise(Math.floor(t * 9) + c.seed * 31) > 0.985) flicker *= 0.45;+ }+ c.hover.position.y = HOVER + (reduced ? 0 : Math.sin(t * 1.3 + c.seed) * 0.022);+ c.body.uniforms.uTime.value = t;+ c.body.uniforms.uFlicker.value = flicker;+ c.screen.uniforms.uTime.value = t;+ c.screen.uniforms.uFlicker.value = flicker;+ c.screen.uniforms.uFrame.value = reduced ? 0 : Math.floor(t * 2 + c.seed) % 2;+ c.beam.uniforms.uFlicker.value = flicker;+ c.edges.opacity = 0.85 * flicker;+ (c.title.material as MeshBasicMaterial).opacity = flicker;+ c.title.getWorldPosition(at);+ c.title.lookAt(camera.position.x, at.y, camera.position.z);+ }+ });++ return <>{cabinets.map((c) => <primitive key={c.game.id} object={c.group} />)}</>;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/attract.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/attract.tsnew file mode 100644index 0000000000..7b363435f6--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/attract.ts@@ -0,0 +1,135 @@+/**+ * Attract mode for the holographic cabinets: two tiny pixel frames per game,+ * drawn once into one atlas. The screens flip between the frames, which is+ * all an attract loop needs to read as "a game is running" from across the+ * deck. Black is empty: the hologram is additive.+ */+import { CanvasTexture, NearestFilter, SRGBColorSpace } from "three";+import { ARCADE_GAMES, type ArcadeGameInfo } from "../../../arcade/arcadeGames";++export const CELL_W = 64;+export const CELL_H = 48;+const ATLAS_W = CELL_W * 2;+const ATLAS_H = 512;++type Paint = (px: (x: number, y: number, w?: number, h?: number, colour?: string) => void, frame: 0 | 1, look: ArcadeGameInfo["look"]) => void;++const SCENES: Record<string, Paint> = {+ "asteroid-run": (px, f, look) => {+ for (const [x, y] of [[6, 5], [50, 9], [20, 40], [58, 30], [33, 3]]) px(x, y, 1, 1, "#9fb3c8");+ const rocks = f ? [[12, 12], [44, 30], [28, 34]] : [[14, 13], [42, 28], [30, 36]];+ for (const [x, y] of rocks) { px(x, y, 5, 4, look.marqueeText); px(x + 1, y - 1, 3, 1, look.marqueeText); px(x + 1, y + 4, 3, 1, look.marqueeText); }+ const sy = f ? 22 : 24;+ px(30, sy, 1, 1, look.accent); px(29, sy + 1, 3, 2, look.accent); px(28, sy + 3, 5, 1, look.accent);+ if (f) px(30, sy - 6, 1, 3, "#ffffff");+ },+ "neon-snake": (px, f, look) => {+ const body = [[4, 6], [5, 6], [6, 6], [7, 6], [7, 5], [7, 4], [8, 4], [9, 4]];+ const cells = f ? [...body.slice(1), [10, 4]] : body;+ for (const [cx, cy] of cells) px(cx * 4 + 1, cy * 4 + 1, 3, 3, look.accent);+ px(12 * 4 + 1, 4 * 4 + 1, 3, 3, look.marqueeText);+ px(0, 0, 64, 1, look.accent); px(0, 47, 64, 1, look.accent); px(0, 0, 1, 48, look.accent); px(63, 0, 1, 48, look.accent);+ },+ "brick-breaker": (px, f, look) => {+ for (let r = 0; r < 3; r += 1) for (let c = 0; c < 6; c += 1) if (!(r === 2 && c === (f ? 3 : 2))) px(3 + c * 10, 4 + r * 5, 8, 3, r === 0 ? look.marqueeText : look.accent);+ px(f ? 26 : 22, 43, 14, 2, "#ffffff");+ px(f ? 34 : 28, f ? 24 : 32, 2, 2, "#ffffff");+ },+ "paddle-duel": (px, f, look) => {+ for (let y = 2; y < 46; y += 6) px(31, y, 2, 3, look.accent);+ px(4, f ? 14 : 20, 2, 10, look.marqueeText);+ px(58, f ? 24 : 18, 2, 10, look.marqueeText);+ px(f ? 40 : 20, f ? 28 : 22, 2, 2, "#ffffff");+ },+ "block-drop": (px, f, look) => {+ const stack = [[0, 5], [1, 5], [2, 5], [4, 5], [5, 5], [6, 5], [7, 5], [0, 4], [1, 4], [5, 4], [6, 4], [7, 4], [0, 3], [6, 3]];+ for (const [c, r] of stack) px(16 + c * 4, 22 + r * 4, 3, 3, r === 5 ? look.accent : look.marqueeText);+ const top = f ? 14 : 6;+ for (const [c, r] of [[2, 0], [3, 0], [4, 0], [3, 1]]) px(16 + c * 4, top + r * 4, 3, 3, "#ffffff");+ px(15, 2, 1, 44, look.accent); px(48, 2, 1, 44, look.accent);+ },+ "maze-muncher": (px, f, look) => {+ px(2, 2, 60, 1, look.accent); px(2, 45, 60, 1, look.accent); px(2, 2, 1, 44, look.accent); px(61, 2, 1, 44, look.accent);+ px(12, 14, 16, 1, look.accent); px(36, 14, 16, 1, look.accent); px(12, 33, 40, 1, look.accent); px(31, 14, 1, 10, look.accent);+ for (let x = 30; x < 58; x += 5) px(x, 24, 1, 1, "#ffe9b8");+ // The muncher: mouth open, then closed.+ const cx = f ? 22 : 18;+ px(cx - 2, 20, 5, 9, look.marqueeText); px(cx - 4, 22, 9, 5, look.marqueeText); px(cx - 3, 21, 7, 7, look.marqueeText);+ if (!f) { px(cx + 1, 24, 4, 1, "#000000"); px(cx + 2, 23, 3, 3, "#000000"); }+ px(44, 37, 6, 6, "#ff5d7a"); px(45, 36, 4, 1, "#ff5d7a");+ },+ "desert-dash": (px, f, look) => {+ px(0, 40, 64, 1, look.accent);+ for (const x of [8, 27, 50]) px((x + (f ? 60 : 0)) % 64, 42, 2, 1, look.accent);+ const cx = f ? 40 : 46;+ px(cx, 31, 2, 9, "#7ed957"); px(cx - 3, 34, 3, 1, "#7ed957"); px(cx - 3, 31, 1, 3, "#7ed957"); px(cx + 2, 33, 3, 1, "#7ed957"); px(cx + 4, 30, 1, 3, "#7ed957");+ const y = f ? 24 : 31;+ px(12, y, 6, 6, look.marqueeText); px(16, y - 2, 4, 3, look.marqueeText);+ px(f ? 12 : 13, y + 6, 1, 3, look.marqueeText); px(f ? 17 : 16, y + 6, 1, 3, look.marqueeText);+ },+ "pixel-raiders": (px, f, look) => {+ for (let r = 0; r < 2; r += 1) for (let c = 0; c < 5; c += 1) {+ const x = 6 + c * 11 + (f ? 2 : 0), y = 6 + r * 9;+ const colour = r ? look.accent : look.marqueeText;+ px(x + 1, y, 5, 1, colour); px(x, y + 1, 7, 2, colour); px(x + 1, y + 1, 1, 1, "#000000"); px(x + 5, y + 1, 1, 1, "#000000");+ if (f) { px(x, y + 3, 1, 2, colour); px(x + 6, y + 3, 1, 2, colour); } else { px(x + 2, y + 3, 1, 2, colour); px(x + 4, y + 3, 1, 2, colour); }+ }+ px(f ? 34 : 28, 41, 7, 3, "#7cf0ff"); px((f ? 34 : 28) + 3, 39, 1, 2, "#7cf0ff");+ px(f ? 37 : 31, f ? 26 : 32, 1, 4, "#ffffff");+ },+ "road-hopper": (px, f, look) => {+ for (const y of [12, 22, 32]) for (let x = 0; x < 64; x += 8) px(x, y, 4, 1, "#5d6672");+ px(0, 41, 64, 1, look.accent); px(0, 3, 64, 1, look.accent);+ const shift = f ? 6 : 0;+ for (const [x, y, w] of [[6, 14, 10], [40, 14, 8], [20, 24, 12], [52, 24, 8], [10, 34, 9], [44, 34, 11]]) px((x + (y === 24 ? -shift : shift) + 64) % 64, y + 2, w, 4, y === 24 ? look.marqueeText : "#ff7a5a");+ const fy = f ? 27 : 37;+ px(30, fy, 4, 3, look.accent); px(29, fy + 1, 1, 2, look.accent); px(34, fy + 1, 1, 2, look.accent);+ },+ "city-defense": (px, f, look) => {+ for (const [x, h] of [[4, 6], [12, 9], [20, 5], [40, 8], [48, 6], [56, 10]]) px(x, 46 - h, 6, h, look.accent);+ px(29, 40, 6, 6, "#9aa3ae"); px(31, 37, 2, 3, "#9aa3ae");+ const len = f ? 22 : 12;+ for (let k = 0; k < len; k += 1) { px(8 + k, 2 + k, 1, 1, "#ff6a4c"); px(54 - Math.floor(k * 0.6), 2 + k, 1, 1, "#ff6a4c"); }+ if (f) { px(22, 10, 7, 7, look.marqueeText); px(24, 8, 3, 11, look.marqueeText); px(20, 12, 11, 3, look.marqueeText); }+ },+};++/** The atlas of every game's two frames: row = game, column = frame. */+export class AttractAtlas {+ readonly texture: CanvasTexture;+ private readonly rows = new Map<string, number>();++ constructor(games: readonly ArcadeGameInfo[] = ARCADE_GAMES) {+ const canvas = document.createElement("canvas");+ canvas.width = ATLAS_W; canvas.height = ATLAS_H;+ const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;+ ctx.fillStyle = "#000000"; ctx.fillRect(0, 0, ATLAS_W, ATLAS_H);+ games.forEach((game, row) => {+ this.rows.set(game.id, row);+ const paint = SCENES[game.id];+ for (const frame of [0, 1] as const) {+ const ox = frame * CELL_W, oy = row * CELL_H;+ const px = (x: number, y: number, w = 1, h = 1, colour = game.look.accent) => {+ ctx.fillStyle = colour;+ ctx.fillRect(ox + Math.max(0, x), oy + Math.max(0, y), Math.min(w, CELL_W - x), Math.min(h, CELL_H - y));+ };+ if (paint) paint(px, frame, game.look);+ else px(28, 20 + frame * 4, 8, 8);+ }+ });+ this.texture = new CanvasTexture(canvas);+ this.texture.magFilter = NearestFilter;+ this.texture.minFilter = NearestFilter;+ this.texture.generateMipmaps = false;+ this.texture.colorSpace = SRGBColorSpace;+ }++ /** The uv rectangle of a game's first frame: [u0, v0, du, dv]; the second frame sits du to the right. */+ cell(gameId: string): [number, number, number, number] {+ const row = this.rows.get(gameId) ?? 0;+ const dv = CELL_H / ATLAS_H;+ return [0, 1 - (row + 1) * dv, CELL_W / ATLAS_W, dv];+ }++ dispose(): void { this.texture.dispose(); }+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/holodeck.css b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/holodeck.cssnew file mode 100644index 0000000000..be7a622f95--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/holodeck.css@@ -0,0 +1,31 @@+/* The holodeck's own panel pieces; the game players bring their own look. Uses the ship HUD's tokens (hud/ship.css). */++/* Above the HUD, below the game players (z-index 70). The stage loads ship.css after this file, hence the double class. */+.ship-scrim.holo-scrim { z-index: 60; }++.holo-card {+ width: min(340px, calc(100% - 32px)); padding: 16px 18px; display: flex; flex-direction: column; gap: 12px;+ font-size: 13px; color: var(--ship-text);+}+.holo-card p { margin: 0; line-height: 1.45; }++.holo-loading { flex-direction: row; align-items: center; gap: 14px; }+.holo-loading > span:last-child { display: flex; flex-direction: column; gap: 2px; min-width: 0; }+.holo-loading-title { font: 600 15px "Space Grotesk", "Inter Variable", sans-serif; letter-spacing: 0.02em; }+.holo-loading small { color: var(--ship-muted); font-size: 12px; }++/* A small emitter: a gold ring with a cyan field rising out of it. */+.holo-loading-mark {+ position: relative; flex: none; width: 38px; height: 38px; border-radius: 8px;+ border: 1px solid rgba(217, 164, 65, 0.45); background: rgba(217, 164, 65, 0.06); overflow: hidden;+}+.holo-loading-mark::before {+ content: ""; position: absolute; left: 8px; right: 8px; bottom: 6px; height: 3px; border-radius: 2px; background: var(--ship-gold);+}+.holo-loading-mark::after {+ content: ""; position: absolute; left: 11px; right: 11px; bottom: 9px; height: 20px;+ background: repeating-linear-gradient(180deg, rgba(95, 212, 255, 0.55) 0 2px, transparent 2px 4px);+ animation: holo-field 1.4s ease-in-out infinite;+}+@keyframes holo-field { 0%, 100% { opacity: 0.35; transform: scaleY(0.6); transform-origin: bottom; } 50% { opacity: 1; transform: scaleY(1); } }+@media (prefers-reduced-motion: reduce) { .holo-loading-mark::after { animation: none; opacity: 0.8; } }diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/holodeckMeter.test.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/holodeckMeter.test.tsnew file mode 100644index 0000000000..c13a320ecf--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/holodeckMeter.test.ts@@ -0,0 +1,51 @@+import { beforeEach, describe, expect, it } from "vitest";+import type { RetroGame } from "../../../arcade/retroGame";+import { clearBestMemory, saveBest } from "../../../arcade/retroScores";+import { meteredGame, type HolodeckAction } from "./holodeckMeter";++interface S { score: number; over: boolean }++const game: RetroGame<S> = {+ id: "neon-snake", width: 10, height: 10,+ create: () => ({ score: 0, over: false }),+ step: (s) => { s.score += 10; },+ draw: () => undefined,+ status: (s) => ({ score: s.score, over: s.over }),+};++describe("holodeck metering", () => {+ beforeEach(() => { window.localStorage.clear(); clearBestMemory(); });++ it("reports a finished, scored run once, a record when it beats the best", () => {+ const reports: [HolodeckAction, string][] = [];+ const metered = meteredGame(game, "neon-snake", (a, id) => reports.push([a, id]));+ const run = metered.create(Math.random);+ metered.step(run, {} as never, 1, Math.random);+ expect(metered.status(run).over).toBe(false);+ run.over = true;+ metered.status(run);+ metered.status(run);+ expect(reports).toEqual([["holodeck_record", "neon-snake"]]);++ saveBest("neon-snake", 500);+ const second = metered.create(Math.random);+ second.score = 40; second.over = true;+ metered.status(second);+ expect(reports[1]).toEqual(["holodeck_round", "neon-snake"]);+ });++ it("does not report a run that scored nothing", () => {+ const reports: string[] = [];+ const metered = meteredGame(game, "neon-snake", (a) => reports.push(a));+ const run = metered.create(Math.random);+ run.over = true;+ metered.status(run);+ expect(reports).toEqual([]);+ });++ it("keeps the rest of the game as it was", () => {+ const metered = meteredGame(game, "neon-snake", () => undefined);+ expect(metered.width).toBe(10);+ expect(metered.create(Math.random)).toEqual({ score: 0, over: false });+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/holodeckMeter.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/holodeckMeter.tsnew file mode 100644index 0000000000..b87befea3d--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/holodeckMeter.ts@@ -0,0 +1,49 @@+/**+ * Metering the holodeck's games for the level system. The retro overlay has+ * no round callback, but it takes the loader of its game, so the holodeck+ * hands it the same game with a watched `status`: the first time a run reads+ * as over, a scored round is reported, as a record when it beats the stored+ * best. The overlay checks `status` right after the step that ends a run and+ * only then stores the new best, so the best read here is still the old one.+ */+import { loadRetroGame, type RetroGameId } from "../../../arcade/arcadeGames";+import type { RetroGame, RetroStatus } from "../../../arcade/retroGame";+import { readBest } from "../../../arcade/retroScores";++export type HolodeckAction = "holodeck_round" | "holodeck_record";+export type Report = (action: HolodeckAction, gameId: string) => void;++/** The same game, reporting each finished, scored run once. */+export function meteredGame<S>(game: RetroGame<S>, gameId: string, report: Report): RetroGame<S> {+ const finished = new WeakSet<object>();+ let finishedValue: unknown = undefined;+ const status = (state: S): RetroStatus => {+ const s = game.status(state);+ if (!s.over) return s;+ // States are objects in every game; a primitive state is remembered by value instead.+ const isObject = typeof state === "object" && state !== null;+ if (isObject ? finished.has(state as object) : finishedValue === state) return s;+ if (isObject) finished.add(state as object); else finishedValue = state;+ const score = Math.max(0, Math.floor(s.score));+ if (score > 0) report(score > readBest(gameId) ? "holodeck_record" : "holodeck_round", gameId);+ return s;+ };+ return Object.assign(Object.create(game) as RetroGame<S>, { status });+}++/** A loader for RetroArcadeOverlay that meters every game it loads. */+export function meteredLoader(report: Report): (id: RetroGameId) => Promise<RetroGame<unknown>> {+ return (id) => loadRetroGame(id).then((game) => meteredGame(game as RetroGame<unknown>, id, report));+}++/** Asteroid Run keeps its best score here (office/ArcadeCabinet.tsx); it has no loader to watch. */+export const ASTEROID_BEST_KEY = "jarvis.office.arcade.asteroids.best";++export function readAsteroidBest(): number {+ try {+ const n = Number(window.localStorage.getItem(ASTEROID_BEST_KEY));+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;+ } catch {+ return 0;+ }+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/holodeckPlan.test.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/holodeckPlan.test.tsnew file mode 100644index 0000000000..f4e28ca911--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/holodeckPlan.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from "vitest";+import { ARCADE_GAMES } from "../../../arcade/arcadeGames";+import { insidePolygon } from "../../plan/builder";+import { buildNavGrid, findPath, isFree } from "../../nav/shipNav";+import { Matrix4 } from "three";+import { GeoBatch } from "../../render/kit/geo";+import { buildProps } from "../../render/deck/props";+import { buildHolodeck, cabinetStationId, emitterId } from "./holodeckPlan";+import { buildArch } from "./holodeckProps";++describe("holodeck plan", () => {+ const plan = buildHolodeck();++ it("gives every game one emitter and one cabinet station", () => {+ const stations = plan.stations.filter((s) => s.kind === "holoCabinet");+ expect(stations.map((s) => s.ref).sort()).toEqual(ARCADE_GAMES.map((g) => g.id).sort());+ for (const game of ARCADE_GAMES) {+ const station = plan.stations.find((s) => s.id === cabinetStationId(game.id));+ expect(station?.propId).toBe(emitterId(game.id));+ const prop = plan.props.find((p) => p.id === emitterId(game.id));+ expect(prop?.kind).toBe("cabinet");+ expect(prop?.ref).toBe(game.id);+ }+ });++ it("stands the player 0.9 m in front of each emitter, facing it", () => {+ for (const s of plan.stations.filter((st) => st.kind === "holoCabinet")) {+ const p = plan.props.find((q) => q.id === s.propId)!;+ const ahead = (s.x - p.x) * Math.sin(p.yaw) + (s.z - p.z) * Math.cos(p.yaw);+ expect(ahead).toBeCloseTo(p.d / 2 + 0.9, 5);+ }+ });++ it("has the turbolift centred on the stern wall", () => {+ const lift = plan.stations.find((s) => s.kind === "lift");+ expect(lift?.x).toBe(0);+ expect(plan.lift.x).toBe(0);+ expect(plan.props.find((p) => p.kind === "liftDoors")?.z).toBeCloseTo(plan.bounds.z1 - 0.3, 5);+ expect(plan.doors.some((d) => d.id === "lift-door")).toBe(true);+ });++ it("reaches every station and place from the turbolift", () => {+ const grid = buildNavGrid(plan);+ expect(isFree(grid, plan.lift)).toBe(true);+ const misses = [...plan.stations, ...plan.places].filter((t) => !findPath(grid, plan.lift, t)).map((t) => t.id);+ expect(misses).toEqual([]);+ });++ it("keeps ids unique and everything inside the hull", () => {+ const ids = [...plan.props.map((x) => `prop:${x.id}`), ...plan.places.map((x) => `place:${x.id}`), ...plan.stations.map((x) => `station:${x.id}`)];+ expect(new Set(ids).size).toBe(ids.length);+ for (const p of [...plan.props, ...plan.places, ...plan.stations]) expect(insidePolygon(plan.hull, p)).toBe(true);+ });++ it("is a black holo chamber nobody is seated in", () => {+ expect(plan.rooms.find((r) => r.kind === "holodeck")?.floor).toBe("holo");+ expect(plan.divisions).toEqual([]);+ expect(plan.places.some((p) => p.kind === "console")).toBe(false);+ });++ it("builds the emitters and the arch into the deck's batch", () => {+ const batch = new GeoBatch();+ buildProps(plan, batch);+ buildArch(batch.frame(new Matrix4()));+ const parts = batch.merged();+ expect(parts.some((p) => p.finish === "glow")).toBe(true);+ for (const p of parts) expect(p.geometry.attributes.position.count).toBeGreaterThan(0);+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/holodeckPlan.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/holodeckPlan.tsnew file mode 100644index 0000000000..ab08c106af--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/holodeckPlan.ts@@ -0,0 +1,110 @@+/**+ * The holodeck: a black chamber with a gold grid, where the ship's ten retro+ * games stand as holographic cabinets.+ *+ * bow ── the chamber: ten emitters on an arc round the program spot+ * (every emitter faces the spot, its player stands in front)+ * ───── the holodeck arch (sliding doors)+ * stern ── the vestibule with the turbolift+ *+ * Nobody lives here (population "none"): the places are for the captain's+ * companion and for standing about. The plan depends on nothing but the game+ * list, so it is built once.+ */+import { ARCADE_GAMES } from "../../../arcade/arcadeGames";+import { arcPoints, COMMAND_GOLD, HOLO_CYAN, PlanBuilder, polygonBounds, yawTowards } from "../../plan/builder";+import type { DeckPlan, Vec2 } from "../../plan/types";+import { rect } from "../../plan/types";++/** Half the deck's width. */+export const HOLO_HALF_W = 15;+/** The chamber runs from the bow to the arch. */+export const CHAMBER_D = 30;+export const VESTIBULE_D = 8;+export const HOLO_END = CHAMBER_D + VESTIBULE_D;+/** The open spot the emitters face: where a program is "set". */+export const PROGRAM_SPOT: Vec2 = { x: 0, z: 17 };+/** The arc the emitters stand on. */+export const CABINET_RING = 10.5;+const CABINET_SPAN = (200 / 180) * Math.PI;+/** The emitter pedestal's footprint. */+export const EMITTER_W = 1.1;+export const EMITTER_D = 0.9;+/** The player stands this far in front of the emitter's front edge. */+export const PLAY_GAP = 0.9;+export const ARCH_W = 3.6;++/** The prop id of a game's emitter and the id of its station. */+export function emitterId(gameId: string): string { return `cabinet-${gameId}`; }+export function cabinetStationId(gameId: string): string { return `holo:${gameId}`; }++export function holodeckHull(): Vec2[] {+ const w = HOLO_HALF_W;+ return [+ { x: -9, z: 0 }, { x: 9, z: 0 }, { x: w, z: 6 },+ { x: w, z: HOLO_END - 2 }, { x: w - 2, z: HOLO_END },+ { x: -w + 2, z: HOLO_END }, { x: -w, z: HOLO_END - 2 }, { x: -w, z: 6 },+ ];+}++export function buildHolodeck(): DeckPlan {+ const b = new PlanBuilder("holodeck");+ const hull = holodeckHull();+ const bounds = polygonBounds(hull);+ const zEnd = HOLO_END;++ // ── hull ───────────────────────────────────────────────────────────+ hull.forEach((p, i) => {+ const q = hull[(i + 1) % hull.length];+ if (p.z === zEnd && q.z === zEnd) {+ // The turbolift sits in the middle of the stern wall.+ b.wallWithDoors(`hull-${i}`, "hull", p, q, [{ at: Math.abs(q.x - p.x) / 2, width: 3, slides: true, id: "lift-door" }], 0.5);+ } else {+ // A holodeck has no windows: the chamber is a closed black room.+ b.wall(`hull-${i}`, "hull", p, q, 0.5, false);+ }+ });++ // ── the chamber ────────────────────────────────────────────────────+ b.room({ id: "holodeck", kind: "holodeck", rect: rect(-HOLO_HALF_W, 0, HOLO_HALF_W, CHAMBER_D), floor: "holo", accent: COMMAND_GOLD,+ sign: { key: "ship.holodeck.room" }, signAt: { x: 0, z: CHAMBER_D + 0.24, yaw: 0 } });+ b.wallWithDoors("arch", "bulkhead", { x: -HOLO_HALF_W, z: CHAMBER_D }, { x: HOLO_HALF_W, z: CHAMBER_D },+ [{ at: HOLO_HALF_W, width: ARCH_W, slides: true, id: "holo-arch" }]);++ // Ten emitters on an arc round the program spot, the first game on the port end.+ const ring = arcPoints(PROGRAM_SPOT, CABINET_RING, ARCADE_GAMES.length, Math.PI, CABINET_SPAN);+ ARCADE_GAMES.forEach((game, i) => {+ // With mid = π the arc starts at its starboard end; reversed, the list reads port to starboard.+ const p = ring[ARCADE_GAMES.length - 1 - i];+ const yaw = yawTowards(p, PROGRAM_SPOT);+ const fx = Math.sin(yaw), fz = Math.cos(yaw);+ const id = emitterId(game.id);+ b.prop({ id, kind: "cabinet", x: p.x, z: p.z, yaw, w: EMITTER_W, d: EMITTER_D, h: 2.2, solid: true, ref: game.id, accent: game.look.accent });+ const reach = EMITTER_D / 2 + PLAY_GAP;+ const sx = p.x + fx * reach, sz = p.z + fz * reach;+ b.station({ id: cabinetStationId(game.id), kind: "holoCabinet", x: sx, z: sz, radius: 1.1, propId: id, ref: game.id });+ b.place({ id: `play-${game.id}`, kind: "stroll", x: sx, z: sz, yaw: yaw + Math.PI, pose: "stand", seatY: 0 });+ });+ // A few places to stand and watch: the program spot and the chamber's aft corners.+ b.place({ id: "program-spot", kind: "stroll", x: PROGRAM_SPOT.x, z: PROGRAM_SPOT.z + 1.2, yaw: Math.PI, pose: "stand", seatY: 0 });+ for (const [k, x] of [-9.5, 9.5].entries()) {+ b.place({ id: `chamber-stroll-${k}`, kind: "stroll", x, z: CHAMBER_D - 3.5, yaw: yawTowards({ x, z: CHAMBER_D - 3.5 }, PROGRAM_SPOT), pose: "stand", seatY: 0 });+ }++ // ── the vestibule ──────────────────────────────────────────────────+ b.room({ id: "vestibule", kind: "lift", rect: rect(-HOLO_HALF_W, CHAMBER_D, HOLO_HALF_W, zEnd), floor: "deck", accent: HOLO_CYAN,+ sign: { key: "ship.room.lift" }, signAt: { x: 0, z: zEnd - 0.35, yaw: Math.PI } });+ b.prop({ id: "lift-doors", kind: "liftDoors", x: 0, z: zEnd - 0.3, yaw: Math.PI, w: 3.4, d: 0.5, h: 2.7, solid: true });+ b.station({ id: "lift", kind: "lift", x: 0, z: zEnd - 1.4, radius: 1.6, propId: "lift-doors" });+ for (const [k, x] of [-8, 8].entries()) {+ b.prop({ id: `vestibule-bench-${k}`, kind: "bench", x, z: zEnd - 4.2, yaw: 0, w: 2.6, d: 0.55, h: 0.45, solid: true });+ b.prop({ id: `vestibule-plant-${k}`, kind: "plant", x: x + (k ? 2.2 : -2.2), z: zEnd - 4.2, yaw: 0, w: 0.8, d: 0.8, h: 1.4, solid: true });+ b.place({ id: `vestibule-stroll-${k}`, kind: "stroll", x, z: zEnd - 5.4, yaw: Math.PI, pose: "stand", seatY: 0 });+ }++ return b.build({+ bounds, hull,+ arrival: { x: 0, z: zEnd - 1.6 },+ lift: { x: 0, z: zEnd - 1.6, yaw: Math.PI },+ });+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/holodeckProps.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/holodeckProps.tsnew file mode 100644index 0000000000..8b857be850--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/holodeckProps.ts@@ -0,0 +1,67 @@+/**+ * The holodeck's fittings in the deck's merged batch: the emitter pedestal+ * under every game (prop kind "cabinet") and the holodeck arch. The hologram+ * itself is drawn live by the scene.+ */+import { arcadeGame } from "../../../arcade/arcadeGames";+import type { Frame } from "../../render/kit/geo";+import { SHIP } from "../../render/kit/palette";+import { PROP_BUILDERS, registerPropBuilders, type PropBuilder } from "../../render/deck/props";+import { WALL_H } from "../../render/deck/structure";+import { ARCH_W } from "./holodeckPlan";++/** Height of the emitter lens; the hologram hovers above it. */+export const LENS_Y = 0.25;++/** An emitter pedestal: an octagonal foot, a projector lens and four field nubs. Front (the player's side) is +z. */+const emitter: PropBuilder = (f, p) => {+ f.chamfer("structure", p.w, 0.08, p.d, 0.16, SHIP.charcoal, {});+ f.chamfer("structure", p.w - 0.18, 0.14, p.d - 0.16, 0.12, SHIP.graphite, { y: 0.08 });+ f.chamfer("metal", p.w - 0.26, 0.03, p.d - 0.24, 0.1, SHIP.steel, { y: 0.22 });+ // The lens: the light the hologram is made of.+ f.ring("metal", 0.25, 0.022, SHIP.steelLight, { y: LENS_Y }, Math.PI * 2, 32);+ f.cylinder("glow", 0.2, 0.2, 0.012, "#bfeaff", { y: LENS_Y - 0.006 }, 32);+ // Field nubs at the corners, each with a lit tip.+ for (const sx of [-1, 1]) for (const sz of [-1, 1]) {+ const x = sx * (p.w / 2 - 0.2), z = sz * (p.d / 2 - 0.17);+ f.cylinder("metal", 0.045, 0.055, 0.07, SHIP.steelLight, { x, z, y: 0.25 }, 12);+ f.cylinder("glow", 0.025, 0.025, 0.012, SHIP.cyan, { x, z, y: 0.32 }, 10);+ }+ // The player's edge: a gold inlay and the game's own colour as a ready light.+ f.box("metal", p.w - 0.5, 0.02, 0.03, SHIP.gold, { y: 0.2, z: (p.d - 0.16) / 2 + 0.005 });+ f.box("glow", 0.14, 0.022, 0.02, p.accent ?? SHIP.cyan, { y: 0.12, z: (p.d - 0.16) / 2 + 0.01 });+};++// "cabinet" is a shared prop kind; a pedestal is drawn only for a holodeck game, anything else keeps the builder it had.+const previous = PROP_BUILDERS.cabinet;+registerPropBuilders({+ cabinet: (f, p) => {+ if (p.ref && arcadeGame(p.ref)) emitter(f, p);+ else previous?.(f, p);+ },+});++/**+ * The holodeck arch round the chamber's doors, in the arch's own frame+ * (centred on the doorway, +z towards the vestibule): two pylons that rise+ * above the wall line, a lintel with a lit program lens, gold on the+ * vestibule face where the captain walks in.+ */+export function buildArch(f: Frame): void {+ const half = ARCH_W / 2;+ const top = WALL_H + 0.7;+ for (const s of [-1, 1]) {+ const x = s * (half + 0.42);+ f.chamfer("structure", 0.84, top, 0.9, 0.14, SHIP.graphite, { x });+ f.chamfer("structure", 0.96, 0.12, 1.0, 0.16, SHIP.charcoal, { x });+ // Gold edges on both faces, a cyan field line on the inner face.+ for (const face of [-1, 1]) f.box("metal", 0.05, top - 0.3, 0.03, SHIP.gold, { x: x - s * 0.36, y: 0.15, z: face * 0.46 });+ f.box("glow", 0.02, top - 0.6, 0.6, SHIP.cyan, { x: x - s * 0.43, y: 0.3 });+ }+ f.chamfer("structure", ARCH_W + 1.9, 0.5, 0.96, 0.18, SHIP.graphite, { y: top - 0.5 });+ f.box("metal", ARCH_W + 1.6, 0.04, 0.03, SHIP.gold, { y: top - 0.42, z: 0.49 });+ f.box("metal", ARCH_W + 1.6, 0.04, 0.03, SHIP.gold, { y: top - 0.42, z: -0.49 });+ // The program lens over the doorway, facing the vestibule.+ f.cylinder("metal", 0.22, 0.22, 0.06, SHIP.steelLight, { y: top - 0.25, z: 0.48, pitch: Math.PI / 2 }, 24);+ f.cylinder("glow", 0.15, 0.15, 0.02, SHIP.gold, { y: top - 0.25, z: 0.52, pitch: Math.PI / 2 }, 24);+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/index.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/index.tsnew file mode 100644index 0000000000..bb99996d82--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/holodeck/index.ts@@ -0,0 +1,28 @@+/**+ * Deck 4, the holodeck: the ship's ten retro games as holographic cabinets.+ * Using a cabinet opens its program in the deck's panel.+ */+import { arcadeGame } from "../../../arcade/arcadeGames";+import { registerDeck } from "../registry";+import { buildHolodeck } from "./holodeckPlan";+import { HolodeckPanel } from "./HolodeckPanel";+import { HolodeckScene } from "./HolodeckScene";+import "./holodeckProps";++// The plan depends on nothing but the game list: build it once.+let plan: ReturnType<typeof buildHolodeck> | null = null;++registerDeck({+ id: "holodeck",+ population: "none",+ build: () => (plan ??= buildHolodeck()),+ Scene: HolodeckScene,+ useStation: (station, _plan, actions) => {+ if (station.kind !== "holoCabinet") return false;+ actions.openPanel(station.id);+ return true;+ },+ Panel: HolodeckPanel,+ // The prompt names the game: "E · Play · Neon Snake".+ stationName: (station) => (station.kind === "holoCabinet" && station.ref ? arcadeGame(station.ref)?.title : undefined),+});diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/honors/HonorsScene.tsx b/dodaios/ui/web/frontend/src/components/society/starship/decks/honors/HonorsScene.tsxnew file mode 100644index 0000000000..6af6f4b185--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/honors/HonorsScene.tsx@@ -0,0 +1,312 @@+/**+ * The Hall of Honour on screen, beyond the shared kit: the runner, the rank+ * wall's sixteen plaques (enlisted and warrant at the foot, officers above,+ * the flag ranks at the top; ranks held lit, the captain's own framed in+ * gold, ranks ahead dim) under a slow sweep of light, and the display cases,+ * whose insignia are lit once their rank is held. Reduced motion holds it+ * all still.+ */+import { useFrame } from "@react-three/fiber";+import { useEffect, useMemo } from "react";+import {+ AdditiveBlending, BoxGeometry, CanvasTexture, Color, CylinderGeometry, DoubleSide, Group, Matrix4, Mesh, MeshBasicMaterial,+ PlaneGeometry, RepeatWrapping, SRGBColorSpace, BufferAttribute, type BufferGeometry,+} from "three";+import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";+import { useProgression } from "../../../progression/progressionStore";+import { PERSON_SUBJECT } from "../../../progression/progressionApi";+import { RANKS, rankFor, type Rank } from "../../levels/ranks";+import type { DeckSceneProps } from "../registry";+import type { DeckPlan, Prop } from "../../plan/types";+import { GeoBatch, type CutLine } from "../../render/kit/geo";+import { castsShadow, finishMaterial, receivesShadow } from "../../render/kit/materials";+import { withCutaway } from "../../render/kit/cutaway";+import { SHIP } from "../../render/kit/palette";+import { wallCutFor } from "../../render/deck/props";+import { DAIS, HALL_D, RUNNER_W } from "./honorsPlan";+import { buildRunner, HALL, PLAQUE_FACE, VITRINE } from "./honorsProps";+import { drawInsignia, GOLD, GOLD_DEEP, SILVER_DEEP } from "./insignia";++export function HonorsScene({ plan, reduced, actions }: DeckSceneProps) {+ const level = useProgression((s) => s.subjects[PERSON_SUBJECT]?.level ?? 1);+ const t = actions.t;+ // One string for everything the plaques say, so a redraw happens only when a word changes.+ const words = [t("ship.honors.wall_title"), t("ship.level"), ...RANKS.map((r) => t(`ship.rank.${r.id}`))].join("\u0001");+ return (+ <>+ <HallFittings plan={plan} />+ <RankWallFace plan={plan} level={level} words={words} reduced={reduced} />+ <CaseLights plan={plan} level={level} reduced={reduced} />+ </>+ );+}++function HallFittings({ plan }: { plan: DeckPlan }) {+ const meshes = useMemo(() => {+ const batch = new GeoBatch();+ buildRunner(batch.frame(new Matrix4()), DAIS.z + DAIS.d / 2 + 0.05, HALL_D + 0.3, RUNNER_W);+ return batch.merged().map(({ finish, geometry }) => {+ const mesh = new Mesh(geometry, finishMaterial(finish));+ mesh.castShadow = castsShadow(finish);+ mesh.receiveShadow = receivesShadow(finish);+ mesh.raycast = () => undefined;+ return mesh;+ });+ }, [plan]);+ useEffect(() => () => { for (const m of meshes) m.geometry.dispose(); }, [meshes]);+ return <>{meshes.map((m, i) => <primitive key={i} object={m} />)}</>;+}++// ── the rank wall ─────────────────────────────────────────────────────++/** A plaque's place on the wall's face, as fractions of the face (u across, v down). */+export interface PlaqueCell { rank: Rank; u0: number; v0: number; u1: number; v1: number }++const TITLE_V = 0.13;+const COLUMNS = 6;++/**+ * The ladder as a pyramid that climbs: enlisted and warrant ranks on the+ * bottom row, the officers above them, the flag ranks on top, each row left+ * to right in order.+ */+export function plaqueLayout(ranks: readonly Rank[] = RANKS): PlaqueCell[] {+ const rows: Rank[][] = [+ ranks.filter((r) => r.tier === "flag"),+ ranks.filter((r) => r.tier === "officer"),+ ranks.filter((r) => r.tier === "enlisted" || r.tier === "warrant"),+ ];+ const rowH = (1 - TITLE_V) / rows.length;+ const cells: PlaqueCell[] = [];+ rows.forEach((row, r) => {+ const cols = Math.max(COLUMNS, row.length);+ const offset = (cols - row.length) / 2;+ row.forEach((rank, c) => {+ const u0 = (offset + c) / cols, v0 = TITLE_V + r * rowH;+ cells.push({ rank, u0: u0 + 0.006, v0: v0 + 0.02, u1: u0 + 1 / cols - 0.006, v1: v0 + rowH - 0.02 });+ });+ });+ return cells;+}++type PlaqueState = "held" | "current" | "ahead";++function roundRect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number): void {+ ctx.beginPath();+ ctx.moveTo(x + r, y); ctx.arcTo(x + w, y, x + w, y + h, r); ctx.arcTo(x + w, y + h, x, y + h, r);+ ctx.arcTo(x, y + h, x, y, r); ctx.arcTo(x, y, x + w, y, r); ctx.closePath();+}++const FACE_PX = { w: 2048, h: 564 } as const;++function drawWall(ctx: CanvasRenderingContext2D, cells: readonly PlaqueCell[], level: number, words: string): void {+ const [title, levelFmt, ...names] = words.split("\u0001");+ const { w: W, h: H } = FACE_PX;+ ctx.clearRect(0, 0, W, H);+ ctx.fillStyle = HALL.stone; ctx.fillRect(0, 0, W, H);+ // The title, engraved in gold between two rules.+ ctx.textAlign = "center"; ctx.textBaseline = "middle";+ ctx.font = "600 40px 'Space Grotesk', 'Inter Variable', sans-serif";+ ctx.fillStyle = GOLD;+ const label = (title ?? "").toUpperCase();+ ctx.fillText(label, W / 2, (TITLE_V * H) / 2 + 2);+ const half = Math.min(W / 2 - 40, ctx.measureText(label).width / 2 + 40);+ ctx.fillStyle = GOLD_DEEP;+ ctx.fillRect(60, (TITLE_V * H) / 2, W / 2 - half - 60, 2);+ ctx.fillRect(W / 2 + half, (TITLE_V * H) / 2, W / 2 - half - 60, 2);+ const current = rankFor(level).id;+ for (const cell of cells) {+ const x = cell.u0 * W, y = cell.v0 * H, w = (cell.u1 - cell.u0) * W, h = (cell.v1 - cell.v0) * H;+ const state: PlaqueState = cell.rank.id === current ? "current" : level >= cell.rank.level ? "held" : "ahead";+ const metal = cell.rank.tier === "enlisted" ? SILVER_DEEP : GOLD_DEEP;+ const bg = ctx.createLinearGradient(0, y, 0, y + h);+ if (state === "current") { bg.addColorStop(0, "#33280f"); bg.addColorStop(1, "#191309"); }+ else if (state === "held") { bg.addColorStop(0, "#1c222c"); bg.addColorStop(1, "#11151b"); }+ else { bg.addColorStop(0, "#0e1014"); bg.addColorStop(1, "#0a0b0e"); }+ roundRect(ctx, x, y, w, h, 12);+ ctx.fillStyle = bg; ctx.fill();+ ctx.lineWidth = state === "current" ? 5 : 2.5;+ ctx.strokeStyle = state === "current" ? GOLD : state === "held" ? metal : "#23272e";+ ctx.stroke();+ drawInsignia(ctx, cell.rank, x + w / 2, y + h * 0.33, h * 0.62, state === "ahead");+ const index = RANKS.findIndex((r) => r.id === cell.rank.id);+ ctx.textAlign = "center"; ctx.textBaseline = "middle";+ ctx.font = "600 25px 'Space Grotesk', 'Inter Variable', sans-serif";+ ctx.fillStyle = state === "current" ? GOLD : state === "held" ? "#e8eef6" : "#4b5159";+ ctx.fillText(names[index] ?? cell.rank.id, x + w / 2, y + h * 0.7, w - 20);+ ctx.font = "500 18px 'Inter Variable', sans-serif";+ ctx.fillStyle = state === "ahead" ? "#363b43" : "#8f9db0";+ ctx.fillText((levelFmt ?? "{n}").replace("{n}", String(cell.rank.level)), x + w / 2, y + h * 0.87, w - 20);+ }+}++/** Give a world-space geometry the cut-away line of the wall it hangs on. */+function cutWith(geometry: BufferGeometry, cut: CutLine | undefined): BufferGeometry {+ const n = geometry.attributes.position.count;+ const ab = new Float32Array(n * 4), kind = new Float32Array(n);+ if (cut) for (let i = 0; i < n; i += 1) { ab.set([cut.ax, cut.az, cut.bx, cut.bz], i * 4); kind[i] = cut.kind; }+ geometry.setAttribute("cutAB", new BufferAttribute(ab, 4));+ geometry.setAttribute("cutKind", new BufferAttribute(kind, 1));+ return geometry;+}++/** The face of the rank wall in world space: centre, size and the matrix of its plane. */+function wallFace(wall: Prop, lift: number) {+ const w = wall.w - 2 * PLAQUE_FACE.inset, h = PLAQUE_FACE.y1 - PLAQUE_FACE.y0;+ const at = new Matrix4().makeRotationY(wall.yaw).setPosition(wall.x, 0, wall.z)+ .multiply(new Matrix4().makeTranslation(0, (PLAQUE_FACE.y0 + PLAQUE_FACE.y1) / 2, wall.d / 2 + PLAQUE_FACE.z + lift));+ return { w, h, at };+}++function bandTexture(): CanvasTexture {+ const c = document.createElement("canvas");+ c.width = 512; c.height = 128;+ const ctx = c.getContext("2d") as CanvasRenderingContext2D;+ // A soft, slanted band of light in the middle of the strip.+ for (let y = 0; y < 128; y += 1) {+ const cx = 256 + (64 - y) * 0.5;+ const g = ctx.createLinearGradient(cx - 46, 0, cx + 46, 0);+ g.addColorStop(0, "rgba(255,236,200,0)"); g.addColorStop(0.5, "rgba(255,236,200,1)"); g.addColorStop(1, "rgba(255,236,200,0)");+ ctx.fillStyle = g; ctx.fillRect(cx - 46, y, 92, 1);+ }+ const t = new CanvasTexture(c);+ t.wrapS = RepeatWrapping;+ t.colorSpace = SRGBColorSpace;+ return t;+}++function RankWallFace({ plan, level, words, reduced }: { plan: DeckPlan; level: number; words: string; reduced: boolean }) {+ const wall = plan.props.find((p) => p.kind === "rankWall");+ const cells = useMemo(() => plaqueLayout(), []);+ const parts = useMemo(() => {+ if (!wall) return null;+ const cut = wallCutFor(plan, wall);+ const face = wallFace(wall, 0);+ const canvas = document.createElement("canvas");+ canvas.width = FACE_PX.w; canvas.height = FACE_PX.h;+ const texture = new CanvasTexture(canvas);+ texture.colorSpace = SRGBColorSpace;+ texture.anisotropy = 8;+ const plaques = new Mesh(cutWith(new PlaneGeometry(face.w, face.h).applyMatrix4(face.at), cut),+ withCutaway(new MeshBasicMaterial({ map: texture, toneMapped: false, color: new Color(1.12, 1.12, 1.12) }), 0, 0.6));+ const sweepMap = bandTexture();+ const sweep = new Mesh(cutWith(new PlaneGeometry(face.w, face.h).applyMatrix4(wallFace(wall, 0.004).at), cut),+ withCutaway(new MeshBasicMaterial({ map: sweepMap, transparent: true, opacity: 0.16, blending: AdditiveBlending, depthWrite: false, toneMapped: false }), 0, 0.6));+ // The frame round the captain's plaque: four bars, rebuilt when the rank changes.+ const frameMat = withCutaway(new MeshBasicMaterial({ color: new Color(SHIP.gold).multiplyScalar(2.4), toneMapped: false }), 0, 0.6);+ const frame = new Mesh<BufferGeometry, MeshBasicMaterial>(new BoxGeometry(0.01, 0.01, 0.01), frameMat);+ for (const m of [plaques, sweep, frame]) m.raycast = () => undefined;+ sweep.renderOrder = 2;+ return { canvas, texture, plaques, sweep, sweepMap, frame, frameMat, cut, face };+ }, [plan, wall]);++ useEffect(() => {+ if (!parts) return;+ const ctx = parts.canvas.getContext("2d");+ if (ctx) drawWall(ctx, cells, level, words);+ parts.texture.needsUpdate = true;+ // Frame the current plaque.+ const cell = cells.find((c) => c.rank.id === rankFor(level).id);+ if (!cell) return;+ const { w, h, at } = parts.face;+ const x0 = -w / 2 + cell.u0 * w, x1 = -w / 2 + cell.u1 * w, y0 = h / 2 - cell.v1 * h, y1 = h / 2 - cell.v0 * h;+ const bar = 0.025, pad = 0.02;+ const bars = [+ [x0 - pad, y1 + pad, x1 + pad, y1 + pad - bar], [x0 - pad, y0 - pad + bar, x1 + pad, y0 - pad],+ [x0 - pad, y1 + pad, x0 - pad + bar, y0 - pad], [x1 + pad - bar, y1 + pad, x1 + pad, y0 - pad],+ ].map(([ax, ay, bx, by]) => new BoxGeometry(Math.abs(bx - ax), Math.abs(by - ay), 0.02).translate((ax + bx) / 2, (ay + by) / 2, 0.012));+ const merged = mergeGeometries(bars, false) as BufferGeometry;+ for (const g of bars) g.dispose();+ merged.applyMatrix4(at);+ parts.frame.geometry.dispose();+ parts.frame.geometry = cutWith(merged, parts.cut);+ }, [parts, cells, level, words]);++ useEffect(() => () => {+ if (!parts) return;+ for (const m of [parts.plaques, parts.sweep, parts.frame]) { m.geometry.dispose(); (m.material as MeshBasicMaterial).dispose(); }+ parts.texture.dispose(); parts.sweepMap.dispose();+ }, [parts]);++ const base = useMemo(() => new Color(SHIP.gold), []);+ useFrame(({ clock }) => {+ if (!parts) return;+ const t = clock.elapsedTime;+ parts.sweep.visible = !reduced;+ parts.sweepMap.offset.x = reduced ? 0 : -((t / 14) % 1);+ parts.frameMat.color.copy(base).multiplyScalar(reduced ? 2.4 : 2.1 + Math.sin(t * 1.6) * 0.4);+ });+ if (!parts) return null;+ return <><primitive object={parts.plaques} /><primitive object={parts.sweep} /><primitive object={parts.frame} /></>;+}++// ── the display cases ─────────────────────────────────────────────────++function insigniaTexture(rank: Rank, dim: boolean): CanvasTexture {+ const c = document.createElement("canvas");+ c.width = 256; c.height = 256;+ const ctx = c.getContext("2d") as CanvasRenderingContext2D;+ // A dark enamel medallion with the mark on it.+ ctx.beginPath(); ctx.arc(128, 128, 112, 0, Math.PI * 2);+ ctx.fillStyle = dim ? "rgba(14,16,20,0.95)" : "rgba(24,28,36,0.96)"; ctx.fill();+ ctx.lineWidth = 7; ctx.strokeStyle = dim ? "#3a3d43" : GOLD; ctx.stroke();+ drawInsignia(ctx, rank, 128, 128, 170, dim);+ const t = new CanvasTexture(c);+ t.colorSpace = SRGBColorSpace;+ return t;+}++interface CaseView { rank: Rank; group: Group; medal: Mesh; lamp: MeshBasicMaterial; beam: Mesh; lit: CanvasTexture; dim: CanvasTexture; medalMat: MeshBasicMaterial; seed: number }++function CaseLights({ plan, level, reduced }: { plan: DeckPlan; level: number; reduced: boolean }) {+ const shared = useMemo(() => ({+ medal: new PlaneGeometry(0.36, 0.36),+ lamp: new BoxGeometry(0.78, 0.012, 0.58),+ beam: new CylinderGeometry(0.28, 0.36, VITRINE.y1 - VITRINE.y0 - 0.04, 20, 1, true),+ beamMat: new MeshBasicMaterial({ color: new Color(SHIP.lightWarm).multiplyScalar(0.22), transparent: true, blending: AdditiveBlending, depthWrite: false, side: DoubleSide, toneMapped: false }),+ }), []);+ const cases = useMemo(() => plan.props.filter((p) => p.kind === "honorCase" && p.ref).map((p, i): CaseView | null => {+ const rank = RANKS.find((r) => r.id === p.ref);+ if (!rank) return null;+ const group = new Group();+ group.position.set(p.x, 0, p.z);+ group.rotation.y = p.yaw;+ const lit = insigniaTexture(rank, false), dim = insigniaTexture(rank, true);+ const medalMat = new MeshBasicMaterial({ map: dim, transparent: true, alphaTest: 0.05, side: DoubleSide, toneMapped: false });+ const medal = new Mesh(shared.medal, medalMat);+ medal.position.y = (VITRINE.y0 + 0.08 + VITRINE.y1) / 2;+ const lamp = new MeshBasicMaterial({ color: new Color("#2a2d33"), toneMapped: false });+ const lampMesh = new Mesh(shared.lamp, lamp);+ lampMesh.position.y = VITRINE.y1 - 0.012;+ const beam = new Mesh(shared.beam, shared.beamMat);+ beam.position.y = (VITRINE.y0 + VITRINE.y1) / 2;+ beam.renderOrder = 3;+ for (const m of [medal, lampMesh, beam]) { m.raycast = () => undefined; group.add(m); }+ return { rank, group, medal, lamp, beam, lit, dim, medalMat, seed: i * 0.9 };+ }).filter((c): c is CaseView => c !== null), [plan, shared]);++ useEffect(() => {+ const current = rankFor(level).id;+ for (const c of cases) {+ const held = level >= c.rank.level;+ c.medalMat.map = held ? c.lit : c.dim;+ c.medalMat.color.setScalar(held ? 1.25 : 0.7);+ c.medalMat.needsUpdate = true;+ c.lamp.color.set(held ? (c.rank.id === current ? SHIP.gold : SHIP.lightWarm) : "#24272c").multiplyScalar(held ? 2.3 : 1);+ c.beam.visible = held;+ }+ }, [cases, level]);+ useEffect(() => () => {+ for (const c of cases) { c.lit.dispose(); c.dim.dispose(); c.medalMat.dispose(); c.lamp.dispose(); }+ }, [cases]);+ useEffect(() => () => { shared.medal.dispose(); shared.lamp.dispose(); shared.beam.dispose(); shared.beamMat.dispose(); }, [shared]);++ useFrame(({ clock }) => {+ const t = clock.elapsedTime;+ for (const c of cases) {+ const held = level >= c.rank.level;+ c.medal.rotation.y = reduced || !held ? 0 : Math.sin(t * 0.5 + c.seed) * 0.5;+ }+ });+ return <>{cases.map((c) => <primitive key={c.rank.id} object={c.group} />)}</>;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/honors/honorsPlan.test.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/honors/honorsPlan.test.tsnew file mode 100644index 0000000000..984b8464b8--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/honors/honorsPlan.test.ts@@ -0,0 +1,73 @@+import { describe, expect, it } from "vitest";+import { RANKS } from "../../levels/ranks";+import { insidePolygon } from "../../plan/builder";+import { buildNavGrid, findPath, isFree } from "../../nav/shipNav";+import { Matrix4 } from "three";+import { GeoBatch } from "../../render/kit/geo";+import { buildProps } from "../../render/deck/props";+import { buildHonorsDeck, caseId, caseRanks } from "./honorsPlan";+import { buildRunner } from "./honorsProps";+import { insigniaSpec } from "./insignia";++describe("hall of honour plan", () => {+ const plan = buildHonorsDeck();++ it("keeps one display case for every officer and flag rank", () => {+ const wanted = RANKS.filter((r) => r.tier === "officer" || r.tier === "flag").map((r) => r.id);+ expect(caseRanks().map((r) => r.id)).toEqual(wanted);+ const cases = plan.stations.filter((s) => s.kind === "honorCase");+ expect(cases.map((s) => s.ref)).toEqual(wanted);+ for (const id of wanted) {+ const prop = plan.props.find((p) => p.id === caseId(id));+ expect(prop?.kind).toBe("honorCase");+ expect(prop?.ref).toBe(id);+ }+ });++ it("puts the rank wall at the bow with the dais before it, and higher ranks nearer the wall", () => {+ const wall = plan.props.find((p) => p.kind === "rankWall")!;+ const dais = plan.props.find((p) => p.kind === "dais")!;+ expect(wall.z).toBeLessThan(dais.z);+ expect(plan.stations.find((s) => s.kind === "rankWall")?.propId).toBe(wall.id);+ const zOf = (id: string) => plan.props.find((p) => p.id === caseId(id))!.z;+ expect(zOf("admiral")).toBeLessThan(zOf("ensign"));+ });++ it("has the turbolift centred on the stern wall", () => {+ expect(plan.stations.find((s) => s.kind === "lift")?.x).toBe(0);+ expect(plan.props.find((p) => p.kind === "liftDoors")?.z).toBeCloseTo(plan.bounds.z1 - 0.3, 5);+ expect(plan.lift.x).toBe(0);+ });++ it("reaches every station and place from the turbolift", () => {+ const grid = buildNavGrid(plan);+ expect(isFree(grid, plan.lift)).toBe(true);+ const misses = [...plan.stations, ...plan.places].filter((t) => !findPath(grid, plan.lift, t)).map((t) => t.id);+ expect(misses).toEqual([]);+ });++ it("keeps ids unique and everything inside the hull", () => {+ const ids = [...plan.props.map((x) => `prop:${x.id}`), ...plan.places.map((x) => `place:${x.id}`), ...plan.stations.map((x) => `station:${x.id}`)];+ expect(new Set(ids).size).toBe(ids.length);+ for (const p of [...plan.props, ...plan.places, ...plan.stations]) expect(insidePolygon(plan.hull, p)).toBe(true);+ });++ it("is a ceremonial hall nobody is seated in", () => {+ expect(plan.rooms.find((r) => r.kind === "hall")?.floor).toBe("honor");+ expect(plan.divisions).toEqual([]);+ });++ it("builds the wall, the dais, the cases and the runner into the deck's batch", () => {+ const batch = new GeoBatch();+ buildProps(plan, batch);+ buildRunner(batch.frame(new Matrix4()), 5, 38, 2.2);+ const finishes = batch.merged().map((p) => p.finish);+ expect(finishes).toContain("glass");+ expect(finishes).toContain("fabric");+ });++ it("gives every rank a distinct insignia", () => {+ const marks = RANKS.map((r) => JSON.stringify(insigniaSpec(r)));+ expect(new Set(marks).size).toBe(RANKS.length);+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/honors/honorsPlan.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/honors/honorsPlan.tsnew file mode 100644index 0000000000..32fd104ba1--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/honors/honorsPlan.ts@@ -0,0 +1,125 @@+/**+ * The Hall of Honour: a long ceremonial hall where the captain's ranks are+ * kept.+ *+ * bow ── the rank wall, a dais in front of it+ * display cases down both sides (the officer and flag+ * ranks, higher ranks nearer the wall), benches between+ * them, a runner up the middle+ * ───── an open arch+ * stern ── the lobby with the turbolift+ *+ * Nobody lives here (population "none"). The plan depends on nothing but the+ * rank ladder, so it is built once.+ */+import { RANKS, type Rank } from "../../levels/ranks";+import { COMMAND_GOLD, PlanBuilder, polygonBounds } from "../../plan/builder";+import type { DeckPlan, Vec2 } from "../../plan/types";+import { rect } from "../../plan/types";++export const HALL_HALF_W = 9;+export const HALL_D = 38;+export const LOBBY_D = 8;+export const HALL_END = HALL_D + LOBBY_D;+export const HALL_ARCH_W = 5;+/** The rank wall stands this far from the bow. */+export const RANK_WALL = { z: 1.0, w: 10.4, d: 0.6, h: 3.4 } as const;+export const DAIS = { z: 3.4, w: 7, d: 2.2, h: 0.32 } as const;+/** The runner: from the dais steps to the lift. */+export const RUNNER_W = 2.2;+/** The display cases stand this far off the centre line. */+export const CASE_X = 7.0;+export const CASE = { w: 1.0, d: 0.8, h: 1.75 } as const;+/** The case pairs, stern first; the next rank up stands across the hall, the pair after one step nearer the wall. */+export const CASE_ROWS = [31, 26, 21, 16, 11] as const;+const BENCH_ROWS = [28.5, 23.5, 18.5, 13.5] as const;++/** The ranks that have a case: the officer and flag tiers, lowest first. */+export function caseRanks(): Rank[] {+ return RANKS.filter((r) => r.tier === "officer" || r.tier === "flag");+}++export function caseId(rankId: string): string { return `case-${rankId}`; }++export function hallHull(): Vec2[] {+ const w = HALL_HALF_W;+ return [+ { x: -6, z: 0 }, { x: 6, z: 0 }, { x: w, z: 4 },+ { x: w, z: HALL_END - 2 }, { x: w - 2, z: HALL_END },+ { x: -w + 2, z: HALL_END }, { x: -w, z: HALL_END - 2 }, { x: -w, z: 4 },+ ];+}++export function buildHonorsDeck(): DeckPlan {+ const b = new PlanBuilder("honors");+ const hull = hallHull();+ const bounds = polygonBounds(hull);+ const zEnd = HALL_END;++ // ── hull ───────────────────────────────────────────────────────────+ hull.forEach((p, i) => {+ const q = hull[(i + 1) % hull.length];+ if (p.z === zEnd && q.z === zEnd) {+ b.wallWithDoors(`hull-${i}`, "hull", p, q, [{ at: Math.abs(q.x - p.x) / 2, width: 3, slides: true, id: "lift-door" }], 0.5);+ } else {+ // Tall windows down the sides; the bow is the rank wall's back.+ b.wall(`hull-${i}`, "hull", p, q, 0.5, !(p.z === 0 && q.z === 0));+ }+ });++ // ── the hall ───────────────────────────────────────────────────────+ b.room({ id: "hall", kind: "hall", rect: rect(-HALL_HALF_W, 0, HALL_HALF_W, HALL_D), floor: "honor", accent: COMMAND_GOLD,+ sign: { key: "ship.honors.room" }, signAt: { x: 0, z: HALL_D + 0.24, yaw: 0 } });+ b.wallWithDoors("hall-arch", "bulkhead", { x: -HALL_HALF_W, z: HALL_D }, { x: HALL_HALF_W, z: HALL_D },+ [{ at: HALL_HALF_W, width: HALL_ARCH_W, slides: false, id: "hall-arch" }]);++ b.prop({ id: "rank-wall", kind: "rankWall", x: 0, z: RANK_WALL.z, yaw: 0, w: RANK_WALL.w, d: RANK_WALL.d, h: RANK_WALL.h, solid: true });+ b.prop({ id: "dais", kind: "dais", x: 0, z: DAIS.z, yaw: 0, w: DAIS.w, d: DAIS.d, h: DAIS.h, solid: true });+ b.station({ id: "rank-wall", kind: "rankWall", x: 0, z: DAIS.z + DAIS.d / 2 + 0.9, radius: 1.8, propId: "rank-wall" });+ b.place({ id: "dais-front", kind: "stroll", x: -2.2, z: DAIS.z + DAIS.d / 2 + 1.1, yaw: Math.PI, pose: "stand", seatY: 0 });++ // Display cases, alternating sides up the hall: port takes the first of each pair.+ caseRanks().forEach((rank, i) => {+ const row = Math.floor(i / 2), west = i % 2 === 0;+ const z = CASE_ROWS[Math.min(row, CASE_ROWS.length - 1)];+ const x = west ? -CASE_X : CASE_X;+ const yaw = west ? Math.PI / 2 : -Math.PI / 2;+ const id = caseId(rank.id);+ b.prop({ id, kind: "honorCase", x, z, yaw, w: CASE.w, d: CASE.d, h: CASE.h, solid: true, ref: rank.id, accent: COMMAND_GOLD });+ const sx = x + Math.sin(yaw) * (CASE.d / 2 + 0.9);+ b.station({ id, kind: "honorCase", x: sx, z, radius: 1.1, propId: id, ref: rank.id });+ });++ // Benches between the cases, facing the runner, and pillars against the windows.+ BENCH_ROWS.forEach((z, k) => {+ for (const west of [true, false]) {+ const side = west ? -1 : 1;+ const yaw = west ? Math.PI / 2 : -Math.PI / 2;+ b.prop({ id: `bench-${k}-${west ? "w" : "e"}`, kind: "bench", x: side * 3.4, z, yaw, w: 2.4, d: 0.5, h: 0.45, solid: true });+ for (const [s, dz] of [-0.6, 0.6].entries()) {+ b.place({ id: `bench-${k}-${west ? "w" : "e"}-${s}`, kind: "lounge", x: side * 3.4 - side * 0.05, z: z + dz, yaw, pose: "sit", seatY: 0.45 });+ }+ b.prop({ id: `pillar-${k}-${west ? "w" : "e"}`, kind: "pillar", x: side * 8.25, z, yaw, w: 0.7, d: 0.7, h: 2.6, solid: true });+ }+ });+ for (const [k, z] of [33.5, 8.2].entries()) {+ b.place({ id: `hall-stroll-${k}`, kind: "stroll", x: k ? 2.4 : -2.4, z, yaw: Math.PI, pose: "stand", seatY: 0 });+ }++ // ── the lobby ──────────────────────────────────────────────────────+ b.room({ id: "lobby", kind: "lift", rect: rect(-HALL_HALF_W, HALL_D, HALL_HALF_W, zEnd), floor: "deck", accent: COMMAND_GOLD,+ sign: { key: "ship.room.lift" }, signAt: { x: 0, z: zEnd - 0.35, yaw: Math.PI } });+ b.prop({ id: "lift-doors", kind: "liftDoors", x: 0, z: zEnd - 0.3, yaw: Math.PI, w: 3.4, d: 0.5, h: 2.7, solid: true });+ b.station({ id: "lift", kind: "lift", x: 0, z: zEnd - 1.4, radius: 1.6, propId: "lift-doors" });+ for (const [k, x] of [-5.4, 5.4].entries()) {+ b.prop({ id: `lobby-plant-${k}`, kind: "plant", x, z: HALL_D + 1.4, yaw: 0, w: 0.8, d: 0.8, h: 1.4, solid: true });+ b.prop({ id: `lobby-bench-${k}`, kind: "bench", x, z: zEnd - 3.6, yaw: 0, w: 2.4, d: 0.5, h: 0.45, solid: true });+ b.place({ id: `lobby-stroll-${k}`, kind: "stroll", x: x * 0.6, z: zEnd - 4.8, yaw: Math.PI, pose: "stand", seatY: 0 });+ }++ return b.build({+ bounds, hull,+ arrival: { x: 0, z: zEnd - 1.6 },+ lift: { x: 0, z: zEnd - 1.6, yaw: Math.PI },+ });+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/honors/honorsProps.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/honors/honorsProps.tsnew file mode 100644index 0000000000..2c5074a92f--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/honors/honorsProps.ts@@ -0,0 +1,90 @@+/**+ * The Hall of Honour's fittings in the deck's merged batch: the rank wall's+ * frame (its plaques are drawn live by the scene), the dais before it and+ * the display cases (their insignia and lights are live too), plus the+ * runner up the middle of the hall.+ */+import { annulus, type Frame } from "../../render/kit/geo";+import { SHIP } from "../../render/kit/palette";+import { registerPropBuilders, type PropBuilder } from "../../render/deck/props";++/** Dark polished stone and bronze: the hall's own materials, in the ship's palette. */+export const HALL = {+ stone: "#1b1e24",+ stoneLight: "#2b2f37",+ bronze: "#6b5532",+ runner: "#252b3a",+} as const;++/** Where the plaques sit on the rank wall's face, in the wall's own frame. */+export const PLAQUE_FACE = { y0: 0.42, y1: 3.12, inset: 0.3, z: 0.012 } as const;+/** The display case's glass, in the case's own frame. */+export const VITRINE = { y0: 0.95, y1: 1.63 } as const;++const rankWall: PropBuilder = (f, p) => {+ const { w, h, d } = p;+ f.chamfer("structure", w + 0.3, 0.3, d + 0.24, 0.12, SHIP.charcoal, {});+ f.box("structure", w, h - 0.48, d, HALL.stone, { y: 0.3 });+ f.chamfer("structure", w + 0.44, 0.18, d + 0.3, 0.12, HALL.stoneLight, { y: h - 0.18 });+ // Bronze pilasters at both ends, a gold frame round the plaque field.+ for (const s of [-1, 1]) f.chamfer("metal", 0.32, h - 0.3, d + 0.12, 0.06, HALL.bronze, { x: s * (w / 2 - 0.1), y: 0.3 });+ const fz = d / 2 + 0.01;+ const fw = w - 2 * PLAQUE_FACE.inset + 0.12;+ f.box("metal", fw, 0.04, 0.03, SHIP.gold, { y: PLAQUE_FACE.y0 - 0.08, z: fz });+ f.box("metal", fw, 0.04, 0.03, SHIP.gold, { y: PLAQUE_FACE.y1 + 0.04, z: fz });+ for (const s of [-1, 1]) f.box("metal", 0.04, PLAQUE_FACE.y1 - PLAQUE_FACE.y0 + 0.16, 0.03, SHIP.gold, { x: s * (fw / 2), y: PLAQUE_FACE.y0 - 0.08, z: fz });+ // Warm uplights in the plinth wash the plaques from below.+ f.box("glowSoft", w - 0.6, 0.02, 0.02, SHIP.lightWarm, { y: 0.31, z: d / 2 + 0.1 });+};++const dais: PropBuilder = (f, p) => {+ const { w, d } = p;+ const step = p.h / 2;+ f.chamfer("structure", w, step, d, 0.14, HALL.stoneLight, {});+ f.chamfer("structure", w - 0.6, step, d - 0.5, 0.12, HALL.stone, { y: step, z: -0.1 });+ // Gold inlay round the upper step and an emblem ring in its middle.+ const tw = w - 0.75, td = d - 0.65;+ f.box("metal", tw, 0.006, 0.04, SHIP.gold, { y: p.h, z: -0.1 + td / 2 });+ f.box("metal", tw, 0.006, 0.04, SHIP.gold, { y: p.h, z: -0.1 - td / 2 });+ for (const s of [-1, 1]) f.box("metal", 0.04, 0.006, td, SHIP.gold, { x: s * tw / 2, y: p.h, z: -0.1 });+ f.geo("metal", annulus(0.5, 0.56, 0, Math.PI * 2, 48), SHIP.gold, { y: p.h + 0.004, z: -0.1 });+ f.geo("metal", annulus(0.3, 0.33, 0, Math.PI * 2, 48), SHIP.gold, { y: p.h + 0.004, z: -0.1 });+ f.box("metal", w - 0.1, 0.02, 0.03, HALL.bronze, { y: step - 0.02, z: d / 2 });+ // Two lanterns at the front corners: the dais's own light.+ for (const s of [-1, 1]) {+ const x = s * (w / 2 - 0.55), z = d / 2 - 0.5;+ f.cylinder("structure", 0.16, 0.2, 0.12, SHIP.charcoal, { x, z, y: p.h }, 16);+ f.cylinder("metal", 0.05, 0.06, 1.0, HALL.bronze, { x, z, y: p.h + 0.12 }, 12);+ f.cylinder("glow", 0.08, 0.08, 0.36, SHIP.lightWarm, { x, z, y: p.h + 1.12 }, 16);+ f.cylinder("metal", 0.11, 0.09, 0.05, HALL.bronze, { x, z, y: p.h + 1.48 }, 16);+ }+};++const honorCase: PropBuilder = (f, p) => {+ const { w, d } = p;+ f.chamfer("metal", w + 0.04, 0.08, d + 0.04, 0.06, HALL.bronze, {});+ f.chamfer("structure", w, VITRINE.y0 - 0.08, d, 0.06, HALL.stone, { y: 0.08 });+ f.box("metal", w - 0.1, 0.02, 0.02, SHIP.gold, { y: VITRINE.y0 - 0.1, z: d / 2 + 0.005 });+ f.box("structure", w * 0.5, 0.12, 0.012, HALL.stoneLight, { y: 0.62, z: d / 2 + 0.004 });+ // The glass, its corner posts and a small stand for the insignia.+ const gw = w - 0.1, gd = d - 0.1, gh = VITRINE.y1 - VITRINE.y0;+ f.box("glass", gw, gh, gd, "#d8ecff", { y: VITRINE.y0 });+ for (const sx of [-1, 1]) for (const sz of [-1, 1]) f.box("metal", 0.03, gh, 0.03, SHIP.steelLight, { x: sx * gw / 2, z: sz * gd / 2, y: VITRINE.y0 });+ f.cylinder("metal", 0.1, 0.13, 0.08, SHIP.steel, { y: VITRINE.y0 }, 20);+ f.chamfer("structure", w, 0.1, d, 0.06, HALL.stoneLight, { y: VITRINE.y1 });+ f.box("metal", w - 0.08, 0.02, 0.015, SHIP.gold, { y: VITRINE.y1 + 0.04, z: d / 2 + 0.002 });+};++registerPropBuilders({ rankWall, dais, honorCase });++/** The runner up the middle of the hall, from the dais steps to the arch, in world coordinates. */+export function buildRunner(f: Frame, z0: number, z1: number, width: number): void {+ const len = z1 - z0, z = (z0 + z1) / 2;+ f.box("fabric", width, 0.012, len, HALL.runner, { z, y: 0.006 });+ // Gold borders, a fine inner line, and a cross-bar every few metres.+ for (const s of [-1, 1]) {+ f.box("metal", 0.05, 0.004, len, SHIP.gold, { x: s * (width / 2 - 0.08), y: 0.018, z });+ f.box("metal", 0.015, 0.004, len, SHIP.goldDeep, { x: s * (width / 2 - 0.2), y: 0.018, z });+ }+ for (let k = z0 + 2.5; k < z1 - 1; k += 5) f.box("metal", width - 0.5, 0.004, 0.02, SHIP.goldDeep, { y: 0.018, z: k });+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/honors/index.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/honors/index.tsnew file mode 100644index 0000000000..398ea9ea11--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/honors/index.ts@@ -0,0 +1,19 @@+/**+ * Deck 5, the Hall of Honour: the rank wall, the dais and the display cases.+ * Its stations (the rank wall and the cases) open the captain's service+ * record, which the stage owns; this module draws the hall and leaves them be.+ */+import { registerDeck } from "../registry";+import { buildHonorsDeck } from "./honorsPlan";+import { HonorsScene } from "./HonorsScene";+import "./honorsProps";++// The plan depends on nothing but the rank ladder: build it once.+let plan: ReturnType<typeof buildHonorsDeck> | null = null;++registerDeck({+ id: "honors",+ population: "none",+ build: () => (plan ??= buildHonorsDeck()),+ Scene: HonorsScene,+});diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/honors/insignia.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/honors/insignia.tsnew file mode 100644index 0000000000..91f26437e1--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/honors/insignia.ts@@ -0,0 +1,126 @@+/**+ * The ship's rank insignia, drawn on a 2D canvas: silver chevrons for the+ * enlisted ranks, a gold bar for the warrant officer, gold pips for officers+ * (a hollow pip is the half step between two full ones) and gold stars over+ * a bar for the flag ranks. Original marks, deliberately plain, so they read+ * at a plaque's size from across the hall.+ */+import type { Rank } from "../../levels/ranks";++export const SILVER = "#cfd5dc";+export const SILVER_DEEP = "#7d8794";+export const GOLD = "#e1b04f";+export const GOLD_DEEP = "#9c6d22";++/** What a rank's mark is made of. */+export interface InsigniaSpec {+ kind: "candidate" | "chevrons" | "bar" | "pips" | "stars";+ /** Chevrons, pips or stars. */+ count: number;+ /** Officers: how many of the pips are hollow (the half steps). */+ hollow: number;+ /** Chevrons: a rocker arc under them (the chief). */+ rocker: boolean;+}++const SPECS: Record<string, InsigniaSpec> = {+ cadet: { kind: "candidate", count: 0, hollow: 0, rocker: false },+ crewman: { kind: "chevrons", count: 1, hollow: 0, rocker: false },+ specialist: { kind: "chevrons", count: 2, hollow: 0, rocker: false },+ petty_officer: { kind: "chevrons", count: 3, hollow: 0, rocker: false },+ chief_petty_officer: { kind: "chevrons", count: 3, hollow: 0, rocker: true },+ warrant_officer: { kind: "bar", count: 1, hollow: 0, rocker: false },+ ensign: { kind: "pips", count: 1, hollow: 0, rocker: false },+ lieutenant_junior_grade: { kind: "pips", count: 2, hollow: 1, rocker: false },+ lieutenant: { kind: "pips", count: 2, hollow: 0, rocker: false },+ lieutenant_commander: { kind: "pips", count: 3, hollow: 1, rocker: false },+ commander: { kind: "pips", count: 3, hollow: 0, rocker: false },+ captain: { kind: "pips", count: 4, hollow: 0, rocker: false },+ commodore: { kind: "stars", count: 1, hollow: 0, rocker: false },+ rear_admiral: { kind: "stars", count: 2, hollow: 0, rocker: false },+ vice_admiral: { kind: "stars", count: 3, hollow: 0, rocker: false },+ admiral: { kind: "stars", count: 4, hollow: 0, rocker: false },+};++/** The mark of a rank; a rank the table does not know falls back by its tier. */+export function insigniaSpec(rank: Rank): InsigniaSpec {+ const known = SPECS[rank.id];+ if (known) return known;+ if (rank.tier === "flag") return { kind: "stars", count: Math.max(1, rank.pips), hollow: 0, rocker: false };+ if (rank.tier === "enlisted") return { kind: "chevrons", count: Math.max(1, rank.pips), hollow: 0, rocker: false };+ return { kind: "pips", count: Math.max(1, rank.pips), hollow: 0, rocker: false };+}++function metal(ctx: CanvasRenderingContext2D, x: number, y0: number, y1: number, light: string, deep: string): CanvasGradient {+ const g = ctx.createLinearGradient(x, y0, x, y1);+ g.addColorStop(0, light); g.addColorStop(0.55, light); g.addColorStop(1, deep);+ return g;+}++function star(ctx: CanvasRenderingContext2D, cx: number, cy: number, r: number): void {+ ctx.beginPath();+ for (let i = 0; i < 10; i += 1) {+ const a = -Math.PI / 2 + (i * Math.PI) / 5;+ const rr = i % 2 ? r * 0.42 : r;+ ctx.lineTo(cx + Math.cos(a) * rr, cy + Math.sin(a) * rr);+ }+ ctx.closePath();+ ctx.fill();+}++/**+ * Draw a rank's insignia centred on (cx, cy), `size` pixels across. `dim`+ * draws it as an unlit outline-grey (a rank still ahead).+ */+export function drawInsignia(ctx: CanvasRenderingContext2D, rank: Rank, cx: number, cy: number, size: number, dim = false): void {+ const spec = insigniaSpec(rank);+ const u = size / 100;+ ctx.save();+ ctx.lineJoin = "round";+ ctx.lineCap = "round";+ const silver = dim ? "#59606a" : metal(ctx, cx, cy - 30 * u, cy + 30 * u, SILVER, SILVER_DEEP);+ const gold = dim ? "#5f5644" : metal(ctx, cx, cy - 30 * u, cy + 30 * u, GOLD, GOLD_DEEP);+ if (!dim) { ctx.shadowColor = spec.kind === "chevrons" || spec.kind === "candidate" ? "rgba(220,230,240,0.45)" : "rgba(240,190,90,0.55)"; ctx.shadowBlur = 8 * u; }++ if (spec.kind === "candidate") {+ // An open diamond: on the ladder, no stripe yet.+ ctx.strokeStyle = silver; ctx.lineWidth = 7 * u;+ ctx.beginPath(); ctx.moveTo(cx, cy - 24 * u); ctx.lineTo(cx + 20 * u, cy); ctx.lineTo(cx, cy + 24 * u); ctx.lineTo(cx - 20 * u, cy); ctx.closePath(); ctx.stroke();+ } else if (spec.kind === "chevrons") {+ ctx.strokeStyle = silver; ctx.lineWidth = 9 * u;+ const gap = 15 * u;+ const top = cy - ((spec.count - 1) * gap) / 2 - (spec.rocker ? 8 * u : 0) - 6 * u;+ for (let i = 0; i < spec.count; i += 1) {+ const y = top + i * gap;+ ctx.beginPath(); ctx.moveTo(cx - 30 * u, y + 16 * u); ctx.lineTo(cx, y); ctx.lineTo(cx + 30 * u, y + 16 * u); ctx.stroke();+ }+ if (spec.rocker) {+ const y = top + spec.count * gap + 8 * u;+ ctx.beginPath(); ctx.moveTo(cx - 30 * u, y); ctx.quadraticCurveTo(cx, y + 18 * u, cx + 30 * u, y); ctx.stroke();+ }+ } else if (spec.kind === "bar") {+ ctx.fillStyle = gold;+ ctx.fillRect(cx - 34 * u, cy - 8 * u, 68 * u, 16 * u);+ // The warrant's break: a dark notch in the middle of the bar.+ ctx.shadowBlur = 0;+ ctx.fillStyle = dim ? "#2a2c30" : "#1a1c22";+ ctx.fillRect(cx - 5 * u, cy - 8 * u, 10 * u, 16 * u);+ } else if (spec.kind === "pips") {+ const r = 9 * u, gap = 25 * u;+ const x0 = cx - ((spec.count - 1) * gap) / 2;+ for (let i = 0; i < spec.count; i += 1) {+ const x = x0 + i * gap;+ const hollow = i >= spec.count - spec.hollow;+ ctx.beginPath(); ctx.arc(x, cy, hollow ? r - 2.5 * u : r, 0, Math.PI * 2);+ if (hollow) { ctx.strokeStyle = gold; ctx.lineWidth = 4.5 * u; ctx.stroke(); }+ else { ctx.fillStyle = gold; ctx.fill(); }+ }+ } else {+ const r = 12 * u, gap = 25 * u;+ const x0 = cx - ((spec.count - 1) * gap) / 2;+ ctx.fillStyle = gold;+ for (let i = 0; i < spec.count; i += 1) star(ctx, x0 + i * gap, cy - 6 * u, r);+ ctx.fillRect(cx - 44 * u, cy + 12 * u, 88 * u, 7 * u);+ }+ ctx.restore();+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/index.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/index.tsnew file mode 100644index 0000000000..0e0764d828--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/index.ts@@ -0,0 +1,7 @@+/** Every deck module registers itself on import. */+import "./registry";+import "./ops";+import "./bridge";+import "./engineering";+import "./holodeck";+import "./honors";diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/ops/DivisionPanel.tsx b/dodaios/ui/web/frontend/src/components/society/starship/decks/ops/DivisionPanel.tsxnew file mode 100644index 0000000000..3a01462acb--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/ops/DivisionPanel.tsx@@ -0,0 +1,74 @@+/**+ * A division's holo-table: who belongs to the team and what each is doing,+ * the team's chat, and a briefing — the free members walk to the table and+ * stand round it for a minute and a half. A briefing is a gathering on the+ * map only: nothing is posted to the team and nobody starts work.+ */+import { useEffect, useRef } from "react";+import { AgentSwatch } from "../../../AgentSwatch";+import { rankFor } from "../../levels/ranks";+import { useProgression } from "../../../progression/progressionStore";+import { useShip } from "../../shipStore";+import type { DeckPanelProps } from "../registry";+import "./quartermaster.css";++export const BRIEFING_MS = 90_000;++export function DivisionPanel({ plan, station, actions, agents }: DeckPanelProps) {+ const { t } = actions;+ const division = plan.divisions.find((d) => `division:${d.room}` === station.id);+ const subjects = useProgression((s) => s.subjects);+ const gathering = useShip((s) => s.gathering);+ const first = useRef<HTMLButtonElement>(null);+ useEffect(() => { first.current?.focus(); }, []);+ if (!division) return null;+ const name = division.teamId ? division.name : t("ship.division.pool");+ const briefing = gathering?.place === division.room;+ const free = division.members.filter((id) => agents.get(id)?.state !== "working");+ const brief = () => {+ const store = useShip.getState();+ if (briefing) { store.gather(null); actions.say(t("ship.ops.division.briefing_over")); return; }+ if (free.length === 0) { actions.say(t("ship.ops.division.nobody_free")); return; }+ store.gather({ place: division.room, agentIds: free, untilMs: Date.now() + BRIEFING_MS });+ actions.reportAction("team_briefing", division.teamId ?? "");+ actions.say(t("ship.ops.division.briefing_called").replace("{count}", String(free.length)).replace("{team}", name));+ actions.closePanel();+ };+ return (+ <aside className="ship-panel qm-panel" role="dialog" aria-label={name}+ onKeyDown={(e) => { if (e.key === "Escape") { e.stopPropagation(); actions.closePanel(); } }}>+ <header className="qm-head">+ <div>+ <div className="ship-eyebrow" style={{ color: division.colour }}>{t("ship.ops.division.eyebrow")}</div>+ <h2>{name}</h2>+ </div>+ <button type="button" className="ship-tool" aria-label={t("ship.close")} onClick={actions.closePanel}>✕</button>+ </header>+ <ul className="div-members">+ {division.members.map((id) => {+ const agent = agents.get(id);+ if (!agent) return null;+ const lead = division.leadId === id;+ return (+ <li key={id}>+ <span className="div-face"><AgentSwatch agent={{ ...agent, state: undefined }} size={26} /></span>+ <span className="div-name">{agent.name}{lead && <small className="div-lead">{t("ship.ops.division.lead")}</small>}</span>+ <span className="div-state"><i className="ship-dot" data-state={agent.state} />{t(`ship.state.${agent.state}`)}</span>+ <small className="div-rank">{t(`ship.rank.${rankFor(subjects[`agent:${id}`]?.level ?? 1).id}`)}</small>+ </li>+ );+ })}+ {division.members.length === 0 && <li className="div-empty">{t("ship.ops.division.empty")}</li>}+ </ul>+ <div className="div-actions">+ {division.teamId+ ? <button ref={first} type="button" className="ship-btn" data-primary="true" onClick={() => { actions.closePanel(); actions.openGroup(division.teamId as string); }}>{t("ship.ops.division.open_chat")}</button>+ : <button ref={first} type="button" className="ship-btn" data-primary="true" onClick={() => { actions.closePanel(); actions.openLedger(); }}>{t("ship.ops.division.open_agents")}</button>}+ {division.members.length > 0 && (+ <button type="button" className="ship-btn" onClick={brief}>{briefing ? t("ship.ops.division.end_briefing") : t("ship.ops.division.briefing")}</button>+ )}+ </div>+ <p className="qm-note">{t("ship.ops.division.note")}</p>+ </aside>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/ops/QuartermasterPanel.tsx b/dodaios/ui/web/frontend/src/components/society/starship/decks/ops/QuartermasterPanel.tsxnew file mode 100644index 0000000000..70cd7dac0e--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/ops/QuartermasterPanel.tsx@@ -0,0 +1,76 @@+/**+ * The quartermaster: the captain's suit. Docked at the side, so the captain+ * stays in view and every change shows on the figure at once. Suit colour,+ * trim and visor are free choices; the cuts beyond the duty suit open with+ * rank (the level system's `suit` rewards) and say at which level.+ */+import { useEffect, useRef } from "react";+import { useProgression } from "../../../progression/progressionStore";+import type { SuitChoice } from "../../../progression/cosmetics";+import { useShip, type CaptainLook } from "../../shipStore";+import type { DeckPanelProps } from "../registry";+import "./quartermaster.css";++const SUITS = ["#2c3340", "#1c2a4a", "#4a1d26", "#20372d", "#6e6248", "#3b3f46"] as const;+const TRIMS = ["#d9a441", "#c9cdd3", "#5fd4ff", "#e04a5a"] as const;+const VISORS = ["#d6a440", "#b9c3cc", "#3c7fd0", "#1d2026"] as const;+++export function QuartermasterPanel({ actions }: DeckPanelProps) {+ const { t } = actions;+ const look = useShip((s) => s.captainLook);+ const level = useProgression((s) => s.subjects.person?.level ?? 1);+ const choice = useProgression((s) => s.suit);+ const rewards = useProgression((s) => s.snapshot?.rewards);+ // Automatic (the finest open), the duty suit, then every suit the rulebook lists, lowest first.+ const cuts: { id: SuitChoice; level: number }[] = [+ { id: "auto", level: 1 }, { id: "none", level: 1 },+ ...(rewards ?? []).filter((r) => r.slot === "suit").map((r) => ({ id: r.rewardId as SuitChoice, level: r.levels.person ?? 99 })).sort((a, b) => a.level - b.level),+ ];+ const set = (patch: Partial<CaptainLook>) => useShip.getState().setCaptainLook({ ...look, ...patch });+ const first = useRef<HTMLButtonElement>(null);+ useEffect(() => { first.current?.focus(); }, []);+ const swatches = (key: "suit" | "trim" | "visor", list: readonly string[], label: string) => (+ <fieldset className="qm-row">+ <legend className="ship-eyebrow">{label}</legend>+ <div className="qm-swatches" role="radiogroup" aria-label={label}>+ {list.map((c, i) => (+ <button key={c} ref={key === "suit" && i === 0 ? first : undefined} type="button" role="radio" aria-checked={look[key] === c}+ className="qm-swatch" style={{ background: c }} aria-label={`${label} ${i + 1}`} onClick={() => set({ [key]: c })} />+ ))}+ </div>+ </fieldset>+ );+ return (+ <aside className="ship-panel qm-panel" role="dialog" aria-label={t("ship.ops.quartermaster.title")}+ onKeyDown={(e) => { if (e.key === "Escape") { e.stopPropagation(); actions.closePanel(); } }}>+ <header className="qm-head">+ <div>+ <div className="ship-eyebrow">{t("ship.station.quartermaster.name")}</div>+ <h2>{t("ship.ops.quartermaster.title")}</h2>+ </div>+ <button type="button" className="ship-tool" aria-label={t("ship.close")} onClick={actions.closePanel}>✕</button>+ </header>+ <fieldset className="qm-row">+ <legend className="ship-eyebrow">{t("ship.ops.quartermaster.cut")}</legend>+ <div className="qm-cuts">+ {cuts.map((cut) => {+ const open = level >= cut.level;+ const key = cut.id === "none" ? "duty" : cut.id.replace(/^suit_/, "");+ return (+ <button key={cut.id} type="button" className="qm-cut" aria-pressed={choice === cut.id} disabled={!open}+ onClick={() => useProgression.getState().chooseSuit(cut.id)}>+ <span>{t(`ship.ops.quartermaster.cuts.${key}`)}</span>+ <small>{open ? t("ship.ops.quartermaster.open") : t("ship.ops.quartermaster.at_level").replace("{n}", String(cut.level))}</small>+ </button>+ );+ })}+ </div>+ </fieldset>+ {swatches("suit", SUITS, t("ship.ops.quartermaster.suit"))}+ {swatches("trim", TRIMS, t("ship.ops.quartermaster.trim"))}+ {swatches("visor", VISORS, t("ship.ops.quartermaster.visor"))}+ <p className="qm-note">{t("ship.ops.quartermaster.note")}</p>+ </aside>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/ops/index.tsx b/dodaios/ui/web/frontend/src/components/society/starship/decks/ops/index.tsxnew file mode 100644index 0000000000..5d890f9335--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/ops/index.tsx@@ -0,0 +1,22 @@+/** The operations deck: the Jarvis agents' divisions, the mess, the transporter and the quartermaster. */+import { buildOpsDeck } from "../../plan/opsDeck";+import { registerDeck, type DeckPanelProps } from "../registry";+import { DivisionPanel } from "./DivisionPanel";+import { QuartermasterPanel } from "./QuartermasterPanel";++function OpsPanel(props: DeckPanelProps) {+ return props.station.kind === "division" ? <DivisionPanel {...props} /> : <QuartermasterPanel {...props} />;+}++registerDeck({+ id: "ops",+ population: "agents",+ build: (input) => buildOpsDeck({ crew: input.crew, teams: input.teams }),+ // The holo-table and the quartermaster open their panels; the rest is the stage's.+ useStation: (station, _plan, actions) => {+ if (station.kind !== "quartermaster" && station.kind !== "division") return false;+ actions.openPanel(station.id);+ return true;+ },+ Panel: OpsPanel,+});diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/ops/quartermaster.css b/dodaios/ui/web/frontend/src/components/society/starship/decks/ops/quartermaster.cssnew file mode 100644index 0000000000..cafe6a93a7--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/ops/quartermaster.css@@ -0,0 +1,34 @@+.qm-panel { position: absolute; top: 14px; right: 70px; bottom: 14px; width: 320px; padding: 16px 18px; z-index: 7; overflow-y: auto; }+.qm-head { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 14px; }+.qm-head h2 { margin: 2px 0 0; font: 600 17px "Space Grotesk", sans-serif; letter-spacing: 0.02em; }+.qm-row { border: none; margin: 0 0 16px; padding: 0; }+.qm-row legend { margin-bottom: 8px; padding: 0; }+.qm-swatches { display: flex; gap: 8px; flex-wrap: wrap; }+.qm-swatch {+ width: 34px; height: 34px; border-radius: 50%; border: 2px solid rgba(255, 255, 255, 0.12); cursor: pointer;+ box-shadow: inset 0 -6px 10px rgba(0, 0, 0, 0.35);+}+.qm-swatch[aria-checked="true"] { border-color: var(--ship-gold); box-shadow: 0 0 0 3px rgba(217, 164, 65, 0.25), inset 0 -6px 10px rgba(0, 0, 0, 0.35); }+.qm-swatch:focus-visible { outline: 2px solid var(--ship-cyan); outline-offset: 2px; }+.qm-cuts { display: flex; flex-direction: column; gap: 6px; }+.qm-cut {+ display: flex; justify-content: space-between; align-items: center; padding: 9px 12px; border-radius: 8px; text-align: left;+ border: 1px solid var(--ship-line); background: rgba(255, 255, 255, 0.025); color: var(--ship-text); font: 500 13px "Inter Variable", sans-serif;+ cursor: pointer;+}+.qm-cut small { color: var(--ship-muted); font-size: 11.5px; }+.qm-cut[aria-pressed="true"] { border-color: rgba(217, 164, 65, 0.6); background: rgba(217, 164, 65, 0.08); }+.qm-cut:disabled { cursor: default; opacity: 0.5; }+.qm-cut:focus-visible { outline: 2px solid var(--ship-cyan); outline-offset: 1px; }+.qm-note { margin: 4px 0 0; font-size: 12px; line-height: 1.45; color: var(--ship-muted); }++/* A division's holo-table panel. */+.div-members { list-style: none; margin: 0 0 14px; padding: 0; display: flex; flex-direction: column; gap: 4px; }+.div-members li { display: grid; grid-template-columns: 34px 1fr auto; grid-template-rows: auto auto; column-gap: 10px; align-items: center; padding: 6px 4px; border-bottom: 1px solid var(--ship-line); }+.div-face { grid-row: span 2; width: 34px; height: 34px; border-radius: 8px; background: #050a10; display: grid; place-items: center; border: 1px solid var(--ship-line); }+.div-name { font-weight: 500; font-size: 13px; }+.div-lead { margin-left: 6px; color: var(--ship-gold); font-size: 10.5px; letter-spacing: 0.08em; text-transform: uppercase; }+.div-state { font-size: 11.5px; color: var(--ship-muted); display: inline-flex; align-items: center; gap: 6px; justify-self: end; }+.div-rank { grid-column: 2; color: var(--ship-muted); font-size: 11px; }+.div-empty { color: var(--ship-muted); font-size: 12.5px; padding: 8px 0; }+.div-actions { display: flex; gap: 8px; flex-wrap: wrap; }diff --git a/dodaios/ui/web/frontend/src/components/society/starship/decks/registry.ts b/dodaios/ui/web/frontend/src/components/society/starship/decks/registry.tsnew file mode 100644index 0000000000..1d9f25ee49--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/decks/registry.ts@@ -0,0 +1,91 @@+/**+ * The decks of the ship and how each one is built. A deck module registers+ * its plan builder and, when it needs them, a scene of its own (things that+ * move or change beyond the shared kit), its own station behaviour and a DOM+ * panel its stations open. The stage never needs editing for a new deck.+ */+import type { ComponentType } from "react";+import type { SocietyAgent } from "../../data";+import type { PaneOccupant } from "../../crewFeeds/codingFloor";+import type { CrewInput, DeckId, DeckPlan, Station, TeamInput } from "../plan/types";++export interface DeckInput {+ crew: readonly CrewInput[];+ teams: readonly TeamInput[];+ /** Engineering: every coding pane of the IDE (its `agent` is the pane projected into a crew member). */+ panes: readonly PaneOccupant[];+}++/** What a deck's stations and panels may do; the stage implements it. */+export interface ShipActions {+ t: (key: string) => string;+ /** One short line in the HUD. */+ say: (text: string) => void;+ /** Open a Jarvis agent's chat (or a pane's command panel on engineering). */+ openAgent: (agentId: string) => void;+ openLedger: () => void;+ createAgent: () => void;+ openGroup: (groupId: string) => void;+ /** Navigate the app to a section ("agentic-ide", "agents", …). */+ openSection: (section: string) => void;+ /** Ride the turbolift to another deck (with the doors). */+ ride: (deck: DeckId) => void;+ /** Seat the captain (the captain's chair); null stands up. */+ sit: (seat: { x: number; z: number; yaw: number; seatY: number } | null) => void;+ /** Open this deck's panel for a station (rendered by the module's `Panel`). */+ openPanel: (stationId: string) => void;+ closePanel: () => void;+ /** Report a small action to the level system (metered on the server). */+ reportAction: (action: string, ref?: string) => void;+}++export interface DeckSceneProps {+ plan: DeckPlan;+ reduced: boolean;+ quality: "high" | "low";+ awake: boolean;+ /** The deck's crew (agents, or panes on engineering) by id. */+ agents: ReadonlyMap<string, SocietyAgent>;+ panes: readonly PaneOccupant[];+ actions: ShipActions;+}++export interface DeckPanelProps {+ plan: DeckPlan;+ /** The station whose panel is open. */+ station: Station;+ actions: ShipActions;+ agents: ReadonlyMap<string, SocietyAgent>;+ panes: readonly PaneOccupant[];+}++export interface DeckModule {+ id: DeckId;+ /** Who lives here: the Jarvis agents, the coding panes, or nobody (the captain and the pet only). */+ population: "agents" | "panes" | "none";+ build: (input: DeckInput) => DeckPlan;+ Scene?: ComponentType<DeckSceneProps>;+ /**+ * Handle a station of this deck. Return true when handled; the stage's+ * shared behaviour (transporter, turbolift, divisions, mess) covers the rest.+ */+ useStation?: (station: Station, plan: DeckPlan, actions: ShipActions, far: boolean) => boolean;+ Panel?: ComponentType<DeckPanelProps>;+ /** The prompt's name for a station of this deck; undefined = the shared name. */+ stationName?: (station: Station, t: (key: string) => string) => string | undefined;+}++const modules = new Map<DeckId, DeckModule>();++export function registerDeck(module: DeckModule): void {+ modules.set(module.id, module);+}++export function deckModule(id: DeckId): DeckModule | undefined {+ return modules.get(id);+}++export function availableDecks(): DeckId[] {+ return [...modules.keys()];+}+diff --git a/dodaios/ui/web/frontend/src/components/society/starship/hud/Plates.tsx b/dodaios/ui/web/frontend/src/components/society/starship/hud/Plates.tsxnew file mode 100644index 0000000000..b76cb0bb55--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/hud/Plates.tsx@@ -0,0 +1,64 @@+/**+ * Name plates over the crew: a state dot from afar, the name and rank up+ * close, for the agent under the pointer and the selected one. The DOM+ * layer renders the plates once; a driver inside the canvas moves them every+ * frame without React.+ */+import { useFrame, useThree } from "@react-three/fiber";+import { useEffect, useRef } from "react";+import { Vector3 } from "three";+import { crewPoses } from "../life/CrewLayer";+import { captain, useShip } from "../shipStore";++const elements = new Map<string, HTMLElement>();++export interface PlateView { agentId: string; name: string; state: string; rank: string; say?: string | null }++export function PlateLayer({ plates, onPick }: { plates: readonly PlateView[]; onPick: (id: string) => void }) {+ return (+ <div className="ship-plates" aria-hidden="false">+ {plates.map((p) => (+ <button key={p.agentId} type="button" className="ship-plate" data-far="true" data-plate={p.agentId}+ ref={(el) => { if (el) elements.set(p.agentId, el); else elements.delete(p.agentId); }}+ onClick={() => onPick(p.agentId)} aria-label={p.name}>+ <span className="ship-dot" data-state={p.state} />+ <span className="ship-plate-text">{p.name}{p.rank ? <span className="ship-plate-rank"> · {p.rank}</span> : null}</span>+ {p.say ? <span className="ship-plate-say">{p.say}</span> : null}+ </button>+ ))}+ </div>+ );+}++const NEAR_CAMERA = 13;+const NEAR_CAPTAIN = 5.5;++export function PlateDriver() {+ const { camera, size } = useThree();+ const v = useRef(new Vector3());+ const open = useRef(new Set<string>());+ useEffect(() => () => open.current.clear(), []);+ useFrame(() => {+ const { selection, hovered } = useShip.getState();+ for (const [id, el] of elements) {+ const pose = crewPoses.get(id);+ if (!pose) { el.style.transform = "translate(-9999px,0)"; continue; }+ v.current.set(pose.x, pose.headY + 0.32, pose.z);+ const dCam = v.current.distanceTo(camera.position);+ v.current.project(camera);+ if (v.current.z > 1 || v.current.x < -1.1 || v.current.x > 1.1 || v.current.y < -1.1 || v.current.y > 1.1) { el.style.transform = "translate(-9999px,0)"; continue; }+ const x = (v.current.x * 0.5 + 0.5) * size.width, y = (-v.current.y * 0.5 + 0.5) * size.height;+ const dCap = Math.hypot(pose.x - captain.x, pose.z - captain.z);+ const focused = (selection?.kind === "agent" && selection.id === id) || (hovered?.kind === "agent" && hovered.id === id);+ const was = open.current.has(id);+ // A little hysteresis, so a plate at the threshold does not flicker.+ const near = focused || dCam < (was ? NEAR_CAMERA + 2 : NEAR_CAMERA) || dCap < (was ? NEAR_CAPTAIN + 1 : NEAR_CAPTAIN);+ if (near) open.current.add(id); else open.current.delete(id);+ const far = near ? "false" : "true";+ if (el.dataset.far !== far) el.dataset.far = far;+ el.style.transform = `translate(${Math.round(x)}px, ${Math.round(y)}px) translate(-50%, -100%)`;+ el.style.zIndex = String(10000 - Math.round(dCam * 10));+ }+ });+ return null;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/hud/ship.css b/dodaios/ui/web/frontend/src/components/society/starship/hud/ship.cssnew file mode 100644index 0000000000..beb44c4bd2--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/hud/ship.css@@ -0,0 +1,171 @@+/* The ship's HUD. The scene is always deep space, so the HUD keeps one dark glass look in both themes. */++.ship-stage {+ --ship-glass: rgba(9, 13, 20, 0.74);+ --ship-glass-strong: rgba(9, 13, 20, 0.9);+ --ship-line: rgba(255, 255, 255, 0.09);+ --ship-line-strong: rgba(255, 255, 255, 0.16);+ --ship-text: #e8eef6;+ --ship-muted: #8f9db0;+ --ship-gold: #d9a441;+ --ship-cyan: #5fd4ff;+ --ship-working: #3fd27f;+ --ship-waiting: #ffb020;+ --ship-idle: #8a96a8;+ --ship-paused: #8a7fc8;+ position: relative;+ width: 100%;+ height: 100%;+ min-height: 0;+ overflow: hidden;+ background: #02040a;+ isolation: isolate;+ color: var(--ship-text);+ font-family: "Inter Variable", system-ui, sans-serif;+ outline: none;+}++.ship-stage canvas { display: block; touch-action: none; }++.ship-hud { position: absolute; inset: 0; pointer-events: none; z-index: 5; }+.ship-hud > * { pointer-events: auto; }++.ship-panel {+ background: var(--ship-glass);+ border: 1px solid var(--ship-line);+ border-radius: 10px;+ backdrop-filter: blur(14px) saturate(1.2);+ -webkit-backdrop-filter: blur(14px) saturate(1.2);+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.35);+}++.ship-eyebrow {+ font-family: "Space Grotesk", "Inter Variable", sans-serif;+ font-size: 10.5px;+ font-weight: 600;+ letter-spacing: 0.16em;+ text-transform: uppercase;+ color: var(--ship-muted);+}++/* Deck card, top left. */+.ship-deck {+ position: absolute; top: 14px; left: 14px; padding: 12px 16px 12px 14px; min-width: 220px;+ display: grid; grid-template-columns: auto 1fr; column-gap: 12px; row-gap: 2px; align-items: center;+}+.ship-deck-number {+ grid-row: span 2; width: 38px; height: 38px; border-radius: 8px; display: grid; place-items: center;+ font-family: "Space Grotesk", sans-serif; font-weight: 700; font-size: 18px; color: var(--ship-gold);+ border: 1px solid rgba(217, 164, 65, 0.45); background: rgba(217, 164, 65, 0.08);+}+.ship-deck-name { font-family: "Space Grotesk", sans-serif; font-weight: 600; font-size: 16px; letter-spacing: 0.02em; }+.ship-crewline { grid-column: 1 / -1; margin-top: 8px; display: flex; gap: 14px; font-size: 12px; color: var(--ship-muted); }+.ship-crewline span { display: inline-flex; align-items: center; gap: 6px; }+.ship-dot { width: 7px; height: 7px; border-radius: 50%; display: inline-block; background: var(--ship-idle); }+.ship-dot[data-state="working"] { background: var(--ship-working); box-shadow: 0 0 8px var(--ship-working); }+.ship-dot[data-state="waiting"] { background: var(--ship-waiting); box-shadow: 0 0 8px var(--ship-waiting); }+.ship-dot[data-state="paused"] { background: var(--ship-paused); }++/* Rank card under the deck card. */+.ship-rank {+ position: absolute; top: 112px; left: 14px; width: 252px; padding: 10px 14px; display: grid;+ grid-template-columns: 34px 1fr; column-gap: 10px; align-items: center; cursor: pointer; text-align: left;+ color: inherit; font: inherit;+}+.ship-rank:hover { border-color: var(--ship-line-strong); }+.ship-rank:focus-visible { outline: 2px solid var(--ship-gold); outline-offset: 2px; }+.ship-rank-title { font-weight: 600; font-size: 13px; }+.ship-rank-sub { font-size: 11px; color: var(--ship-muted); }+.ship-xp { grid-column: 1 / -1; margin-top: 8px; height: 3px; border-radius: 2px; background: rgba(255, 255, 255, 0.08); overflow: hidden; }+.ship-xp > i { display: block; height: 100%; background: linear-gradient(90deg, #b07a26, var(--ship-gold)); transition: width 0.8s ease; }++/* Toolbar, top right. */+.ship-tools { position: absolute; top: 14px; right: 14px; display: flex; flex-direction: column; gap: 6px; padding: 6px; }+.ship-tool {+ width: 36px; height: 36px; border-radius: 8px; display: grid; place-items: center; color: var(--ship-muted);+ background: transparent; border: 1px solid transparent; cursor: pointer;+}+.ship-tool:hover { color: var(--ship-text); background: rgba(255, 255, 255, 0.05); }+.ship-tool[aria-pressed="true"] { color: var(--ship-gold); border-color: rgba(217, 164, 65, 0.35); }+.ship-tool:focus-visible { outline: 2px solid var(--ship-gold); outline-offset: 1px; }++/* The one prompt, bottom centre. */+.ship-prompt {+ position: absolute; left: 50%; bottom: 18px; transform: translateX(-50%); display: flex; align-items: center; gap: 10px;+ padding: 8px 14px 8px 8px; font-size: 13px; color: var(--ship-text); cursor: pointer; white-space: nowrap;+ font-family: inherit;+}+.ship-key {+ min-width: 26px; height: 26px; padding: 0 6px; border-radius: 6px; display: grid; place-items: center;+ font-family: "JetBrains Mono", monospace; font-size: 12px; font-weight: 600; color: #0b0f15; background: var(--ship-gold);+}+.ship-prompt small { color: var(--ship-muted); font-size: 12px; }++.ship-notice { position: absolute; left: 50%; bottom: 66px; transform: translateX(-50%); padding: 8px 14px; font-size: 13px; }++/* Agent card, bottom left. */+.ship-agent { position: absolute; left: 14px; bottom: 14px; width: 300px; padding: 14px; }+.ship-agent-head { display: flex; gap: 12px; align-items: center; }+.ship-agent-face { width: 46px; height: 46px; border-radius: 10px; overflow: hidden; background: #050a10; border: 1px solid var(--ship-line); flex: none; }+.ship-agent-face canvas, .ship-agent-face img { width: 100%; height: 100%; image-rendering: pixelated; }+.ship-agent-name { font-weight: 600; font-size: 15px; }+.ship-agent-meta { font-size: 12px; color: var(--ship-muted); display: flex; gap: 8px; align-items: center; margin-top: 2px; }+.ship-agent-actions { display: flex; gap: 6px; margin-top: 12px; flex-wrap: wrap; }+.ship-btn {+ height: 30px; padding: 0 12px; border-radius: 7px; border: 1px solid var(--ship-line-strong); background: rgba(255, 255, 255, 0.04);+ color: var(--ship-text); font: 500 12.5px "Inter Variable", sans-serif; cursor: pointer;+}+.ship-btn:hover { background: rgba(255, 255, 255, 0.09); }+.ship-btn[data-primary="true"] { background: var(--ship-gold); border-color: var(--ship-gold); color: #0b0f15; font-weight: 600; }+.ship-btn[data-primary="true"]:hover { filter: brightness(1.08); }+.ship-btn:focus-visible { outline: 2px solid var(--ship-cyan); outline-offset: 1px; }+.ship-close { position: absolute; top: 8px; right: 8px; }++/* Turbolift. */+.ship-scrim { position: absolute; inset: 0; background: rgba(2, 4, 8, 0.45); display: grid; place-items: center; z-index: 8; }+.ship-lift { width: 340px; padding: 18px; }+.ship-lift h2 { margin: 0 0 12px; font: 600 15px "Space Grotesk", sans-serif; letter-spacing: 0.04em; }+.ship-lift-list { display: flex; flex-direction: column; gap: 6px; }+.ship-lift-row {+ display: grid; grid-template-columns: 40px 1fr auto; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 8px;+ border: 1px solid var(--ship-line); background: rgba(255, 255, 255, 0.025); color: var(--ship-text); text-align: left;+ font: inherit; cursor: pointer;+}+.ship-lift-row:hover, .ship-lift-row:focus-visible { border-color: rgba(217, 164, 65, 0.5); background: rgba(217, 164, 65, 0.06); outline: none; }+.ship-lift-row[aria-current="true"] { border-color: rgba(95, 212, 255, 0.4); }+.ship-lift-row b { font: 700 16px "Space Grotesk", sans-serif; color: var(--ship-gold); }+.ship-lift-row span small { display: block; color: var(--ship-muted); font-size: 11.5px; margin-top: 2px; }++/* The ride: doors close over the stage and open on the new deck. */+.ship-doors { position: absolute; inset: 0; z-index: 9; pointer-events: none; display: flex; }+.ship-doors > i { flex: 1; background: linear-gradient(90deg, #15191f, #232931 40%, #1a1e25); transition: transform 0.55s cubic-bezier(.7, 0, .3, 1); }+.ship-doors > i:first-child { transform: translateX(-101%); border-right: 2px solid var(--ship-gold); }+.ship-doors > i:last-child { transform: translateX(101%); border-left: 2px solid var(--ship-gold); }+.ship-doors[data-shut="true"] > i { transform: translateX(0); }++/* Name plates. */+.ship-plates { position: absolute; inset: 0; pointer-events: none; overflow: hidden; z-index: 3; }+.ship-plate {+ position: absolute; left: 0; top: 0; transform: translate(-9999px, 0); display: flex; align-items: center; gap: 6px;+ padding: 3px 8px 3px 6px; border-radius: 6px; font-size: 11.5px; font-weight: 500; white-space: nowrap; color: var(--ship-text);+ background: rgba(8, 12, 18, 0.78); border: 1px solid var(--ship-line); pointer-events: auto; cursor: pointer;+ will-change: transform; transition: opacity 0.2s;+}+.ship-plate[data-far="true"] { padding: 0; width: 9px; height: 9px; border-radius: 50%; background: transparent; border: none; }+.ship-plate[data-far="true"] .ship-plate-text { display: none; }+.ship-plate-rank { color: var(--ship-gold); font-family: "JetBrains Mono", monospace; font-size: 10px; }+.ship-plate-say {+ position: absolute; bottom: calc(100% + 6px); left: 50%; transform: translateX(-50%); max-width: 240px; white-space: normal;+ padding: 6px 9px; border-radius: 8px; background: rgba(232, 238, 246, 0.95); color: #0b0f15; font-size: 12px; line-height: 1.35;+}++.ship-fallback { position: absolute; inset: 0; display: grid; place-items: center; color: var(--ship-muted); font-size: 14px; text-align: center; padding: 24px; }++.ship-stage[data-compact="true"] .ship-deck { min-width: 0; padding: 8px 10px; }+.ship-stage[data-compact="true"] .ship-rank { display: none; }+.ship-stage[data-compact="true"] .ship-agent { width: calc(100% - 28px); }++@media (prefers-reduced-motion: reduce) {+ .ship-doors > i { transition: none; }+ .ship-xp > i { transition: none; }+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/levels/Insignia.tsx b/dodaios/ui/web/frontend/src/components/society/starship/levels/Insignia.tsxnew file mode 100644index 0000000000..e43fb2aa8e--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/levels/Insignia.tsx@@ -0,0 +1,107 @@+/**+ * The ship's rank insignia as SVG, original to Dodaios (no franchise insignia+ * is copied): silver chevrons for the enlisted ranks, gold pips on a dark bar+ * for the warrant officer and the officers, a gold bar under stars for the+ * flag officers. Drawn on a 48-unit grid with chunky shapes and real gaps, so+ * it stays crisp from 20 to 96 px. `levelModel.insigniaFor` says what each+ * rank wears.+ */+import { useId, type ReactElement } from "react";+import { insigniaFor } from "./levelModel";++export interface InsigniaProps {+ /** A rank id (`ship.rank.<id>`); an unknown id wears the cadet's bar. */+ rank: string;+ /** Edge length in px (default 32). */+ size?: number;+ /** "muted": a flat grey silhouette, for ranks not reached yet. */+ tone?: "metal" | "muted";+ /** Accessible name; without it the insignia is decorative (aria-hidden). */+ title?: string;+ className?: string;+}++const MUTED = "#4b5461";+const BAR_FILL = "#0c1118";++/** A chevron pointing up whose apex sits at `y`. */+const chevron = (y: number) => `7,${y + 11} 24,${y} 41,${y + 11} 41,${y + 16.5} 24,${y + 5.5} 7,${y + 16.5}`;++function star(cx: number, cy: number, r: number): string {+ const pts: string[] = [];+ for (let i = 0; i < 10; i += 1) {+ const a = -Math.PI / 2 + (i * Math.PI) / 5;+ const rr = i % 2 === 0 ? r : r * 0.45;+ pts.push(`${(cx + Math.cos(a) * rr).toFixed(2)},${(cy + Math.sin(a) * rr).toFixed(2)}`);+ }+ return pts.join(" ");+}++/** Centres of `n` marks spaced `step` apart round x = 24. */+const row = (n: number, step: number) => Array.from({ length: n }, (_, i) => 24 + (i - (n - 1) / 2) * step);++export function Insignia({ rank, size = 32, tone = "metal", title, className }: InsigniaProps) {+ const uid = useId().replace(/:/g, "");+ const spec = insigniaFor(rank);+ const muted = tone === "muted";+ const silver = muted ? MUTED : `url(#${uid}s)`;+ const gold = muted ? MUTED : `url(#${uid}g)`;+ const goldLine = muted ? MUTED : "#c8963c";+ const edge = "rgba(0,0,0,0.45)";++ let body: ReactElement;+ if (spec.kind === "bar") {+ body = <rect x="6" y="19" width="36" height="10" rx="3" fill={BAR_FILL} stroke={silver} strokeWidth="1.8" />;+ } else if (spec.kind === "chevrons") {+ const step = 8.5;+ const height = 16.5 + (spec.count - 1) * step + (spec.rocker ? 13 : 0);+ const top = (48 - height) / 2;+ const rockerY = top + (spec.count - 1) * step + 16.5 + 2.5;+ body = (+ <g fill={silver} stroke={edge} strokeWidth="0.6" strokeLinejoin="miter">+ {Array.from({ length: spec.count }, (_, i) => <polygon key={i} points={chevron(top + i * step)} />)}+ {spec.rocker && <path d={`M7 ${rockerY} Q24 ${rockerY + 10} 41 ${rockerY} L41 ${rockerY + 5.5} Q24 ${rockerY + 15.5} 7 ${rockerY + 5.5} Z`} />}+ </g>+ );+ } else if (spec.kind === "pips") {+ const xs = row(spec.solid + spec.hollow, 10);+ body = (+ <g>+ <rect x="3" y="16" width="42" height="16" rx="4" fill={BAR_FILL} stroke={spec.warrant ? silver : goldLine} strokeWidth="1.3" />+ {xs.map((x, i) => (i < spec.solid+ ? <circle key={i} cx={x} cy="24" r="3.9" fill={gold} stroke={edge} strokeWidth="0.5" />+ : <circle key={i} cx={x} cy="24" r="3.2" fill={BAR_FILL} stroke={gold} strokeWidth="1.7" />))}+ </g>+ );+ } else {+ const n = spec.stars;+ const r = n === 1 ? 6.2 : 4.7;+ body = (+ <g fill={gold} stroke={edge} strokeWidth="0.5" strokeLinejoin="round">+ {row(n, 10.4).map((x, i) => <polygon key={i} points={star(x, 19, r)} />)}+ <rect x="5" y="30" width="38" height="7" rx="2" />+ </g>+ );+ }++ return (+ <svg className={className} width={size} height={size} viewBox="0 0 48 48" shapeRendering="geometricPrecision"+ role={title ? "img" : undefined} aria-label={title} aria-hidden={title ? undefined : true}>+ {!muted && (+ <defs>+ <linearGradient id={`${uid}s`} x1="0" y1="0" x2="0" y2="1">+ <stop offset="0" stopColor="#f6f8fb" />+ <stop offset="0.55" stopColor="#b9c1cc" />+ <stop offset="1" stopColor="#848e9b" />+ </linearGradient>+ <linearGradient id={`${uid}g`} x1="0" y1="0" x2="0" y2="1">+ <stop offset="0" stopColor="#fbe6a6" />+ <stop offset="0.5" stopColor="#e1b04f" />+ <stop offset="1" stopColor="#a8741f" />+ </linearGradient>+ </defs>+ )}+ {body}+ </svg>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/levels/PromotionCeremony.tsx b/dodaios/ui/web/frontend/src/components/society/starship/levels/PromotionCeremony.tsxnew file mode 100644index 0000000000..fdcedbef9b--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/levels/PromotionCeremony.tsx@@ -0,0 +1,109 @@+/**+ * The promotion moment. For the captain and the companion: a centred card+ * where the old insignia steps aside and the new one is laid on and catches+ * the light, then the rank, the level and what just opened. A level between+ * two ranks shows the insignia alone. For an android: a quiet toast in the+ * corner. Everything comes from the progression store (`banners`, `toasts`);+ * the fanfare itself is played by `useProgressionSync` when the award lands.+ *+ * A card goes on a click, Escape or after six seconds; a toast after five or+ * on a click. Reduced motion keeps every word and drops the movement.+ */+import { useEffect } from "react";+import { useReducedMotion } from "framer-motion";+import { useLocaleChunk } from "@/i18n";+import { useSocietyRoster } from "../../data";+import { useProgression, type Celebration } from "../../progression/progressionStore";+import { Insignia } from "./Insignia";+import { isPromotion } from "./levelModel";+import { fill, useLevelText } from "./levelText";+import { rankFor } from "./ranks";+import "./levels.css";++export const CEREMONY_MS = 6000;+export const TOAST_MS = 5000;+const MAX_VISIBLE_TOASTS = 3;++export function PromotionLayer() {+ useLocaleChunk("ship");+ const banner = useProgression((s) => s.banners[0]);+ const toasts = useProgression((s) => s.toasts);+ const reduced = !!useReducedMotion();+ const roster = useSocietyRoster();+ const agents = roster.data?.agents;+ const nameOf = (agentId: string) => agents?.find((a) => a.agentId === agentId)?.name ?? agentId;+ const companion = agents?.find((a) => a.tier === "lead")?.name ?? "Jarvis";+ if (!banner && toasts.length === 0) return null;+ return (+ <div className="promo-layer" data-reduced={reduced}>+ {banner && <Ceremony key={banner.id} party={banner} reduced={reduced} companion={companion} />}+ {toasts.length > 0 && (+ <div className="promo-toasts" role="status" aria-live="polite">+ {toasts.slice(-MAX_VISIBLE_TOASTS).map((toast) => <AgentToast key={toast.id} party={toast} name={nameOf(toast.subjectId.replace(/^agent:/, ""))} />)}+ </div>+ )}+ </div>+ );+}++function Ceremony({ party, reduced, companion }: { party: Celebration; reduced: boolean; companion: string }) {+ const text = useLevelText();+ const { t } = text;+ const dismiss = useProgression((s) => s.dismissBanner);+ const promoted = isPromotion(party.previousLevel, party.level);+ const before = rankFor(party.previousLevel), after = rankFor(party.level);++ useEffect(() => {+ const timer = setTimeout(dismiss, CEREMONY_MS);+ const onKey = (event: KeyboardEvent) => { if (event.key === "Escape") dismiss(); };+ document.addEventListener("keydown", onKey);+ return () => { clearTimeout(timer); document.removeEventListener("keydown", onKey); };+ }, [dismiss]);++ const eyebrow = party.away ? t("ship.levels.promotion.away")+ : promoted ? t("ship.levels.promotion.promoted") : t("ship.levels.promotion.level_up");+ const who = party.kind === "pet" ? `${t("ship.levels.who.companion")} · ${companion}` : t("ship.levels.who.captain");++ return (+ <div className="promo-scrim" onClick={dismiss}>+ <section className="promo-card" data-promotion={promoted} role="status" aria-live="polite"+ aria-label={`${eyebrow}: ${text.rank(after.id)}, ${text.level(party.level)}`} onClick={(e) => e.stopPropagation()}>+ <div className="lv-eyebrow">{eyebrow}</div>+ <div className="promo-who">{who}</div>+ <div className="promo-stage" aria-hidden="true">+ {promoted && !reduced && <span className="promo-old"><Insignia rank={before.id} size={80} /></span>}+ <span className="promo-new"><Insignia rank={after.id} size={96} /></span>+ </div>+ <h2 className="promo-rank">{text.rank(after.id)}</h2>+ <div className="promo-level">{text.level(party.level)}</div>+ {party.unlocked.length > 0 && (+ <div className="promo-open">+ <div className="lv-eyebrow">{t("ship.levels.promotion.now_open")}</div>+ <p>{party.unlocked.map((id) => text.reward(id)).join(" · ")}</p>+ </div>+ )}+ <button type="button" onClick={dismiss}>{t("ship.levels.promotion.continue")}</button>+ </section>+ </div>+ );+}++function AgentToast({ party, name }: { party: Celebration; name: string }) {+ const text = useLevelText();+ const { t } = text;+ const dismiss = useProgression((s) => s.dismissToast);+ useEffect(() => {+ const timer = setTimeout(() => dismiss(party.id), TOAST_MS);+ return () => clearTimeout(timer);+ }, [dismiss, party.id]);+ const rank = rankFor(party.level);+ const line = isPromotion(party.previousLevel, party.level)+ ? fill(t("ship.levels.promotion.agent_promoted"), { agent: name, rank: text.rank(rank.id) })+ : fill(t("ship.levels.promotion.agent_level"), { agent: name, n: party.level });+ return (+ <button type="button" className="promo-toast" onClick={() => dismiss(party.id)}>+ <Insignia rank={rank.id} size={24} />+ <span>{line}</span>+ </button>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/levels/RewardGlyph.tsx b/dodaios/ui/web/frontend/src/components/society/starship/levels/RewardGlyph.tsxnew file mode 100644index 0000000000..c4beff86b2--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/levels/RewardGlyph.tsx@@ -0,0 +1,122 @@+/**+ * Small pictures of what a level opens: the captain's suits as tunic+ * silhouettes in their cloth and trim, decorations as their ribbon (and medal),+ * destinations as a swatch painted in the destination's own sky and planet+ * colours from `space/destinations.ts`. 48-unit grid like the insignia.+ */+import { useId } from "react";+import { slotOf, type RewardId } from "../../progression/levelCatalog";+import { destinationById, type Destination } from "../space/destinations";+import { destinationOf } from "./levelModel";++const SUITS: Record<string, { cloth: string; shade: string; trim: string; plates?: boolean; buttons?: boolean; cuffs?: boolean }> = {+ suit_field_armor: { cloth: "#566270", shade: "#3a434e", trim: "#5fd4ff", plates: true },+ suit_command_coat: { cloth: "#232a36", shade: "#161b23", trim: "#d9a441" },+ suit_dress_whites: { cloth: "#eef1f5", shade: "#c9d0d8", trim: "#d9a441", buttons: true },+ suit_admiral_coat: { cloth: "#17284a", shade: "#0f1b33", trim: "#e1b04f", cuffs: true, buttons: true },+};++const RIBBONS: Record<string, { stripes: string[]; medal?: "disc" | "star" | "cross" }> = {+ decoration_service_ribbon: { stripes: ["#1e2a3a", "#5fd4ff", "#1e2a3a", "#d9a441", "#1e2a3a"] },+ decoration_commendation: { stripes: ["#2f6b4f", "#eef1f5", "#2f6b4f"], medal: "disc" },+ decoration_star_medal: { stripes: ["#17284a", "#d9a441", "#17284a"], medal: "star" },+ decoration_legion_of_merit: { stripes: ["#8c1c3a", "#eef1f5", "#8c1c3a"], medal: "cross" },+};++function Suit({ id }: { id: string }) {+ const s = SUITS[id] ?? SUITS.suit_command_coat;+ return (+ <g>+ {/* Tunic: shoulders, sleeves, body. */}+ <path d="M13 10 L19 7 L24 12 L29 7 L35 10 L41 20 L37 23 L35 19 L35 41 L13 41 L13 19 L11 23 L7 20 Z" fill={s.cloth} stroke={s.shade} strokeWidth="1" strokeLinejoin="round" />+ <path d="M19 7 L24 17 L29 7" fill="none" stroke={s.trim} strokeWidth="1.8" strokeLinejoin="round" />+ <line x1="24" y1="17" x2="24" y2="41" stroke={s.shade} strokeWidth="1" />+ {s.plates && <><rect x="15.5" y="21" width="7" height="8" rx="1.5" fill={s.shade} /><rect x="25.5" y="21" width="7" height="8" rx="1.5" fill={s.shade} /><line x1="13" y1="33" x2="35" y2="33" stroke={s.trim} strokeWidth="1" opacity="0.8" /></>}+ {s.buttons && [22, 27, 32, 37].map((y) => <circle key={y} cx="26.6" cy={y} r="0.95" fill={s.trim} />)}+ {s.cuffs && <><path d="M7 20 L11 23" stroke={s.trim} strokeWidth="2.2" /><path d="M41 20 L37 23" stroke={s.trim} strokeWidth="2.2" /><path d="M13 10 L19 7 M35 10 L29 7" stroke={s.trim} strokeWidth="2" /></>}+ </g>+ );+}++function Decoration({ id }: { id: string }) {+ const r = RIBBONS[id] ?? RIBBONS.decoration_service_ribbon;+ const w = 26 / r.stripes.length;+ const top = r.medal ? 7 : 18;+ return (+ <g>+ {r.stripes.map((c, i) => <rect key={i} x={11 + i * w} y={top} width={w + 0.05} height="10" fill={c} />)}+ <rect x="11" y={top} width="26" height="10" rx="1" fill="none" stroke="rgba(0,0,0,0.5)" strokeWidth="0.8" />+ {r.medal && <line x1="24" y1="17" x2="24" y2="23" stroke="#c8963c" strokeWidth="1.4" />}+ {r.medal === "disc" && <circle cx="24" cy="31" r="8" fill="#e1b04f" stroke="#a8741f" strokeWidth="1.2" />}+ {r.medal === "star" && <polygon points="24,22 26.6,28.4 33.5,28.9 28.2,33.3 29.9,40 24,36.3 18.1,40 19.8,33.3 14.5,28.9 21.4,28.4" fill="#e1b04f" stroke="#a8741f" strokeWidth="1" strokeLinejoin="round" />}+ {r.medal === "cross" && <path d="M24 22 L27 28 L33 31 L27 34 L24 40 L21 34 L15 31 L21 28 Z" fill="#eef1f5" stroke="#d9a441" strokeWidth="1.4" strokeLinejoin="round" />}+ </g>+ );+}++/** The destination's sky with its planet (or singularity) as a round swatch. */+export function DestinationSwatch({ destination, size = 40 }: { destination: Destination; size?: number }) {+ const uid = useId().replace(/:/g, "");+ const { planet, sky, sun, singularity } = destination;+ const [deep, mid, bright] = planet.colours;+ return (+ <svg className="svc-glyph" width={size} height={size} viewBox="0 0 48 48" aria-hidden="true">+ <defs>+ <radialGradient id={`${uid}k`} cx="0.3" cy="0.25" r="0.95">+ <stop offset="0" stopColor={sky.nebula[1]} stopOpacity={0.35 + sky.nebulaStrength * 0.5} />+ <stop offset="0.6" stopColor={sky.nebula[0]} stopOpacity={0.25 + sky.nebulaStrength * 0.55} />+ <stop offset="1" stopColor="#04060b" />+ </radialGradient>+ <radialGradient id={`${uid}p`} cx="0.35" cy="0.3" r="0.8">+ <stop offset="0" stopColor={bright} />+ <stop offset="0.45" stopColor={mid} />+ <stop offset="1" stopColor={deep} />+ </radialGradient>+ <clipPath id={`${uid}c`}><circle cx="24" cy="24" r="22" /></clipPath>+ </defs>+ <g clipPath={`url(#${uid}c)`}>+ <rect width="48" height="48" fill="#04060b" />+ <rect width="48" height="48" fill={`url(#${uid}k)`} />+ {[[9, 12], [36, 9], [40, 30], [14, 37], [28, 15], [20, 26]].map(([x, y], i) => <circle key={i} cx={x} cy={y} r={i % 2 ? 0.6 : 0.9} fill="#fff" opacity="0.75" />)}+ <circle cx="35" cy="12" r={2.2 * sun.size} fill={sun.colour} opacity="0.9" />+ {sun.twin && <circle cx="40" cy="18" r="1.6" fill={sun.colour} opacity="0.8" />}+ {singularity && (+ <g>+ <ellipse cx="24" cy="27" rx="15" ry="3.4" fill="none" stroke={sun.colour} strokeWidth="1.6" opacity="0.85" />+ <circle cx="24" cy="27" r="7" fill="#000" stroke={sun.colour} strokeOpacity="0.5" strokeWidth="0.8" />+ </g>+ )}+ {planet.kind !== "none" && (+ <g>+ <circle cx="20" cy="44" r="21" fill={`url(#${uid}p)`} />+ <circle cx="20" cy="44" r="21" fill="none" stroke={planet.atmosphere} strokeOpacity="0.6" strokeWidth="1.4" />+ {planet.rings && <ellipse cx="20" cy="40" rx="27" ry="4" fill="none" stroke={planet.rings.colour} strokeOpacity="0.75" strokeWidth="1.3" />}+ </g>+ )}+ </g>+ <circle cx="24" cy="24" r="22" fill="none" stroke="rgba(255,255,255,0.14)" />+ </svg>+ );+}++/** The picture of any reward; `home` paints the ship's home orbit. */+export function RewardGlyph({ reward, size = 40 }: { reward: RewardId | "home"; size?: number }) {+ if (reward === "home") return <DestinationSwatch destination={destinationById("home")} size={size} />;+ const destination = destinationOf(reward);+ if (destination) return <DestinationSwatch destination={destination} size={size} />;+ return (+ <svg className="svc-glyph" width={size} height={size} viewBox="0 0 48 48" aria-hidden="true">+ {slotOf(reward) === "suit" ? <Suit id={reward} /> : <Decoration id={reward} />}+ </svg>+ );+}++/** "Own clothes" / "Automatic" in the suit choice: a plain or a starred tunic outline. */+export function SuitOutline({ starred, size = 40 }: { starred: boolean; size?: number }) {+ return (+ <svg className="svc-glyph" width={size} height={size} viewBox="0 0 48 48" aria-hidden="true">+ <path d="M13 10 L19 7 L24 12 L29 7 L35 10 L41 20 L37 23 L35 19 L35 41 L13 41 L13 19 L11 23 L7 20 Z" fill="none" stroke="#5c6878" strokeWidth="1.4" strokeLinejoin="round" />+ {starred && <polygon points="24,20 25.8,24.4 30.5,24.7 26.9,27.7 28,32.3 24,29.8 20,32.3 21.1,27.7 17.5,24.7 22.2,24.4" fill="#d9a441" />}+ </svg>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/levels/ServiceRecord.tsx b/dodaios/ui/web/frontend/src/components/society/starship/levels/ServiceRecord.tsxnew file mode 100644index 0000000000..4b8b7612ac--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/levels/ServiceRecord.tsx@@ -0,0 +1,407 @@+/**+ * The captain's service record: one dialog for everything the level system+ * knows. Record (where you stand, what comes next, the ship's log), Ranks (the+ * whole ladder), Rewards (suits, destinations, decorations), How to earn+ * (every rule in plain words) and Crew (every android's rank).+ *+ * It replaces the office tower's Level Hall screen. One hierarchy per page,+ * hairlines instead of boxes, gold only on what the captain holds or earns.+ * Accessible: a modal dialog with a focus trap, Escape closes, tabs and+ * choices are real buttons with arrow-key navigation.+ */+import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type ReactElement } from "react";+import { Lock, Volume2, VolumeX, X } from "lucide-react";+import { useLocaleChunk } from "@/i18n";+import { useSocietyRoster } from "../../data";+import { useLevelSound } from "../../progression/levelSounds";+import { suitFor, type SuitChoice } from "../../progression/cosmetics";+import { petSubject, PERSON_SUBJECT } from "../../progression/progressionApi";+import { SERVICE_TABS, useProgression, type ServiceTab } from "../../progression/progressionStore";+import type { SuitId } from "../../progression/levelCatalog";+import { useShip } from "../shipStore";+import { DESTINATIONS } from "../space/destinations";+import { Insignia } from "./Insignia";+import { crewRanking, nextReward, rankLadder, rewardShelves, ruleGroups, shipLog, xpToReach } from "./levelModel";+import { fill, useLevelText, type LevelText } from "./levelText";+import { nextRank, rankFor } from "./ranks";+import { DestinationSwatch, RewardGlyph, SuitOutline } from "./RewardGlyph";+import "./levels.css";++export interface ServiceRecordProps {+ onClose: () => void;+ initialTab?: ServiceTab;+}++const FOCUSABLE = 'button:not([disabled]), [href], input:not([disabled]), select, textarea, [tabindex]:not([tabindex="-1"])';++export function ServiceRecord({ onClose, initialTab = "record" }: ServiceRecordProps) {+ useLocaleChunk("ship");+ const text = useLevelText();+ const { t } = text;+ const [tab, setTab] = useState<ServiceTab>(initialTab);+ const dialogRef = useRef<HTMLDivElement>(null);+ const tabRefs = useRef<Partial<Record<ServiceTab, HTMLButtonElement | null>>>({});+ const ids = useId();+ const sound = useLevelSound();++ // Focus the open tab; give focus back to whatever opened the record.+ useEffect(() => {+ const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;+ tabRefs.current[initialTab]?.focus();+ return () => { opener?.focus?.(); };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {+ // Keys typed in the record never steer the captain.+ event.stopPropagation();+ if (event.key === "Escape") { event.preventDefault(); onClose(); return; }+ if (event.key !== "Tab" || !dialogRef.current) return;+ const nodes = [...dialogRef.current.querySelectorAll<HTMLElement>(FOCUSABLE)];+ if (nodes.length === 0) return;+ const first = nodes[0], last = nodes[nodes.length - 1];+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }+ };++ const onTabKey = (event: KeyboardEvent<HTMLButtonElement>) => {+ const at = SERVICE_TABS.indexOf(tab);+ const to = event.key === "ArrowRight" ? (at + 1) % SERVICE_TABS.length+ : event.key === "ArrowLeft" ? (at - 1 + SERVICE_TABS.length) % SERVICE_TABS.length+ : event.key === "Home" ? 0 : event.key === "End" ? SERVICE_TABS.length - 1 : -1;+ if (to < 0) return;+ event.preventDefault();+ setTab(SERVICE_TABS[to]);+ tabRefs.current[SERVICE_TABS[to]]?.focus();+ };++ return (+ <div className="svc-scrim" onKeyDown={onKeyDown} onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>+ <div ref={dialogRef} className="svc" role="dialog" aria-modal="true" aria-labelledby={`${ids}-title`}>+ <header className="svc-head">+ <h2 id={`${ids}-title`} className="svc-title">{t("ship.levels.record")}</h2>+ <div className="svc-head-tools">+ <button type="button" className="svc-icon" aria-pressed={sound.on} aria-label={t("ship.levels.sound")} title={t("ship.levels.sound")} onClick={() => sound.set(!sound.on)}>+ {sound.on ? <Volume2 size={16} /> : <VolumeX size={16} />}+ </button>+ <button type="button" className="svc-icon" aria-label={t("ship.levels.close")} title={t("ship.levels.close")} onClick={onClose}><X size={17} /></button>+ </div>+ </header>+ <div className="svc-tabs" role="tablist" aria-label={t("ship.levels.tabs.label")}>+ {SERVICE_TABS.map((id) => (+ <button key={id} ref={(el) => { tabRefs.current[id] = el; }} type="button" role="tab" className="svc-tab"+ id={`${ids}-tab-${id}`} aria-selected={tab === id} aria-controls={`${ids}-panel`} tabIndex={tab === id ? 0 : -1}+ onClick={() => setTab(id)} onKeyDown={onTabKey}>+ {t(`ship.levels.tabs.${id}`)}+ </button>+ ))}+ </div>+ <div className="svc-body" role="tabpanel" id={`${ids}-panel`} aria-labelledby={`${ids}-tab-${tab}`} tabIndex={0}>+ {tab === "record" && <RecordPage text={text} />}+ {tab === "ranks" && <RanksPage text={text} />}+ {tab === "rewards" && <RewardsPage text={text} />}+ {tab === "earn" && <EarnPage text={text} />}+ {tab === "crew" && <CrewPage text={text} />}+ </div>+ </div>+ </div>+ );+}++/** The captain's level and the curve; level 1 with no XP until the first read. */+function useCaptain() {+ const person = useProgression((s) => s.subjects[PERSON_SUBJECT]);+ const snapshot = useProgression((s) => s.snapshot);+ return { level: person?.level ?? 1, xp: person?.xp ?? 0, person, snapshot, levelXp: snapshot?.levelXp ?? [] };+}++/** The companion's name: the lead on the roster (the pet IS Jarvis aboard). */+function useCompanionName(): string {+ const roster = useSocietyRoster();+ return roster.data?.agents.find((a) => a.tier === "lead")?.name ?? "Jarvis";+}++// ------------------------------------------------------------------ Record++function RecordPage({ text }: { text: LevelText }) {+ const { t, num } = text;+ const { level, xp, person, snapshot, levelXp } = useCaptain();+ const petId = useProgression((s) => s.petId);+ const companion = useCompanionName();+ const rank = rankFor(level);+ const next = nextRank(level);+ const reward = snapshot ? nextReward(snapshot.rewards, "person", level) : null;+ const atCap = !!person && person.xpForNext <= 0 && level > 1;+ const share = person && person.xpForNext > 0 ? Math.min(1, person.xpIntoLevel / person.xpForNext) : atCap ? 1 : 0;+ const log = useMemo(() => (snapshot ? shipLog(snapshot.recent, new Set([PERSON_SUBJECT, petSubject(petId)])) : []), [snapshot, petId]);+ const toNext = next ? xpToReach(levelXp, xp, next.level) : null;+ const toReward = reward ? xpToReach(levelXp, xp, reward.level) : null;++ return (+ <div className="svc-record">+ <section className="svc-plate" aria-label={t("ship.levels.who.captain")}>+ <div className="svc-plate-insignia"><Insignia rank={rank.id} size={84} title={text.rank(rank.id)} /></div>+ <span className="lv-eyebrow">{t("ship.levels.who.captain")} · {t(`ship.levels.tier.${rank.tier}`)}</span>+ <div className="svc-rank">{text.rank(rank.id)}</div>+ <div className="svc-level"><b>{text.level(level)}</b>{person ? <> · {fill(t("ship.levels.xp"), { n: num(person.xp) })}</> : null}</div>+ <div className="lv-bar" role="progressbar" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(share * 100)} aria-label={text.level(level)}>+ <i style={{ width: `${Math.round(share * 100)}%` }} />+ </div>+ <div className="lv-bar-legend">+ {atCap ? <span>{t("ship.levels.at_cap")}</span> : (+ <>+ <span>{fill(t("ship.levels.xp_progress"), { have: num(person?.xpIntoLevel ?? 0), need: num(person?.xpForNext ?? 0) })}</span>+ {person && <span>{fill(t("ship.levels.xp_missing"), { n: num(Math.max(0, person.xpForNext - person.xpIntoLevel)), level: level + 1 })}</span>}+ </>+ )}+ </div>+ <div className="svc-next">+ <div className="svc-next-row">+ <span className="lv-eyebrow">{t("ship.levels.next_promotion")}</span>+ {next ? (+ <>+ <Insignia rank={next.id} size={30} tone="muted" />+ <div>+ <strong>{fill(t("ship.levels.next_promotion_line"), { rank: text.rank(next.id), level: next.level })}</strong>+ {toNext !== null && <span>{text.xpToGo(toNext)}</span>}+ </div>+ </>+ ) : <div style={{ gridColumn: "1 / -1" }}><span>{t("ship.levels.top_rank")}</span></div>}+ </div>+ <div className="svc-next-row">+ <span className="lv-eyebrow">{t("ship.levels.next_reward")}</span>+ {reward ? (+ <>+ <RewardGlyph reward={reward.reward.rewardId} size={30} />+ <div>+ <strong>{fill(t("ship.levels.next_reward_line"), { reward: text.reward(reward.reward.rewardId), level: reward.level })}</strong>+ {toReward !== null && <span>{text.xpToGo(toReward)}</span>}+ </div>+ </>+ ) : <div style={{ gridColumn: "1 / -1" }}><span>{snapshot ? t("ship.levels.all_open") : t("ship.levels.unavailable")}</span></div>}+ </div>+ </div>+ </section>+ <section className="svc-log" aria-labelledby="svc-log-title">+ <h3 id="svc-log-title" className="lv-eyebrow">{t("ship.levels.log")}</h3>+ {!snapshot ? <p className="svc-empty">{t("ship.levels.unavailable")}</p>+ : log.length === 0 ? <p className="svc-empty">{t("ship.levels.log_empty")}</p> : (+ <ol>+ {log.map((entry) => {+ const mark = entry.line.kind === "promoted" || entry.line.kind === "level";+ return (+ <li key={entry.seq} data-mark={mark}>+ <time dateTime={new Date(entry.tsMs).toISOString()}>{text.when(entry.tsMs)}</time>+ <span>+ {entry.subjectId !== PERSON_SUBJECT && <span className="who">{companion}</span>}+ <span className="what">+ {entry.line.kind === "promoted" && <Insignia rank={entry.line.rank} size={18} />}+ {text.logLine(entry.line)}+ </span>+ </span>+ <span className="xp">+{num(entry.xp)}</span>+ </li>+ );+ })}+ </ol>+ )}+ </section>+ </div>+ );+}++// ------------------------------------------------------------------ Ranks++function RanksPage({ text }: { text: LevelText }) {+ const { t } = text;+ const { level, xp, levelXp } = useCaptain();+ const groups = useMemo(() => rankLadder(level, xp, levelXp), [level, xp, levelXp]);+ return (+ <div>+ {groups.map((group) => (+ <section key={group.tier} className="svc-tier" aria-labelledby={`svc-tier-${group.tier}`}>+ <div className="svc-tier-head">+ <h3 id={`svc-tier-${group.tier}`} className="lv-eyebrow">{t(`ship.levels.tier.${group.tier}`)}</h3>+ <p>{t(`ship.levels.tier_about.${group.tier}`)}</p>+ </div>+ <ol className="svc-rungs">+ {group.rungs.map(({ rank, state, xpToGo }) => (+ <li key={rank.id} className="svc-rung" data-state={state} aria-current={state === "current" ? "true" : undefined}>+ <span className="svc-node" aria-hidden="true" />+ <Insignia rank={rank.id} size={40} tone={state === "ahead" ? "muted" : "metal"} />+ <span className="svc-rung-name">{text.rank(rank.id)}<small>{text.level(rank.level)}</small></span>+ <span className="svc-rung-state">+ {state === "current" ? <span className="svc-tag">{t("ship.levels.rank_current")}</span>+ : state === "held" ? t("ship.levels.rank_held")+ : xpToGo !== null ? text.xpToGo(xpToGo) : ""}+ </span>+ </li>+ ))}+ </ol>+ </section>+ ))}+ </div>+ );+}++// ------------------------------------------------------------------ Rewards++function RewardsPage({ text }: { text: LevelText }) {+ const { t } = text;+ const { level, xp, snapshot, levelXp } = useCaptain();+ const choice = useProgression((s) => s.suit);+ const course = useShip((s) => s.destination);+ const shelves = useMemo(() => (snapshot ? rewardShelves(snapshot.rewards, level, xp, levelXp) : []), [snapshot, level, xp, levelXp]);+ if (!snapshot) return <p className="svc-empty">{t("ship.levels.unavailable")}</p>;+ const worn = suitFor(snapshot.rewards, level, choice);+ const state = (open: boolean, at: number, toGo: number | null) => (open ? t("ship.levels.open_state")+ : `${fill(t("ship.levels.opens_at"), { n: at })}${toGo !== null ? ` · ${text.xpToGo(toGo)}` : ""}`);++ return (+ <div>+ {shelves.map((shelf) => (+ <section key={shelf.slot} className="svc-section" aria-labelledby={`svc-shelf-${shelf.slot}`}>+ <h3 id={`svc-shelf-${shelf.slot}`} className="lv-eyebrow">{t(`ship.levels.rewards.${shelf.slot}`)}</h3>+ <p>{t(`ship.levels.rewards.${shelf.slot}_about`)}</p>+ {shelf.slot === "suit" ? (+ <SuitChoices text={text} choice={choice} worn={worn}+ suits={shelf.items.map((item) => ({ id: item.reward.rewardId as SuitId, open: item.open, state: state(item.open, item.level, item.xpToGo) }))} />+ ) : (+ <ul className="svc-list">+ {shelf.slot === "destination" && (+ <li className="svc-item" data-open="true">+ <DestinationSwatch destination={DESTINATIONS[0]} />+ <span className="svc-item-name">{t("ship.levels.home")}<small>{text.level(1)}</small></span>+ <span className="svc-item-state">{course === "home" ? <span className="svc-tag" data-tone="info">{t("ship.levels.current_course")}</span> : t("ship.levels.open_state")}</span>+ </li>+ )}+ {shelf.items.map((item) => {+ const isCourse = shelf.slot === "destination" && `destination_${course}` === item.reward.rewardId;+ return (+ <li key={item.reward.rewardId} className="svc-item" data-open={item.open}>+ <RewardGlyph reward={item.reward.rewardId} />+ <span className="svc-item-name">{text.reward(item.reward.rewardId)}<small>{text.level(item.level)}</small></span>+ <span className="svc-item-state">+ {isCourse ? <span className="svc-tag" data-tone="info">{t("ship.levels.current_course")}</span> : state(item.open, item.level, item.xpToGo)}+ {!item.open && <Lock size={12} style={{ marginLeft: 6, verticalAlign: -1 }} aria-hidden="true" />}+ </span>+ </li>+ );+ })}+ </ul>+ )}+ </section>+ ))}+ </div>+ );+}++function SuitChoices({ text, choice, worn, suits }: {+ text: LevelText; choice: SuitChoice; worn: SuitId | null; suits: { id: SuitId; open: boolean; state: string }[];+}) {+ const { t } = text;+ const chooseSuit = useProgression((s) => s.chooseSuit);+ const options: { value: SuitChoice; open: boolean; name: string; sub: string; state: string; glyph: ReactElement }[] = [+ { value: "auto", open: true, name: t("ship.levels.auto"), sub: t("ship.levels.auto_about"), state: "", glyph: <SuitOutline starred /> },+ { value: "none", open: true, name: t("ship.levels.own"), sub: t("ship.levels.own_about"), state: "", glyph: <SuitOutline starred={false} /> },+ ...suits.map((s) => ({ value: s.id as SuitChoice, open: s.open, name: text.reward(s.id), sub: s.state, state: s.id === worn ? t("ship.levels.wearing") : "", glyph: <RewardGlyph reward={s.id} /> })),+ ];+ const refs = useRef<(HTMLButtonElement | null)[]>([]);+ const onKey = (event: KeyboardEvent<HTMLButtonElement>, index: number) => {+ const step = event.key === "ArrowDown" || event.key === "ArrowRight" ? 1 : event.key === "ArrowUp" || event.key === "ArrowLeft" ? -1 : 0;+ if (!step) return;+ event.preventDefault();+ for (let i = 1; i <= options.length; i += 1) {+ const at = (index + step * i + options.length) % options.length;+ if (options[at].open) { chooseSuit(options[at].value); refs.current[at]?.focus(); return; }+ }+ };+ const checkedIndex = Math.max(0, options.findIndex((o) => o.value === choice));+ return (+ <div role="radiogroup" aria-label={t("ship.levels.suit_choice")}>+ {options.map((o, i) => (+ <button key={o.value} ref={(el) => { refs.current[i] = el; }} type="button" role="radio" className="svc-item svc-choice"+ aria-checked={o.value === choice} aria-disabled={!o.open} data-open={o.open} tabIndex={i === checkedIndex ? 0 : -1}+ onClick={() => { if (o.open) chooseSuit(o.value); }} onKeyDown={(e) => onKey(e, i)}>+ {o.glyph}+ <span className="svc-item-name"><span className="svc-radio" aria-hidden="true" />{o.name}<small>{o.sub}</small></span>+ <span className="svc-item-state">{o.state ? <span className="svc-tag">{o.state}</span> : !o.open ? <Lock size={12} aria-hidden="true" /> : null}</span>+ </button>+ ))}+ </div>+ );+}++// ------------------------------------------------------------------ How to earn++function EarnPage({ text }: { text: LevelText }) {+ const { t, num } = text;+ const snapshot = useProgression((s) => s.snapshot);+ const groups = useMemo(() => ruleGroups(snapshot?.rules ?? []), [snapshot]);+ if (groups.length === 0) return <p className="svc-empty">{t("ship.levels.unavailable")}</p>;+ return (+ <div>+ <p className="svc-lead">{t("ship.levels.earn.lead")}</p>+ {groups.map((group) => (+ <section key={group.kind} className="svc-section" aria-labelledby={`svc-earn-${group.kind}`}>+ <h3 id={`svc-earn-${group.kind}`} className="lv-eyebrow">{t(`ship.levels.earn.${group.kind}`)}</h3>+ <table className="svc-rules">+ <tbody>+ {group.rules.map(({ rule, limit }) => (+ <tr key={rule.source}>+ <td>{t(`ship.levels.rule.${rule.source}`)}</td>+ <td className="limit">{text.limit(limit)}</td>+ <td className="amount">+{num(rule.xp)} XP</td>+ </tr>+ ))}+ </tbody>+ </table>+ </section>+ ))}+ </div>+ );+}++// ------------------------------------------------------------------ Crew++function CrewPage({ text }: { text: LevelText }) {+ const { t } = text;+ const roster = useSocietyRoster();+ const subjects = useProgression((s) => s.subjects);+ const petId = useProgression((s) => s.petId);+ const crew = useMemo(() => crewRanking(roster.data?.agents ?? [], subjects), [roster.data, subjects]);+ const lead = roster.data?.agents.find((a) => a.tier === "lead");+ const petLevel = subjects[petSubject(petId)]?.level ?? 1;+ const petRank = rankFor(petLevel);+ return (+ <div>+ <section className="svc-section" aria-label={t("ship.levels.who.companion")}>+ <h3 className="lv-eyebrow">{t("ship.levels.who.companion")}</h3>+ <ul className="svc-list svc-crew">+ <li className="svc-item">+ <span className="pos" aria-hidden="true" />+ <Insignia rank={petRank.id} size={32} />+ <span className="svc-item-name">{lead?.name ?? "Jarvis"}<small>{text.rank(petRank.id)}</small></span>+ <span className="svc-item-state">{text.level(petLevel)}</span>+ </li>+ </ul>+ </section>+ <section className="svc-section" aria-label={t("ship.levels.who.crew")}>+ <h3 className="lv-eyebrow">{t("ship.levels.who.crew")}</h3>+ <p>{t("ship.levels.crew.about")}</p>+ {crew.length === 0 ? <p className="svc-empty">{t("ship.levels.crew.empty")}</p> : (+ <ol className="svc-list svc-crew">+ {crew.map((row, i) => (+ <li key={row.agentId} className="svc-item">+ <span className="pos">{i + 1}</span>+ <Insignia rank={row.rank.id} size={32} />+ <span className="svc-item-name">{row.name}<small>{text.rank(row.rank.id)}</small></span>+ <span className="svc-item-state">{text.level(row.level)}</span>+ </li>+ ))}+ </ol>+ )}+ </section>+ </div>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/levels/levelModel.ts b/dodaios/ui/web/frontend/src/components/society/starship/levels/levelModel.tsnew file mode 100644index 0000000000..26ff2a107b--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/levels/levelModel.ts@@ -0,0 +1,200 @@+/**+ * The pure side of the ship's level UI: what an insignia shows, the ladder+ * with the viewer's place on it, the rewards per shelf, the ship's log and+ * the rules in plain groups. The service record and the promotion ceremony+ * only lay these out; tests check them without a DOM.+ */+import type { RewardRow, AwardRow, SubjectLevel, XpRuleRow } from "../../progression/progressionApi";+import { rewardKey, slotOf, type RewardId, type Slot, type SubjectKind } from "../../progression/levelCatalog";+import { RANKS, rankFor, type Rank, type RankTier } from "./ranks";+import { destinationById, type Destination } from "../space/destinations";++// ------------------------------------------------------------------ insignia++/**+ * How a rank's insignia is drawn. Enlisted: silver chevrons (cadet an empty+ * bar, chief petty officer three chevrons over a rocker). Warrant: one gold+ * pip on a silver-edged bar. Officers: gold pips, some hollow. Flag: a gold+ * bar under one to four stars.+ */+export type InsigniaSpec =+ | { kind: "bar" }+ | { kind: "chevrons"; count: number; rocker: boolean }+ | { kind: "pips"; solid: number; hollow: number; warrant: boolean }+ | { kind: "flag"; stars: number };++const INSIGNIA: Record<string, InsigniaSpec> = {+ cadet: { kind: "bar" },+ crewman: { kind: "chevrons", count: 1, rocker: false },+ specialist: { kind: "chevrons", count: 2, rocker: false },+ petty_officer: { kind: "chevrons", count: 3, rocker: false },+ chief_petty_officer: { kind: "chevrons", count: 3, rocker: true },+ warrant_officer: { kind: "pips", solid: 1, hollow: 0, warrant: true },+ ensign: { kind: "pips", solid: 1, hollow: 0, warrant: false },+ lieutenant_junior_grade: { kind: "pips", solid: 1, hollow: 1, warrant: false },+ lieutenant: { kind: "pips", solid: 2, hollow: 0, warrant: false },+ lieutenant_commander: { kind: "pips", solid: 2, hollow: 1, warrant: false },+ commander: { kind: "pips", solid: 3, hollow: 0, warrant: false },+ captain: { kind: "pips", solid: 4, hollow: 0, warrant: false },+ commodore: { kind: "flag", stars: 1 },+ rear_admiral: { kind: "flag", stars: 2 },+ vice_admiral: { kind: "flag", stars: 3 },+ admiral: { kind: "flag", stars: 4 },+};++/** The insignia of a rank id; an id this build does not know wears the cadet's bar. */+export function insigniaFor(rankId: string): InsigniaSpec {+ return INSIGNIA[rankId] ?? INSIGNIA.cadet;+}++export function isPromotion(previousLevel: number, level: number): boolean {+ return rankFor(level).id !== rankFor(previousLevel).id;+}++// ------------------------------------------------------------------ XP++/** Total XP at which `level` starts, from the server's curve (0 before it arrives). */+export function levelStartXp(levelXp: readonly number[], level: number): number {+ return levelXp[Math.max(0, level - 1)] ?? 0;+}++/** XP still missing until `level` (0 once reached; null when the curve does not reach it). */+export function xpToReach(levelXp: readonly number[], totalXp: number, level: number): number | null {+ const at = levelXp[level - 1];+ if (at === undefined) return null;+ return Math.max(0, at - totalXp);+}++// ------------------------------------------------------------------ ranks++export type RungState = "held" | "current" | "ahead";+export interface Rung { rank: Rank; state: RungState; xpToGo: number | null }+export interface TierGroup { tier: RankTier; rungs: Rung[] }++export const TIER_ORDER: readonly RankTier[] = ["enlisted", "warrant", "officer", "flag"];++/** The whole ladder grouped by tier, with the viewer's place on it. */+export function rankLadder(level: number, totalXp: number, levelXp: readonly number[]): TierGroup[] {+ const current = rankFor(level).id;+ return TIER_ORDER.map((tier) => ({+ tier,+ rungs: RANKS.filter((r) => r.tier === tier).map((rank) => ({+ rank,+ state: rank.id === current ? "current" : rank.level <= level ? "held" : "ahead",+ xpToGo: rank.level > level ? xpToReach(levelXp, totalXp, rank.level) : null,+ })),+ }));+}++// ------------------------------------------------------------------ rewards++export interface Shelf { slot: Slot; items: { reward: RewardRow; level: number; open: boolean; xpToGo: number | null }[] }++/** What the captain can earn, one shelf per slot, each in the order it opens. */+export function rewardShelves(rewards: readonly RewardRow[], level: number, totalXp: number, levelXp: readonly number[]): Shelf[] {+ const slots: Slot[] = ["suit", "destination", "decoration"];+ return slots.map((slot) => ({+ slot,+ items: rewards+ .filter((r) => r.slot === slot && r.levels.person !== null)+ .sort((a, b) => (a.levels.person ?? 0) - (b.levels.person ?? 0))+ .map((reward) => {+ const at = reward.levels.person ?? 0;+ return { reward, level: at, open: level >= at, xpToGo: level >= at ? null : xpToReach(levelXp, totalXp, at) };+ }),+ })).filter((shelf) => shelf.items.length > 0);+}++/** The next reward a kind opens above `level`. */+export function nextReward(rewards: readonly RewardRow[], kind: SubjectKind, level: number): { reward: RewardRow; level: number } | null {+ let best: { reward: RewardRow; level: number } | null = null;+ for (const reward of rewards) {+ const at = reward.levels[kind];+ if (at === null || at <= level) continue;+ if (!best || at < best.level) best = { reward, level: at };+ }+ return best;+}++/** A destination reward's helm destination (the colours its swatch is painted in). */+export function destinationOf(reward: RewardId): Destination | null {+ return slotOf(reward) === "destination" ? destinationById(rewardKey(reward)) : null;+}++// ------------------------------------------------------------------ the ship's log++export type LogLine =+ | { kind: "promoted"; rank: string }+ | { kind: "level"; level: number }+ | { kind: "warp"; destination: string }+ | { kind: "deck"; deck: string }+ | { kind: "source"; source: string };++export interface LogEntry { seq: number; subjectId: string; tsMs: number; xp: number; line: LogLine }++/**+ * The captain's and the companion's latest awards, newest first, each in+ * plain words. A level-up reads as the level (or the promotion) it brought;+ * a source this build no longer knows is still listed.+ */+export function shipLog(recent: readonly AwardRow[], subjectIds: ReadonlySet<string>, limit = 14): LogEntry[] {+ const out: LogEntry[] = [];+ for (let i = recent.length - 1; i >= 0 && out.length < limit; i -= 1) {+ const row = recent[i];+ if (!subjectIds.has(row.subjectId)) continue;+ let line: LogLine;+ if (row.levelAfter > row.levelBefore) {+ line = isPromotion(row.levelBefore, row.levelAfter) ? { kind: "promoted", rank: rankFor(row.levelAfter).id } : { kind: "level", level: row.levelAfter };+ } else if (row.source === "warp_jump" && row.ref) {+ line = { kind: "warp", destination: row.ref.split("@")[0] };+ } else if (row.source === "deck_discovered" && row.ref) {+ line = { kind: "deck", deck: row.ref };+ } else {+ line = { kind: "source", source: row.source };+ }+ out.push({ seq: row.seq, subjectId: row.subjectId, tsMs: row.tsMs, xp: row.xp, line });+ }+ return out;+}++// ------------------------------------------------------------------ rules++export type RuleLimit =+ | { kind: "once_day" }+ | { kind: "once_deck" }+ | { kind: "metered"; cooldownS: number; dailyCap: number }+ | { kind: "none" };++export interface RuleGroup { kind: SubjectKind; rules: { rule: XpRuleRow; limit: RuleLimit }[] }++export function ruleLimit(rule: XpRuleRow): RuleLimit {+ if (rule.source === "daily_visit") return { kind: "once_day" };+ if (rule.source === "deck_discovered") return { kind: "once_deck" };+ if (rule.cooldownS > 0 || rule.dailyCap > 0) return { kind: "metered", cooldownS: rule.cooldownS, dailyCap: rule.dailyCap };+ return { kind: "none" };+}++/** Every rule for the captain, the companion and the crew, the richest first within a group. */+export function ruleGroups(rules: readonly XpRuleRow[]): RuleGroup[] {+ const kinds: SubjectKind[] = ["person", "pet", "agent"];+ return kinds.map((kind) => ({+ kind,+ rules: rules.filter((r) => r.kind === kind).sort((a, b) => b.xp - a.xp).map((rule) => ({ rule, limit: ruleLimit(rule) })),+ })).filter((g) => g.rules.length > 0);+}++// ------------------------------------------------------------------ crew++export interface CrewRow { agentId: string; name: string; level: number; xp: number; rank: Rank }++/** Every android's rank, best first (level, then XP, then name). */+export function crewRanking(agents: readonly { agentId: string; name: string; tier: string }[], subjects: Readonly<Record<string, SubjectLevel>>): CrewRow[] {+ return agents+ .filter((a) => a.tier !== "lead")+ .map((a) => {+ const s = subjects[`agent:${a.agentId}`];+ const level = s?.level ?? 1;+ return { agentId: a.agentId, name: a.name, level, xp: s?.xp ?? 0, rank: rankFor(level) };+ })+ .sort((a, b) => b.level - a.level || b.xp - a.xp || a.name.localeCompare(b.name));+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/levels/levelText.ts b/dodaios/ui/web/frontend/src/components/society/starship/levels/levelText.tsnew file mode 100644index 0000000000..dfd68c4441--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/levels/levelText.ts@@ -0,0 +1,73 @@+/**+ * Words for the level UI: rank, reward and source names, limits and log+ * lines in the UI language (`ship.levels.*`, `ship.rank.*`, `ship.deck.*`).+ * A source the ledger still carries from the office tower reads in its old+ * words; anything unknown reads as "Earned XP", never as a raw key.+ */+import { useMemo } from "react";+import { useT } from "@/i18n";+import { useRunLocale } from "@/components/runs/format";+import { isXpSource } from "../../progression/levelCatalog";+import type { LogLine, RuleLimit } from "./levelModel";++/** The office tower's sources, still in old ledgers (`ship.levels.legacy_source.*`). */+export const LEGACY_SOURCES = ["floor_discovered", "dog_petted", "dog_treat", "arcade_round", "arcade_record", "team_meeting"] as const;++export function fill(template: string, vars: Record<string, string | number>): string {+ return template.replace(/\{(\w+)\}/g, (all, key: string) => (key in vars ? String(vars[key]) : all));+}++/** The i18n key a ledger source reads with. */+export function sourceKey(source: string): string {+ if (isXpSource(source)) return `ship.levels.source.${source}`;+ if ((LEGACY_SOURCES as readonly string[]).includes(source)) return `ship.levels.legacy_source.${source}`;+ return "ship.levels.legacy_source.other";+}++const DAY_MS = 86_400_000;++export function useLevelText() {+ const t = useT();+ const locale = useRunLocale();+ return useMemo(() => {+ const num = (n: number) => n.toLocaleString(locale);+ const rank = (id: string) => t(`ship.rank.${id}`);+ const reward = (id: string) => t(`ship.levels.reward.${id}`);+ const place = (destination: string) => (destination === "home" ? t("ship.levels.home") : reward(`destination_${destination}`));+ const duration = (s: number) => (s < 60 ? fill(t("ship.levels.earn.seconds"), { n: s }) : fill(t("ship.levels.earn.minutes"), { n: Math.round(s / 60) }));+ return {+ t, num, rank, reward, place,+ level: (n: number) => fill(t("ship.levels.level"), { n }),+ xpToGo: (n: number) => fill(t("ship.levels.to_go"), { n: num(n) }),+ source: (source: string) => t(sourceKey(source)),+ limit: (limit: RuleLimit): string => {+ if (limit.kind === "once_day") return t("ship.levels.earn.once_day");+ if (limit.kind === "once_deck") return t("ship.levels.earn.once_deck");+ if (limit.kind === "none") return "";+ const parts: string[] = [];+ if (limit.cooldownS > 0) parts.push(fill(t("ship.levels.earn.every"), { t: duration(limit.cooldownS) }));+ if (limit.dailyCap > 0) parts.push(fill(t("ship.levels.earn.per_day"), { n: num(limit.dailyCap) }));+ return parts.join(", ");+ },+ logLine: (line: LogLine): string => {+ switch (line.kind) {+ case "promoted": return fill(t("ship.levels.log_promoted"), { rank: rank(line.rank) });+ case "level": return fill(t("ship.levels.log_level"), { n: line.level });+ case "warp": return fill(t("ship.levels.log_warp"), { place: place(line.destination) });+ case "deck": return fill(t("ship.levels.log_deck"), { deck: t(`ship.deck.${line.deck}`) });+ default: return t(sourceKey(line.source));+ }+ },+ /** A log time: the clock today, "Yesterday", else the date. */+ when: (tsMs: number, nowMs = Date.now()): string => {+ const at = new Date(tsMs), now = new Date(nowMs);+ const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();+ if (tsMs >= startOfToday) return at.toLocaleTimeString(locale, { hour: "2-digit", minute: "2-digit" });+ if (tsMs >= startOfToday - DAY_MS) return t("ship.levels.yesterday");+ return at.toLocaleDateString(locale, { day: "numeric", month: "short" });+ },+ };+ }, [t, locale]);+}++export type LevelText = ReturnType<typeof useLevelText>;diff --git a/dodaios/ui/web/frontend/src/components/society/starship/levels/levels.css b/dodaios/ui/web/frontend/src/components/society/starship/levels/levels.cssnew file mode 100644index 0000000000..0d1ea2ea19--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/levels/levels.css@@ -0,0 +1,250 @@+/*+ * The service record and the promotion moment. Same dark glass as the ship's+ * HUD (hud/ship.css) whatever the app theme: the scene behind is always deep+ * space. Gold marks only what the viewer holds or earns; cyan stays for+ * information; everything else is warm white on charcoal.+ */++.svc-scrim, .promo-layer {+ --lv-text: #e8eef6;+ --lv-muted: #8f9db0;+ --lv-faint: #5c6878;+ --lv-line: rgba(255, 255, 255, 0.07);+ --lv-line-strong: rgba(255, 255, 255, 0.14);+ --lv-gold: #d9a441;+ --lv-gold-soft: #e9c27a;+ --lv-cyan: #5fd4ff;+ --lv-display: "Space Grotesk", "Inter Variable", system-ui, sans-serif;+ --lv-body: "Inter Variable", system-ui, sans-serif;+ --lv-mono: "JetBrains Mono", ui-monospace, monospace;+ color: var(--lv-text);+ font-family: var(--lv-body);+}++/* ------------------------------------------------------------ dialog */++.svc-scrim {+ position: absolute; inset: 0; z-index: 20; display: grid; place-items: center; padding: 16px;+ background: radial-gradient(ellipse at 50% 40%, rgba(2, 4, 8, 0.45), rgba(2, 4, 8, 0.78));+ animation: svc-fade 180ms ease-out;+}++.svc {+ position: relative; container-type: inline-size;+ width: min(940px, 100%); height: min(680px, 100%);+ display: grid; grid-template-rows: auto auto 1fr; overflow: hidden;+ background: linear-gradient(180deg, rgba(15, 20, 29, 0.97), rgba(8, 11, 17, 0.98));+ border: 1px solid var(--lv-line-strong); border-radius: 14px;+ box-shadow: 0 30px 80px rgba(0, 0, 0, 0.55), inset 0 1px 0 rgba(255, 255, 255, 0.04);+ animation: svc-rise 220ms cubic-bezier(.2, .8, .2, 1);+}+/* A single gold rule along the top edge: the record is a document of rank. */+.svc::before {+ content: ""; position: absolute; top: 0; left: 28px; right: 28px; height: 1px;+ background: linear-gradient(90deg, transparent, rgba(217, 164, 65, 0.75), transparent);+}++.svc-head { display: flex; align-items: center; gap: 12px; padding: 20px 20px 0 28px; }+.svc-title { margin: 0; font: 600 17px/1.2 var(--lv-display); letter-spacing: 0.02em; }+.svc-title small { display: block; margin-bottom: 4px; }+.svc-head-tools { margin-left: auto; display: flex; gap: 4px; }++.lv-eyebrow {+ font-family: var(--lv-display); font-size: 10.5px; font-weight: 600; letter-spacing: 0.16em;+ text-transform: uppercase; color: var(--lv-muted);+}++.svc-icon {+ width: 34px; height: 34px; border-radius: 8px; display: grid; place-items: center; cursor: pointer;+ background: transparent; border: 1px solid transparent; color: var(--lv-muted);+}+.svc-icon:hover { color: var(--lv-text); background: rgba(255, 255, 255, 0.05); }+.svc-icon[aria-pressed="true"] { color: var(--lv-text); }+.svc-icon:focus-visible, .svc-tab:focus-visible, .svc-choice:focus-visible, .promo-card button:focus-visible, .promo-toast:focus-visible {+ outline: 2px solid var(--lv-cyan); outline-offset: 2px;+}++.svc-tabs { display: flex; gap: 22px; padding: 14px 28px 0; border-bottom: 1px solid var(--lv-line); overflow-x: auto; scrollbar-width: none; }+.svc-tab {+ position: relative; padding: 8px 0 12px; background: none; border: 0; cursor: pointer; white-space: nowrap;+ font: 500 13px var(--lv-body); color: var(--lv-muted);+}+.svc-tab:hover { color: var(--lv-text); }+.svc-tab[aria-selected="true"] { color: var(--lv-text); }+.svc-tab[aria-selected="true"]::after {+ content: ""; position: absolute; left: 0; right: 0; bottom: -1px; height: 2px; border-radius: 2px; background: var(--lv-gold);+}++.svc-body { overflow-y: auto; padding: 26px 28px 30px; scrollbar-width: thin; scrollbar-color: rgba(255, 255, 255, 0.14) transparent; }+.svc-body:focus-visible { outline: none; }+.svc-empty { color: var(--lv-muted); font-size: 13.5px; line-height: 1.6; max-width: 56ch; }++/* ------------------------------------------------------------ record */++.svc-record { display: grid; grid-template-columns: minmax(260px, 320px) 1fr; gap: 44px; align-items: start; }+@container (max-width: 700px) { .svc-record { grid-template-columns: 1fr; gap: 30px; } }++.svc-plate { display: flex; flex-direction: column; }+.svc-plate-insignia {+ width: 108px; height: 108px; margin: -10px 0 8px -10px; display: grid; place-items: center;+ background: radial-gradient(circle, rgba(217, 164, 65, 0.16), transparent 68%);+}+.svc-rank { margin: 6px 0 2px; font: 600 28px/1.15 var(--lv-display); letter-spacing: 0.005em; }+.svc-level { font-size: 14px; color: var(--lv-muted); }+.svc-level b { color: var(--lv-text); font-weight: 600; }++.lv-bar { margin-top: 18px; height: 4px; border-radius: 2px; background: rgba(255, 255, 255, 0.08); overflow: hidden; }+.lv-bar > i { display: block; height: 100%; border-radius: 2px; background: linear-gradient(90deg, #a8741f, var(--lv-gold) 70%, #f1cf83); transition: width 0.8s ease; }+.lv-bar-legend { display: flex; justify-content: space-between; gap: 12px; margin-top: 8px; font-size: 12px; color: var(--lv-muted); font-variant-numeric: tabular-nums; }++.svc-next { margin-top: 26px; padding-top: 18px; border-top: 1px solid var(--lv-line); display: grid; gap: 18px; }+.svc-next-row { display: grid; grid-template-columns: 34px 1fr; column-gap: 12px; align-items: center; }+.svc-next-row .lv-eyebrow { grid-column: 1 / -1; margin-bottom: 8px; }+.svc-next-row strong { font-weight: 600; font-size: 14px; display: block; }+.svc-next-row span { font-size: 12px; color: var(--lv-muted); }++.svc-log h3, .svc-section h3 { margin: 0 0 12px; }+.svc-log ol { list-style: none; margin: 0; padding: 0; }+.svc-log li {+ display: grid; grid-template-columns: 68px 1fr auto; gap: 14px; align-items: baseline;+ padding: 10px 0; border-bottom: 1px solid var(--lv-line); font-size: 13px;+}+.svc-log li:last-child { border-bottom: 0; }+.svc-log time { font: 11.5px var(--lv-mono); color: var(--lv-faint); }+.svc-log .who { color: var(--lv-muted); margin-right: 6px; }+.svc-log .xp { font: 12px var(--lv-mono); color: var(--lv-muted); }+.svc-log li[data-mark="true"] .what { color: var(--lv-gold-soft); display: inline-flex; align-items: center; gap: 8px; }+.svc-log li[data-mark="true"] svg { flex: none; align-self: center; }++/* ------------------------------------------------------------ ranks */++.svc-tier + .svc-tier { margin-top: 30px; }+.svc-tier-head { display: flex; align-items: baseline; gap: 14px; flex-wrap: wrap; margin-bottom: 10px; }+.svc-tier-head h3 { margin: 0; }+.svc-tier-head p { margin: 0; font-size: 12.5px; color: var(--lv-faint); }+.svc-rungs { list-style: none; margin: 0; padding: 0; }+.svc-rung {+ position: relative; display: grid; grid-template-columns: 22px 44px 1fr auto; gap: 14px; align-items: center;+ padding: 8px 14px 8px 6px; border: 1px solid transparent; border-radius: 10px;+}+/* The ladder's rail: gold up to the rank held, grey above it. */+.svc-rung::before {+ content: ""; position: absolute; left: 16.5px; top: 0; bottom: 0; width: 1px; background: var(--lv-line-strong);+}+.svc-rung[data-state="held"]::before, .svc-rung[data-state="current"]::before { background: rgba(217, 164, 65, 0.45); }+.svc-node { position: relative; width: 9px; height: 9px; margin-left: 6px; border-radius: 50%; background: #1b222c; border: 1px solid var(--lv-line-strong); }+.svc-rung[data-state="held"] .svc-node { background: var(--lv-gold); border-color: var(--lv-gold); }+.svc-rung[data-state="current"] .svc-node { background: #0b0f15; border: 2px solid var(--lv-gold); width: 11px; height: 11px; margin-left: 5px; box-shadow: 0 0 10px rgba(217, 164, 65, 0.6); }+.svc-rung[data-state="current"] { border-color: rgba(217, 164, 65, 0.42); background: linear-gradient(90deg, rgba(217, 164, 65, 0.08), rgba(217, 164, 65, 0.015)); }+.svc-rung-name { font-size: 14px; font-weight: 500; }+.svc-rung-name small { display: block; font-size: 12px; color: var(--lv-muted); font-weight: 400; margin-top: 2px; }+.svc-rung-state { font-size: 12px; color: var(--lv-muted); text-align: right; font-variant-numeric: tabular-nums; }+.svc-rung[data-state="current"] .svc-rung-state { color: var(--lv-gold-soft); }+.svc-rung[data-state="ahead"] .svc-rung-name { color: var(--lv-muted); }++/* ------------------------------------------------------------ rewards, rules, crew */++.svc-section + .svc-section { margin-top: 32px; }+.svc-section > p { margin: -4px 0 12px; font-size: 12.5px; color: var(--lv-faint); max-width: 64ch; line-height: 1.5; }+.svc-list { list-style: none; margin: 0; padding: 0; }+.svc-item {+ display: grid; grid-template-columns: 40px 1fr auto; gap: 14px; align-items: center;+ padding: 10px 0; border-bottom: 1px solid var(--lv-line);+}+.svc-item:last-child { border-bottom: 0; }+.svc-item-name { font-size: 14px; }+.svc-item-name small { display: block; font-size: 12px; color: var(--lv-muted); margin-top: 2px; }+.svc-item-state { font-size: 12px; color: var(--lv-muted); text-align: right; white-space: nowrap; font-variant-numeric: tabular-nums; }+.svc-item[data-open="false"] .svc-item-name { color: var(--lv-muted); }+.svc-item[data-open="false"] .svc-glyph { opacity: 0.4; filter: saturate(0.2); }+.svc-tag { font-family: var(--lv-display); font-size: 10.5px; font-weight: 600; letter-spacing: 0.14em; text-transform: uppercase; color: var(--lv-gold-soft); }+.svc-tag[data-tone="info"] { color: var(--lv-cyan); }++.svc-choice {+ width: 100%; margin: 0; background: none; border: 0; border-bottom: 1px solid var(--lv-line); border-radius: 0;+ color: inherit; font: inherit; text-align: left; cursor: pointer;+}+.svc-choice:hover:not([aria-disabled="true"]) .svc-item-name { color: var(--lv-text); }+.svc-choice[aria-disabled="true"] { cursor: default; }+.svc-radio { width: 14px; height: 14px; border-radius: 50%; border: 1.5px solid var(--lv-line-strong); display: inline-grid; place-items: center; margin-right: 10px; vertical-align: -2px; }+.svc-choice[aria-checked="true"] .svc-radio { border-color: var(--lv-gold); }+.svc-choice[aria-checked="true"] .svc-radio::after { content: ""; width: 6px; height: 6px; border-radius: 50%; background: var(--lv-gold); }++.svc-rules { width: 100%; border-collapse: collapse; font-size: 13.5px; }+.svc-rules td { padding: 10px 0; border-bottom: 1px solid var(--lv-line); vertical-align: baseline; }+.svc-rules tr:last-child td { border-bottom: 0; }+.svc-rules .limit { color: var(--lv-muted); font-size: 12px; padding-left: 16px; }+.svc-rules .amount { text-align: right; font: 12.5px var(--lv-mono); color: var(--lv-text); white-space: nowrap; padding-left: 16px; width: 1%; }+.svc-lead { margin: 0 0 28px; max-width: 62ch; color: var(--lv-muted); font-size: 13.5px; line-height: 1.6; }++.svc-crew li { grid-template-columns: 26px 36px 1fr auto; }+.svc-crew .pos { font: 12px var(--lv-mono); color: var(--lv-faint); text-align: right; }++/* ------------------------------------------------------------ promotion */++.promo-layer { position: absolute; inset: 0; z-index: 22; pointer-events: none; }+.promo-scrim {+ position: absolute; inset: 0; display: grid; place-items: center; pointer-events: auto; cursor: pointer;+ background: radial-gradient(circle at 50% 45%, rgba(4, 6, 10, 0.25), rgba(2, 4, 8, 0.7));+ animation: svc-fade 240ms ease-out;+}+.promo-card {+ position: relative; width: min(400px, calc(100% - 32px)); padding: 30px 32px 26px; text-align: center; cursor: default;+ background: linear-gradient(180deg, rgba(16, 21, 31, 0.97), rgba(8, 11, 17, 0.98));+ border: 1px solid rgba(217, 164, 65, 0.35); border-radius: 16px;+ box-shadow: 0 30px 90px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(0, 0, 0, 0.4), 0 0 60px rgba(217, 164, 65, 0.08);+ animation: svc-rise 320ms cubic-bezier(.2, .8, .2, 1);+}+.promo-card::before {+ content: ""; position: absolute; top: 0; left: 40px; right: 40px; height: 1px;+ background: linear-gradient(90deg, transparent, var(--lv-gold), transparent);+}+.promo-who { margin-top: 6px; font-size: 12.5px; color: var(--lv-muted); }+.promo-stage { position: relative; height: 128px; margin: 16px 0 6px; display: grid; place-items: center; }+.promo-stage::after {+ content: ""; position: absolute; width: 150px; height: 150px; border-radius: 50%; z-index: -1;+ background: radial-gradient(circle, rgba(217, 164, 65, 0.22), transparent 66%);+}+.promo-old, .promo-new { position: absolute; display: grid; place-items: center; }+.promo-old { animation: promo-aside 700ms 250ms cubic-bezier(.5, 0, .3, 1) both; }+.promo-new { animation: promo-lay 620ms 650ms cubic-bezier(.2, .9, .25, 1.05) both; }+.promo-new::after {+ content: ""; position: absolute; inset: 8px; pointer-events: none; mix-blend-mode: screen;+ background: linear-gradient(115deg, transparent 35%, rgba(255, 244, 214, 0.55) 50%, transparent 65%) no-repeat;+ background-size: 260% 100%; background-position: 130% 0;+ animation: promo-sheen 900ms 1250ms ease-out both;+}+.promo-card[data-promotion="false"] .promo-new { animation-delay: 150ms; }+.promo-card[data-promotion="false"] .promo-new::after { animation-delay: 700ms; }+.promo-rank { margin: 4px 0 0; font: 600 26px/1.2 var(--lv-display); animation: svc-fade 400ms 1000ms both; }+.promo-level { margin-top: 4px; font-size: 13.5px; color: var(--lv-muted); animation: svc-fade 400ms 1100ms both; }+.promo-open { margin: 20px 0 0; padding-top: 16px; border-top: 1px solid var(--lv-line); animation: svc-fade 400ms 1300ms both; }+.promo-open p { margin: 6px 0 0; font-size: 13.5px; color: var(--lv-gold-soft); line-height: 1.5; }+.promo-card button {+ margin-top: 22px; height: 34px; padding: 0 18px; border-radius: 8px; cursor: pointer;+ background: rgba(255, 255, 255, 0.04); border: 1px solid var(--lv-line-strong); color: var(--lv-text); font: 500 13px var(--lv-body);+}+.promo-card button:hover { background: rgba(255, 255, 255, 0.09); }++.promo-toasts { position: absolute; right: 16px; bottom: 16px; display: flex; flex-direction: column; gap: 8px; align-items: flex-end; }+.promo-toast {+ pointer-events: auto; display: flex; align-items: center; gap: 10px; padding: 8px 14px 8px 10px; max-width: 320px;+ background: rgba(9, 13, 20, 0.86); border: 1px solid var(--lv-line-strong); border-radius: 10px; cursor: pointer;+ color: var(--lv-text); font: 13px var(--lv-body); text-align: left;+ backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); box-shadow: 0 10px 30px rgba(0, 0, 0, 0.35);+ animation: promo-toast-in 260ms cubic-bezier(.2, .8, .2, 1);+}+.promo-toast svg { flex: none; }++/* Reduced motion keeps every word and drops the movement. */+[data-reduced="true"] *, [data-reduced="true"]::before, [data-reduced="true"]::after { animation: none !important; transition: none !important; }+@media (prefers-reduced-motion: reduce) {+ .svc-scrim *, .svc-scrim, .promo-layer *, .promo-layer *::after { animation: none !important; transition: none !important; }+}++@keyframes svc-fade { from { opacity: 0; } to { opacity: 1; } }+@keyframes svc-rise { from { opacity: 0; transform: translateY(10px) scale(0.985); } to { opacity: 1; transform: none; } }+@keyframes promo-aside { from { transform: none; opacity: 1; } to { transform: translateX(-112px) scale(0.62); opacity: 0.28; } }+@keyframes promo-lay { from { transform: translateY(-34px) scale(1.3); opacity: 0; } 70% { opacity: 1; } to { transform: none; opacity: 1; } }+@keyframes promo-sheen { from { background-position: 130% 0; } to { background-position: -30% 0; } }+@keyframes promo-toast-in { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }diff --git a/dodaios/ui/web/frontend/src/components/society/starship/levels/levels.test.ts b/dodaios/ui/web/frontend/src/components/society/starship/levels/levels.test.tsnew file mode 100644index 0000000000..cebcf59103--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/levels/levels.test.ts@@ -0,0 +1,188 @@+/**+ * The level UI's pure side: every rank wears the insignia its ladder entry+ * promises, the catalog agrees with ranks.ts, destinations.ts and the Python+ * rulebook, and the record's lists (ladder, shelves, log, rules, crew) come+ * out in the order the dialog shows them.+ */+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { RANK_IDS, REWARD_IDS, SLOTS, XP_SOURCES, rewardKey, slotOf } from "../../progression/levelCatalog";+import type { AwardRow, RewardRow, XpRuleRow } from "../../progression/progressionApi";+import { DESTINATIONS } from "../space/destinations";+import { RANKS, rankFor } from "./ranks";+import {+ crewRanking, insigniaFor, isPromotion, nextReward, rankLadder, rewardShelves, ruleGroups, ruleLimit, shipLog, xpToReach,+} from "./levelModel";+import { fill, LEGACY_SOURCES, sourceKey } from "./levelText";++const RULES_PY = readFileSync(join(__dirname, "..", "..", "..", "..", "..", "..", "..", "..", "progression", "rules.py"), "utf8");++/** The person level of every reward in rules.py, by id. */+function pythonRewards(): Map<string, number | null> {+ const out = new Map<string, number | null>();+ for (const m of RULES_PY.matchAll(/Reward\("([a-z_]+)", "[a-z]+", person=(\d+|None)/g)) out.set(m[1], m[2] === "None" ? null : Number(m[2]));+ return out;+}++/** A full curve shaped like the server's (exact numbers do not matter here). */+const CURVE = Array.from({ length: 50 }, (_, i) => i * i * 20);++describe("insignia", () => {+ it("has a design for every rank, in the metal of its tier", () => {+ for (const rank of RANKS) {+ const spec = insigniaFor(rank.id);+ if (rank.tier === "enlisted") expect(["bar", "chevrons"]).toContain(spec.kind);+ if (rank.tier === "warrant") expect(spec).toEqual({ kind: "pips", solid: 1, hollow: 0, warrant: true });+ if (rank.tier === "officer") expect(spec.kind).toBe("pips");+ if (rank.tier === "flag") expect(spec.kind).toBe("flag");+ // Silver for the enlisted ranks only; gold from the warrant officer up.+ expect(rank.gold).toBe(rank.tier !== "enlisted");+ }+ });++ it("counts as many marks as the ladder's pips below the flag ranks", () => {+ for (const rank of RANKS.filter((r) => r.tier !== "flag")) {+ const spec = insigniaFor(rank.id);+ const marks = spec.kind === "bar" ? 0 : spec.kind === "chevrons" ? spec.count + (spec.rocker ? 1 : 0)+ : spec.kind === "pips" ? spec.solid + spec.hollow : 0;+ expect(marks, rank.id).toBe(rank.pips);+ }+ });++ it("follows the officers' ladder and gives the flag ranks one to four stars", () => {+ const pips = (id: string) => { const s = insigniaFor(id); return s.kind === "pips" ? [s.solid, s.hollow] : null; };+ expect(pips("ensign")).toEqual([1, 0]);+ expect(pips("lieutenant_junior_grade")).toEqual([1, 1]);+ expect(pips("lieutenant")).toEqual([2, 0]);+ expect(pips("lieutenant_commander")).toEqual([2, 1]);+ expect(pips("commander")).toEqual([3, 0]);+ expect(pips("captain")).toEqual([4, 0]);+ expect(["commodore", "rear_admiral", "vice_admiral", "admiral"].map((id) => insigniaFor(id))).toEqual(+ [1, 2, 3, 4].map((stars) => ({ kind: "flag", stars })));+ expect(insigniaFor("cadet")).toEqual({ kind: "bar" });+ expect(insigniaFor("general_of_the_army")).toEqual({ kind: "bar" });+ });++ it("tells a promotion from a level between two ranks", () => {+ expect(isPromotion(2, 3)).toBe(true);+ expect(isPromotion(3, 4)).toBe(false);+ expect(isPromotion(12, 17)).toBe(true);+ });+});++describe("the catalog", () => {+ it("lists the ranks of ranks.ts, lowest first", () => {+ expect([...RANK_IDS]).toEqual(RANKS.map((r) => r.id));+ expect(RANKS[0].level).toBe(1);+ expect(RANKS[RANKS.length - 1].level).toBe(50);+ });++ it("opens each destination at the level destinations.ts says, and the rulebook agrees", () => {+ const py = pythonRewards();+ expect([...py.keys()]).toEqual([...REWARD_IDS]);+ const fromCatalog = REWARD_IDS.filter((id) => slotOf(id) === "destination").map((id) => [rewardKey(id), py.get(id)]);+ expect(fromCatalog).toEqual(DESTINATIONS.filter((d) => d.id !== "home").map((d) => [d.id, d.level]));+ expect(DESTINATIONS[0]).toMatchObject({ id: "home", level: 1 });+ });++ it("names every reward by its slot", () => {+ for (const id of REWARD_IDS) expect(SLOTS).toContain(slotOf(id));+ });+});++const row = (rewardId: RewardRow["rewardId"], person: number | null, agent: number | null = null): RewardRow =>+ ({ rewardId, slot: slotOf(rewardId), levels: { person, agent, pet: null } });+const REWARDS: RewardRow[] = [+ row("suit_command_coat", 16), row("suit_field_armor", 6), row("destination_gas_giant", 5),+ row("destination_ice_moon", 15), row("decoration_service_ribbon", 8, 3),+];++describe("the record's lists", () => {+ it("measures what is missing on the curve", () => {+ expect(xpToReach(CURVE, 100, 4)).toBe(80);+ expect(xpToReach(CURVE, 999, 2)).toBe(0);+ expect(xpToReach(CURVE, 0, 99)).toBeNull();+ });++ it("lays out the ladder by tier with the viewer's place on it", () => {+ const groups = rankLadder(17, CURVE[16], CURVE);+ expect(groups.map((g) => g.tier)).toEqual(["enlisted", "warrant", "officer", "flag"]);+ expect(groups.flatMap((g) => g.rungs.map((r) => r.rank.id))).toEqual(RANKS.map((r) => r.id));+ const state = Object.fromEntries(groups.flatMap((g) => g.rungs.map((r) => [r.rank.id, r.state])));+ expect(state.cadet).toBe("held");+ expect(state.warrant_officer).toBe("held");+ expect(state.ensign).toBe("current");+ expect(state.lieutenant_junior_grade).toBe("ahead");+ const ltjg = groups[2].rungs.find((r) => r.rank.id === "lieutenant_junior_grade");+ expect(ltjg?.xpToGo).toBe(CURVE[18] - CURVE[16]);+ expect(rankFor(17).id).toBe("ensign");+ });++ it("puts each reward on its shelf in the order it opens, and finds the next one", () => {+ const shelves = rewardShelves(REWARDS, 10, CURVE[9], CURVE);+ expect(shelves.map((s) => [s.slot, s.items.map((i) => [i.reward.rewardId, i.open])])).toEqual([+ ["suit", [["suit_field_armor", true], ["suit_command_coat", false]]],+ ["destination", [["destination_gas_giant", true], ["destination_ice_moon", false]]],+ ["decoration", [["decoration_service_ribbon", true]]],+ ]);+ expect(nextReward(REWARDS, "person", 10)).toMatchObject({ level: 15, reward: { rewardId: "destination_ice_moon" } });+ expect(nextReward(REWARDS, "agent", 3)).toBeNull();+ });++ it("writes the ship's log newest first, for the captain and the companion only, without losing old sources", () => {+ const award = (seq: number, subjectId: string, source: string, ref = "", before = 1, after = 1): AwardRow =>+ ({ seq, subjectId, kind: subjectId === "person" ? "person" : subjectId.startsWith("pet:") ? "pet" : "agent", source, xp: 5, levelBefore: before, levelAfter: after, ref, tsMs: seq });+ const recent = [+ award(1, "person", "dog_petted"),+ award(2, "agent:scout", "task_done"),+ award(3, "person", "warp_jump", "ice_moon@1790000000000"),+ award(4, "person", "deck_discovered", "holodeck"),+ award(5, "pet:gigi", "jarvis_answered", "", 3, 4),+ award(6, "person", "chat_turn", "", 2, 3),+ ];+ const log = shipLog(recent, new Set(["person", "pet:gigi"]));+ expect(log.map((e) => [e.seq, e.line])).toEqual([+ [6, { kind: "promoted", rank: "crewman" }],+ [5, { kind: "level", level: 4 }],+ [4, { kind: "deck", deck: "holodeck" }],+ [3, { kind: "warp", destination: "ice_moon" }],+ [1, { kind: "source", source: "dog_petted" }],+ ]);+ expect(shipLog(recent, new Set(["person"]), 2).map((e) => e.seq)).toEqual([6, 4]);+ });++ it("reads every source in words, the office tower's too", () => {+ for (const source of XP_SOURCES) expect(sourceKey(source)).toBe(`ship.levels.source.${source}`);+ for (const source of LEGACY_SOURCES) expect(sourceKey(source)).toBe(`ship.levels.legacy_source.${source}`);+ expect(sourceKey("something_new")).toBe("ship.levels.legacy_source.other");+ expect(fill("{a} and {b}", { a: 1 })).toBe("1 and {b}");+ });++ it("groups the rules for the captain, the companion and the crew, richest first, with their limits", () => {+ const rule = (source: string, kind: XpRuleRow["kind"], xp: number, cooldownS = 0, dailyCap = 0): XpRuleRow =>+ ({ source, kind, xp, trigger: "world", cooldownS, dailyCap });+ const groups = ruleGroups([rule("chat_turn", "person", 5, 0, 100), rule("task_done", "agent", 40), rule("agent_hired", "person", 50),+ rule("walk_together", "pet", 3, 20, 60), rule("daily_visit", "person", 25), rule("deck_discovered", "person", 20)]);+ expect(groups.map((g) => [g.kind, g.rules.map((r) => r.rule.source)])).toEqual([+ ["person", ["agent_hired", "daily_visit", "deck_discovered", "chat_turn"]],+ ["pet", ["walk_together"]],+ ["agent", ["task_done"]],+ ]);+ expect(ruleLimit(rule("walk_together", "pet", 3, 20, 60))).toEqual({ kind: "metered", cooldownS: 20, dailyCap: 60 });+ expect(ruleLimit(rule("daily_visit", "person", 25))).toEqual({ kind: "once_day" });+ expect(ruleLimit(rule("task_done", "agent", 40))).toEqual({ kind: "none" });+ });++ it("ranks the crew best first and leaves the lead to the companion", () => {+ const agents = [+ { agentId: "jarvis", name: "Jarvis", tier: "lead" },+ { agentId: "a", name: "Ada", tier: "member" },+ { agentId: "b", name: "Bo", tier: "member" },+ { agentId: "c", name: "Cy", tier: "member" },+ ];+ const subject = (level: number, xp: number) => ({ subjectId: "", kind: "agent" as const, xp, level, xpIntoLevel: 0, xpForNext: 1, title: "" });+ const rows = crewRanking(agents, { "agent:a": subject(3, 50), "agent:b": subject(8, 400), "agent:c": subject(3, 60) });+ expect(rows.map((r) => [r.name, r.level, r.rank.id])).toEqual([["Bo", 8, "petty_officer"], ["Cy", 3, "crewman"], ["Ada", 3, "crewman"]]);+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/starship/levels/levelsLocales.test.ts b/dodaios/ui/web/frontend/src/components/society/starship/levels/levelsLocales.test.tsnew file mode 100644index 0000000000..40baf0e3be--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/levels/levelsLocales.test.ts@@ -0,0 +1,63 @@+/**+ * The level UI's strings (`locales/ship/levels.<lang>.json`) carry the same+ * keys and placeholders in all five languages, name every id the catalog+ * knows, and the German file writes its umlauts and ß as real letters. (i18n-allow)+ */+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { REWARD_IDS, SLOTS, XP_SOURCES } from "../../progression/levelCatalog";+import { SERVICE_TABS } from "../../progression/progressionStore";+import { TIER_ORDER } from "./levelModel";+import { LEGACY_SOURCES } from "./levelText";++const DIR = join(__dirname, "..", "..", "..", "..", "i18n", "locales", "ship");+const LANGS = ["en", "de", "es", "pt", "zh"] as const;+type Tree = Record<string, unknown>;++const load = (lang: string) => JSON.parse(readFileSync(join(DIR, `levels.${lang}.json`), "utf8")) as { ship: { levels: Tree } };++function leaves(tree: Tree, prefix = ""): Map<string, string> {+ const out = new Map<string, string>();+ for (const [key, value] of Object.entries(tree)) {+ const path = prefix ? `${prefix}.${key}` : key;+ if (value && typeof value === "object") for (const [k, v] of leaves(value as Tree, path)) out.set(k, v);+ else out.set(path, String(value));+ }+ return out;+}++const placeholders = (text: string) => (text.match(/\{\w+\}/g) ?? []).sort();++describe("the level UI's locale files", () => {+ const en = leaves(load("en").ship.levels);++ it("have the same keys and placeholders in every language, none empty", () => {+ for (const lang of LANGS) {+ const other = leaves(load(lang).ship.levels);+ expect([...other.keys()].sort(), lang).toEqual([...en.keys()].sort());+ for (const [key, text] of other) {+ expect(text.trim(), `${lang}:${key}`).not.toBe("");+ expect(placeholders(text), `${lang}:${key}`).toEqual(placeholders(en.get(key) ?? ""));+ }+ }+ });++ it("name every reward, source, slot, tier and page", () => {+ const levels = load("en").ship.levels as Record<string, Tree>;+ expect(Object.keys(levels.reward).sort()).toEqual([...REWARD_IDS].sort());+ expect(Object.keys(levels.source).sort()).toEqual([...XP_SOURCES].sort());+ expect(Object.keys(levels.rule).sort()).toEqual([...XP_SOURCES].sort());+ expect(Object.keys(levels.slot).sort()).toEqual([...SLOTS].sort());+ expect(Object.keys(levels.tier).sort()).toEqual([...TIER_ORDER].sort());+ expect(Object.keys(levels.tier_about).sort()).toEqual([...TIER_ORDER].sort());+ expect(Object.keys(levels.legacy_source).sort()).toEqual([...LEGACY_SOURCES, "other"].sort());+ for (const tab of SERVICE_TABS) expect(levels.tabs[tab], tab).toBeTruthy();+ });++ it("writes German with real umlauts", () => {+ const raw = readFileSync(join(DIR, "levels.de.json"), "utf8");+ expect(raw).toMatch(/[äöüß]/); // i18n-allow+ expect(raw).not.toMatch(/\b(Schliessen|Naechst|fuer|Ruecken|Grosse|hoechst)/i); // i18n-allow+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/starship/levels/levelsUi.test.tsx b/dodaios/ui/web/frontend/src/components/society/starship/levels/levelsUi.test.tsxnew file mode 100644index 0000000000..79235ca247--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/levels/levelsUi.test.tsx@@ -0,0 +1,147 @@+/**+ * The level UI in the DOM: the insignia draws what its rank wears, the+ * service record is an accessible dialog (tabs, Escape, focus trap, the suit+ * choice), and the promotion layer shows the ceremony and the crew's toasts+ * and lets them go.+ */+import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react";+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { loadLocaleChunk } from "@/i18n";+import type { ProgressionSnapshot, RewardRow } from "../../progression/progressionApi";+import { celebrationOf, useProgression } from "../../progression/progressionStore";+import { slotOf } from "../../progression/levelCatalog";+import { Insignia } from "./Insignia";+import { ServiceRecord } from "./ServiceRecord";+import { CEREMONY_MS, PromotionLayer, TOAST_MS } from "./PromotionCeremony";++vi.mock("../../data", () => ({+ useSocietyRoster: () => ({+ data: { agents: [+ { agentId: "jarvis", name: "Gigi", tier: "lead" },+ { agentId: "scout", name: "Scout", tier: "member" },+ { agentId: "forge", name: "Forge", tier: "member" },+ ] },+ }),+}));++const CURVE = Array.from({ length: 50 }, (_, i) => i * i * 20);+const reward = (id: RewardRow["rewardId"], person: number): RewardRow => ({ rewardId: id, slot: slotOf(id), levels: { person, agent: null, pet: null } });++function snapshot(): ProgressionSnapshot {+ return {+ subjects: [+ { subjectId: "person", kind: "person", xp: CURVE[16] + 40, level: 17, xpIntoLevel: 40, xpForNext: CURVE[17] - CURVE[16], title: "ensign" },+ { subjectId: "agent:scout", kind: "agent", xp: 900, level: 8, xpIntoLevel: 0, xpForNext: 100, title: "petty_officer" },+ ],+ petId: "gigi",+ recent: [+ { seq: 1, subjectId: "person", kind: "person", source: "dog_petted", xp: 3, levelBefore: 16, levelAfter: 16, ref: "", tsMs: Date.now() - 60_000 },+ { seq: 2, subjectId: "person", kind: "person", source: "warp_jump", xp: 5, levelBefore: 16, levelAfter: 16, ref: "gas_giant@1", tsMs: Date.now() },+ ],+ latestSeq: 2, maxLevel: 50, levelXp: CURVE,+ rules: [{ source: "chat_turn", kind: "person", xp: 5, trigger: "server", cooldownS: 0, dailyCap: 100 }],+ rewards: [reward("suit_field_armor", 6), reward("suit_command_coat", 16), reward("suit_dress_whites", 26), reward("destination_gas_giant", 5), reward("destination_ice_moon", 20)],+ ranks: [], titles: { person: [], agent: [], pet: [] }, looks: {},+ };+}++beforeAll(async () => { await loadLocaleChunk("ship"); });+beforeEach(() => {+ useProgression.setState({ snapshot: null, subjects: {}, banners: [], toasts: [], suit: "auto", record: null });+ useProgression.getState().hydrate(snapshot(), []);+});+afterEach(() => { cleanup(); vi.useRealTimers(); });++describe("Insignia", () => {+ it("draws chevrons, pips and stars, and is decorative without a title", () => {+ const { container, rerender } = render(<Insignia rank="petty_officer" />);+ expect(container.querySelectorAll("polygon")).toHaveLength(3);+ expect(container.querySelector("svg")?.getAttribute("aria-hidden")).toBe("true");+ rerender(<Insignia rank="lieutenant_commander" title="Lieutenant Commander" size={64} />);+ expect(container.querySelectorAll("circle")).toHaveLength(3);+ expect(screen.getByRole("img", { name: "Lieutenant Commander" }).getAttribute("width")).toBe("64");+ rerender(<Insignia rank="admiral" />);+ expect(container.querySelectorAll("polygon")).toHaveLength(4);+ rerender(<Insignia rank="cadet" tone="muted" />);+ expect(container.querySelector("defs")).toBeNull();+ });+});++describe("ServiceRecord", () => {+ it("is a dialog that opens on the asked page and closes on Escape", () => {+ const onClose = vi.fn();+ render(<ServiceRecord onClose={onClose} initialTab="ranks" />);+ const dialog = screen.getByRole("dialog", { name: "Service record" });+ expect(screen.getByRole("tab", { name: "Ranks" }).getAttribute("aria-selected")).toBe("true");+ expect(document.activeElement).toBe(screen.getByRole("tab", { name: "Ranks" }));+ expect(within(dialog).getByText("Your rank")).toBeTruthy();+ fireEvent.keyDown(dialog, { key: "Escape" });+ expect(onClose).toHaveBeenCalledTimes(1);+ });++ it("shows the record with the next promotion and a log in words", () => {+ render(<ServiceRecord onClose={() => {}} />);+ expect(screen.getAllByText("Ensign").length).toBeGreaterThan(0);+ expect(screen.getByText("Lieutenant Junior Grade at level 19")).toBeTruthy();+ expect(screen.getByText("Jumped to Banded Giant")).toBeTruthy();+ expect(screen.getByText("Petted the office dog")).toBeTruthy();+ });++ it("moves between pages with the arrow keys and keeps focus inside", () => {+ render(<ServiceRecord onClose={() => {}} />);+ fireEvent.keyDown(screen.getByRole("tab", { name: "Record" }), { key: "ArrowLeft" });+ expect(screen.getByRole("tab", { name: "Crew" }).getAttribute("aria-selected")).toBe("true");+ expect(screen.getByText("Scout")).toBeTruthy();+ const dialog = screen.getByRole("dialog");+ const closeButton = screen.getByRole("button", { name: "Close" });+ const focusables = dialog.querySelectorAll<HTMLElement>("button:not([disabled]), [tabindex]:not([tabindex='-1'])");+ focusables[focusables.length - 1].focus();+ fireEvent.keyDown(dialog, { key: "Tab" });+ expect(document.activeElement).toBe(focusables[0]);+ expect(closeButton).toBeTruthy();+ });++ it("lets the captain choose an open suit, never a locked one", () => {+ render(<ServiceRecord onClose={() => {}} initialTab="rewards" />);+ const group = screen.getByRole("radiogroup", { name: "Suit to wear" });+ expect(within(group).getByRole("radio", { name: /Automatic/ }).getAttribute("aria-checked")).toBe("true");+ // Automatic wears the finest suit open at level 17.+ expect(within(within(group).getByRole("radio", { name: /Command Coat/ })).getByText("Wearing")).toBeTruthy();+ fireEvent.click(within(group).getByRole("radio", { name: /Field Armour/ }));+ expect(useProgression.getState().suit).toBe("suit_field_armor");+ fireEvent.click(within(group).getByRole("radio", { name: /Dress Whites/ }));+ expect(useProgression.getState().suit).toBe("suit_field_armor");+ expect(screen.getByText("Banded Giant")).toBeTruthy();+ });+});++describe("PromotionLayer", () => {+ it("lays the new insignia on for the captain and goes after six seconds", () => {+ vi.useFakeTimers();+ useProgression.setState({ banners: [celebrationOf({ subjectId: "person", kind: "person", level: 16, previousLevel: 15, title: "ensign", unlocked: ["suit_command_coat"] })] });+ render(<PromotionLayer />);+ expect(screen.getByText("Promotion")).toBeTruthy();+ expect(screen.getByRole("heading", { name: "Ensign" })).toBeTruthy();+ expect(screen.getByText("Command Coat")).toBeTruthy();+ act(() => { vi.advanceTimersByTime(CEREMONY_MS); });+ expect(useProgression.getState().banners).toHaveLength(0);+ });++ it("says level up between two ranks, and Escape dismisses", () => {+ useProgression.setState({ banners: [celebrationOf({ subjectId: "pet:gigi", kind: "pet", level: 4, previousLevel: 3, title: "crewman", unlocked: [] })] });+ render(<PromotionLayer />);+ expect(screen.getByText("Level up")).toBeTruthy();+ expect(screen.getByText("Companion · Gigi")).toBeTruthy();+ fireEvent.keyDown(document, { key: "Escape" });+ expect(useProgression.getState().banners).toHaveLength(0);+ });++ it("tells an android's promotion quietly in the corner", () => {+ vi.useFakeTimers();+ useProgression.setState({ toasts: [celebrationOf({ subjectId: "agent:scout", kind: "agent", level: 3, previousLevel: 2, title: "crewman", unlocked: [] })] });+ render(<PromotionLayer />);+ expect(screen.getByText("Scout was promoted to Crewman")).toBeTruthy();+ act(() => { vi.advanceTimersByTime(TOAST_MS); });+ expect(useProgression.getState().toasts).toHaveLength(0);+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/starship/levels/ranks.ts b/dodaios/ui/web/frontend/src/components/society/starship/levels/ranks.tsnew file mode 100644index 0000000000..e5019ffdb5--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/levels/ranks.ts@@ -0,0 +1,49 @@+/**+ * The ship's rank ladder, mirrored from the rulebook (dodaios/progression/rules.py+ * `RANKS`; a parity test pins the two). Everyone aboard climbs it: the+ * captain (the person), every android (agent) and the pet.+ *+ * What a rank looks like on a figure: enlisted ranks wear silver pips at the+ * collar, officers gold pips, flag officers four gold pips over a gold bar.+ */++export type RankTier = "enlisted" | "warrant" | "officer" | "flag";++export interface Rank {+ id: string;+ /** First level of the rank. */+ level: number;+ tier: RankTier;+ /** Collar pips on a figure (0–4) and their metal. */+ pips: number;+ gold: boolean;+}++export const RANKS: readonly Rank[] = [+ { id: "cadet", level: 1, tier: "enlisted", pips: 0, gold: false },+ { id: "crewman", level: 3, tier: "enlisted", pips: 1, gold: false },+ { id: "specialist", level: 5, tier: "enlisted", pips: 2, gold: false },+ { id: "petty_officer", level: 7, tier: "enlisted", pips: 3, gold: false },+ { id: "chief_petty_officer", level: 10, tier: "enlisted", pips: 4, gold: false },+ { id: "warrant_officer", level: 13, tier: "warrant", pips: 1, gold: true },+ { id: "ensign", level: 16, tier: "officer", pips: 1, gold: true },+ { id: "lieutenant_junior_grade", level: 19, tier: "officer", pips: 2, gold: true },+ { id: "lieutenant", level: 22, tier: "officer", pips: 2, gold: true },+ { id: "lieutenant_commander", level: 26, tier: "officer", pips: 3, gold: true },+ { id: "commander", level: 30, tier: "officer", pips: 3, gold: true },+ { id: "captain", level: 34, tier: "officer", pips: 4, gold: true },+ { id: "commodore", level: 38, tier: "flag", pips: 4, gold: true },+ { id: "rear_admiral", level: 42, tier: "flag", pips: 4, gold: true },+ { id: "vice_admiral", level: 46, tier: "flag", pips: 4, gold: true },+ { id: "admiral", level: 50, tier: "flag", pips: 4, gold: true },+];++export function rankFor(level: number): Rank {+ let rank = RANKS[0];+ for (const r of RANKS) if (level >= r.level) rank = r;+ return rank;+}++export function nextRank(level: number): Rank | null {+ return RANKS.find((r) => r.level > level) ?? null;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/life/Captain.tsx b/dodaios/ui/web/frontend/src/components/society/starship/life/Captain.tsxnew file mode 100644index 0000000000..957a83a8b6--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/life/Captain.tsx@@ -0,0 +1,190 @@+/**+ * The captain: the person's own figure. WASD or the arrows walk relative to+ * the camera (Shift runs), a click on the floor walks there along a route+ * drawn as a line of lights, E uses the station the captain stands at.+ * The captain never comes to rest inside anything solid.+ */+import { useFrame, useThree } from "@react-three/fiber";+import { useEffect, useMemo, useRef } from "react";+import { BufferGeometry, Color, Float32BufferAttribute, Points, PointsMaterial } from "three";+import { CrewFigure } from "../crew/figure";+import { findPath, isFree, nearestFree, type NavGrid } from "../nav/shipNav";+import type { DeckPlan, Vec2 } from "../plan/types";+import { orbit } from "../render/CameraRig";+import { captain, useShip, type CaptainLook } from "../shipStore";+import { stepAlong, turnTowards, wrapAngle } from "./motion";++export const WALK = 2.0;+export const RUN = 4.2;++/** Text fields keep their keys. */+export function typesText(target: EventTarget | null): boolean {+ return target instanceof HTMLElement && (target.isContentEditable || target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.tagName === "SELECT");+}++const KEYS = new Set(["KeyW", "KeyA", "KeyS", "KeyD", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "ShiftLeft", "ShiftRight"]);+++export function CaptainFigure(props: {+ plan: DeckPlan;+ grid: NavGrid;+ /** Colours from the quartermaster, the cut from the level system. */+ look: CaptainLook & { cut: string | null };+ pips: number;+ awake: boolean;+ reduced: boolean;+ /** Host element that owns the walking keys (focus inside it). */+ keyHost: React.RefObject<HTMLElement | null>;+}) {+ const { plan, grid, look, pips, awake } = props;+ const figure = useMemo(() => new CrewFigure({ kind: "captain", captain: { ...look, pips } }), [look, pips]);+ useEffect(() => () => figure.dispose(), [figure]);+ const keys = useRef(new Set<string>());+ const t = useRef(0);+ const body = useRef({ x: captain.x, z: captain.z, yaw: captain.yaw, path: [] as Vec2[], speed: 0, phase: 0 });+ const arrivals = useShip((s) => s.arrivals);+ const walkTo = useShip((s) => s.walkTo);++ // Arriving on a deck: out of the turbolift.+ useEffect(() => {+ const at = nearestFree(grid, plan.lift) ?? plan.lift;+ Object.assign(body.current, { x: at.x, z: at.z, yaw: plan.lift.yaw, path: [], speed: 0 });+ Object.assign(captain, { x: at.x, z: at.z, yaw: plan.lift.yaw, path: [], moving: false, seated: null });+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [arrivals, plan.deck]);+ // A rebuilt plan may have put something where the captain stands.+ useEffect(() => {+ if (!isFree(grid, body.current)) {+ const at = nearestFree(grid, body.current) ?? plan.lift;+ body.current.x = at.x; body.current.z = at.z;+ }+ }, [grid, plan]);++ const placeAt = useShip((s) => s.placeAt);+ const usedPlace = useRef(0);+ useEffect(() => {+ if (!placeAt || placeAt.seq === usedPlace.current) return;+ usedPlace.current = placeAt.seq;+ const at = nearestFree(grid, placeAt.at) ?? placeAt.at;+ Object.assign(body.current, { x: at.x, z: at.z, path: [], speed: 0 });+ captain.seated = null;+ }, [placeAt, grid]);++ const usedWalk = useRef(0);+ useEffect(() => {+ if (!walkTo || walkTo.seq === usedWalk.current) return;+ usedWalk.current = walkTo.seq;+ const route = findPath(grid, body.current, walkTo.at);+ if (route) { body.current.path = route; captain.seated = null; }+ }, [walkTo, grid]);++ useEffect(() => {+ if (!awake) return;+ const owns = (e: KeyboardEvent) => {+ if (typesText(e.target)) return false;+ const host = props.keyHost.current;+ const active = document.activeElement;+ return !active || active === document.body || (host?.contains(active) ?? false);+ };+ const down = (e: KeyboardEvent) => {+ if (!KEYS.has(e.code) || !owns(e)) return;+ keys.current.add(e.code);+ if (e.code.startsWith("Arrow")) e.preventDefault();+ };+ const up = (e: KeyboardEvent) => keys.current.delete(e.code);+ const blur = () => keys.current.clear();+ window.addEventListener("keydown", down);+ window.addEventListener("keyup", up);+ window.addEventListener("blur", blur);+ return () => { window.removeEventListener("keydown", down); window.removeEventListener("keyup", up); window.removeEventListener("blur", blur); keys.current.clear(); };+ }, [awake, props.keyHost]);++ // The route marker: a dotted line of lights to the destination.+ const marker = useMemo(() => {+ const g = new BufferGeometry();+ g.setAttribute("position", new Float32BufferAttribute(new Float32Array(3 * 200), 3));+ const m = new PointsMaterial({ color: new Color(1.6, 1.25, 0.5), size: 0.16, sizeAttenuation: true, toneMapped: false, transparent: true, opacity: 0.9, depthWrite: false });+ const p = new Points(g, m);+ p.frustumCulled = false;+ return p;+ }, []);+ useEffect(() => () => { marker.geometry.dispose(); (marker.material as PointsMaterial).dispose(); }, [marker]);++ const { camera } = useThree();+ void camera;+ useFrame((_, rawDt) => {+ const dt = Math.min(0.1, rawDt);+ t.current += dt;+ const b = body.current;+ const k = keys.current;+ const fwd = (k.has("KeyW") || k.has("ArrowUp") ? 1 : 0) - (k.has("KeyS") || k.has("ArrowDown") ? 1 : 0);+ const side = (k.has("KeyD") || k.has("ArrowRight") ? 1 : 0) - (k.has("KeyA") || k.has("ArrowLeft") ? 1 : 0);+ const run = k.has("ShiftLeft") || k.has("ShiftRight");+ let moving = false;+ if (fwd !== 0 || side !== 0) {+ b.path = [];+ captain.seated = null;+ // Camera-relative: forward is away from the camera on the floor.+ const cy = orbit.yaw;+ const dx = -Math.sin(cy) * fwd + Math.cos(cy) * side;+ const dz = -Math.cos(cy) * fwd - Math.sin(cy) * side;+ const len = Math.hypot(dx, dz) || 1;+ const pace = run ? RUN : WALK;+ b.speed += (pace - b.speed) * Math.min(1, dt * 8);+ const step = b.speed * dt;+ const nx = b.x + (dx / len) * step, nz = b.z + (dz / len) * step;+ if (isFree(grid, { x: nx, z: nz })) { b.x = nx; b.z = nz; }+ else if (isFree(grid, { x: nx, z: b.z })) b.x = nx;+ else if (isFree(grid, { x: b.x, z: nz })) b.z = nz;+ b.yaw = turnTowards(b.yaw, Math.atan2(dx, dz), dt, 10);+ b.phase += step / 1.3;+ moving = true;+ } else if (b.path.length > 0) {+ const left = b.path.reduce((s, p, i) => s + Math.hypot(p.x - (i ? b.path[i - 1].x : b.x), p.z - (i ? b.path[i - 1].z : b.z)), 0);+ const pace = left > 14 ? RUN : WALK;+ const before = { x: b.x, z: b.z };+ stepAlong(b, dt, pace);+ moving = Math.hypot(b.x - before.x, b.z - before.z) > 1e-4 || b.path.length > 0;+ } else {+ b.speed = 0;+ }+ if (captain.seated) {+ b.x = captain.seated.x; b.z = captain.seated.z;+ b.yaw = turnTowards(b.yaw, captain.seated.yaw, dt, 6);+ }+ Object.assign(captain, { x: b.x, z: b.z, yaw: wrapAngle(b.yaw), path: b.path, moving, speed: b.speed });+ figure.apply({+ activity: captain.seated ? "sit" : moving ? "walk" : "stand", t: props.reduced ? 0 : t.current, phase: b.phase, speed: b.speed,+ seatY: captain.seated?.seatY, seed: 0.42,+ }, dt);+ figure.group.position.set(b.x, 0, b.z);+ figure.group.rotation.y = b.yaw;+ // Route marker.+ const pos = marker.geometry.attributes.position as Float32BufferAttribute;+ let n = 0, prev: Vec2 = { x: b.x, z: b.z };+ for (const p of b.path) {+ const len = Math.hypot(p.x - prev.x, p.z - prev.z);+ for (let d = 0.45; d < len && n < 199; d += 0.45) {+ const tt = d / len;+ pos.setXYZ(n++, prev.x + (p.x - prev.x) * tt, 0.05, prev.z + (p.z - prev.z) * tt);+ }+ prev = p;+ }+ marker.geometry.setDrawRange(0, n);+ pos.needsUpdate = true;+ });++ return (+ <>+ <primitive object={figure.group} />+ <primitive object={marker} />+ </>+ );+}++/** Walk the captain to a clicked floor point (anything solid resolves to free floor beside it). */+export function walkCaptainTo(grid: NavGrid, at: Vec2): void {+ const target = nearestFree(grid, at, 4);+ if (!target) return;+ useShip.getState().requestWalk(target);+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/life/CrewLayer.tsx b/dodaios/ui/web/frontend/src/components/society/starship/life/CrewLayer.tsxnew file mode 100644index 0000000000..375d3d0b1c--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/life/CrewLayer.tsx@@ -0,0 +1,263 @@+/**+ * The crew on a deck: one android per agent, each living its day (crewLife)+ * and walking the deck (motion + navigation). Figures are imperative objects+ * updated in one frame callback; React only adds and removes them.+ */+import { useFrame, type ThreeEvent } from "@react-three/fiber";+import { useEffect, useMemo, useRef } from "react";+import { CylinderGeometry, Group, Mesh, MeshBasicMaterial, type Material } from "three";+import type { AgentRunState } from "../../data";+import { CrewFigure } from "../crew/figure";+import type { FaceAtlas, FaceLook, FaceMood } from "../crew/faceAtlas";+import type { Activity } from "../crew/rig";+import { findPath, isFree, nearestFree, type NavGrid } from "../nav/shipNav";+import type { DeckPlan, Vec2 } from "../plan/types";+import { captain } from "../shipStore";+import { seatedCrew } from "../../crewFeeds/seated";+import { decide, PlaceBook, type Intent, type RoundView } from "./crewLife";+import { BODY_GAP, stepAlong, turnTowards, type Body } from "./motion";++export interface CrewView {+ agentId: string;+ name: string;+ state: AgentRunState;+ division: string | null;+ face: FaceLook;+ accent: string;+ pips: number;+ gold: boolean;+ lead: boolean;+ ribbons: number;+}++export interface CrewPose { x: number; z: number; yaw: number; activity: Activity; headY: number; moving: boolean }++/** Where every crew member is, for name plates, the minimap and the captain's prompt. */+export const crewPoses = new Map<string, CrewPose>();++interface Walker extends Body {+ id: string;+ figure: CrewFigure;+ hit: Mesh;+ lookKey: string;+ intent: Intent | null;+ state: AgentRunState;+ turn: number;+ last: string | null;+ blockedS: number;+ arrived: boolean;+ seed: number;+ t: number;+}++const HIT_GEO = new CylinderGeometry(0.34, 0.34, 1.8, 8);+HIT_GEO.translate(0, 0.9, 0);+const HIT_MAT = new MeshBasicMaterial({ visible: false });++const PACE = 1.35;++function moodOf(state: AgentRunState, activity: Activity): FaceMood {+ if (activity === "talk") return "talking";+ if (state === "working") return "working";+ if (state === "waiting") return "waiting";+ if (state === "paused") return "paused";+ return "idle";+}++export function CrewLayer(props: {+ plan: DeckPlan;+ grid: NavGrid;+ crew: readonly CrewView[];+ rounds: ReadonlyMap<string, RoundView>;+ called: { place: string; agentIds: readonly string[] } | null;+ atlas: FaceAtlas;+ faceMaterial: Material;+ reduced: boolean;+ /** Agents that just joined: they beam in at the transporter and walk to their place. */+ newcomers: ReadonlySet<string>;+ onPick: (agentId: string) => void;+ onHover: (agentId: string | null) => void;+}) {+ const { plan, grid, crew, atlas, faceMaterial, reduced } = props;+ const group = useMemo(() => new Group(), []);+ const walkers = useRef(new Map<string, Walker>());+ const book = useMemo(() => new PlaceBook(), []);+ const ctxRef = useRef(props);+ ctxRef.current = props;++ useEffect(() => { book.retain(new Set(plan.places.map((p) => p.id))); }, [book, plan]);++ // Add, rebuild and remove figures as the crew changes.+ useEffect(() => {+ const live = walkers.current;+ const seen = new Set<string>();+ for (const member of crew) {+ seen.add(member.agentId);+ const lookKey = `${member.accent}|${member.pips}|${member.gold}|${member.lead}|${member.ribbons}`;+ const uv = atlas.cell(member.agentId, member.face);+ let w = live.get(member.agentId);+ if (w && w.lookKey !== lookKey) {+ group.remove(w.figure.group);+ w.figure.dispose();+ w.figure = new CrewFigure({ kind: "android", android: { accent: member.accent, pips: member.pips, gold: member.gold, lead: member.lead, ribbons: member.ribbons }, face: { material: faceMaterial, uv } });+ w.figure.group.add(w.hit);+ group.add(w.figure.group);+ w.lookKey = lookKey;+ }+ if (!w) {+ const figure = new CrewFigure({ kind: "android", android: { accent: member.accent, pips: member.pips, gold: member.gold, lead: member.lead, ribbons: member.ribbons }, face: { material: faceMaterial, uv } });+ const hit = new Mesh(HIT_GEO, HIT_MAT);+ hit.userData.agentId = member.agentId;+ figure.group.add(hit);+ group.add(figure.group);+ const fresh = props.newcomers.has(member.agentId);+ const start = fresh ? plan.arrival : (plan.seatOf.get(member.agentId) ?? nearestFree(grid, plan.arrival) ?? plan.arrival);+ w = {+ id: member.agentId, figure, hit, lookKey, x: start.x, z: start.z, yaw: Math.PI, path: [], speed: 0, phase: 0,+ intent: null, state: member.state, turn: 0, last: null, blockedS: 0, arrived: !fresh, seed: (hashSeed(member.agentId) % 1000) / 1000, t: 0,+ };+ live.set(member.agentId, w);+ // Everyone already aboard is simply at their place; a newcomer walks from the pad.+ settle(w, fresh);+ }+ w.state = member.state;+ atlas.setMood(member.agentId, moodOf(member.state, w.intent?.activity ?? "stand"));+ }+ for (const [id, w] of [...live]) {+ if (seen.has(id)) continue;+ group.remove(w.figure.group);+ w.figure.dispose();+ book.release(id);+ atlas.release(id);+ crewPoses.delete(id);+ seatedCrew.delete(id);+ live.delete(id);+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [crew, atlas, faceMaterial, group]);++ // A rebuilt plan: everyone decides again (their places may have moved).+ useEffect(() => {+ for (const w of walkers.current.values()) { w.intent = null; w.path = []; }+ }, [plan]);++ useEffect(() => () => {+ for (const w of walkers.current.values()) { w.figure.dispose(); crewPoses.delete(w.id); seatedCrew.delete(w.id); }+ walkers.current.clear();+ }, []);++ function settle(w: Walker, walk: boolean) {+ const ctx = ctxRef.current;+ const member = ctx.crew.find((c) => c.agentId === w.id);+ if (!member) return;+ w.intent = decide({ agentId: w.id, state: member.state, division: member.division }, {+ plan: ctx.plan, book, nowMs: Date.now(), rounds: ctx.rounds, called: ctx.called, turn: w.turn++, last: w.last, at: { x: w.x, z: w.z },+ });+ w.last = w.intent.placeId;+ if (!walk || ctx.reduced) {+ w.x = w.intent.target.x; w.z = w.intent.target.z; w.yaw = w.intent.yaw; w.path = []; w.arrived = true;+ } else {+ w.path = findPath(ctx.grid, { x: w.x, z: w.z }, w.intent.target) ?? [];+ w.arrived = w.path.length === 0;+ if (w.arrived) { w.x = w.intent.target.x; w.z = w.intent.target.z; }+ }+ }++ const callKey = props.called ? `${props.called.place}|${props.called.agentIds.join(",")}` : "";+ const roundKey = [...props.rounds].map(([k, r]) => `${k}:${r.running}:${r.speakerId}`).join(",");+ // A change in state, rounds or calls makes the affected crew decide again.+ useEffect(() => {+ for (const member of crew) {+ const w = walkers.current.get(member.agentId);+ if (!w || !w.intent) continue;+ const stale = w.intent.reason === "work" ? member.state !== "working"+ : w.intent.reason === "wait" ? member.state !== "waiting"+ : w.intent.reason === "rest" ? member.state !== "paused"+ : member.state === "working" || member.state === "waiting" || member.state === "paused";+ if (stale) w.intent = null;+ }+ }, [crew]);+ useEffect(() => {+ for (const w of walkers.current.values()) {+ if (!w.intent) continue;+ if (w.intent.reason === "round" || w.intent.reason === "called" || w.intent.reason === "idle") w.intent = null;+ }+ }, [callKey, roundKey]);++ useFrame((_, rawDt) => {+ const dt = Math.min(0.1, rawDt);+ const now = Date.now();+ const list = [...walkers.current.values()];+ for (const w of list) {+ w.t += dt;+ if (!w.intent || (w.arrived && now > w.intent.untilMs)) {+ settle(w, true);+ }+ if (!w.arrived) {+ const arrived = stepAlong(w, dt, PACE, (nx, nz) => {+ if (Math.hypot(nx - captain.x, nz - captain.z) < BODY_GAP && Math.hypot(w.x - captain.x, w.z - captain.z) > Math.hypot(nx - captain.x, nz - captain.z)) return true;+ for (const o of list) {+ if (o === w || o.arrived) continue;+ const now2 = Math.hypot(nx - o.x, nz - o.z), before = Math.hypot(w.x - o.x, w.z - o.z);+ if (now2 < BODY_GAP && now2 < before) return true;+ }+ return false;+ });+ if (w.speed < 0.05 && !arrived) {+ w.blockedS += dt;+ if (w.blockedS > 1.4) {+ w.blockedS = 0;+ // Step aside and plan again from there.+ const side = { x: w.x + Math.cos(w.yaw) * 0.6, z: w.z - Math.sin(w.yaw) * 0.6 };+ if (isFree(grid, side) && w.intent) w.path = [side, ...(findPath(grid, side, w.intent.target) ?? [])];+ }+ } else w.blockedS = 0;+ if (arrived && w.intent) {+ w.arrived = true;+ w.x = w.intent.target.x; w.z = w.intent.target.z;+ }+ } else if (w.intent) {+ // Settle into the place's facing; a waiting agent turns to the captain when the captain comes close.+ let goal = w.intent.yaw;+ if (w.intent.reason === "wait" && Math.hypot(captain.x - w.x, captain.z - w.z) < 6) goal = Math.atan2(captain.x - w.x, captain.z - w.z);+ w.yaw = turnTowards(w.yaw, goal, dt, 5);+ }+ const activity: Activity = w.arrived ? (w.intent?.activity ?? "stand") : "walk";+ // Seated at its own console: its screen is worth reading.+ const atConsole = w.arrived && !!w.intent?.placeId && w.intent.placeId === ctxRef.current.plan.seatOf.get(w.id)?.id;+ if (atConsole) seatedCrew.add(w.id); else seatedCrew.delete(w.id);+ w.figure.apply({ activity, t: reduced ? 0 : w.t, phase: w.phase, speed: w.speed, seatY: w.intent?.seatY, seed: w.seed }, dt);+ w.figure.group.position.set(w.x, 0, w.z);+ w.figure.group.rotation.y = w.yaw;+ atlas.setMood(w.id, moodOf(w.state, activity));+ const pose = crewPoses.get(w.id);+ const headY = activity === "rest" ? 0.9 : activity === "sit" || activity === "type" ? 1.35 : 1.85;+ if (pose) { pose.x = w.x; pose.z = w.z; pose.yaw = w.yaw; pose.activity = activity; pose.headY = headY; pose.moving = !w.arrived; }+ else crewPoses.set(w.id, { x: w.x, z: w.z, yaw: w.yaw, activity, headY, moving: !w.arrived });+ }+ atlas.tick(now, reduced);+ });++ const pick = (e: ThreeEvent<MouseEvent>) => {+ const id = e.object.userData.agentId as string | undefined;+ if (!id) return;+ e.stopPropagation();+ props.onPick(id);+ };+ const over = (e: ThreeEvent<PointerEvent>) => {+ const id = e.object.userData.agentId as string | undefined;+ if (id) { e.stopPropagation(); props.onHover(id); }+ };+ return <primitive object={group} onClick={pick} onPointerOver={over} onPointerOut={() => props.onHover(null)} />;+}++function hashSeed(id: string): number {+ let h = 7;+ for (let i = 0; i < id.length; i += 1) h = (h * 33 + id.charCodeAt(i)) >>> 0;+ return h;+}++/** Points that a waiting body would turn to (for tests and the plates). */+export function facingCaptain(from: Vec2): number {+ return Math.atan2(captain.x - from.x, captain.z - from.z);+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/life/ShipPet.tsx b/dodaios/ui/web/frontend/src/components/society/starship/life/ShipPet.tsxnew file mode 100644index 0000000000..91b3652490--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/life/ShipPet.tsx@@ -0,0 +1,96 @@+/**+ * The captain's companion: the pet from My Pets (Gigi when none is chosen),+ * who is the user's assistant in the Verse. It keeps a little behind the+ * captain's shoulder; flyers hover at head height, pets that walk stay on+ * free floor and turn the way they move. A soft glow marks a flyer.+ */+import { Component, Suspense, useMemo, useRef, type ReactNode } from "react";+import { useFrame } from "@react-three/fiber";+import { Color, type Group } from "three";+import { CompanionModel } from "../../companion/AgentFollower";+import { defaultCompanion } from "../../companion/appearance";+import { useCompanionPet } from "../../companion/companionPetStore";+import { companionFlies, type CompanionPet } from "../../companion/petCompanions";+import { PetModel, VoxelPet, type PetDrive } from "../../companion/PetModel";+import { isFree, type NavGrid } from "../nav/shipNav";+import { captain } from "../shipStore";+import { turnTowards } from "./motion";++/** A missing or broken model hides the body, never the ship. */+class Boundary extends Component<{ children: ReactNode }, { failed: boolean }> {+ state = { failed: false };+ static getDerivedStateFromError() { return { failed: true }; }+ componentDidCatch(error: Error) { console.warn("Companion model unavailable", error.name); }+ render() { return this.state.failed ? null : this.props.children; }+}++const GIGI_SIZE_M = 0.5;+const FOLLOW_BACK = 1.05;+const FOLLOW_SIDE = 0.75;+/** Every this many metres walked together pays the companion a little XP (metered on the server). */+export const WALK_REPORT_M = 50;++function Body({ pet, drive, reduced }: { pet: CompanionPet; drive: { current: PetDrive }; reduced: boolean }) {+ const gigi = useMemo(() => ({ ...defaultCompanion("jarvis"), sizeM: GIGI_SIZE_M }), []);+ if (pet.kind === "model") return <PetModel pet={pet} drive={drive} reduced={reduced} paused={false} />;+ if (pet.kind === "voxel") return <VoxelPet pet={pet} reduced={reduced} paused={false} />;+ return <CompanionModel appearance={gigi} lead />;+}++export function ShipPet({ grid, reduced, onWalked }: { grid: NavGrid; reduced: boolean; onWalked?: () => void }) {+ const pet = useCompanionPet((s) => s.pet);+ const flies = companionFlies(pet);+ const root = useRef<Group>(null);+ const body = useRef({ x: captain.x + FOLLOW_SIDE, z: captain.z + FOLLOW_BACK, yaw: captain.yaw, t: 0 });+ const drive = useRef<PetDrive>({ speed: 0, mood: "idle" });+ const walked = useRef({ x: captain.x, z: captain.z, metres: 0 });+ const glow = useMemo(() => new Color("#ffd98a").multiplyScalar(1.6), []);+ useFrame((_, rawDt) => {+ const dt = Math.min(0.1, rawDt);+ const b = body.current;+ b.t += dt;+ const w = walked.current;+ const step = Math.hypot(captain.x - w.x, captain.z - w.z);+ // A jump (a deck change, a placement) is not a walk.+ if (step < 3) w.metres += step;+ w.x = captain.x; w.z = captain.z;+ if (w.metres >= WALK_REPORT_M) { w.metres -= WALK_REPORT_M; onWalked?.(); }+ // Behind the captain's right shoulder, in the captain's own frame.+ const s = Math.sin(captain.yaw), c = Math.cos(captain.yaw);+ let tx = captain.x - s * FOLLOW_BACK - c * FOLLOW_SIDE;+ let tz = captain.z - c * FOLLOW_BACK + s * FOLLOW_SIDE;+ if (!flies && !isFree(grid, { x: tx, z: tz })) { tx = captain.x - s * FOLLOW_BACK; tz = captain.z - c * FOLLOW_BACK; }+ const dx = tx - b.x, dz = tz - b.z;+ const dist = Math.hypot(dx, dz);+ const k = 1 - Math.exp(-dt * (dist > 4 ? 5 : 2.6));+ const nx = b.x + dx * k, nz = b.z + dz * k;+ if (flies || isFree(grid, { x: nx, z: nz })) { b.x = nx; b.z = nz; }+ const speed = (dist * k) / Math.max(dt, 1e-3);+ drive.current.speed = speed;+ drive.current.mood = "idle";+ b.yaw = speed > 0.15 ? turnTowards(b.yaw, Math.atan2(dx, dz), dt, 6) : turnTowards(b.yaw, captain.yaw, dt, 2);+ const g = root.current;+ if (g) {+ const bob = flies && !reduced ? Math.sin(b.t * 2.1) * 0.06 : 0;+ g.position.set(b.x, flies ? 1.45 + bob : 0, b.z);+ g.rotation.y = b.yaw;+ }+ });+ return (+ <group ref={root}>+ <Boundary>+ <Suspense fallback={null}>+ <group position={[0, flies && pet.kind === "gigi" ? -0.26 : flies ? -pet.heightM / 2 : 0, 0]}>+ <Body pet={pet} drive={drive} reduced={reduced} />+ </group>+ </Suspense>+ </Boundary>+ {flies && (+ <mesh position={[0, -0.35, 0]} rotation={[-Math.PI / 2, 0, 0]} raycast={() => undefined}>+ <circleGeometry args={[0.18, 24]} />+ <meshBasicMaterial color={glow} transparent opacity={0.35} toneMapped={false} depthWrite={false} />+ </mesh>+ )}+ </group>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/life/crewLife.ts b/dodaios/ui/web/frontend/src/components/society/starship/life/crewLife.tsnew file mode 100644index 0000000000..b3fa37fb4a--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/life/crewLife.ts@@ -0,0 +1,191 @@+/**+ * What a crew member does next. Pure and deterministic per agent: the real+ * run state decides the place (working sits at its own console, waiting+ * stands at it and waves for the captain, paused rests in a pod), a running+ * round of its team gathers it at the division's holo-table, and an idle+ * agent lives a seeded day between its console, the mess, the lounge, the+ * windows and the gardens. Nothing here starts or stops work.+ */+import type { AgentRunState } from "../../data";+import type { Activity } from "../crew/rig";+import { hash } from "../plan/builder";+import type { DeckPlan, Place, PlaceKind, Vec2 } from "../plan/types";++export type Reason = "work" | "wait" | "rest" | "idle" | "round" | "called" | "arrive";++export interface Intent {+ placeId: string | null;+ target: Vec2;+ yaw: number;+ /** What the body does once there. */+ activity: Activity;+ seatY: number;+ /** When an idle stay ends (ms since epoch); Infinity for state-bound places. */+ untilMs: number;+ reason: Reason;+}++/** Who holds which free place, so nobody sits on anybody. */+export class PlaceBook {+ private readonly byPlace = new Map<string, string>();+ private readonly byAgent = new Map<string, string>();++ holder(placeId: string): string | undefined { return this.byPlace.get(placeId); }++ reserve(placeId: string, agentId: string): boolean {+ const held = this.byPlace.get(placeId);+ if (held && held !== agentId) return false;+ this.release(agentId);+ this.byPlace.set(placeId, agentId);+ this.byAgent.set(agentId, placeId);+ return true;+ }++ release(agentId: string): void {+ const place = this.byAgent.get(agentId);+ if (place) { this.byPlace.delete(place); this.byAgent.delete(agentId); }+ }++ /** Forget places a rebuilt plan no longer has. */+ retain(ids: ReadonlySet<string>): void {+ for (const [place, agent] of [...this.byPlace]) if (!ids.has(place)) { this.byPlace.delete(place); this.byAgent.delete(agent); }+ }+}++export interface CrewState {+ agentId: string;+ state: AgentRunState;+ /** The division (room id) the agent belongs to, if it is seated. */+ division: string | null;+}++export interface RoundView {+ running: boolean;+ speakerId: string | null;+}++export interface LifeContext {+ plan: DeckPlan;+ book: PlaceBook;+ nowMs: number;+ /** Running rounds by division room id. */+ rounds: ReadonlyMap<string, RoundView>;+ /** A gathering the captain called (by place: a division room id or "mess"). */+ called: { place: string; agentIds: readonly string[] } | null;+ /** How many idle decisions this agent made so far (feeds its seed). */+ turn: number;+ /** The place it took last time, so the same is not taken twice in a row. */+ last: string | null;+ /** Where the agent stands now. */+ at: Vec2;+}++const IDLE_WEIGHTS: Partial<Record<PlaceKind, number>> = {+ console: 26, mess: 16, lounge: 14, window: 14, galley: 9, stroll: 11, table: 10,+};++function rng(seed: number): () => number {+ let s = seed >>> 0 || 1;+ return () => { s ^= s << 13; s >>>= 0; s ^= s >> 17; s ^= s << 5; s >>>= 0; return s / 4294967296; };+}++function activityAt(place: Place, state: AgentRunState, reason: Reason): Activity {+ if (place.pose === "rest") return "rest";+ if (place.pose === "sit") return place.kind === "console" && state === "working" ? "type" : "sit";+ if (reason === "wait") return "wave";+ if (place.kind === "galley") return "lean";+ if (place.kind === "table") return reason === "round" ? "listen" : "talk";+ return "stand";+}++function intentFor(place: Place, state: AgentRunState, reason: Reason, untilMs: number): Intent {+ return { placeId: place.id, target: { x: place.x, z: place.z }, yaw: place.yaw, activity: activityAt(place, state, reason), seatY: place.seatY, untilMs, reason };+}++/** A standing place in front of the agent's own console (for waiting). */+function standAtConsole(seat: Place): Intent {+ return { placeId: null, target: { x: seat.x, z: seat.z }, yaw: seat.yaw, activity: "wave", seatY: 0, untilMs: Infinity, reason: "wait" };+}++export function decide(member: CrewState, ctx: LifeContext): Intent {+ const { plan, book } = ctx;+ const seat = plan.seatOf.get(member.agentId) ?? null;+ const division = member.division;++ // The captain's call outranks everything but work.+ if (ctx.called && ctx.called.agentIds.includes(member.agentId) && member.state !== "working") {+ const pool = ctx.called.place === "mess"+ ? plan.places.filter((p) => p.kind === "mess" || p.kind === "galley")+ : plan.places.filter((p) => p.kind === "table" && p.division === ctx.called?.place);+ const free = pool.filter((p) => !book.holder(p.id) || book.holder(p.id) === member.agentId);+ const pick = nearest(free, ctx.at);+ if (pick && book.reserve(pick.id, member.agentId)) return intentFor(pick, member.state, "called", Infinity);+ }++ if (member.state === "working" && seat) {+ book.release(member.agentId);+ return intentFor(seat, member.state, "work", Infinity);+ }+ // A round of the agent's team: idle and waiting members gather at the table.+ const round = division ? ctx.rounds.get(division) : undefined;+ if (round?.running && division && member.state !== "paused") {+ const gather = plan.places.filter((p) => p.kind === "table" && p.division === division);+ const own = gather.find((p) => book.holder(p.id) === member.agentId);+ const pick = own ?? nearest(gather.filter((p) => !book.holder(p.id)), ctx.at);+ if (pick && book.reserve(pick.id, member.agentId)) {+ const intent = intentFor(pick, member.state, "round", Infinity);+ if (round.speakerId === member.agentId) intent.activity = "talk";+ return intent;+ }+ }+ if (member.state === "waiting" && seat) {+ book.release(member.agentId);+ return standAtConsole(seat);+ }+ if (member.state === "paused") {+ const pods = plan.places.filter((p) => p.kind === "pod");+ const own = pods.find((p) => book.holder(p.id) === member.agentId);+ const pick = own ?? pods.find((p) => !book.holder(p.id));+ if (pick && book.reserve(pick.id, member.agentId)) return intentFor(pick, member.state, "rest", Infinity);+ if (seat) return { ...intentFor(seat, "idle", "rest", Infinity), activity: "sit" };+ }++ // Idle: a seeded choice of place.+ const random = rng(hash(member.agentId) ^ Math.imul(ctx.turn + 1, 2654435761));+ const stay = 25_000 + random() * 65_000;+ const candidates: { place: Place; weight: number }[] = [];+ for (const place of plan.places) {+ const w = IDLE_WEIGHTS[place.kind];+ if (!w || place.id === ctx.last) continue;+ if (place.kind === "console") { if (place.id !== seat?.id) continue; }+ else if (book.holder(place.id) && book.holder(place.id) !== member.agentId) continue;+ // The own division's table and windows are home; somebody else's division is not a hangout.+ if (place.division && place.division !== division) continue;+ const d = Math.hypot(place.x - ctx.at.x, place.z - ctx.at.z);+ const near = 1 / (1 + d / 18);+ candidates.push({ place, weight: w * (place.division ? 1.4 : 1) * (0.35 + near) });+ }+ const total = candidates.reduce((s, c) => s + c.weight, 0);+ let roll = random() * total;+ for (const c of candidates) {+ roll -= c.weight;+ if (roll <= 0) {+ if (c.place.kind === "console" || book.reserve(c.place.id, member.agentId)) {+ if (c.place.kind === "console") book.release(member.agentId);+ return intentFor(c.place, member.state, "idle", ctx.nowMs + stay);+ }+ }+ }+ // Nowhere free: stay where it is a while.+ book.release(member.agentId);+ return { placeId: null, target: ctx.at, yaw: 0, activity: "stand", seatY: 0, untilMs: ctx.nowMs + 15_000, reason: "idle" };+}++function nearest(list: readonly Place[], at: Vec2): Place | undefined {+ let best: Place | undefined, bd = Infinity;+ for (const p of list) {+ const d = Math.hypot(p.x - at.x, p.z - at.z);+ if (d < bd) { bd = d; best = p; }+ }+ return best;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/life/motion.ts b/dodaios/ui/web/frontend/src/components/society/starship/life/motion.tsnew file mode 100644index 0000000000..f02e533abb--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/life/motion.ts@@ -0,0 +1,65 @@+/**+ * Walking along a route: a body turns towards its next waypoint (and slows+ * while it is still turning), keeps a steady pace, gives way to other bodies+ * in front of it and lands exactly on its last waypoint.+ */+import type { Vec2 } from "../plan/types";++export interface Body {+ x: number;+ z: number;+ yaw: number;+ path: Vec2[];+ /** Current speed (m/s). */+ speed: number;+ /** Walk cycle, in strides. */+ phase: number;+}++export const BODY_GAP = 0.6;+const TURN_RATE = 7;++export function wrapAngle(a: number): number {+ return Math.atan2(Math.sin(a), Math.cos(a));+}++export function turnTowards(yaw: number, goal: number, dt: number, rate = TURN_RATE): number {+ const d = wrapAngle(goal - yaw);+ const step = Math.sign(d) * Math.min(Math.abs(d), rate * dt);+ return wrapAngle(yaw + step);+}++/**+ * Advance `body` along its path for `dt` seconds at up to `pace` m/s.+ * `blocked(x, z)` reports another body in the way. Returns true on arrival+ * (the path is empty).+ */+export function stepAlong(body: Body, dt: number, pace: number, blocked?: (x: number, z: number) => boolean): boolean {+ if (body.path.length === 0) { body.speed = 0; return true; }+ const next = body.path[0];+ const dx = next.x - body.x, dz = next.z - body.z;+ const dist = Math.hypot(dx, dz);+ if (dist < 0.02) {+ body.x = next.x; body.z = next.z;+ body.path.shift();+ return body.path.length === 0;+ }+ const heading = Math.atan2(dx, dz);+ body.yaw = turnTowards(body.yaw, heading, dt);+ const off = Math.abs(wrapAngle(heading - body.yaw));+ // Slow down while facing away; ease into the last metre.+ const last = body.path.length === 1;+ const target = pace * Math.max(0.08, Math.cos(Math.min(off, Math.PI / 2))) * (last ? Math.min(1, 0.35 + dist) : 1);+ body.speed += (target - body.speed) * Math.min(1, dt * 6);+ let step = Math.min(dist, body.speed * dt);+ const nx = body.x + (dx / dist) * step, nz = body.z + (dz / dist) * step;+ if (blocked && blocked(nx, nz)) {+ body.speed *= 0.5;+ step = 0;+ return false;+ }+ body.x = nx; body.z = nz;+ body.phase += step / 1.25;+ if (step >= dist - 1e-6) body.path.shift();+ return body.path.length === 0;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/nav/shipNav.ts b/dodaios/ui/web/frontend/src/components/society/starship/nav/shipNav.tsnew file mode 100644index 0000000000..a6b6c4545f--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/nav/shipNav.ts@@ -0,0 +1,225 @@+/**+ * Walking on a deck: an occupancy grid rasterised from the plan, A* over it+ * and a line-of-sight pass that turns the cell path into a few straight legs.+ *+ * Everything solid (the hull, bulkheads, glass, rails and solid furniture)+ * is grown by a body's clearance, so a route through free cells keeps every+ * body clear of it. A target inside something solid (a rest pod, a seat+ * tucked against a console) is reached by walking to the nearest free cell+ * and stepping onto it, which is what sitting down looks like.+ */+import { insidePolygon } from "../plan/builder";+import type { DeckPlan, Vec2 } from "../plan/types";++export const CELL = 0.2;+/** How far every body keeps from anything solid. */+export const CLEARANCE = 0.3;++export interface NavGrid {+ x0: number;+ z0: number;+ cols: number;+ rows: number;+ /** 1 = blocked. */+ blocked: Uint8Array;+}++export function cellOf(grid: NavGrid, p: Vec2): [number, number] {+ return [Math.floor((p.x - grid.x0) / CELL), Math.floor((p.z - grid.z0) / CELL)];+}++export function centreOf(grid: NavGrid, c: number, r: number): Vec2 {+ return { x: grid.x0 + (c + 0.5) * CELL, z: grid.z0 + (r + 0.5) * CELL };+}++export function isFree(grid: NavGrid, p: Vec2): boolean {+ const [c, r] = cellOf(grid, p);+ return c >= 0 && r >= 0 && c < grid.cols && r < grid.rows && grid.blocked[r * grid.cols + c] === 0;+}++function distToSegment(p: Vec2, a: Vec2, b: Vec2): number {+ const dx = b.x - a.x, dz = b.z - a.z;+ const len2 = dx * dx + dz * dz || 1e-9;+ const t = Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.z - a.z) * dz) / len2));+ return Math.hypot(p.x - (a.x + dx * t), p.z - (a.z + dz * t));+}++export function buildNavGrid(plan: DeckPlan, clearance = CLEARANCE): NavGrid {+ const pad = 1;+ const x0 = plan.bounds.x0 - pad, z0 = plan.bounds.z0 - pad;+ const cols = Math.ceil((plan.bounds.x1 - plan.bounds.x0 + pad * 2) / CELL);+ const rows = Math.ceil((plan.bounds.z1 - plan.bounds.z0 + pad * 2) / CELL);+ const blocked = new Uint8Array(cols * rows);+ const grid: NavGrid = { x0, z0, cols, rows, blocked };+ // Outside the hull.+ for (let r = 0; r < rows; r += 1) for (let c = 0; c < cols; c += 1) {+ if (!insidePolygon(plan.hull, centreOf(grid, c, r))) blocked[r * cols + c] = 1;+ }+ const mark = (minX: number, minZ: number, maxX: number, maxZ: number, test: (p: Vec2) => boolean) => {+ const c0 = Math.max(0, Math.floor((minX - x0) / CELL)), c1 = Math.min(cols - 1, Math.floor((maxX - x0) / CELL));+ const r0 = Math.max(0, Math.floor((minZ - z0) / CELL)), r1 = Math.min(rows - 1, Math.floor((maxZ - z0) / CELL));+ for (let r = r0; r <= r1; r += 1) for (let c = c0; c <= c1; c += 1) {+ if (blocked[r * cols + c]) continue;+ if (test(centreOf(grid, c, r))) blocked[r * cols + c] = 1;+ }+ };+ for (const wall of plan.walls) {+ const reach = wall.t / 2 + clearance;+ mark(Math.min(wall.a.x, wall.b.x) - reach, Math.min(wall.a.z, wall.b.z) - reach, Math.max(wall.a.x, wall.b.x) + reach, Math.max(wall.a.z, wall.b.z) + reach,+ (p) => distToSegment(p, wall.a, wall.b) <= reach);+ }+ for (const prop of plan.props) {+ if (!prop.solid) continue;+ const cos = Math.cos(prop.yaw), sin = Math.sin(prop.yaw);+ const hw = prop.w / 2 + clearance, hd = prop.d / 2 + clearance;+ const reach = Math.hypot(hw, hd);+ mark(prop.x - reach, prop.z - reach, prop.x + reach, prop.z + reach, (p) => {+ const dx = p.x - prop.x, dz = p.z - prop.z;+ // Into the piece's own frame: its x axis is (cos, -sin), its z axis (sin, cos) for a yaw about +y.+ const lx = dx * cos - dz * sin, lz = dx * sin + dz * cos;+ return Math.abs(lx) <= hw && Math.abs(lz) <= hd;+ });+ }+ return grid;+}++/** The nearest free point to `p` (spiral search), or null if there is none within `maxM`. */+export function nearestFree(grid: NavGrid, p: Vec2, maxM = 6): Vec2 | null {+ if (isFree(grid, p)) return p;+ const [c0, r0] = cellOf(grid, p);+ const maxRing = Math.ceil(maxM / CELL);+ let best: Vec2 | null = null, bestD = Infinity;+ for (let ring = 1; ring <= maxRing; ring += 1) {+ for (let dr = -ring; dr <= ring; dr += 1) for (let dc = -ring; dc <= ring; dc += 1) {+ if (Math.max(Math.abs(dr), Math.abs(dc)) !== ring) continue;+ const c = c0 + dc, r = r0 + dr;+ if (c < 0 || r < 0 || c >= grid.cols || r >= grid.rows || grid.blocked[r * grid.cols + c]) continue;+ const q = centreOf(grid, c, r);+ const d = Math.hypot(q.x - p.x, q.z - p.z);+ if (d < bestD) { bestD = d; best = q; }+ }+ if (best && bestD <= (ring + 0.5) * CELL) return best;+ }+ return best;+}++/** True when the straight line from a to b crosses only free cells. */+export function lineOfSight(grid: NavGrid, a: Vec2, b: Vec2): boolean {+ const len = Math.hypot(b.x - a.x, b.z - a.z);+ const steps = Math.max(1, Math.ceil(len / (CELL * 0.5)));+ for (let i = 0; i <= steps; i += 1) {+ const t = i / steps;+ if (!isFree(grid, { x: a.x + (b.x - a.x) * t, z: a.z + (b.z - a.z) * t })) return false;+ }+ return true;+}++class Heap {+ private readonly items: number[] = [];+ private readonly keys: number[] = [];+ get size() { return this.items.length; }+ push(item: number, key: number) {+ const { items, keys } = this;+ items.push(item); keys.push(key);+ let i = items.length - 1;+ while (i > 0) {+ const p = (i - 1) >> 1;+ if (keys[p] <= keys[i]) break;+ [items[p], items[i]] = [items[i], items[p]]; [keys[p], keys[i]] = [keys[i], keys[p]];+ i = p;+ }+ }+ pop(): number {+ const { items, keys } = this;+ const top = items[0];+ const lastItem = items.pop() as number, lastKey = keys.pop() as number;+ if (items.length > 0) {+ items[0] = lastItem; keys[0] = lastKey;+ let i = 0;+ for (;;) {+ const l = i * 2 + 1, r = l + 1;+ let m = i;+ if (l < items.length && keys[l] < keys[m]) m = l;+ if (r < items.length && keys[r] < keys[m]) m = r;+ if (m === i) break;+ [items[m], items[i]] = [items[i], items[m]]; [keys[m], keys[i]] = [keys[i], keys[m]];+ i = m;+ }+ }+ return top;+ }+}++const SQRT2 = Math.SQRT2;+const NEIGHBOURS: [number, number, number][] = [+ [1, 0, 1], [-1, 0, 1], [0, 1, 1], [0, -1, 1], [1, 1, SQRT2], [1, -1, SQRT2], [-1, 1, SQRT2], [-1, -1, SQRT2],+];++/**+ * A walkable route from `from` to `to` as a list of points (excluding the+ * start). An unreachable target returns null. A blocked start or end is+ * moved to the nearest free cell; a blocked end is then stepped onto.+ */+export function findPath(grid: NavGrid, from: Vec2, to: Vec2): Vec2[] | null {+ const start = nearestFree(grid, from, 3);+ const goal = nearestFree(grid, to, 3);+ if (!start || !goal) return null;+ const [sc, sr] = cellOf(grid, start), [gc, gr] = cellOf(grid, goal);+ const { cols, rows, blocked } = grid;+ const startIdx = sr * cols + sc, goalIdx = gr * cols + gc;+ const g = new Float32Array(cols * rows).fill(Infinity);+ const came = new Int32Array(cols * rows).fill(-1);+ const closed = new Uint8Array(cols * rows);+ const heap = new Heap();+ g[startIdx] = 0;+ heap.push(startIdx, 0);+ const h = (c: number, r: number) => {+ const dx = Math.abs(c - gc), dz = Math.abs(r - gr);+ return (dx + dz) + (SQRT2 - 2) * Math.min(dx, dz);+ };+ let found = startIdx === goalIdx;+ while (heap.size > 0 && !found) {+ const idx = heap.pop();+ if (closed[idx]) continue;+ closed[idx] = 1;+ if (idx === goalIdx) { found = true; break; }+ const c = idx % cols, r = (idx - c) / cols;+ for (const [dc, dr, cost] of NEIGHBOURS) {+ const nc = c + dc, nr = r + dr;+ if (nc < 0 || nr < 0 || nc >= cols || nr >= rows) continue;+ const n = nr * cols + nc;+ if (blocked[n] || closed[n]) continue;+ // No corner cutting.+ if (dc !== 0 && dr !== 0 && (blocked[r * cols + nc] || blocked[nr * cols + c])) continue;+ const ng = g[idx] + cost;+ if (ng < g[n]) { g[n] = ng; came[n] = idx; heap.push(n, ng + h(nc, nr)); }+ }+ }+ if (!found) return null;+ const cells: Vec2[] = [];+ for (let idx = goalIdx; idx !== -1 && idx !== startIdx; idx = came[idx]) {+ const c = idx % cols;+ cells.push(centreOf(grid, c, (idx - c) / cols));+ }+ cells.reverse();+ // String pulling: keep only the corners the straight line cannot skip.+ const legs: Vec2[] = [];+ let anchor = start;+ for (let i = 0; i < cells.length; i += 1) {+ const next = cells[i + 1];+ if (!next || !lineOfSight(grid, anchor, next)) {+ legs.push(cells[i]);+ anchor = cells[i];+ }+ }+ const end = legs[legs.length - 1];+ if (!end || Math.hypot(end.x - goal.x, end.z - goal.z) > 0.01) legs.push(goal);+ if (Math.hypot(goal.x - to.x, goal.z - to.z) > 0.02) legs.push({ x: to.x, z: to.z });+ return legs;+}++export function pathLength(from: Vec2, path: readonly Vec2[]): number {+ let len = 0, prev = from;+ for (const p of path) { len += Math.hypot(p.x - prev.x, p.z - prev.z); prev = p; }+ return len;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/plan/builder.ts b/dodaios/ui/web/frontend/src/components/society/starship/plan/builder.tsnew file mode 100644index 0000000000..6444376a6f--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/plan/builder.ts@@ -0,0 +1,138 @@+/**+ * Small helpers every deck plan is assembled with: a collector that refuses+ * duplicate ids, walls with doorways cut into them, arcs of seats, and the+ * team colours. Pure; no rendering here.+ */+import type { DeckId, DeckPlan, Door, Place, Prop, Rect, Room, Station, Vec2, Wall, WallKind, Division } from "./types";++/** Twelve division colours, picked to stay apart on a dark deck and from the state colours. */+export const DIVISION_COLOURS = [+ "#3fb6ff", "#f2a33a", "#a68cff", "#4fd1a6", "#ff6f91", "#e8d44d",+ "#5b8cff", "#ff8a4c", "#c06bd6", "#35c3c9", "#9bd65b", "#f07ad0",+] as const;++/** The crew without a team wears the ship's own steel blue. */+export const POOL_COLOUR = "#8aa4c8";+/** Command: everything the captain uses, and the leads' marks. */+export const COMMAND_GOLD = "#d9a441";+/** Information: holograms, screens. */+export const HOLO_CYAN = "#5fd4ff";++export function slug(id: string): string {+ return id.replace(/[^A-Za-z0-9_-]/g, "_");+}++export class PlanBuilder {+ readonly rooms: Room[] = [];+ readonly walls: Wall[] = [];+ readonly doors: Door[] = [];+ readonly props: Prop[] = [];+ readonly places: Place[] = [];+ readonly stations: Station[] = [];+ readonly divisions: Division[] = [];+ private readonly ids = new Set<string>();++ constructor(readonly deck: DeckId) {}++ /** Ids are unique per kind of thing: a station may share its prop's id. */+ private claim(kind: string, id: string): string {+ const key = `${kind}:${id}`;+ if (this.ids.has(key)) throw new Error(`duplicate plan id ${key}`);+ this.ids.add(key);+ return id;+ }++ room(room: Room): Room { this.claim("room", room.id); this.rooms.push(room); return room; }+ prop(prop: Prop): Prop { this.claim("prop", prop.id); this.props.push(prop); return prop; }+ place(place: Place): Place { this.claim("place", place.id); this.places.push(place); return place; }+ station(station: Station): Station { this.claim("station", station.id); this.stations.push(station); return station; }+ door(door: Door): Door { this.claim("door", door.id); this.doors.push(door); return door; }++ wall(id: string, kind: WallKind, a: Vec2, b: Vec2, t = kind === "hull" ? 0.5 : kind === "glass" ? 0.12 : kind === "rail" ? 0.1 : 0.24, windows = false): void {+ if (Math.hypot(b.x - a.x, b.z - a.z) < 0.05) return;+ this.walls.push({ id: this.claim("wall", id), kind, a, b, t, windows });+ }++ /**+ * A straight wall from `a` to `b` (axis-aligned) with doorways cut at the+ * given offsets (metres from `a`). Each doorway becomes a `Door`.+ */+ wallWithDoors(id: string, kind: WallKind, a: Vec2, b: Vec2, gaps: { at: number; width: number; slides?: boolean; id?: string }[], t?: number): void {+ const len = Math.hypot(b.x - a.x, b.z - a.z);+ const ux = (b.x - a.x) / len, uz = (b.z - a.z) / len;+ const axis: "x" | "z" = Math.abs(ux) > Math.abs(uz) ? "x" : "z";+ const sorted = [...gaps].sort((p, q) => p.at - q.at);+ let from = 0;+ sorted.forEach((gap, i) => {+ const s = Math.max(0, gap.at - gap.width / 2), e = Math.min(len, gap.at + gap.width / 2);+ this.wall(`${id}:${i}`, kind, { x: a.x + ux * from, z: a.z + uz * from }, { x: a.x + ux * s, z: a.z + uz * s }, t);+ this.door({ id: gap.id ?? `${id}:door${i}`, at: { x: a.x + ux * gap.at, z: a.z + uz * gap.at }, width: gap.width, axis, slides: gap.slides ?? true });+ from = e;+ });+ this.wall(`${id}:${sorted.length}`, kind, { x: a.x + ux * from, z: a.z + uz * from }, b, t);+ }++ build(extra: Pick<DeckPlan, "bounds" | "hull" | "arrival" | "lift"> & { seatOf?: Map<string, Place>; unseated?: string[] }): DeckPlan {+ return {+ deck: this.deck,+ bounds: extra.bounds,+ hull: extra.hull,+ rooms: this.rooms,+ walls: this.walls,+ doors: this.doors,+ props: this.props,+ places: this.places,+ stations: this.stations,+ divisions: this.divisions,+ seatOf: extra.seatOf ?? new Map(),+ arrival: extra.arrival,+ lift: extra.lift,+ unseated: extra.unseated ?? [],+ };+ }+}++/** Bounding box of a polygon. */+export function polygonBounds(points: readonly Vec2[]): Rect {+ let x0 = Infinity, z0 = Infinity, x1 = -Infinity, z1 = -Infinity;+ for (const p of points) { x0 = Math.min(x0, p.x); z0 = Math.min(z0, p.z); x1 = Math.max(x1, p.x); z1 = Math.max(z1, p.z); }+ return { x0, z0, x1, z1 };+}++/** Even-odd point-in-polygon. */+export function insidePolygon(points: readonly Vec2[], p: Vec2): boolean {+ let inside = false;+ for (let i = 0, j = points.length - 1; i < points.length; j = i++) {+ const a = points[i], b = points[j];+ if ((a.z > p.z) !== (b.z > p.z) && p.x < ((b.x - a.x) * (p.z - a.z)) / (b.z - a.z) + a.x) inside = !inside;+ }+ return inside;+}++/** Yaw that faces from `from` towards `to` (0 = +z). */+export function yawTowards(from: Vec2, to: Vec2): number {+ return Math.atan2(to.x - from.x, to.z - from.z);+}++/**+ * Points on an arc round `centre`: `count` evenly spaced over `span` radians,+ * centred on `mid` (the direction, as a yaw, the middle of the arc lies in).+ */+export function arcPoints(centre: Vec2, radius: number, count: number, mid: number, span: number): (Vec2 & { yaw: number })[] {+ const out: (Vec2 & { yaw: number })[] = [];+ if (count <= 0) return out;+ const step = count === 1 ? 0 : span / (count - 1);+ const start = mid - (step * (count - 1)) / 2;+ for (let i = 0; i < count; i += 1) {+ const a = start + step * i;+ out.push({ x: centre.x + Math.sin(a) * radius, z: centre.z + Math.cos(a) * radius, yaw: a });+ }+ return out;+}++/** A stable small hash for deterministic choices. */+export function hash(text: string): number {+ let h = 2166136261;+ for (let i = 0; i < text.length; i += 1) { h ^= text.charCodeAt(i); h = Math.imul(h, 16777619); }+ return h >>> 0;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/plan/opsDeck.test.ts b/dodaios/ui/web/frontend/src/components/society/starship/plan/opsDeck.test.tsnew file mode 100644index 0000000000..5ed7793404--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/plan/opsDeck.test.ts@@ -0,0 +1,108 @@+import { describe, expect, it } from "vitest";+import { buildOpsDeck, planDivisions, BAY_SEATS, ringRadius } from "./opsDeck";+import { buildNavGrid, findPath, isFree } from "../nav/shipNav";+import type { CrewInput, DeckPlan, TeamInput } from "./types";++function crew(n: number, prefix = "a"): CrewInput[] {+ return Array.from({ length: n }, (_, i) => ({ agentId: `${prefix}${i}`, name: `Agent ${i}`, tier: "specialist", state: "idle", createdMs: 1000 + i }));+}++function teams(groups: string[][]): TeamInput[] {+ return groups.map((members, i) => ({ id: `t${i}`, name: `Team ${i}`, members, createdMs: 10 + i, leadId: members[0] ?? null }));+}++function reachable(plan: DeckPlan) {+ const grid = buildNavGrid(plan);+ const from = plan.lift;+ const misses: string[] = [];+ for (const place of plan.places) if (!findPath(grid, from, place)) misses.push(place.id);+ for (const station of plan.stations) if (!findPath(grid, from, station)) misses.push(station.id);+ return { grid, misses };+}++describe("operations deck plan", () => {+ it("seats the crew without a team in the first bay and keeps a free bay", () => {+ const plan = buildOpsDeck({ crew: crew(5), teams: [] });+ expect(plan.divisions).toHaveLength(1);+ expect(plan.divisions[0].teamId).toBeNull();+ expect(plan.divisions[0].members).toHaveLength(5);+ expect(plan.stations.some((s) => s.kind === "newDivision")).toBe(true);+ for (const c of crew(5)) expect(plan.seatOf.get(c.agentId)?.owner).toBe(c.agentId);+ });++ it("gives every team its division, the lead the head console", () => {+ const all = crew(12);+ const groups = teams([["a3", "a4", "a5"], ["a6", "a7"], ["a8", "a9", "a10", "a11"]]);+ const plan = buildOpsDeck({ crew: all, teams: groups });+ expect(plan.divisions.map((d) => d.teamId)).toEqual([null, "t0", "t1", "t2"]);+ const t0 = plan.divisions[1];+ expect(t0.leadId).toBe("a3");+ expect(t0.members[0]).toBe("a3");+ // The head console is the gold one.+ const head = plan.props.find((p) => p.kind === "console" && p.ref === "a3");+ expect(head?.accent).toBe("#d9a441");+ expect(plan.divisions[0].members).toEqual(["a0", "a1", "a2"]);+ });++ it("is deterministic and does not depend on run state", () => {+ const a = buildOpsDeck({ crew: crew(9), teams: teams([["a1", "a2"]]) });+ const busy = crew(9).map((c, i) => ({ ...c, state: i % 2 ? ("working" as const) : ("waiting" as const) }));+ const b = buildOpsDeck({ crew: busy, teams: teams([["a1", "a2"]]) });+ expect(b.places.map((p) => [p.id, p.x, p.z])).toEqual(a.places.map((p) => [p.id, p.x, p.z]));+ });++ it("puts an agent in several teams in the oldest, unless it leads a younger one", () => {+ const groups: TeamInput[] = [+ { id: "old", name: "Old", members: ["a1", "a2"], createdMs: 1, leadId: null },+ { id: "young", name: "Young", members: ["a1", "a3"], createdMs: 2, leadId: "a3" },+ { id: "led", name: "Led", members: ["a2"], createdMs: 3, leadId: "a2" },+ ];+ const { divisions } = planDivisions(crew(4), groups, 6);+ const of = (id: string) => divisions.find((d) => d.members.some((m) => m.agentId === id))?.teamId;+ expect(of("a1")).toBe("old");+ expect(of("a2")).toBe("led");+ expect(of("a3")).toBe("young");+ });++ it("never seats the lead tier on this deck", () => {+ const all = [...crew(3), { agentId: "jarvis", name: "Jarvis", tier: "lead" as const, state: "idle" as const, createdMs: 0 }];+ const plan = buildOpsDeck({ crew: all, teams: [] });+ expect(plan.seatOf.has("jarvis")).toBe(false);+ });++ it("caps a division and sends the rest to the crew without a team", () => {+ const all = crew(BAY_SEATS + 4);+ const plan = buildOpsDeck({ crew: all, teams: teams([all.map((c) => c.agentId)]) });+ const team = plan.divisions.find((d) => d.teamId === "t0");+ expect(team?.members).toHaveLength(BAY_SEATS);+ expect(plan.divisions[0].members).toHaveLength(4);+ expect(plan.unseated).toEqual([]);+ });++ it("grows the ring with the team", () => {+ expect(ringRadius(6)).toBeLessThan(ringRadius(18));+ expect(ringRadius(1)).toBeGreaterThan(3);+ });++ it.each([+ ["empty", 0, [] as string[][]],+ ["one team", 6, [["a0", "a1", "a2"]]],+ ["eight teams", 40, Array.from({ length: 8 }, (_, t) => Array.from({ length: 5 }, (_, k) => `a${t * 5 + k}`))],+ ])("reaches every place and station from the turbolift (%s)", (_name, n, groups) => {+ const plan = buildOpsDeck({ crew: crew(n), teams: teams(groups) });+ const { grid, misses } = reachable(plan);+ expect(misses).toEqual([]);+ expect(isFree(grid, plan.lift)).toBe(true);+ expect(isFree(grid, plan.arrival)).toBe(true);+ });++ it("keeps ids unique and every seat inside the hull", () => {+ const plan = buildOpsDeck({ crew: crew(30), teams: teams([["a0", "a1"], ["a2", "a3", "a4"]]) });+ const ids = [...plan.props.map((x) => `prop:${x.id}`), ...plan.places.map((x) => `place:${x.id}`), ...plan.stations.map((x) => `station:${x.id}`)];+ expect(new Set(ids).size).toBe(ids.length);+ for (const place of plan.places) {+ expect(place.x).toBeGreaterThan(plan.bounds.x0);+ expect(place.x).toBeLessThan(plan.bounds.x1);+ }+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/starship/plan/opsDeck.ts b/dodaios/ui/web/frontend/src/components/society/starship/plan/opsDeck.tsnew file mode 100644index 0000000000..53a7e110f0--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/plan/opsDeck.ts@@ -0,0 +1,314 @@+/**+ * The operations deck: where the Jarvis agents live and work.+ *+ * bow ── observation lounge and mess, a panoramic window+ * quartermaster │ transporter plaza │ rest pods+ * division bays │ spine │ division bays (rows grow with the teams)+ * stern ── turbolift lobby+ *+ * Every team (a society chat group) gets a division: a bay off the spine+ * with a horseshoe of consoles round a holo-table, its lead at the head+ * console. The crew without a team shares the first bay; one empty bay waits+ * for the next team. Seating is by arrival, so a refresh never re-seats+ * anyone; only a change of who belongs where rebuilds the plan.+ */+import {+ arcPoints, COMMAND_GOLD, DIVISION_COLOURS, hash, PlanBuilder, polygonBounds, POOL_COLOUR, slug, yawTowards,+} from "./builder";+import type { CrewInput, DeckPlan, Division, Place, TeamInput, Vec2 } from "./types";+import { rect } from "./types";++/** A bay is one cell of the division grid. */+export const BAY_W = 13.5;+export const BAY_D = 13;+/** The spine corridor between the two columns of bays. */+export const SPINE_W = 6;+export const HALF_W = SPINE_W / 2 + BAY_W;+export const LOUNGE_D = 15;+export const PLAZA_D = 12;+export const STERN_D = 10;+export const MIN_ROWS = 2;+export const MAX_ROWS = 6;+/** Consoles a division's horseshoe holds; later members of a larger team sit with the crew without a team. */+export const BAY_SEATS = 18;+/** Console spacing along the horseshoe. */+const CONSOLE_PITCH = 1.32;+/** The horseshoe's widest opening: everything but the side facing the door. */+const MAX_SPAN = (250 / 180) * Math.PI;+const MIN_RING = 3.1;+const MAX_RING = 5.3;+/** Where a seated agent sits, inside the console ring. */+const SEAT_INSET = 0.82;+const TABLE_R = 1.15;++const DOOR_W = 3.2;++export interface OpsInput {+ crew: readonly CrewInput[];+ teams: readonly TeamInput[];+}++function byArrival(a: CrewInput, b: CrewInput): number {+ return a.createdMs - b.createdMs || a.agentId.localeCompare(b.agentId);+}++interface DivisionPlan { id: string; teamId: string | null; name: string; leadId: string | null; members: CrewInput[] }++/**+ * Who sits in which division. Lead-tier agents are on the bridge (the lead+ * is the captain's pet), so they are not seated here. Teams are taken oldest+ * first; an agent in several sits with the oldest, unless it leads a younger+ * one. A team's lead sits first. The crew without a team comes first and+ * opens a second bay only when it outgrows one.+ */+export function planDivisions(crew: readonly CrewInput[], teams: readonly TeamInput[], maxBays: number): { divisions: DivisionPlan[]; unseated: string[] } {+ const staff = crew.filter((c) => c.tier !== "lead");+ const known = new Map(staff.map((c) => [c.agentId, c]));+ const ordered = [...teams].sort((a, b) => a.createdMs - b.createdMs || a.id.localeCompare(b.id));+ const home = new Map<string, string>();+ // Leading comes first: a lead sits with the team it leads (the oldest such team).+ for (const team of ordered) {+ if (team.leadId && known.has(team.leadId) && team.members.includes(team.leadId) && !home.has(team.leadId)) home.set(team.leadId, team.id);+ }+ for (const team of ordered) {+ for (const id of team.members) if (known.has(id) && !home.has(id)) home.set(id, team.id);+ }+ const teamBays = Math.max(0, maxBays - 1);+ const shown = ordered.slice(0, teamBays);+ const shownIds = new Set(shown.map((t) => t.id));+ const pool: CrewInput[] = [];+ const divisions: DivisionPlan[] = [];+ for (const team of shown) {+ const members = staff.filter((c) => home.get(c.agentId) === team.id).sort(byArrival);+ const lead = team.leadId && members.some((m) => m.agentId === team.leadId) ? team.leadId : null;+ if (lead) members.sort((a, b) => (a.agentId === lead ? -1 : b.agentId === lead ? 1 : 0));+ pool.push(...members.slice(BAY_SEATS));+ // The index keeps ids apart that slug alike ("a b" and "a_b").+ divisions.push({ id: `div-${divisions.length}-${slug(team.id)}`, teamId: team.id, name: team.name, leadId: lead, members: members.slice(0, BAY_SEATS) });+ }+ for (const c of staff) {+ const team = home.get(c.agentId);+ if (!team || !shownIds.has(team)) pool.push(c);+ }+ pool.sort(byArrival);+ const pools: DivisionPlan[] = [];+ const free = Math.max(1, maxBays - divisions.length);+ for (let i = 0; i === 0 || (i * BAY_SEATS < pool.length && pools.length < free); i += 1) {+ pools.push({ id: i === 0 ? "div-pool" : `div-pool-${i + 1}`, teamId: null, name: "", leadId: null, members: pool.slice(i * BAY_SEATS, (i + 1) * BAY_SEATS) });+ }+ const unseated = pool.slice(pools.length * BAY_SEATS).map((c) => c.agentId);+ return { divisions: [...pools, ...divisions], unseated };+}++/** The radius of a horseshoe that seats `n` consoles at the console pitch. */+export function ringRadius(n: number): number {+ return Math.min(MAX_RING, Math.max(MIN_RING, ((Math.max(1, n) - 1) * CONSOLE_PITCH) / MAX_SPAN));+}++export function rowsFor(bays: number): number {+ return Math.min(MAX_ROWS, Math.max(MIN_ROWS, Math.ceil(bays / 2)));+}++/** The hull outline of an operations deck with `rows` rows of bays. */+export function opsHull(rows: number): Vec2[] {+ const end = LOUNGE_D + PLAZA_D + rows * BAY_D + STERN_D;+ return [+ { x: -7, z: 0 }, { x: 7, z: 0 }, { x: HALF_W, z: 9 },+ { x: HALF_W, z: end - 3 }, { x: HALF_W - 3, z: end },+ { x: -HALF_W + 3, z: end }, { x: -HALF_W, z: end - 3 }, { x: -HALF_W, z: 9 },+ ];+}++export function buildOpsDeck({ crew, teams }: OpsInput): DeckPlan {+ const b = new PlanBuilder("ops");+ // How many bays: every team, the crew without a team, one free bay; at least two rows.+ const wanted = teams.length + 2;+ const rows = rowsFor(wanted);+ const bays = rows * 2;+ const { divisions: planned, unseated } = planDivisions(crew, teams, bays - 1);+ const hull = opsHull(rows);+ const bounds = polygonBounds(hull);+ const zPlaza = LOUNGE_D, zBays = LOUNGE_D + PLAZA_D, zStern = zBays + rows * BAY_D, zEnd = zStern + STERN_D;+ const spine = SPINE_W / 2;++ // ── hull ───────────────────────────────────────────────────────────+ hull.forEach((p, i) => {+ const q = hull[(i + 1) % hull.length];+ const stern = p.z === zEnd && q.z === zEnd;+ if (stern) {+ // The turbolift sits in the middle of the stern wall.+ b.wallWithDoors(`hull-${i}`, "hull", p, q, [{ at: Math.abs(q.x - p.x) / 2, width: 3, slides: true, id: "lift-door" }], 0.5);+ } else {+ b.wall(`hull-${i}`, "hull", p, q, 0.5, true);+ }+ });++ // ── bow: observation lounge and mess ───────────────────────────────+ b.room({ id: "lounge", kind: "lounge", rect: rect(-HALF_W, 0, HALF_W, zPlaza), floor: "carpet", accent: COMMAND_GOLD,+ sign: { key: "ship.room.lounge" }, signAt: { x: 0, z: zPlaza - 0.3, yaw: Math.PI } });+ b.wallWithDoors("lounge-s", "bulkhead", { x: -HALF_W, z: zPlaza }, { x: HALF_W, z: zPlaza }, [{ at: HALF_W, width: 8, slides: false, id: "lounge-arch" }]);+ // Mess tables, four stools each, in the port half.+ const mess: Vec2[] = [{ x: -12.2, z: 10.6 }, { x: -7.6, z: 10.6 }, { x: -9.4, z: 6.4 }];+ mess.forEach((m, i) => {+ b.prop({ id: `mess-${i}`, kind: "messTable", x: m.x, z: m.z, yaw: 0, w: 1.3, d: 1.3, h: 0.74, solid: true });+ for (let k = 0; k < 4; k += 1) {+ const a = (k / 4) * Math.PI * 2 + Math.PI / 4;+ const sx = m.x + Math.sin(a) * 1.05, sz = m.z + Math.cos(a) * 1.05;+ b.place({ id: `mess-${i}-${k}`, kind: "mess", x: sx, z: sz, yaw: yawTowards({ x: sx, z: sz }, m), pose: "sit", seatY: 0.48 });+ b.prop({ id: `stool-${i}-${k}`, kind: "messStool", x: sx, z: sz, yaw: 0, w: 0.42, d: 0.42, h: 0.46, solid: false });+ }+ });+ // The galley: a long counter on the lounge's aft wall, standing places in front.+ b.prop({ id: "galley", kind: "galley", x: -11.8, z: zPlaza - 0.75, yaw: Math.PI, w: 6.4, d: 0.9, h: 1.05, solid: true });+ for (let k = 0; k < 3; k += 1) b.place({ id: `galley-${k}`, kind: "galley", x: -14 + k * 2.2, z: zPlaza - 1.75, yaw: Math.PI, pose: "stand", seatY: 0 });+ b.station({ id: "mess", kind: "mess", x: -11.8, z: zPlaza - 1.9, radius: 1.6, propId: "galley" });+ // Sofas facing the bow window in the starboard half.+ const sofas: (Vec2 & { yaw: number })[] = [{ x: 4.6, z: 8.6, yaw: Math.PI }, { x: 9.6, z: 9.4, yaw: Math.PI * 0.82 }, { x: 13.2, z: 12.4, yaw: Math.PI * 0.72 }];+ sofas.forEach((s, i) => {+ b.prop({ id: `sofa-${i}`, kind: "sofa", x: s.x, z: s.z, yaw: s.yaw, w: 2.4, d: 0.95, h: 0.8, solid: true });+ const fx = Math.sin(s.yaw), fz = Math.cos(s.yaw);+ b.prop({ id: `lowtable-${i}`, kind: "lowTable", x: s.x + fx * 1.35, z: s.z + fz * 1.35, yaw: s.yaw, w: 1.3, d: 0.6, h: 0.38, solid: true });+ for (let k = -1; k <= 1; k += 2) {+ const lx = Math.cos(s.yaw) * 0.62 * k, lz = -Math.sin(s.yaw) * 0.62 * k;+ b.place({ id: `sofa-${i}-${k}`, kind: "lounge", x: s.x + lx + fx * 0.12, z: s.z + lz + fz * 0.12, yaw: s.yaw, pose: "sit", seatY: 0.44 });+ }+ });+ // Standing at the bow window.+ for (let k = 0; k < 5; k += 1) b.place({ id: `window-${k}`, kind: "window", x: -4.8 + k * 2.4, z: 1.25, yaw: Math.PI, pose: "stand", seatY: 0 });+ b.prop({ id: "plant-bow-w", kind: "plant", x: -6.2, z: 1.4, yaw: 0, w: 0.8, d: 0.8, h: 1.4, solid: true });+ b.prop({ id: "plant-bow-e", kind: "plant", x: 6.2, z: 1.4, yaw: 0, w: 0.8, d: 0.8, h: 1.4, solid: true });++ // ── plaza: transporter, quartermaster, rest pods ───────────────────+ const zMid = zPlaza + PLAZA_D / 2;+ b.room({ id: "plaza", kind: "plaza", rect: rect(-7, zPlaza, 7, zBays), floor: "deck", accent: "#5fd4ff", sign: null });+ b.prop({ id: "transporter", kind: "transporter", x: 0, z: zMid - 0.4, yaw: 0, w: 4.2, d: 4.2, h: 0.18, solid: false });+ b.prop({ id: "transporter-console", kind: "transporterConsole", x: 4.4, z: zMid - 0.4, yaw: -Math.PI / 2, w: 1.5, d: 0.75, h: 1.05, solid: true });+ b.station({ id: "transporter", kind: "transporter", x: 3.3, z: zMid - 0.4, radius: 1.5, propId: "transporter-console" });+ for (const [i, x] of [-6.2, 6.2].entries()) for (const [k, z] of [zPlaza + 1.0, zBays - 1.0].entries()) {+ b.prop({ id: `pillar-${i}-${k}`, kind: "pillar", x, z, yaw: 0, w: 0.9, d: 0.9, h: 2.6, solid: true });+ }++ b.room({ id: "quartermaster", kind: "quartermaster", rect: rect(-HALF_W, zPlaza, -7, zBays), floor: "ceramic", accent: COMMAND_GOLD,+ sign: { key: "ship.room.quartermaster" }, signAt: { x: -7.15, z: zMid - 2.4, yaw: Math.PI / 2 } });+ b.wallWithDoors("qm-e", "bulkhead", { x: -7, z: zPlaza }, { x: -7, z: zBays }, [{ at: PLAZA_D / 2, width: 2.2 }]);+ for (let k = 0; k < 5; k += 1) b.prop({ id: `locker-${k}`, kind: "locker", x: -HALF_W + 0.65, z: zPlaza + 2.2 + k * 1.05, yaw: Math.PI / 2, w: 0.95, d: 0.6, h: 2.1, solid: true });+ b.prop({ id: "mirror", kind: "mirror", x: -11.6, z: zBays - 0.55, yaw: Math.PI, w: 1.6, d: 0.3, h: 2.2, solid: true });+ b.station({ id: "quartermaster", kind: "quartermaster", x: -11.6, z: zBays - 1.7, radius: 1.5, propId: "mirror" });+ b.prop({ id: "qm-bench", kind: "bench", x: -11.6, z: zMid - 1.6, yaw: 0, w: 2.2, d: 0.5, h: 0.45, solid: true });++ b.room({ id: "pods", kind: "quarters", rect: rect(7, zPlaza, HALF_W, zBays), floor: "carpet", accent: "#a68cff",+ sign: { key: "ship.room.pods" }, signAt: { x: 7.15, z: zMid - 2.4, yaw: -Math.PI / 2 } });+ b.wallWithDoors("pods-w", "bulkhead", { x: 7, z: zPlaza }, { x: 7, z: zBays }, [{ at: PLAZA_D / 2, width: 2.2 }]);+ const podZ = [zPlaza + 2.0, zPlaza + 4.6, zPlaza + 7.2, zPlaza + 9.8];+ podZ.forEach((z, k) => {+ for (const [r, x] of [HALF_W - 0.95, HALF_W - 3.9].entries()) {+ b.prop({ id: `pod-${r}-${k}`, kind: "pod", x, z, yaw: Math.PI / 2, w: 2.3, d: 1.05, h: 1.0, solid: true });+ // Resting inside the pod: the place sits on the pod's own footprint, so it is reached from the aisle beside it.+ b.place({ id: `pod-${r}-${k}`, kind: "pod", x, z, yaw: 0, pose: "rest", seatY: 0.62 });+ }+ });++ // ── divisions ──────────────────────────────────────────────────────+ const seatOf = new Map<string, Place>();+ for (let r = 0; r <= rows; r += 1) {+ const z = zBays + r * BAY_D;+ // Row 0 is the plaza's aft edge, the last row the lobby's fore wall; the spine stays open.+ b.wall(`row-${r}-w`, "bulkhead", { x: -HALF_W, z }, { x: -spine, z });+ b.wall(`row-${r}-e`, "bulkhead", { x: spine, z }, { x: HALF_W, z });+ }+ b.room({ id: "spine", kind: "corridor", rect: rect(-spine, zBays, spine, zStern), floor: "deck", accent: "#5fd4ff", sign: null });+ let colour = 0;+ for (let i = 0; i < bays; i += 1) {+ const row = Math.floor(i / 2), west = i % 2 === 0;+ const z0 = zBays + row * BAY_D, z1 = z0 + BAY_D;+ const x0 = west ? -HALF_W : spine, x1 = west ? -spine : HALF_W;+ const centre = { x: (x0 + x1) / 2 + (west ? -0.4 : 0.4), z: (z0 + z1) / 2 };+ const doorX = west ? -spine : spine;+ const towardsDoor = west ? Math.PI / 2 : -Math.PI / 2;+ b.wallWithDoors(`bay-${i}-front`, "glass", { x: doorX, z: z0 }, { x: doorX, z: z1 }, [{ at: BAY_D / 2, width: DOOR_W, id: `bay-${i}-door` }]);+ const plan = planned[i];+ const roomId = plan ? plan.id : i === planned.length ? "div-free" : `garden-${i}`;+ if (plan) {+ const accent = plan.teamId ? DIVISION_COLOURS[colour++ % DIVISION_COLOURS.length] : POOL_COLOUR;+ b.room({ id: roomId, kind: "division", rect: rect(x0, z0, x1, z1), floor: "deck", accent,+ sign: plan.teamId ? { text: plan.name } : { key: "ship.division.pool" },+ signAt: { x: doorX + (west ? 0.2 : -0.2), z: z0 + BAY_D / 2, yaw: west ? Math.PI / 2 : -Math.PI / 2 } });+ const division = layDivision(b, plan, roomId, centre, towardsDoor, accent, seatOf);+ b.divisions.push(division);+ b.station({ id: `division:${roomId}`, kind: "division", x: centre.x + Math.sin(towardsDoor) * (TABLE_R + 0.75), z: centre.z + Math.cos(towardsDoor) * (TABLE_R + 0.75),+ radius: 1.6, propId: `table-${roomId}`, ref: plan.teamId ?? roomId });+ } else if (roomId === "div-free") {+ b.room({ id: roomId, kind: "division", rect: rect(x0, z0, x1, z1), floor: "deck", accent: COMMAND_GOLD,+ sign: { key: "ship.division.free" }, signAt: { x: doorX + (west ? 0.2 : -0.2), z: z0 + BAY_D / 2, yaw: west ? Math.PI / 2 : -Math.PI / 2 } });+ b.prop({ id: "free-plinth", kind: "divisionPlinth", x: centre.x, z: centre.z, yaw: towardsDoor, w: 1.2, d: 1.2, h: 1.1, solid: true });+ b.station({ id: "newDivision", kind: "newDivision", x: centre.x + Math.sin(towardsDoor) * 1.4, z: centre.z + Math.cos(towardsDoor) * 1.4, radius: 1.5, propId: "free-plinth" });+ } else {+ // A bay nobody needs yet is a hydroponics garden: a place to stroll.+ b.room({ id: roomId, kind: "bay", rect: rect(x0, z0, x1, z1), floor: "grate", accent: "#9bd65b", sign: { key: "ship.room.garden" },+ signAt: { x: doorX + (west ? 0.2 : -0.2), z: z0 + BAY_D / 2, yaw: west ? Math.PI / 2 : -Math.PI / 2 } });+ for (let k = 0; k < 3; k += 1) {+ const bx = centre.x + (west ? -1 : 1) * (k - 1) * 3.2;+ b.prop({ id: `${roomId}-bed-${k}`, kind: "plant", x: bx, z: centre.z, yaw: 0, w: 1.4, d: 7.5, h: 0.9, solid: true, ref: "bed" });+ b.place({ id: `${roomId}-stroll-${k}`, kind: "stroll", x: bx + 1.55 * (west ? 1 : -1), z: centre.z + (k - 1) * 2.1, yaw: west ? -Math.PI / 2 : Math.PI / 2, pose: "stand", seatY: 0 });+ }+ }+ // Side walls between neighbouring rows are the row lines; the bay's hull side is the hull.+ }++ // ── stern: turbolift lobby ─────────────────────────────────────────+ b.room({ id: "lobby", kind: "lift", rect: rect(-HALF_W, zStern, HALF_W, zEnd), floor: "deck", accent: COMMAND_GOLD,+ sign: { key: "ship.room.lift" }, signAt: { x: 0, z: zEnd - 0.35, yaw: Math.PI } });+ b.prop({ id: "lift-doors", kind: "liftDoors", x: 0, z: zEnd - 0.3, yaw: Math.PI, w: 3.4, d: 0.5, h: 2.7, solid: true });+ b.station({ id: "lift", kind: "lift", x: 0, z: zEnd - 1.4, radius: 1.6, propId: "lift-doors" });+ for (const [k, x] of [-8, 8].entries()) {+ b.prop({ id: `lobby-bench-${k}`, kind: "bench", x, z: zEnd - 4.2, yaw: 0, w: 2.6, d: 0.55, h: 0.45, solid: true });+ b.prop({ id: `lobby-plant-${k}`, kind: "plant", x: x + (k ? 2.2 : -2.2), z: zEnd - 4.2, yaw: 0, w: 0.8, d: 0.8, h: 1.4, solid: true });+ b.place({ id: `lobby-stroll-${k}`, kind: "stroll", x, z: zEnd - 5.4, yaw: Math.PI, pose: "stand", seatY: 0 });+ }+ for (let k = 0; k < rows; k += 1) {+ b.place({ id: `spine-stroll-${k}`, kind: "stroll", x: (k % 2 ? 1 : -1) * 1.6, z: zBays + k * BAY_D + 2.2, yaw: k % 2 ? -Math.PI / 2 : Math.PI / 2, pose: "stand", seatY: 0 });+ }++ return b.build({+ bounds, hull, seatOf, unseated,+ arrival: { x: 0, z: zMid - 0.4 },+ lift: { x: 0, z: zEnd - 1.6, yaw: Math.PI },+ });+}++function layDivision(b: PlanBuilder, plan: DivisionPlan, roomId: string, centre: Vec2, towardsDoor: number, accent: string, seatOf: Map<string, Place>): Division {+ // One spare console to grow into; at least six, so a new team's bay is a place to work.+ const consoles = Math.min(BAY_SEATS, Math.max(6, plan.members.length + 1));+ const radius = ringRadius(consoles);+ const span = Math.min(MAX_SPAN, consoles <= 1 ? 0 : ((consoles - 1) * CONSOLE_PITCH) / radius);+ const away = towardsDoor + Math.PI;+ const ring = arcPoints(centre, radius, consoles, away, span);+ // The head console (straight across from the door) first, then outwards alternately.+ const order = ring.map((p, i) => ({ p, i, off: Math.abs(i - (consoles - 1) / 2) })).sort((p, q) => p.off - q.off || p.i - q.i);+ b.prop({ id: `table-${roomId}`, kind: "holoTable", x: centre.x, z: centre.z, yaw: towardsDoor, w: TABLE_R * 2, d: TABLE_R * 2, h: 0.95, solid: true, ref: plan.teamId ?? roomId, accent });+ const members: string[] = [];+ order.forEach(({ p, i }, seatIndex) => {+ const owner = plan.members[seatIndex];+ const head = seatIndex === 0 && !!plan.leadId && owner?.agentId === plan.leadId;+ b.prop({ id: `console-${roomId}-${i}`, kind: "console", x: p.x, z: p.z, yaw: p.yaw + Math.PI, w: 1.15, d: 0.72, h: 1.02, solid: true,+ ref: owner?.agentId, accent: head ? COMMAND_GOLD : accent });+ const sx = p.x - Math.sin(p.yaw) * SEAT_INSET, sz = p.z - Math.cos(p.yaw) * SEAT_INSET;+ b.prop({ id: `chair-${roomId}-${i}`, kind: "consoleChair", x: sx, z: sz, yaw: p.yaw, w: 0.55, d: 0.55, h: 1.0, solid: false, ref: owner?.agentId, accent: head ? COMMAND_GOLD : accent });+ if (owner) {+ const seat = b.place({ id: `seat-${roomId}-${i}`, kind: "console", x: sx, z: sz, yaw: p.yaw, pose: "sit", seatY: 0.5, owner: owner.agentId, division: roomId });+ seatOf.set(owner.agentId, seat);+ members.push(owner.agentId);+ }+ });+ // Standing places round the table for a gathering: an arc on the door's side first.+ const gatherCount = Math.max(4, Math.min(10, plan.members.length));+ const gather = arcPoints(centre, TABLE_R + 0.62, gatherCount, towardsDoor, Math.min(Math.PI * 1.5, gatherCount * 0.62)).map((p, k) =>+ b.place({ id: `gather-${roomId}-${k}`, kind: "table", x: p.x, z: p.z, yaw: p.yaw + Math.PI, pose: "stand", seatY: 0, division: roomId }));+ // A quiet corner in every bay: two standing places by the hull window.+ const hullSide = towardsDoor + Math.PI;+ for (let k = 0; k < 2; k += 1) {+ const wx = centre.x + Math.sin(hullSide) * 4.9, wz = centre.z + (k ? 1 : -1) * 5.0;+ b.place({ id: `bay-window-${roomId}-${k}`, kind: hash(roomId + k) % 3 === 0 ? "window" : "stroll", x: wx, z: wz, yaw: hullSide, pose: "stand", seatY: 0, division: roomId });+ }+ return { id: roomId, teamId: plan.teamId, name: plan.name, colour: accent, leadId: plan.leadId, members, centre, room: roomId, gather };+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/plan/types.ts b/dodaios/ui/web/frontend/src/components/society/starship/plan/types.tsnew file mode 100644index 0000000000..e49786d2ad--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/plan/types.ts@@ -0,0 +1,214 @@+/**+ * The shared vocabulary of the starship's deck plans.+ *+ * A deck plan is pure data: rooms, walls with their doorways, furniture+ * footprints, the seats and standing places people use, and the stations the+ * captain interacts with. The renderer draws it, the navigation grid is+ * rasterised from it and the crew's life picks its places from it, so all+ * three always agree. Units are metres; x runs to starboard (east), z towards+ * the stern (south), y up. A yaw of 0 faces +z.+ */+import type { AgentRunState, AgentTier } from "../../data";++export type DeckId = "bridge" | "ops" | "engineering" | "holodeck" | "honors";++/** The turbolift's order, top of the ship first. */+export const DECKS: readonly DeckId[] = ["bridge", "ops", "engineering", "holodeck", "honors"];++/** The number painted beside a deck's turbolift doors. */+export function deckNumber(deck: DeckId): number {+ return DECKS.indexOf(deck) + 1;+}++export interface Vec2 { x: number; z: number }++/** Axis-aligned rectangle. */+export interface Rect { x0: number; z0: number; x1: number; z1: number }++export function rect(x0: number, z0: number, x1: number, z1: number): Rect {+ return { x0: Math.min(x0, x1), z0: Math.min(z0, z1), x1: Math.max(x0, x1), z1: Math.max(z0, z1) };+}++export function rectCentre(r: Rect): Vec2 {+ return { x: (r.x0 + r.x1) / 2, z: (r.z0 + r.z1) / 2 };+}++export function rectContains(r: Rect, p: Vec2, margin = 0): boolean {+ return p.x >= r.x0 - margin && p.x <= r.x1 + margin && p.z >= r.z0 - margin && p.z <= r.z1 + margin;+}++/** One person the plan seats: an agent of the roster or a coding pane projected into one. */+export interface CrewInput {+ agentId: string;+ name: string;+ tier: AgentTier;+ state: AgentRunState;+ createdMs: number;+}++export interface TeamInput {+ id: string;+ name: string;+ members: readonly string[];+ createdMs: number;+ leadId: string | null;+}++/**+ * What a wall is made of. `hull` is the ship's outer skin (thick, with a window+ * band where `windows` says so), `bulkhead` an inner wall, `glass` a framed+ * glass partition, `rail` a waist-high railing people cannot pass.+ */+export type WallKind = "hull" | "bulkhead" | "glass" | "rail";++export interface Wall {+ id: string;+ kind: WallKind;+ a: Vec2;+ b: Vec2;+ /** Thickness in metres. */+ t: number;+ /** A hull wall with a window band (the renderer cuts it; navigation does not care). */+ windows?: boolean;+}++/** A doorway: a gap in a wall that people walk through. `slides` doors open as someone comes near. */+export interface Door {+ id: string;+ at: Vec2;+ /** Clear width of the opening. */+ width: number;+ /** The wall's direction at the door: "x" = the wall runs east-west. */+ axis: "x" | "z";+ slides: boolean;+}++export type FloorFinish = "deck" | "carpet" | "grate" | "ceramic" | "holo" | "honor";++export type RoomKind =+ | "corridor" | "plaza" | "division" | "lounge" | "mess" | "quarters" | "quartermaster" | "transporter"+ | "lift" | "bridge" | "readyroom" | "engineering" | "bay" | "core" | "holodeck" | "hall";++export interface Room {+ id: string;+ kind: RoomKind;+ rect: Rect;+ floor: FloorFinish;+ /** The accent the room's trims and floor lines take (a team's colour, gold for command). */+ accent: string;+ /** i18n key or literal name (a team's name) shown on the room's sign; null = no sign. */+ sign: { key: string } | { text: string } | null;+ /** Where the sign hangs, if the room has one. */+ signAt?: Vec2 & { yaw: number };+}++/**+ * Furniture and fittings. Footprints are rotated rectangles (`w` along the+ * piece's own x, `d` along its own z, turned by `yaw`); solid ones block the+ * navigation grid. `ref` ties a piece to an agent (a console), a team (a+ * holo-table) or a station.+ */+export type PropKind =+ | "console" | "consoleChair" | "holoTable" | "transporter" | "transporterConsole" | "liftDoors"+ | "messTable" | "messStool" | "galley" | "sofa" | "lowTable" | "plant" | "pod" | "locker" | "mirror"+ | "divisionPlinth" | "pillar" | "captainChair" | "commandSeat" | "helmConsole" | "viewscreen" | "tacticalRail"+ | "starChart" | "reactor" | "systemsTable" | "bayConsole" | "cabinet" | "rankWall" | "honorCase" | "dais"+ | "crate" | "bench" | "conduit";++export interface Prop {+ id: string;+ kind: PropKind;+ x: number;+ z: number;+ yaw: number;+ w: number;+ d: number;+ /** Height of the piece (for the renderer's proportions and the camera's occlusion). */+ h: number;+ solid: boolean;+ ref?: string;+ /** Accent colour (team colour on a division's console). */+ accent?: string;+}++/**+ * A place someone sits or stands at. `console` seats belong to one agent+ * (`owner`); the rest are free places reserved by whoever goes there.+ */+export type PlaceKind =+ | "console" | "mess" | "lounge" | "window" | "galley" | "pod" | "table" | "stroll" | "chart" | "command" | "captain";++export type Pose = "sit" | "stand" | "rest" | "lean";++export interface Place {+ id: string;+ kind: PlaceKind;+ x: number;+ z: number;+ yaw: number;+ pose: Pose;+ /** Seat height for `sit`, couch height for `rest`. */+ seatY: number;+ owner?: string;+ /** The division (room id) the place belongs to, if any. */+ division?: string;+}++/** Things the captain uses. The renderer rims the prop with this id when the captain stands at it. */+export type StationKind =+ | "transporter" | "lift" | "division" | "newDivision" | "quartermaster" | "mess" | "captain" | "firstOfficer"+ | "helm" | "ops" | "systems" | "holoCabinet" | "rankWall" | "honorCase" | "pods";++export interface Station {+ id: string;+ kind: StationKind;+ /** Where the captain stands to use it. */+ x: number;+ z: number;+ /** How close counts as "at the station". */+ radius: number;+ /** The prop it rims and whose click it takes. */+ propId: string;+ /** Kind-specific reference: a team id (division), a game id (holo cabinet), a reward id (honour case). */+ ref?: string;+}++/** One team's division on the operations deck (or one IDE workspace's bay in engineering). */+export interface Division {+ id: string;+ /** The team (society chat group) or workspace; null = the crew without a team. */+ teamId: string | null;+ name: string;+ colour: string;+ leadId: string | null;+ /** Members seated here, in seating order. */+ members: string[];+ /** The holo-table (or bay console) in the middle. */+ centre: Vec2;+ room: string;+ /** Standing places round the centre for a gathering. */+ gather: Place[];+}++export interface DeckPlan {+ deck: DeckId;+ /** The floor's extent (the hull's bounding box). */+ bounds: Rect;+ /** The hull outline, clockwise from the bow; the renderer extrudes the outer skin from it. */+ hull: Vec2[];+ rooms: Room[];+ walls: Wall[];+ doors: Door[];+ props: Prop[];+ places: Place[];+ stations: Station[];+ divisions: Division[];+ /** The console seat of each agent the plan seats. */+ seatOf: ReadonlyMap<string, Place>;+ /** Where someone new to the deck appears (the transporter, or the lift doors). */+ arrival: Vec2;+ /** Where the captain steps out of the turbolift. */+ lift: Vec2 & { yaw: number };+ /** Agents the plan could not seat (a full deck); the HUD says so. */+ unseated: string[];+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/render/CameraRig.tsx b/dodaios/ui/web/frontend/src/components/society/starship/render/CameraRig.tsxnew file mode 100644index 0000000000..8d260fced8--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/render/CameraRig.tsx@@ -0,0 +1,173 @@+/**+ * One orbit camera that follows the captain: drag to turn round, right-drag+ * (or Shift-drag) to pan, the wheel to zoom down to the captain's shoulder+ * or out to the whole deck. Following resumes as soon as the captain walks.+ * The overview frames the whole deck; a focus request glides to a point.+ */+import { useFrame, useThree } from "@react-three/fiber";+import { useEffect, useRef } from "react";+import { PerspectiveCamera, Vector3 } from "three";+import type { DeckPlan, Vec2 } from "../plan/types";+import { captain, useShip } from "../shipStore";+import { CUTAWAY } from "./kit/cutaway";++export const CAMERA_FOV = 38;+export const MIN_PITCH = 0.42;+export const MAX_PITCH = 1.38;+export const MIN_DIST = 3.2;++export interface Orbit { yaw: number; pitch: number; dist: number; target: Vec2; targetY: number }++/** Distance that frames a deck of `w` x `d` metres at `pitch` with the given aspect. */+export function overviewDistance(w: number, d: number, aspect: number, pitch: number, fovDeg = CAMERA_FOV): number {+ const vfov = (fovDeg * Math.PI) / 180;+ const hfov = 2 * Math.atan(Math.tan(vfov / 2) * aspect);+ // Seen at an angle, the deck's depth shrinks by sin(pitch).+ const byDepth = (d * Math.sin(pitch) * 0.5) / Math.tan(vfov / 2);+ const byWidth = (w * 0.5) / Math.tan(hfov / 2);+ return Math.max(byDepth, byWidth) * 1.12;+}++export function maxDistance(plan: DeckPlan): number {+ const w = plan.bounds.x1 - plan.bounds.x0, d = plan.bounds.z1 - plan.bounds.z0;+ return Math.max(40, Math.hypot(w, d) * 1.7);+}++export function cameraPosition(o: Orbit, out = new Vector3()): Vector3 {+ const h = Math.cos(o.pitch) * o.dist;+ return out.set(o.target.x + Math.sin(o.yaw) * h, o.targetY + Math.sin(o.pitch) * o.dist, o.target.z + Math.cos(o.yaw) * h);+}++/** Shared with the HUD (the minimap draws the view cone) and the controls. */+export const orbit: Orbit = { yaw: 0.55, pitch: 0.95, dist: 16, target: { x: 0, z: 0 }, targetY: 1.1 };++const tmp = new Vector3();++export function CameraRig({ plan, compact }: { plan: DeckPlan; compact: boolean }) {+ const { camera, gl, size } = useThree();+ const follow = useShip((s) => s.follow);+ const overviewSeq = useShip((s) => s.overviewSeq);+ const focus = useShip((s) => s.focus);+ const goal = useRef<Orbit | null>(null);+ const userDist = useRef(compact ? 20 : 16);++ // Arriving on a deck: start behind the captain.+ const arrivals = useShip((s) => s.arrivals);+ useEffect(() => {+ orbit.target = { x: captain.x, z: captain.z };+ orbit.yaw = captain.yaw + Math.PI;+ orbit.pitch = 0.95;+ orbit.dist = userDist.current;+ goal.current = null;+ }, [arrivals, plan.deck]);++ useEffect(() => {+ if (overviewSeq === 0) return;+ const w = plan.bounds.x1 - plan.bounds.x0, d = plan.bounds.z1 - plan.bounds.z0;+ const pitch = 1.08;+ goal.current = {+ yaw: 0.0, pitch, dist: overviewDistance(w, d, size.width / Math.max(1, size.height), pitch),+ target: { x: (plan.bounds.x0 + plan.bounds.x1) / 2, z: (plan.bounds.z0 + plan.bounds.z1) / 2 + d * 0.04 }, targetY: 0,+ };+ }, [overviewSeq, plan, size.width, size.height]);++ useEffect(() => {+ if (!focus) return;+ goal.current = { ...orbit, target: focus.at, dist: Math.min(orbit.dist, 18), targetY: 1 };+ }, [focus]);++ // Pointer controls on the canvas.+ useEffect(() => {+ const el = gl.domElement;+ let drag: { x: number; y: number; button: number; moved: boolean; pan: boolean } | null = null;+ const down = (e: PointerEvent) => {+ if (e.button !== 0 && e.button !== 2) return;+ drag = { x: e.clientX, y: e.clientY, button: e.button, moved: false, pan: e.button === 2 || e.shiftKey };+ };+ const move = (e: PointerEvent) => {+ if (!drag) return;+ const dx = e.clientX - drag.x, dy = e.clientY - drag.y;+ if (!drag.moved && Math.hypot(dx, dy) < 5) return;+ if (!drag.moved) { drag.moved = true; el.setPointerCapture?.(e.pointerId); }+ drag.x = e.clientX; drag.y = e.clientY;+ goal.current = null;+ if (drag.pan) {+ useShip.getState().setFollow(false);+ const k = orbit.dist * 0.0016;+ const cos = Math.cos(orbit.yaw), sin = Math.sin(orbit.yaw);+ // Screen right is (cos, -sin) on the floor, screen up (further away) is (-sin, -cos).+ orbit.target = { x: orbit.target.x - (dx * cos + dy * sin * 1.2) * k, z: orbit.target.z + (dx * sin - dy * cos * 1.2) * k };+ } else {+ orbit.yaw -= dx * 0.006;+ orbit.pitch = Math.min(MAX_PITCH, Math.max(MIN_PITCH, orbit.pitch + dy * 0.004));+ }+ };+ const up = (e: PointerEvent) => {+ if (drag?.moved) {+ // Swallow the click that ends a drag.+ const stop = (ev: MouseEvent) => { ev.stopPropagation(); el.removeEventListener("click", stop, true); };+ el.addEventListener("click", stop, true);+ setTimeout(() => el.removeEventListener("click", stop, true), 0);+ }+ drag = null;+ el.releasePointerCapture?.(e.pointerId);+ };+ const wheel = (e: WheelEvent) => {+ e.preventDefault();+ goal.current = null;+ const far = maxDistance(plan);+ const step = orbit.dist < 20 ? 0.12 : 0.22;+ orbit.dist = Math.min(far, Math.max(MIN_DIST, orbit.dist * (e.deltaY > 0 ? 1 + step : 1 / (1 + step))));+ userDist.current = Math.min(orbit.dist, 30);+ };+ const menu = (e: Event) => e.preventDefault();+ el.addEventListener("pointerdown", down);+ window.addEventListener("pointermove", move);+ window.addEventListener("pointerup", up);+ el.addEventListener("wheel", wheel, { passive: false });+ el.addEventListener("contextmenu", menu);+ return () => {+ el.removeEventListener("pointerdown", down);+ window.removeEventListener("pointermove", move);+ window.removeEventListener("pointerup", up);+ el.removeEventListener("wheel", wheel);+ el.removeEventListener("contextmenu", menu);+ };+ }, [gl, plan]);++ useFrame((_, dt) => {+ const k = 1 - Math.exp(-dt * 6);+ if (captain.moving && !useShip.getState().follow) useShip.getState().setFollow(true);+ if (goal.current) {+ const g = goal.current;+ orbit.target.x += (g.target.x - orbit.target.x) * k;+ orbit.target.z += (g.target.z - orbit.target.z) * k;+ orbit.targetY += (g.targetY - orbit.targetY) * k;+ orbit.dist += (g.dist - orbit.dist) * k;+ orbit.pitch += (g.pitch - orbit.pitch) * k;+ let dy = g.yaw - orbit.yaw;+ dy = Math.atan2(Math.sin(dy), Math.cos(dy));+ orbit.yaw += dy * k;+ if (Math.abs(g.dist - orbit.dist) < 0.05 && Math.hypot(g.target.x - orbit.target.x, g.target.z - orbit.target.z) < 0.05) goal.current = null;+ } else if (follow) {+ orbit.target.x += (captain.x - orbit.target.x) * k;+ orbit.target.z += (captain.z - orbit.target.z) * k;+ orbit.targetY += (1.1 - orbit.targetY) * k;+ if (orbit.dist > 40) orbit.dist += (userDist.current - orbit.dist) * k * 0.5;+ }+ cameraPosition(orbit, tmp);+ camera.position.copy(tmp);+ // The cut-away looks from the camera at the captain (or, while panning, at what the camera looks at).+ const cam = CUTAWAY.uCutCam.value, focus = CUTAWAY.uCutFocus.value;+ cam[0] = tmp.x; cam[1] = tmp.z;+ const following = useShip.getState().follow;+ focus[0] = following ? captain.x : orbit.target.x; focus[1] = following ? captain.z : orbit.target.z;+ CUTAWAY.uCutInner.value = orbit.dist < 34 ? 1 : 0;+ camera.lookAt(orbit.target.x, orbit.targetY, orbit.target.z);+ const persp = camera as PerspectiveCamera;+ // The near plane follows the distance, against depth fighting at the overview.+ const near = Math.min(2, Math.max(0.08, orbit.dist * 0.02));+ if (Math.abs(persp.near - near) > 0.01) { persp.near = near; persp.updateProjectionMatrix(); }+ });+ return null;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/render/ShipRenderer.tsx b/dodaios/ui/web/frontend/src/components/society/starship/render/ShipRenderer.tsxnew file mode 100644index 0000000000..d29833e615--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/render/ShipRenderer.tsx@@ -0,0 +1,104 @@+/**+ * Renderer set-up shared by every deck: tone mapping, the environment map+ * for reflections, the key light with its shadow over the deck, and a+ * post-processing chain (multisampled HDR render, bloom, output) that makes+ * every light strip, screen and hologram glow. The low quality setting+ * drops bloom and shadows.+ */+import { useFrame, useThree } from "@react-three/fiber";+import { useEffect, useMemo } from "react";+import {+ ACESFilmicToneMapping, DirectionalLight, HalfFloatType, Object3D, PMREMGenerator, Vector2, WebGLRenderTarget, type Texture,+} from "three";+import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";+import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js";+import { UnrealBloomPass } from "three/examples/jsm/postprocessing/UnrealBloomPass.js";+import { OutputPass } from "three/examples/jsm/postprocessing/OutputPass.js";+import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";+import type { DeckPlan } from "../plan/types";++export type Quality = "high" | "low";++export function RendererSetup({ quality }: { quality: Quality }) {+ const { gl, scene } = useThree();+ useEffect(() => {+ gl.toneMapping = ACESFilmicToneMapping;+ gl.toneMappingExposure = 1.05;+ gl.shadowMap.enabled = quality === "high";+ }, [gl, quality]);+ useEffect(() => {+ const pmrem = new PMREMGenerator(gl);+ const room = new RoomEnvironment();+ const env: Texture = pmrem.fromScene(room, 0.04).texture;+ room.dispose();+ scene.environment = env;+ scene.environmentIntensity = 0.55;+ return () => { scene.environment = null; env.dispose(); pmrem.dispose(); };+ }, [gl, scene]);+ return null;+}++/** Hemisphere fill, a cool ambient and one overhead key light whose shadow covers the deck. */+export function DeckLights({ plan, quality, sunDirection }: { plan: DeckPlan; quality: Quality; sunDirection: [number, number, number] }) {+ const key = useMemo(() => {+ const light = new DirectionalLight("#ffeedd", 1.55);+ light.castShadow = quality === "high";+ const w = plan.bounds.x1 - plan.bounds.x0, d = plan.bounds.z1 - plan.bounds.z0;+ const cx = (plan.bounds.x0 + plan.bounds.x1) / 2, cz = (plan.bounds.z0 + plan.bounds.z1) / 2;+ const half = Math.max(w, d) / 2 + 4;+ // Mostly from above, leaning towards the destination's sun, so shadows stay short and readable.+ const sx = sunDirection[0] * 0.35, sz = sunDirection[2] * 0.35;+ light.position.set(cx + sx * 60, 60, cz + sz * 60);+ light.target = new Object3D();+ light.target.position.set(cx, 0, cz);+ const cam = light.shadow.camera;+ cam.left = -half; cam.right = half; cam.top = half; cam.bottom = -half; cam.near = 10; cam.far = 120;+ light.shadow.mapSize.set(4096, 4096);+ light.shadow.bias = -0.0004;+ light.shadow.normalBias = 0.03;+ light.shadow.radius = 3;+ return light;+ }, [plan, quality, sunDirection]);+ useEffect(() => () => key.shadow.map?.dispose(), [key]);+ return (+ <>+ <hemisphereLight args={["#8ea6d6", "#1d1a1c", 0.42]} />+ <ambientLight intensity={0.06} color="#9fb4d6" />+ <primitive object={key} />+ <primitive object={key.target} />+ </>+ );+}++/** Renders the scene through the bloom chain; replaces R3F's own render (priority 1). */+export function PostFx({ quality }: { quality: Quality }) {+ const { gl, scene, camera, size } = useThree();+ const composer = useMemo(() => {+ const target = new WebGLRenderTarget(1, 1, { type: HalfFloatType, samples: quality === "high" ? 4 : 0 });+ const c = new EffectComposer(gl, target);+ c.addPass(new RenderPass(scene, camera));+ if (quality === "high") c.addPass(new UnrealBloomPass(new Vector2(256, 256), 0.5, 0.42, 1.0));+ c.addPass(new OutputPass());+ return c;+ }, [gl, scene, camera, quality]);+ useEffect(() => {+ const dpr = gl.getPixelRatio();+ composer.setPixelRatio(dpr);+ composer.setSize(size.width, size.height);+ }, [composer, size.width, size.height, gl]);+ useEffect(() => () => { composer.renderTarget1.dispose(); composer.renderTarget2.dispose(); for (const p of composer.passes) (p as { dispose?: () => void }).dispose?.(); }, [composer]);+ useFrame((_, dt) => {+ if (!import.meta.env.DEV) { composer.render(dt); return; }+ // Development: what one frame costs, for runtime checks (`window.__shipStats`).+ gl.info.autoReset = false;+ gl.info.reset();+ const t0 = performance.now();+ composer.render(dt);+ const ms = performance.now() - t0;+ const stats = ((window as unknown as { __shipStats?: { ms: number; calls: number; triangles: number } }).__shipStats ??= { ms: 0, calls: 0, triangles: 0 });+ stats.ms = stats.ms * 0.9 + ms * 0.1;+ stats.calls = gl.info.render.calls;+ stats.triangles = gl.info.render.triangles;+ }, 1);+ return null;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/render/deck/DeckScene.tsx b/dodaios/ui/web/frontend/src/components/society/starship/render/deck/DeckScene.tsxnew file mode 100644index 0000000000..9015637d22--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/render/deck/DeckScene.tsx@@ -0,0 +1,341 @@+/**+ * A deck on screen: its merged architecture and furniture, the live console+ * screens, the holo-tables of the divisions, the transporter, sliding doors,+ * the room signs and the lights. Everything static is built once per plan.+ */+import { useFrame, type ThreeEvent } from "@react-three/fiber";+import { useEffect, useMemo, useRef } from "react";+import {+ AdditiveBlending, BoxGeometry, FrontSide, BufferAttribute, CanvasTexture, Color, CylinderGeometry, DoubleSide, Group, IcosahedronGeometry,+ InstancedMesh, Matrix4, Mesh, MeshBasicMaterial, Object3D, PlaneGeometry, Quaternion, SRGBColorSpace, ShaderMaterial, Vector3,+} from "three";+import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";+import type { DeckPlan, Prop, Station } from "../../plan/types";+import { GeoBatch } from "../kit/geo";+import { castsShadow, finishMaterial, receivesShadow } from "../kit/materials";+import { SHIP, STATE } from "../kit/palette";+import { buildProps, CONSOLE_SCREEN, nearestWallCut } from "./props";+import { withCutaway } from "../kit/cutaway";+import { buildStructure, WALL_H } from "./structure";+import { buildExterior } from "./exterior";+import { buildDressing } from "./dressing";+import { ScreenAtlas, type ScreenContent } from "./screens";++export function StaticDeck({ plan, extra }: { plan: DeckPlan; extra?: (batch: GeoBatch) => void }) {+ const meshes = useMemo(() => {+ const batch = buildStructure(plan);+ buildExterior(plan, batch);+ buildDressing(plan, batch);+ buildProps(plan, batch);+ extra?.(batch);+ return batch.merged().map(({ finish, geometry }) => {+ const mesh = new Mesh(geometry, finishMaterial(finish));+ mesh.castShadow = castsShadow(finish);+ mesh.receiveShadow = receivesShadow(finish);+ mesh.raycast = () => undefined;+ if (finish === "glass") mesh.renderOrder = 2;+ return mesh;+ });+ }, [plan, extra]);+ useEffect(() => () => { for (const m of meshes) m.geometry.dispose(); }, [meshes]);+ return <>{meshes.map((m, i) => <primitive key={i} object={m} />)}</>;+}++/** World matrix of a console's screen plane. */+export function screenMatrix(p: Prop): Matrix4 {+ const base = new Matrix4().makeRotationY(p.yaw).setPosition(p.x, 0, p.z);+ const local = new Matrix4().compose(new Vector3(0, CONSOLE_SCREEN.y, CONSOLE_SCREEN.z + 0.004), new Quaternion().setFromAxisAngle(new Vector3(1, 0, 0), CONSOLE_SCREEN.tilt), new Vector3(1, 1, 1));+ return base.multiply(local);+}++/**+ * The console screens: one merged mesh over one atlas. `content(prop)` says+ * what each shows; `onScreen` takes a click on one (the console's owner).+ */+const CONSOLE_KINDS: readonly Prop["kind"][] = ["console"];++export function ConsoleScreens({ plan, content, onScreen, kinds = CONSOLE_KINDS }: {+ plan: DeckPlan;+ content: (prop: Prop) => ScreenContent;+ onScreen?: (prop: Prop) => void;+ kinds?: readonly Prop["kind"][];+}) {+ const atlas = useMemo(() => new ScreenAtlas(), []);+ const consoles = useMemo(() => plan.props.filter((p) => kinds.includes(p.kind)), [plan, kinds]);+ const material = useMemo(() => new MeshBasicMaterial({ map: atlas.texture, toneMapped: false, color: new Color(1.25, 1.25, 1.25) }), [atlas]);+ const mesh = useMemo(() => {+ const geos = consoles.map((p) => {+ const g = new PlaneGeometry(CONSOLE_SCREEN.w, CONSOLE_SCREEN.h);+ const [u0, v0, u1, v1] = atlas.uv(p.id);+ const uv = g.attributes.uv as BufferAttribute;+ for (let i = 0; i < uv.count; i += 1) uv.setXY(i, u0 + uv.getX(i) * (u1 - u0), v0 + uv.getY(i) * (v1 - v0));+ g.applyMatrix4(screenMatrix(p));+ // Which console a face belongs to, for clicks.+ const ids = new Float32Array(g.attributes.position.count).fill(consoles.indexOf(p));+ g.setAttribute("consoleIndex", new BufferAttribute(ids, 1));+ return g;+ });+ const merged = geos.length ? mergeGeometries(geos, false) : null;+ for (const g of geos) g.dispose();+ if (!merged) return null;+ const m = new Mesh(merged, material);+ return m;+ }, [consoles, atlas, material]);+ useEffect(() => () => { mesh?.geometry.dispose(); }, [mesh]);+ // Cells of consoles a rebuilt plan no longer has go back to the atlas.+ const held = useRef(new Set<string>());+ useEffect(() => {+ const now = new Set(consoles.map((p) => p.id));+ for (const id of held.current) if (!now.has(id)) atlas.release(id);+ held.current = now;+ }, [consoles, atlas]);+ useEffect(() => () => { material.dispose(); atlas.texture.dispose(); }, [material, atlas]);+ const contentRef = useRef(content);+ contentRef.current = content;+ useFrame(() => {+ for (const p of consoles) atlas.set(p.id, contentRef.current(p));+ atlas.tick(Date.now());+ });+ if (!mesh) return null;+ const click = (e: ThreeEvent<MouseEvent>) => {+ if (!onScreen || e.face == null) return;+ const attr = mesh.geometry.getAttribute("consoleIndex") as BufferAttribute;+ const p = consoles[attr.getX(e.face.a)];+ if (p) { e.stopPropagation(); onScreen(p); }+ };+ return <primitive object={mesh} onClick={click} />;+}++const HOLO_VERT = /* glsl */ `varying vec2 vUv; varying vec3 vPos; void main() { vUv = uv; vPos = position; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`;+const BEAM_FRAG = /* glsl */ `uniform float uTime; uniform vec3 uColour; uniform float uStrength; varying vec2 vUv; varying vec3 vPos;+ float h(float x) { return fract(sin(x * 91.7) * 43758.5); }+ void main() {+ float a = atan(vPos.z, vPos.x) * 9.0;+ float streak = smoothstep(0.75, 1.0, h(floor(a)) ) * (0.5 + 0.5 * sin(vUv.y * 30.0 - uTime * 6.0 + floor(a)));+ float fade = smoothstep(0.0, 0.15, vUv.y) * (1.0 - smoothstep(0.55, 1.0, vUv.y));+ gl_FragColor = vec4(uColour * (0.25 + streak) * fade * uStrength, (0.08 + streak * 0.5) * fade * uStrength);+ }`;++/** The holo-tables: each division's name floating over its table, the members as lights round a turning emblem. */+export function HoloTables({ plan, label, memberState, reduced }: {+ plan: DeckPlan;+ label: (division: DeckPlan["divisions"][number]) => string;+ memberState: (agentId: string) => string;+ reduced: boolean;+}) {+ const group = useRef<Group>(null);+ const emblems = useMemo(() => plan.divisions.map((d) => {+ const g = new Group();+ g.position.set(d.centre.x, 0, d.centre.z);+ const colour = new Color(d.colour);+ const ico = new Mesh(new IcosahedronGeometry(0.34, 1), new MeshBasicMaterial({ color: colour.clone().multiplyScalar(1.6), wireframe: true, transparent: true, opacity: 0.7, toneMapped: false, depthWrite: false }));+ ico.position.y = 1.55;+ g.add(ico);+ const beam = new Mesh(new CylinderGeometry(0.62, 0.95, 1.1, 32, 1, true), new ShaderMaterial({+ vertexShader: HOLO_VERT, fragmentShader: BEAM_FRAG, transparent: true, blending: AdditiveBlending, depthWrite: false, side: DoubleSide,+ uniforms: { uTime: { value: 0 }, uColour: { value: new Color(SHIP.cyan).multiplyScalar(1.4) }, uStrength: { value: 0.7 } },+ }));+ beam.position.y = 1.5;+ g.add(beam);+ const text = textPlane(label(d), d.colour);+ text.position.y = 2.35;+ g.add(text);+ const dots = new InstancedMesh(new BoxGeometry(0.06, 0.06, 0.06), new MeshBasicMaterial({ toneMapped: false }), Math.max(1, d.members.length));+ dots.position.y = 1.08;+ g.add(dots);+ return { division: d, group: g, ico, beam, text, dots };+ }), [plan, label]);+ useEffect(() => () => {+ for (const e of emblems) e.dots.dispose();+ for (const e of emblems) e.group.traverse((o) => {+ const m = o as Mesh;+ m.geometry?.dispose();+ const mat = m.material as MeshBasicMaterial | undefined;+ mat?.map?.dispose();+ mat?.dispose();+ });+ }, [emblems]);+ const tmp = useMemo(() => new Object3D(), []);+ const c = useMemo(() => new Color(), []);+ const at = useMemo(() => new Vector3(), []);+ useFrame(({ camera, clock }) => {+ const t = reduced ? 0 : clock.elapsedTime;+ for (const e of emblems) {+ e.ico.rotation.set(t * 0.3, t * 0.5, 0);+ (e.beam.material as ShaderMaterial).uniforms.uTime.value = t;+ e.text.lookAt(camera.position.x, e.text.getWorldPosition(at).y, camera.position.z);+ const n = e.division.members.length;+ e.division.members.forEach((id, i) => {+ const a = (i / Math.max(1, n)) * Math.PI * 2 + t * 0.4;+ tmp.position.set(Math.sin(a) * 0.55, Math.sin(t * 2 + i) * 0.02, Math.cos(a) * 0.55);+ tmp.updateMatrix();+ e.dots.setMatrixAt(i, tmp.matrix);+ const s = memberState(id);+ c.set(s === "working" ? STATE.working : s === "waiting" ? STATE.waiting : s === "paused" ? STATE.paused : STATE.idle).multiplyScalar(2);+ e.dots.setColorAt(i, c);+ });+ e.dots.count = n;+ e.dots.instanceMatrix.needsUpdate = true;+ if (e.dots.instanceColor) e.dots.instanceColor.needsUpdate = true;+ }+ });+ return <group ref={group}>{emblems.map((e) => <primitive key={e.division.id} object={e.group} />)}</group>;+}++/** A label on a transparent plane (canvas text), 1 m tall per 128 px. */+export function textPlane(text: string, colour: string, opts: { size?: number; width?: number; font?: string; oneSided?: boolean } = {}): Mesh {+ const size = opts.size ?? 0.34;+ const c = document.createElement("canvas");+ const ctx = c.getContext("2d") as CanvasRenderingContext2D;+ const font = opts.font ?? "600 64px 'Space Grotesk', 'Inter Variable', sans-serif";+ ctx.font = font;+ const w = Math.min(1600, Math.ceil(ctx.measureText(text).width) + 48);+ c.width = w; c.height = 96;+ ctx.font = font;+ ctx.textBaseline = "middle";+ ctx.textAlign = "center";+ ctx.shadowColor = colour; ctx.shadowBlur = 16;+ ctx.fillStyle = "#ffffff";+ ctx.fillText(text, w / 2, 50);+ const tex = new CanvasTexture(c);+ tex.colorSpace = SRGBColorSpace;+ const mat = new MeshBasicMaterial({ map: tex, transparent: true, toneMapped: false, depthWrite: false, color: new Color(colour).lerp(new Color("#ffffff"), 0.55).multiplyScalar(1.3), side: opts.oneSided ? FrontSide : DoubleSide });+ const mesh = new Mesh(new PlaneGeometry((w / 96) * size, size), mat);+ mesh.raycast = () => undefined;+ return mesh;+}++/** Room signs over the doors and on the walls. */+export function RoomSigns({ plan, text }: { plan: DeckPlan; text: (room: DeckPlan["rooms"][number]) => string | null }) {+ const signs = useMemo(() => plan.rooms.filter((r) => r.sign && r.signAt).map((room) => {+ const label = text(room);+ if (!label) return null;+ const mesh = textPlane(label, room.accent, { size: 0.3, oneSided: true });+ const at = room.signAt!;+ // Placed in the geometry itself, so the cut-away (which works on positions) sinks it with its wall.+ mesh.geometry.applyMatrix4(new Matrix4().makeRotationY(at.yaw).setPosition(at.x + Math.sin(at.yaw) * 0.02, WALL_H - 0.32, at.z + Math.cos(at.yaw) * 0.02));+ const cut = nearestWallCut(plan, at.x, at.z, 0.8);+ const n = mesh.geometry.attributes.position.count;+ const ab = new Float32Array(n * 4), kind = new Float32Array(n);+ if (cut) for (let i = 0; i < n; i += 1) { ab.set([cut.ax, cut.az, cut.bx, cut.bz], i * 4); kind[i] = cut.kind; }+ mesh.geometry.setAttribute("cutAB", new BufferAttribute(ab, 4));+ mesh.geometry.setAttribute("cutKind", new BufferAttribute(kind, 1));+ withCutaway(mesh.material as MeshBasicMaterial, 0.14, 0.4);+ return { id: room.id, mesh };+ }).filter((s): s is { id: string; mesh: Mesh } => s !== null), [plan, text]);+ useEffect(() => () => { for (const s of signs) { s.mesh.geometry.dispose(); const m = s.mesh.material as MeshBasicMaterial; m.map?.dispose(); m.dispose(); } }, [signs]);+ return <>{signs.map((s) => <primitive key={s.id} object={s.mesh} />)}</>;+}++/** Sliding doors: two leaves per door that part as anyone comes near. */+export function SlidingDoors({ plan, bodies }: { plan: DeckPlan; bodies: () => Iterable<{ x: number; z: number }> }) {+ const doors = useMemo(() => plan.doors.filter((d) => d.slides && d.id !== "lift-door"), [plan]);+ const mesh = useMemo(() => {+ const m = new InstancedMesh(new BoxGeometry(1, 2.3, 0.08), finishMaterial("panel"), Math.max(1, doors.length * 2));+ m.castShadow = true;+ m.raycast = () => undefined;+ return m;+ }, [doors]);+ const glow = useMemo(() => {+ const m = new InstancedMesh(new BoxGeometry(1, 0.03, 0.1), finishMaterial("glow"), Math.max(1, doors.length * 2));+ m.raycast = () => undefined;+ return m;+ }, [doors]);+ useEffect(() => () => { mesh.geometry.dispose(); glow.geometry.dispose(); mesh.dispose(); glow.dispose(); }, [mesh, glow]);+ const open = useRef<number[]>([]);+ const tmp = useMemo(() => new Object3D(), []);+ const colour = useMemo(() => new Color(), []);+ useEffect(() => {+ open.current = doors.map(() => 0);+ doors.forEach((_, i) => {+ for (const k of [0, 1]) { mesh.setColorAt(i * 2 + k, colour.set(SHIP.panelCool)); glow.setColorAt(i * 2 + k, colour.set(SHIP.cyan)); }+ });+ }, [doors, mesh, glow, colour]);+ useFrame((_, dt) => {+ const near = [...bodies()];+ doors.forEach((d, i) => {+ const want = near.some((b) => Math.hypot(b.x - d.at.x, b.z - d.at.z) < 2.4) ? 1 : 0;+ const o = (open.current[i] += (want - open.current[i]) * Math.min(1, dt * 7));+ const leaf = d.width / 2;+ for (const k of [0, 1]) {+ const s = k ? 1 : -1;+ const along = s * (leaf / 2 + o * leaf * 0.92);+ tmp.position.set(d.axis === "x" ? d.at.x + along : d.at.x, 0.03 + 1.15, d.axis === "x" ? d.at.z : d.at.z + along);+ tmp.rotation.set(0, d.axis === "x" ? 0 : Math.PI / 2, 0);+ tmp.scale.set(leaf, 1, 1);+ tmp.updateMatrix();+ mesh.setMatrixAt(i * 2 + k, tmp.matrix);+ tmp.position.y = 1.4;+ tmp.scale.set(leaf * 0.7, 1, 1);+ tmp.updateMatrix();+ glow.setMatrixAt(i * 2 + k, tmp.matrix);+ }+ });+ mesh.count = glow.count = doors.length * 2;+ mesh.instanceMatrix.needsUpdate = true;+ glow.instanceMatrix.needsUpdate = true;+ if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;+ if (glow.instanceColor) glow.instanceColor.needsUpdate = true;+ });+ return <><primitive object={mesh} /><primitive object={glow} /></>;+}++/** The transporter's shimmer: faint at rest, a column of light while someone beams in. */+export function TransporterBeam({ at, active, reduced }: { at: { x: number; z: number }; active: boolean; reduced: boolean }) {+ const mat = useMemo(() => new ShaderMaterial({+ vertexShader: HOLO_VERT, fragmentShader: BEAM_FRAG, transparent: true, blending: AdditiveBlending, depthWrite: false, side: DoubleSide,+ uniforms: { uTime: { value: 0 }, uColour: { value: new Color("#bfeaff").multiplyScalar(1.6) }, uStrength: { value: 0.25 } },+ }), []);+ const geo = useMemo(() => new CylinderGeometry(1.7, 1.7, 3.2, 48, 1, true), []);+ useEffect(() => () => { mat.dispose(); geo.dispose(); }, [mat, geo]);+ useFrame(({ clock }, dt) => {+ mat.uniforms.uTime.value = reduced ? 0 : clock.elapsedTime;+ const goal = active ? 1.6 : 0.22;+ mat.uniforms.uStrength.value += (goal - mat.uniforms.uStrength.value) * Math.min(1, dt * 3);+ });+ return <mesh geometry={geo} material={mat} position={[at.x, 1.7, at.z]} raycast={() => undefined} />;+}++/**+ * Invisible click targets for the stations, sized to their props, so every+ * station can be used from afar.+ */+export function StationTargets({ plan, onStation, onHover }: { plan: DeckPlan; onStation: (s: Station) => void; onHover: (s: Station | null) => void }) {+ const targets = useMemo(() => plan.stations.map((s) => {+ const p = plan.props.find((q) => q.id === s.propId);+ if (!p) return null;+ return { station: s, prop: p };+ }).filter((x): x is { station: Station; prop: Prop } => x !== null), [plan]);+ return (+ <group>+ {targets.map(({ station, prop }) => (+ <mesh key={station.id} position={[prop.x, Math.max(0.6, prop.h) / 2, prop.z]} rotation={[0, prop.yaw, 0]}+ onClick={(e) => { e.stopPropagation(); onStation(station); }}+ onPointerOver={(e) => { e.stopPropagation(); onHover(station); }}+ onPointerOut={() => onHover(null)}>+ <boxGeometry args={[prop.w + 0.2, Math.max(0.6, prop.h) + 0.2, prop.d + 0.2]} />+ <meshBasicMaterial visible={false} />+ </mesh>+ ))}+ </group>+ );+}++/** A soft rim of light round the station the captain stands at. */+export function StationHalo({ plan, id }: { plan: DeckPlan; id: string | null }) {+ const station = id ? plan.stations.find((s) => s.id === id) : undefined;+ const prop = station ? plan.props.find((p) => p.id === station.propId) : undefined;+ const ring = useRef<Mesh>(null);+ useFrame(({ clock }) => {+ if (ring.current) (ring.current.material as MeshBasicMaterial).opacity = 0.55 + Math.sin(clock.elapsedTime * 3) * 0.2;+ });+ if (!prop) return null;+ const r = Math.max(prop.w, prop.d) / 2 + 0.35;+ return (+ <mesh ref={ring} position={[prop.x, 0.03, prop.z]} rotation={[-Math.PI / 2, 0, 0]} raycast={() => undefined}>+ <ringGeometry args={[r, r + 0.06, 64]} />+ <meshBasicMaterial color={new Color(SHIP.gold).multiplyScalar(2)} transparent opacity={0.7} toneMapped={false} depthWrite={false} />+ </mesh>+ );+}+diff --git a/dodaios/ui/web/frontend/src/components/society/starship/render/deck/dressing.ts b/dodaios/ui/web/frontend/src/components/society/starship/render/deck/dressing.tsnew file mode 100644index 0000000000..51d3ad28fa--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/render/deck/dressing.ts@@ -0,0 +1,126 @@+/**+ * Detail that makes a room read as part of a working ship without changing+ * where anyone can walk: wall consoles, conduit runs and service hatches on+ * the inner faces of the walls (inside the walls' own clearance), and inlays+ * in the floor (a lit runner down the corridors, an emblem in the turbolift+ * lobby, rings round the divisions' horseshoes, lines fanning out from the+ * transporter). Deterministic per wall, so a rebuilt plan dresses the same.+ */+import { Matrix4 } from "three";+import { hash } from "../../plan/builder";+import type { DeckPlan, Room, Wall } from "../../plan/types";+import { annulus, type GeoBatch, type CutLine } from "../kit/geo";+import { SHIP } from "../kit/palette";++const RIB = 2.4;++function wallFaces(wall: Wall): number[] {+ if (wall.kind === "hull") return [1];+ if (wall.kind === "bulkhead") return [-1, 1];+ return [];+}++/** Wall consoles, conduits and hatches between the ribs. */+function dressWalls(plan: DeckPlan, batch: GeoBatch): void {+ const bare = plan.rooms.filter((r) => r.kind === "holodeck");+ for (const wall of plan.walls) {+ const faces = wallFaces(wall);+ if (faces.length === 0) continue;+ const mx = (wall.a.x + wall.b.x) / 2, mz = (wall.a.z + wall.b.z) / 2;+ if (bare.some((r) => mx >= r.rect.x0 - 0.5 && mx <= r.rect.x1 + 0.5 && mz >= r.rect.z0 - 0.5 && mz <= r.rect.z1 + 0.5)) continue;+ const dx = wall.b.x - wall.a.x, dz = wall.b.z - wall.a.z;+ const len = Math.hypot(dx, dz);+ if (len < RIB * 1.5) continue;+ const yaw = Math.atan2(dz, dx);+ const cut: CutLine = { ax: wall.a.x, az: wall.a.z, bx: wall.b.x, bz: wall.b.z, kind: wall.kind === "hull" ? 1 : 2 };+ const f = batch.frame(new Matrix4().makeRotationY(-yaw).setPosition((wall.a.x + wall.b.x) / 2, 0, (wall.a.z + wall.b.z) / 2), cut);+ const bays = Math.max(1, Math.round(len / RIB));+ const pitch = len / bays;+ for (const side of faces) {+ // The window band of a hull wall leaves room only for low fittings.+ const windowed = wall.kind === "hull" && wall.windows;+ const z = side * (wall.t / 2 + 0.05);+ for (let k = 0; k < bays; k += 1) {+ const x = -len / 2 + pitch * (k + 0.5);+ const pick = hash(`${wall.id}:${side}:${k}`) % 7;+ if (pick === 0 && !windowed) {+ // A wall console: a dark panel with a lit screen and a row of keys.+ f.box("structure", 1.1, 0.75, 0.08, SHIP.panelDark, { x, y: 1.15, z });+ f.box("screen", 0.9, 0.45, 0.01, "#16405a", { x, y: 1.4, z: z + side * 0.045 });+ f.box("glow", 0.9, 0.012, 0.012, SHIP.cyan, { x, y: 1.37, z: z + side * 0.05 });+ for (let b = 0; b < 4; b += 1) f.box("glowSoft", 0.08, 0.04, 0.012, b === 1 ? SHIP.gold : "#3f7fa0", { x: x - 0.3 + b * 0.2, y: 1.23, z: z + side * 0.05 });+ } else if (pick === 1 || pick === 2) {+ // A service hatch in the base band, with a gold handle.+ f.box("structure", 0.9, 0.62, 0.04, SHIP.graphite, { x, y: 0.12, z });+ f.box("metal", 0.3, 0.035, 0.03, SHIP.gold, { x, y: 0.62, z: z + side * 0.03 });+ } else if (pick === 3 && !windowed) {+ // A status strip: three small lights stacked beside a vent.+ f.box("structure", 0.5, 0.5, 0.05, SHIP.graphite, { x, y: 1.6, z });+ for (let r = 0; r < 4; r += 1) f.box("structure", 0.42, 0.03, 0.02, SHIP.charcoal, { x, y: 1.66 + r * 0.09, z: z + side * 0.03 });+ for (let r = 0; r < 3; r += 1) f.box("glowSoft", 0.04, 0.04, 0.012, r === 0 ? "#3fd27f" : "#5fd4ff", { x: x + 0.34, y: 1.65 + r * 0.12, z: z + side * 0.03 });+ }+ }+ // A conduit run high on every inner wall, in two pipes.+ if (!windowed) {+ f.box("metal", len - 0.3, 0.07, 0.07, SHIP.steel, { y: 2.32, z: z + side * 0.02 });+ f.box("metal", len - 0.3, 0.05, 0.05, SHIP.steelLight, { y: 2.44, z: z + side * 0.015 });+ }+ }+ }+}++function dressFloor(plan: DeckPlan, batch: GeoBatch): void {+ const root = batch.frame(new Matrix4());+ for (const room of plan.rooms) {+ if (room.kind === "corridor") runner(root, room);+ if (room.kind === "lift") emblem(root, room);+ }+ // The horseshoe rings belong to the operations deck's divisions (engineering's bays draw their own).+ for (const d of plan.divisions) {+ if (plan.rooms.find((r) => r.id === d.room)?.kind !== "division") continue;+ const consoles = plan.props.filter((p) => p.kind === "console" && plan.places.some((pl) => pl.division === d.room && Math.hypot(pl.x - p.x, pl.z - p.z) < 1.2));+ const r = consoles.length ? Math.max(...consoles.map((p) => Math.hypot(p.x - d.centre.x, p.z - d.centre.z))) + 0.75 : 3.6;+ root.geo("structure", annulus(r - 0.06, r, 0, Math.PI * 2, 96), SHIP.charcoal, { x: d.centre.x, y: 0.008, z: d.centre.z });+ root.geo("glowSoft", annulus(r - 0.035, r - 0.015, 0, Math.PI * 2, 96), d.colour, { x: d.centre.x, y: 0.01, z: d.centre.z });+ root.geo("structure", annulus(0, r - 0.08, 0, Math.PI * 2, 64), "#1b1f25", { x: d.centre.x, y: 0.005, z: d.centre.z });+ }+ const pad = plan.props.find((p) => p.kind === "transporter");+ if (pad) {+ root.geo("glowSoft", annulus(2.6, 2.64, 0, Math.PI * 2, 96), SHIP.cyan, { x: pad.x, y: 0.01, z: pad.z });+ for (let k = 0; k < 12; k += 1) {+ const a = (k / 12) * Math.PI * 2;+ root.box("glowSoft", 0.025, 0.004, 2.2, k % 3 === 0 ? SHIP.gold : "#2a6c8f", { x: pad.x + Math.sin(a) * 3.85, y: 0.006, z: pad.z + Math.cos(a) * 3.85, yaw: a });+ }+ }+}++function runner(root: ReturnType<GeoBatch["frame"]>, room: Room): void {+ const r = room.rect;+ const cx = (r.x0 + r.x1) / 2, w = r.x1 - r.x0, d = r.z1 - r.z0;+ const along = d >= w;+ const length = along ? d : w;+ root.box("structure", along ? 1.3 : length, 0.006, along ? length : 1.3, "#15181d", { x: along ? cx : (r.x0 + r.x1) / 2, y: 0.004, z: (r.z0 + r.z1) / 2 });+ for (const s of [-1, 1]) root.box("glowSoft", along ? 0.02 : length, 0.006, along ? length : 0.02, "#2c6f93", { x: cx + (along ? s * 0.66 : 0), y: 0.007, z: (r.z0 + r.z1) / 2 + (along ? 0 : s * 0.66) });+ const n = Math.floor(length / 1.8);+ for (let k = 0; k < n; k += 1) {+ const t = -length / 2 + (k + 0.5) * (length / n);+ root.box("glow", along ? 0.3 : 0.06, 0.006, along ? 0.06 : 0.3, "#9fdcff", { x: along ? cx : cx + t, y: 0.008, z: (r.z0 + r.z1) / 2 + (along ? t : 0) });+ }+}++function emblem(root: ReturnType<GeoBatch["frame"]>, room: Room): void {+ const cx = (room.rect.x0 + room.rect.x1) / 2, cz = (room.rect.z0 + room.rect.z1) / 2 - 0.6;+ root.geo("structure", annulus(0, 3.2, 0, Math.PI * 2, 96), "#171a20", { x: cx, y: 0.005, z: cz });+ root.geo("metal", annulus(3.05, 3.2, 0, Math.PI * 2, 96), "#8a7550", { x: cx, y: 0.007, z: cz });+ root.geo("glowSoft", annulus(2.2, 2.24, 0, Math.PI * 2, 96), SHIP.gold, { x: cx, y: 0.008, z: cz });+ for (let k = 0; k < 8; k += 1) {+ const a = (k / 8) * Math.PI * 2;+ root.box("metal", 0.04, 0.004, 0.8, "#8a7550", { x: cx + Math.sin(a) * 2.65, y: 0.008, z: cz + Math.cos(a) * 2.65, yaw: a });+ }+ root.geo("metal", annulus(0.5, 0.62, 0, Math.PI * 2, 48), "#b89a5e", { x: cx, y: 0.008, z: cz });+}++export function buildDressing(plan: DeckPlan, batch: GeoBatch): void {+ dressWalls(plan, batch);+ dressFloor(plan, batch);+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/render/deck/exterior.ts b/dodaios/ui/web/frontend/src/components/society/starship/render/deck/exterior.tsnew file mode 100644index 0000000000..5c82de2ec7--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/render/deck/exterior.ts@@ -0,0 +1,68 @@+/**+ * The ship around the deck: what the camera sees past the hull walls. Two+ * engine nacelles on swept pylons, the main engines at the stern, ribbed+ * plating and running lights on the sloping hull, a sensor array at the bow.+ * It frames every deck the same way, so a deck reads as a slice of one ship.+ */+import { CylinderGeometry, Matrix4, Quaternion, Vector3 } from "three";+import type { DeckPlan } from "../../plan/types";+import type { GeoBatch } from "../kit/geo";+import { SHIP } from "../kit/palette";++export function buildExterior(plan: DeckPlan, batch: GeoBatch): void {+ const { x0, x1, z0, z1 } = plan.bounds;+ const half = (x1 - x0) / 2, cx = (x0 + x1) / 2, len = z1 - z0;+ const root = batch.frame(new Matrix4());++ // ── nacelles ───────────────────────────────────────────────────────+ const nz0 = z0 + len * 0.32, nz1 = z1 + 8;+ const nlen = nz1 - nz0, nr = 2.3;+ for (const side of [-1, 1]) {+ const nx = cx + side * (half + 8.5), ny = -4.2;+ const along = (r0: number, r1: number, l: number, at: number, finish: "structure" | "panel" | "metal" | "glow" | "glowSoft", colour: string, seg = 28) => {+ const g = new CylinderGeometry(r0, r1, l, seg, 1);+ g.applyMatrix4(new Matrix4().compose(new Vector3(nx, ny, at), new Quaternion().setFromAxisAngle(new Vector3(1, 0, 0), Math.PI / 2), new Vector3(1, 1, 1)));+ root.geo(finish, g, colour);+ };+ along(nr, nr, nlen, nz0 + nlen / 2, "panel", SHIP.hullOuter);+ along(nr * 1.04, nr * 1.04, 1.2, nz0 + 3, "structure", SHIP.graphite);+ along(nr * 1.04, nr * 1.04, 1.2, nz1 - 6, "structure", SHIP.graphite);+ // The intake at the front glows cyan, the exhaust at the back gold.+ along(nr * 0.7, nr, 2.6, nz0 - 1.2, "structure", SHIP.charcoal);+ along(nr * 0.62, nr * 0.62, 0.4, nz0 - 2.5, "glow", "#7fd8ff");+ along(nr * 0.9, nr * 0.8, 0.5, nz1 + 0.2, "glow", "#ffb54a");+ // Lit coil strips along the top and the inner flank.+ root.box("glow", 0.22, 0.12, nlen - 10, "#3fa9ff", { x: nx, y: ny + nr - 0.02, z: nz0 + nlen / 2 });+ root.box("glowSoft", 0.12, 0.12, nlen - 12, "#3fa9ff", { x: nx - side * (nr - 0.05), y: ny, z: nz0 + nlen / 2 });+ // Swept pylons back to the hull.+ for (const pz of [nz0 + nlen * 0.35, nz0 + nlen * 0.72]) {+ const px = cx + side * (half + 3.4);+ root.box("structure", 9, 0.7, 3.2, SHIP.hullDark, { x: px + side * 0.6, y: ny + 0.6, z: pz, roll: side * 0.22 });+ root.box("glowSoft", 8, 0.05, 0.08, SHIP.lightWarm, { x: px + side * 0.6, y: ny + 1.32, z: pz - 1.62, roll: side * 0.22 });+ }+ }++ // ── main engines at the stern ──────────────────────────────────────+ for (const ex of [-half * 0.45, 0, half * 0.45]) {+ const r = ex === 0 ? 2.6 : 2.0;+ const g = new CylinderGeometry(r, r * 1.15, 3, 32, 1);+ g.applyMatrix4(new Matrix4().compose(new Vector3(cx + ex, -3.6, z1 + 1.8), new Quaternion().setFromAxisAngle(new Vector3(1, 0, 0), Math.PI / 2), new Vector3(1, 1, 1)));+ root.geo("structure", g, SHIP.graphite);+ const glow = new CylinderGeometry(r * 0.82, r * 0.82, 0.3, 32, 1);+ glow.applyMatrix4(new Matrix4().compose(new Vector3(cx + ex, -3.6, z1 + 3.4), new Quaternion().setFromAxisAngle(new Vector3(1, 0, 0), Math.PI / 2), new Vector3(1, 1, 1)));+ root.geo("glow", glow, "#ffc46b");+ }+ root.box("structure", half * 1.6, 2.4, 3.4, SHIP.hullDark, { x: cx, y: -5.2, z: z1 + 0.6 });++ // ── bow sensor array ───────────────────────────────────────────────+ root.box("structure", 9, 1.2, 3, SHIP.hullDark, { x: cx, y: -3.4, z: z0 - 1.6 });+ root.box("glow", 7.4, 0.1, 0.1, "#7fd8ff", { x: cx, y: -2.3, z: z0 - 3.1 });++ // ── greebles on the sloping plates ─────────────────────────────────+ for (const side of [-1, 1]) {+ for (let z = z0 + 10; z < z1 - 4; z += 4.8) {+ const w = 1.2 + ((z * 7) % 3) * 0.4;+ root.box("structure", 0.5, 0.35, w, SHIP.graphite, { x: cx + side * (half + 1.6), y: -0.9, z, roll: side * -0.55 });+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/render/deck/props.ts b/dodaios/ui/web/frontend/src/components/society/starship/render/deck/props.tsnew file mode 100644index 0000000000..693b23d552--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/render/deck/props.ts@@ -0,0 +1,254 @@+/**+ * Furniture and fittings, built from primitives into the deck's merged+ * batch. Each builder draws one piece in its own frame: centred on its+ * footprint, its front (where a person uses it) towards +z, its foot on the+ * floor. Screens and holograms that change are drawn by their own+ * components; this only builds what never changes.+ */+import { Matrix4 } from "three";+import type { DeckPlan, Prop, PropKind } from "../../plan/types";+import type { CutLine, Frame, GeoBatch } from "../kit/geo";+import { SHIP } from "../kit/palette";++type Builder = (f: Frame, p: Prop) => void;++/** Where a console's screen sits in the console's own frame. */+export const CONSOLE_SCREEN = { y: 1.16, z: -0.2, w: 0.96, h: 0.52, tilt: -0.22 } as const;++const console: Builder = (f, p) => {+ const accent = p.accent ?? SHIP.cyan;+ // Pedestal and foot.+ f.chamfer("structure", 0.62, 0.08, 0.5, 0.08, SHIP.charcoal, { z: -0.06 });+ f.chamfer("structure", 0.44, 0.7, 0.32, 0.06, SHIP.graphite, { z: -0.1, y: 0.08 });+ // Desk: a dark top with a ceramic rim, sloping towards the user.+ f.rounded("panel", p.w, 0.07, 0.62, 0.08, SHIP.panelCool, { y: 0.74, z: 0.02 });+ f.rounded("structure", p.w - 0.08, 0.02, 0.5, 0.06, SHIP.panelDark, { y: 0.81, z: 0.04, pitch: 0.05 });+ // Input surface: a soft cyan pad and keys.+ f.box("glowSoft", 0.52, 0.006, 0.18, "#2a6c8f", { y: 0.835, z: 0.16 });+ f.box("glow", p.w - 0.1, 0.012, 0.012, accent, { y: 0.76, z: 0.33 });+ // Screen mount and bezel (the face itself is drawn live).+ f.box("structure", 0.08, 0.32, 0.06, SHIP.graphite, { y: 0.8, z: CONSOLE_SCREEN.z - 0.06 });+ const s = f.child({ y: CONSOLE_SCREEN.y, z: CONSOLE_SCREEN.z, pitch: CONSOLE_SCREEN.tilt });+ s.box("structure", CONSOLE_SCREEN.w + 0.06, CONSOLE_SCREEN.h + 0.06, 0.035, SHIP.charcoal, { y: -(CONSOLE_SCREEN.h + 0.06) / 2, z: -0.025 });+ s.box("glow", CONSOLE_SCREEN.w + 0.06, 0.01, 0.04, accent, { y: -(CONSOLE_SCREEN.h + 0.06) / 2 - 0.01, z: -0.025 });+ // A side wing with status lights.+ for (const side of [-1, 1]) {+ f.chamfer("panel", 0.1, 0.24, 0.44, 0.03, SHIP.panel, { x: side * (p.w / 2 - 0.05), y: 0.78, z: 0.0 });+ }+};++const consoleChair: Builder = (f, p) => {+ const accent = p.accent ?? SHIP.cyan;+ f.cylinder("metal", 0.26, 0.28, 0.04, SHIP.steel, {}, 20);+ f.cylinder("metal", 0.04, 0.05, 0.4, SHIP.steelLight, { y: 0.04 }, 12);+ f.rounded("fabric", 0.48, 0.08, 0.46, 0.1, SHIP.fabric, { y: 0.42 });+ // Back towards -z (the chair faces +z, towards the console).+ f.rounded("panel", 0.46, 0.5, 0.07, 0.08, SHIP.panel, { y: 0.52, z: -0.24, pitch: -0.12 });+ f.rounded("fabric", 0.38, 0.4, 0.04, 0.07, SHIP.fabric, { y: 0.56, z: -0.2, pitch: -0.12 });+ f.box("glow", 0.3, 0.015, 0.01, accent, { y: 0.98, z: -0.31 });+ for (const s of [-1, 1]) f.rounded("structure", 0.05, 0.04, 0.32, 0.02, SHIP.graphite, { x: s * 0.26, y: 0.62, z: 0.02 });+};++const holoTable: Builder = (f, p) => {+ const r = p.w / 2;+ const accent = p.accent ?? SHIP.cyan;+ f.cylinder("structure", r * 0.55, r * 0.7, 0.1, SHIP.charcoal, {}, 32);+ f.cylinder("structure", r * 0.4, r * 0.5, 0.72, SHIP.graphite, { y: 0.1 }, 32);+ f.cylinder("panel", r, r * 0.92, 0.1, SHIP.panelCool, { y: 0.82 }, 48);+ f.cylinder("structure", r * 0.86, r * 0.86, 0.02, SHIP.panelDark, { y: 0.92 }, 48);+ f.ring("glow", r * 0.98, 0.014, accent, { y: 0.9 }, Math.PI * 2, 64);+ f.ring("glowSoft", r * 0.62, 0.01, SHIP.cyan, { y: 0.935 }, Math.PI * 2, 48);+ f.ring("glow", r * 0.72, 0.012, accent, { y: 0.02 }, Math.PI * 2, 48);+};++const transporter: Builder = (f, p) => {+ const r = p.w / 2;+ f.cylinder("structure", r, r + 0.08, 0.08, SHIP.graphite, {}, 64);+ f.cylinder("metal", r - 0.18, r - 0.12, 0.1, SHIP.steel, { y: 0.0 }, 64);+ f.ring("glow", r - 0.05, 0.03, SHIP.gold, { y: 0.1 }, Math.PI * 2, 72);+ f.ring("glowSoft", r - 0.45, 0.02, SHIP.cyan, { y: 0.11 }, Math.PI * 2, 64);+ // Six emitter pads in a ring and one in the middle.+ for (let k = 0; k < 7; k += 1) {+ const a = (k / 6) * Math.PI * 2;+ const x = k === 6 ? 0 : Math.sin(a) * (r * 0.52), z = k === 6 ? 0 : Math.cos(a) * (r * 0.52);+ f.cylinder("metal", 0.36, 0.4, 0.04, SHIP.steelLight, { x, z, y: 0.1 }, 24);+ f.cylinder("glow", 0.26, 0.26, 0.012, "#bfeaff", { x, z, y: 0.14 }, 24);+ }+};++const transporterConsole: Builder = (f, p) => {+ f.chamfer("structure", 0.9, 0.9, 0.5, 0.1, SHIP.graphite, { z: -0.08 });+ f.rounded("panel", p.w, 0.08, p.d, 0.1, SHIP.panel, { y: 0.9, pitch: 0.28 });+ f.box("glowSoft", p.w - 0.2, 0.005, p.d - 0.24, "#1f5a7a", { y: 0.99, pitch: 0.28 });+ for (let k = 0; k < 3; k += 1) f.box("glow", 0.16, 0.01, 0.05, k === 1 ? SHIP.gold : SHIP.cyan, { x: (k - 1) * 0.36, y: 1.02, z: 0.12, pitch: 0.28 });+ f.box("glow", p.w, 0.012, 0.012, SHIP.gold, { y: 0.88, z: p.d / 2 });+};++const liftDoors: Builder = (f, p) => {+ f.box("structure", p.w + 0.6, 2.7, p.d, SHIP.graphite, { z: -0.05 });+ f.box("metal", p.w - 0.2, 2.25, 0.08, SHIP.steelLight, { z: p.d / 2 - 0.02 });+ f.box("structure", 0.03, 2.25, 0.1, SHIP.charcoal, { z: p.d / 2 });+ f.box("glow", p.w - 0.2, 0.03, 0.1, SHIP.gold, { y: 2.3, z: p.d / 2 });+ for (const s of [-1, 1]) f.box("glow", 0.03, 2.25, 0.1, SHIP.gold, { x: s * (p.w / 2 - 0.08), z: p.d / 2 });+};++const messTable: Builder = (f, p) => {+ f.cylinder("structure", 0.3, 0.34, 0.04, SHIP.charcoal, {}, 24);+ f.cylinder("metal", 0.06, 0.08, 0.66, SHIP.steelLight, { y: 0.04 }, 16);+ f.cylinder("ceramic", p.w / 2, p.w / 2 - 0.03, 0.05, "#f2f2f0", { y: 0.69 }, 40);+ f.ring("glowSoft", p.w / 2 - 0.12, 0.01, SHIP.lightWarm, { y: 0.685 }, Math.PI * 2, 40);+};++const messStool: Builder = (f) => {+ f.cylinder("metal", 0.03, 0.05, 0.42, SHIP.steelLight, {}, 12);+ f.cylinder("fabric", 0.2, 0.18, 0.06, SHIP.leather, { y: 0.42 }, 20);+};++const galley: Builder = (f, p) => {+ f.box("structure", p.w, 0.9, p.d, SHIP.graphite, {});+ f.rounded("ceramic", p.w + 0.06, 0.05, p.d + 0.08, 0.04, "#f0efec", { y: 0.9 });+ f.box("glowSoft", p.w - 0.2, 0.02, 0.02, SHIP.lightWarm, { y: 0.86, z: p.d / 2 + 0.02 });+ // The dispensers along the wall behind: lit alcoves.+ const n = Math.max(2, Math.floor(p.w / 1.3));+ for (let k = 0; k < n; k += 1) {+ const x = -p.w / 2 + (p.w * (k + 0.5)) / n;+ f.box("panel", 1.0, 1.0, 0.3, SHIP.panel, { x, y: 1.25, z: -p.d / 2 + 0.05 });+ f.box("glowSoft", 0.7, 0.55, 0.02, k % 2 ? "#ffd9a8" : "#b8e4ff", { x, y: 1.45, z: -p.d / 2 + 0.21 });+ }+};++const sofa: Builder = (f, p) => {+ const w = p.w, d = p.d;+ f.rounded("structure", w, 0.12, d, 0.08, SHIP.charcoal, { y: 0.04 });+ f.rounded("fabric", w - 0.1, 0.24, d - 0.22, 0.1, SHIP.fabric, { y: 0.16, z: 0.08 });+ f.rounded("fabric", w - 0.1, 0.42, 0.22, 0.1, SHIP.fabric, { y: 0.16, z: -d / 2 + 0.11 });+ for (const s of [-1, 1]) f.rounded("fabric", 0.18, 0.5, d, 0.08, "#343a47", { x: s * (w / 2 - 0.09), y: 0.12 });+ f.box("glowSoft", w - 0.2, 0.01, 0.01, SHIP.lightWarm, { y: 0.06, z: d / 2 });+};++const lowTable: Builder = (f, p) => {+ for (const sx of [-1, 1]) f.box("metal", 0.04, 0.34, p.d - 0.08, SHIP.steel, { x: sx * (p.w / 2 - 0.06) });+ f.rounded("glass", p.w, 0.03, p.d, 0.05, "#c8e8ff", { y: 0.34 });+ f.rounded("structure", p.w - 0.1, 0.02, p.d - 0.1, 0.04, SHIP.panelDark, { y: 0.12 });+};++const plant: Builder = (f, p) => {+ if (p.ref === "bed") {+ // A hydroponics bed: a long trough, rows of greens and grow lights on two posts.+ f.rounded("structure", p.w, 0.55, p.d, 0.06, SHIP.graphite, {});+ f.box("structure", p.w - 0.1, 0.02, p.d - 0.1, SHIP.soil, { y: 0.55 });+ for (let k = 0; k < Math.floor(p.d / 0.5); k += 1) {+ const z = -p.d / 2 + 0.3 + k * 0.5;+ for (const x of [-0.35, 0, 0.35]) f.sphere("fabric", 0.17 + ((k * 7 + x * 10) % 3) * 0.02, k % 2 ? SHIP.plant : SHIP.plantDark, { x, y: 0.66, z }, 8);+ }+ for (const s of [-1, 1]) f.box("metal", 0.05, 1.6, 0.05, SHIP.steel, { z: s * (p.d / 2 - 0.2), y: 0.55 });+ f.box("structure", 0.16, 0.06, p.d - 0.3, SHIP.graphite, { y: 2.12 });+ f.box("glow", 0.1, 0.012, p.d - 0.4, "#ff7ad0", { y: 2.11 });+ return;+ }+ f.chamfer("structure", p.w, 0.55, p.d, 0.1, SHIP.graphite, {});+ f.box("glowSoft", p.w * 0.8, 0.012, 0.012, SHIP.lightWarm, { y: 0.55, z: p.d / 2 - 0.05 });+ const h = p.h;+ f.sphere("fabric", p.w * 0.42, SHIP.plantDark, { y: 0.55 + h * 0.3 }, 10);+ f.sphere("fabric", p.w * 0.34, SHIP.plant, { y: 0.55 + h * 0.48, x: 0.08 }, 10);+ f.sphere("fabric", p.w * 0.26, SHIP.plant, { y: 0.55 + h * 0.62, x: -0.1, z: 0.05 }, 10);+};++const pod: Builder = (f, p) => {+ // Long along the pod's own x (w).+ f.rounded("panel", p.w, 0.5, p.d, 0.3, SHIP.panel, {});+ f.rounded("structure", p.w - 0.18, 0.08, p.d - 0.18, 0.24, SHIP.panelDark, { y: 0.5 });+ f.rounded("fabric", p.w - 0.4, 0.08, p.d - 0.32, 0.2, "#4b4f6a", { y: 0.55 });+ f.rounded("fabric", 0.35, 0.08, p.d - 0.42, 0.12, "#d9dbe8", { x: -p.w / 2 + 0.4, y: 0.62 });+ f.sphere("glass", 0.5, "#c9b8ff", { y: 0.58 }, 20);+ f.box("glowSoft", p.w - 0.3, 0.02, 0.02, "#a68cff", { y: 0.5, z: p.d / 2 - 0.02 });+};++const locker: Builder = (f, p) => {+ f.box("panel", p.w, p.h, p.d, SHIP.panelCool, {});+ f.box("structure", 0.02, p.h - 0.1, 0.02, SHIP.graphite, { y: 0.05, z: p.d / 2 });+ f.box("glow", 0.05, 0.05, 0.02, SHIP.gold, { x: p.w / 2 - 0.12, y: 1.25, z: p.d / 2 });+ f.box("structure", p.w, 0.06, p.d + 0.02, SHIP.graphite, { y: p.h - 0.06 });+};++const mirror: Builder = (f, p) => {+ f.box("structure", p.w, p.h, 0.12, SHIP.graphite, { z: -0.08 });+ f.box("metal", p.w - 0.16, p.h - 0.3, 0.02, "#d8e4ee", { y: 0.15, z: -0.01 });+ for (const s of [-1, 1]) f.box("glow", 0.02, p.h - 0.3, 0.03, SHIP.gold, { x: s * (p.w / 2 - 0.05), y: 0.15 });+ f.box("glow", p.w - 0.1, 0.02, 0.03, SHIP.gold, { y: p.h - 0.12 });+};++const divisionPlinth: Builder = (f, p) => {+ f.chamfer("structure", p.w, 0.08, p.d, 0.16, SHIP.charcoal, {});+ f.chamfer("panel", p.w * 0.66, p.h - 0.08, p.d * 0.66, 0.1, SHIP.panel, { y: 0.08 });+ f.chamfer("structure", p.w * 0.74, 0.04, p.d * 0.74, 0.1, SHIP.graphite, { y: p.h });+ f.ring("glow", p.w * 0.3, 0.012, SHIP.gold, { y: p.h + 0.04 }, Math.PI * 2, 32);+};++const pillar: Builder = (f, p) => {+ f.chamfer("structure", p.w, p.h, p.d, 0.18, SHIP.graphite, {});+ for (const s of [-1, 1]) f.box("glow", 0.025, p.h - 0.6, 0.025, SHIP.lightCool, { x: s * (p.w / 2 - 0.12), y: 0.3, z: p.d / 2 });+ f.chamfer("panel", p.w + 0.1, 0.12, p.d + 0.1, 0.2, SHIP.panel, { y: 0.0 });+};++const bench: Builder = (f, p) => {+ for (const s of [-1, 1]) f.box("structure", 0.08, 0.4, p.d - 0.06, SHIP.graphite, { x: s * (p.w / 2 - 0.2) });+ f.rounded("fabric", p.w, 0.07, p.d, 0.06, SHIP.leather, { y: 0.4 });+};++const crate: Builder = (f, p) => {+ f.chamfer("structure", p.w, p.h, p.d, 0.06, SHIP.steel, {});+ f.box("glow", p.w * 0.6, 0.02, 0.01, SHIP.gold, { y: p.h * 0.7, z: p.d / 2 });+};++export const PROP_BUILDERS: Partial<Record<PropKind, Builder>> = {+ console, consoleChair, holoTable, transporter, transporterConsole, liftDoors, messTable, messStool, galley, sofa,+ lowTable, plant, pod, locker, mirror, divisionPlinth, pillar, bench, crate,+};++/** Register builders for props that live on other decks. */+export function registerPropBuilders(builders: Partial<Record<PropKind, Builder>>): void {+ Object.assign(PROP_BUILDERS, builders);+}++export type PropBuilder = Builder;++/** Pieces that stand against a wall: they sink with it in the cut-away. */+const WALL_MOUNTED = new Set<PropKind>(["liftDoors", "locker", "mirror", "galley", "viewscreen", "rankWall", "cabinet"]);++function distToSegment(px: number, pz: number, ax: number, az: number, bx: number, bz: number): number {+ const dx = bx - ax, dz = bz - az, l2 = dx * dx + dz * dz || 1e-9;+ const t = Math.max(0, Math.min(1, ((px - ax) * dx + (pz - az) * dz) / l2));+ return Math.hypot(px - (ax + dx * t), pz - (az + dz * t));+}++/** The wall line nearest to a point, as a cut-away line (the hull's own edges first). */+export function nearestWallCut(plan: DeckPlan, x: number, z: number, reach = 1.2): CutLine | undefined {+ for (let i = 0; i < plan.hull.length; i += 1) {+ const a = plan.hull[i], c = plan.hull[(i + 1) % plan.hull.length];+ if (distToSegment(x, z, a.x, a.z, c.x, c.z) < Math.min(1.0, reach)) return { ax: a.x, az: a.z, bx: c.x, bz: c.z, kind: 1 };+ }+ let best: CutLine | undefined, bd = reach;+ for (const w of plan.walls) {+ const d = distToSegment(x, z, w.a.x, w.a.z, w.b.x, w.b.z);+ if (d < bd) { bd = d; best = { ax: w.a.x, az: w.a.z, bx: w.b.x, bz: w.b.z, kind: w.kind === "hull" ? 1 : 2 }; }+ }+ return best;+}++/** The wall a wall-mounted piece stands against, as a cut-away line. */+export function wallCutFor(plan: DeckPlan, p: Prop): CutLine | undefined {+ return WALL_MOUNTED.has(p.kind) ? nearestWallCut(plan, p.x, p.z) : undefined;+}++export function propFrame(batch: GeoBatch, p: Prop, cut?: CutLine): Frame {+ return batch.frame(new Matrix4().makeRotationY(p.yaw).setPosition(p.x, 0, p.z), cut);+}++/** Every prop of the plan with a builder, into `batch`. Props drawn elsewhere are skipped. */+export function buildProps(plan: DeckPlan, batch: GeoBatch): void {+ for (const p of plan.props) {+ const build = PROP_BUILDERS[p.kind];+ if (build) build(propFrame(batch, p, wallCutFor(plan, p)), p);+ }+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/render/deck/screens.ts b/dodaios/ui/web/frontend/src/components/society/starship/render/deck/screens.tsnew file mode 100644index 0000000000..b37aee5a71--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/render/deck/screens.ts@@ -0,0 +1,176 @@+/**+ * Every console screen of a deck in one atlas texture. A screen shows its+ * owner's real work: the tail of its chat (the captain's lines in gold, its+ * own replies in white, running tools in cyan) or a live terminal on+ * engineering; an idle console a calm standby page, an empty one "vacant".+ * Cells are redrawn only when their content changes; a cursor blinks on the+ * working ones.+ */+import { CanvasTexture, SRGBColorSpace } from "three";+import type { ChatLine } from "../../../crewFeeds/deskChat";++export const SCREEN_COLS = 8;+export const SCREEN_ROWS = 8;+export const SCREEN_W = 256;+export const SCREEN_H = 140;++export type ScreenState = "working" | "waiting" | "idle" | "paused" | "vacant" | "error";++export interface ScreenContent {+ title: string;+ state: ScreenState;+ accent: string;+ /** Chat lines (agents deck) or terminal rows (engineering). */+ lines?: readonly ChatLine[];+ rows?: readonly string[];+ /** Words for the state chip, already translated. */+ stateLabel: string;+ /** Shown on a console without live content. */+ standby: string;+}++const STATE_COLOUR: Record<ScreenState, string> = {+ working: "#3fd27f", waiting: "#ffb020", idle: "#8aa4c8", paused: "#8a7fc8", vacant: "#4a5566", error: "#ff4d5e",+};++const LINE_COLOUR: Record<ChatLine["kind"], string> = {+ user: "#f2c46b", agent: "#e8eef6", tool: "#6fd8ff", notice: "#9aa6b8", error: "#ff7a85",+};++interface Cell { index: number; key: string; content: ScreenContent }++export class ScreenAtlas {+ readonly canvas: HTMLCanvasElement;+ readonly texture: CanvasTexture;+ private readonly ctx: CanvasRenderingContext2D;+ private readonly cells = new Map<string, Cell>();+ private readonly free: number[] = [];+ private dirty = false;+ private blink = false;++ constructor() {+ this.canvas = document.createElement("canvas");+ this.canvas.width = SCREEN_COLS * SCREEN_W;+ this.canvas.height = SCREEN_ROWS * SCREEN_H;+ const ctx = this.canvas.getContext("2d");+ if (!ctx) throw new Error("2d canvas unavailable");+ this.ctx = ctx;+ for (let i = SCREEN_COLS * SCREEN_ROWS - 1; i >= 0; i -= 1) this.free.push(i);+ this.texture = new CanvasTexture(this.canvas);+ this.texture.colorSpace = SRGBColorSpace;+ this.texture.anisotropy = 4;+ }++ uv(id: string): [number, number, number, number] {+ let cell = this.cells.get(id);+ if (!cell) {+ const index = this.free.pop() ?? 0;+ cell = { index, key: "", content: { title: "", state: "vacant", accent: "#5fd4ff", stateLabel: "", standby: "" } };+ this.cells.set(id, cell);+ }+ const c = cell.index % SCREEN_COLS, r = Math.floor(cell.index / SCREEN_COLS);+ const e = 0.5 / this.canvas.width;+ return [c / SCREEN_COLS + e, 1 - (r + 1) / SCREEN_ROWS + e, (c + 1) / SCREEN_COLS - e, 1 - r / SCREEN_ROWS - e];+ }++ release(id: string): void {+ const cell = this.cells.get(id);+ if (!cell) return;+ this.cells.delete(id);+ this.free.push(cell.index);+ }++ set(id: string, content: ScreenContent): void {+ const cell = this.cells.get(id);+ if (!cell) return;+ cell.content = content;+ }++ /** Redraw changed cells; the cursor of working screens blinks twice a second. */+ tick(nowMs: number): void {+ const blink = Math.floor(nowMs / 500) % 2 === 0;+ const blinkChanged = blink !== this.blink;+ this.blink = blink;+ for (const cell of this.cells.values()) {+ const c = cell.content;+ const lines = c.lines ? c.lines.map((l) => `${l.kind}:${l.text}`).join("\n") : c.rows?.join("\n") ?? "";+ const live = c.state === "working";+ const key = `${c.title}|${c.state}|${c.accent}|${c.stateLabel}|${lines}|${live && blink ? 1 : 0}`;+ if (key === cell.key && !(live && blinkChanged)) continue;+ cell.key = key;+ this.draw(cell);+ this.dirty = true;+ }+ if (this.dirty) { this.texture.needsUpdate = true; this.dirty = false; }+ }++ private draw(cell: Cell): void {+ const { ctx } = this;+ const x = (cell.index % SCREEN_COLS) * SCREEN_W, y = Math.floor(cell.index / SCREEN_COLS) * SCREEN_H;+ const c = cell.content;+ ctx.save();+ ctx.beginPath(); ctx.rect(x, y, SCREEN_W, SCREEN_H); ctx.clip();+ const bg = ctx.createLinearGradient(x, y, x, y + SCREEN_H);+ bg.addColorStop(0, c.state === "vacant" ? "#05080c" : "#07121c"); bg.addColorStop(1, "#02050a");+ ctx.fillStyle = bg; ctx.fillRect(x, y, SCREEN_W, SCREEN_H);+ // Header: a thin accent rule, the title and the state chip.+ ctx.fillStyle = c.accent; ctx.globalAlpha = 0.9; ctx.fillRect(x, y, SCREEN_W, 3); ctx.globalAlpha = 1;+ ctx.font = "600 13px 'Space Grotesk', 'Inter Variable', sans-serif";+ ctx.textBaseline = "middle";+ ctx.fillStyle = "#e8eef6";+ ctx.fillText(clip(ctx, c.title.toUpperCase(), SCREEN_W - 96), x + 10, y + 16);+ const chip = STATE_COLOUR[c.state];+ ctx.font = "600 10px 'JetBrains Mono', monospace";+ const label = c.stateLabel.toUpperCase();+ const lw = ctx.measureText(label).width + 16;+ ctx.fillStyle = chip; ctx.globalAlpha = 0.18;+ ctx.fillRect(x + SCREEN_W - lw - 8, y + 8, lw, 16); ctx.globalAlpha = 1;+ ctx.fillStyle = chip;+ ctx.beginPath(); ctx.arc(x + SCREEN_W - lw - 1, y + 16, 3, 0, Math.PI * 2); ctx.fill();+ ctx.fillText(label, x + SCREEN_W - lw + 6, y + 16.5);+ ctx.fillStyle = "rgba(255,255,255,0.08)"; ctx.fillRect(x + 8, y + 29, SCREEN_W - 16, 1);+ const body = c.lines?.length ? c.lines.map((l) => ({ text: l.text, colour: LINE_COLOUR[l.kind], mono: l.kind === "tool" }))+ : c.rows?.length ? c.rows.map((r) => ({ text: r, colour: "#cfe6d8", mono: true })) : null;+ if (body) {+ const rowH = 13;+ const fit = Math.floor((SCREEN_H - 40) / rowH);+ const shown = body.slice(-fit);+ shown.forEach((line, i) => {+ ctx.font = line.mono ? "10px 'JetBrains Mono', monospace" : "11px 'Inter Variable', sans-serif";+ ctx.fillStyle = line.colour;+ ctx.globalAlpha = 0.55 + 0.45 * ((i + 1) / shown.length);+ ctx.fillText(clip(ctx, line.text.replace(/\s+/g, " "), SCREEN_W - 22), x + 10, y + 40 + i * rowH);+ });+ ctx.globalAlpha = 1;+ if (c.state === "working" && this.blink) {+ ctx.fillStyle = c.accent;+ ctx.fillRect(x + 10, y + 40 + Math.min(shown.length, fit - 1) * rowH - 5, 7, 10);+ }+ } else {+ // Standby: the division's ring and one quiet word.+ ctx.strokeStyle = c.accent; ctx.globalAlpha = c.state === "vacant" ? 0.25 : 0.6; ctx.lineWidth = 2;+ ctx.beginPath(); ctx.arc(x + SCREEN_W / 2, y + 82, 26, 0, Math.PI * 2); ctx.stroke();+ ctx.beginPath(); ctx.arc(x + SCREEN_W / 2, y + 82, 16, -0.4, Math.PI * 1.3); ctx.stroke();+ ctx.globalAlpha = 1;+ ctx.font = "600 10px 'JetBrains Mono', monospace";+ ctx.fillStyle = "#8aa0b8";+ ctx.textAlign = "center";+ ctx.fillText(c.standby.toUpperCase(), x + SCREEN_W / 2, y + 126);+ ctx.textAlign = "left";+ }+ // Scan lines over everything.+ ctx.fillStyle = "rgba(0,0,0,0.18)";+ for (let k = 0; k < SCREEN_H; k += 3) ctx.fillRect(x, y + k, SCREEN_W, 1);+ ctx.restore();+ }+}++function clip(ctx: CanvasRenderingContext2D, text: string, width: number): string {+ if (ctx.measureText(text).width <= width) return text;+ let lo = 0, hi = text.length;+ while (lo < hi) {+ const mid = (lo + hi + 1) >> 1;+ if (ctx.measureText(text.slice(0, mid) + "…").width <= width) lo = mid; else hi = mid - 1;+ }+ return text.slice(0, lo) + "…";+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/render/deck/structure.ts b/dodaios/ui/web/frontend/src/components/society/starship/render/deck/structure.tsnew file mode 100644index 0000000000..26fd0f94ef--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/render/deck/structure.ts@@ -0,0 +1,293 @@+/**+ * The deck's architecture as merged geometry: the slab and the outer hull+ * below it, the floors by room, the hull walls with their window band,+ * bulkheads, glass partitions, door frames and the light lines that trace+ * the cut-away top of every wall.+ */+import { BufferAttribute, BufferGeometry, Shape, ShapeGeometry, ExtrudeGeometry, Matrix4, BoxGeometry } from "three";+import type { DeckPlan, FloorFinish, Rect, Room, Vec2, Wall } from "../../plan/types";+import { GeoBatch, type CutLine, type Finish } from "../kit/geo";+import { SHIP } from "../kit/palette";++export const WALL_H = 2.7;+const BASE_H = 0.85;+const WINDOW_LO = 0.95;+const WINDOW_HI = 2.2;++/** Sutherland–Hodgman: clip a polygon to a convex clip polygon (both clockwise or both counter-clockwise). */+export function clipPolygon(subject: readonly Vec2[], clip: readonly Vec2[]): Vec2[] {+ let out = [...subject];+ const area = clip.reduce((s, p, i) => { const q = clip[(i + 1) % clip.length]; return s + (p.x * q.z - q.x * p.z); }, 0);+ const sign = area > 0 ? 1 : -1;+ for (let i = 0; i < clip.length && out.length > 0; i += 1) {+ const a = clip[i], b = clip[(i + 1) % clip.length];+ const inside = (p: Vec2) => sign * ((b.x - a.x) * (p.z - a.z) - (b.z - a.z) * (p.x - a.x)) >= -1e-9;+ const cross = (p: Vec2, q: Vec2): Vec2 => {+ const dx = q.x - p.x, dz = q.z - p.z;+ const ex = b.x - a.x, ez = b.z - a.z;+ const t = (ex * (p.z - a.z) - ez * (p.x - a.x)) / (ez * dx - ex * dz);+ return { x: p.x + dx * t, z: p.z + dz * t };+ };+ const input = out;+ out = [];+ for (let k = 0; k < input.length; k += 1) {+ const cur = input[k], prev = input[(k + input.length - 1) % input.length];+ if (inside(cur)) {+ if (!inside(prev)) out.push(cross(prev, cur));+ out.push(cur);+ } else if (inside(prev)) out.push(cross(prev, cur));+ }+ }+ return out;+}++function rectPoly(r: Rect): Vec2[] {+ return [{ x: r.x0, z: r.z0 }, { x: r.x1, z: r.z0 }, { x: r.x1, z: r.z1 }, { x: r.x0, z: r.z1 }];+}++/** A flat polygon at height y with uvs in world metres. */+function flatPolygon(points: readonly Vec2[], y: number): BufferGeometry {+ const shape = new Shape(points.map((p) => ({ x: p.x, y: -p.z }) as never));+ const g = new ShapeGeometry(shape);+ // Shape lies in xy with y = -z; turn it onto the floor.+ g.rotateX(-Math.PI / 2);+ g.translate(0, y, 0);+ const pos = g.attributes.position;+ const uv = new Float32Array(pos.count * 2);+ for (let i = 0; i < pos.count; i += 1) { uv[i * 2] = pos.getX(i); uv[i * 2 + 1] = pos.getZ(i); }+ g.setAttribute("uv", new BufferAttribute(uv, 2));+ return g;+}++const FLOOR_FINISH: Record<FloorFinish, { finish: Finish; color: string }> = {+ deck: { finish: "deck", color: "#c9ced6" },+ carpet: { finish: "carpet", color: "#d9d4e6" },+ grate: { finish: "grate", color: "#ffffff" },+ ceramic: { finish: "ceramic", color: "#9aa0a8" },+ holo: { finish: "holoFloor", color: "#ffffff" },+ honor: { finish: "metal", color: "#3a3226" },+};++/** How warm or cool the light under each kind of room is (additive, so dark = faint). */+const POOL_TONE: Partial<Record<Room["kind"], string>> = {+ lounge: "#6b5236", mess: "#6b5236", division: "#3a5374", plaza: "#2c5a6e", quarters: "#4e3f78", quartermaster: "#5e4c32",+ corridor: "#33465f", lift: "#5a4a2e", bay: "#36573a", bridge: "#4f4d5e", engineering: "#334f6c", holodeck: "#5a4620", hall: "#5a4a2c",+};++function flatQuad(size: number): BufferGeometry {+ const g = new BufferGeometry();+ const h = size / 2;+ g.setAttribute("position", new BufferAttribute(new Float32Array([-h, 0, -h, -h, 0, h, h, 0, h, -h, 0, -h, h, 0, h, h, 0, -h]), 3));+ g.setAttribute("normal", new BufferAttribute(new Float32Array([0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0]), 3));+ g.setAttribute("uv", new BufferAttribute(new Float32Array([0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1]), 2));+ return g;+}++function insideConvex(poly: readonly Vec2[], p: Vec2, margin: number): boolean {+ const area = poly.reduce((s, a, i) => { const b = poly[(i + 1) % poly.length]; return s + (a.x * b.z - b.x * a.z); }, 0);+ const sign = area > 0 ? 1 : -1;+ for (let i = 0; i < poly.length; i += 1) {+ const a = poly[i], b = poly[(i + 1) % poly.length];+ const len = Math.hypot(b.x - a.x, b.z - a.z) || 1;+ if ((sign * ((b.x - a.x) * (p.z - a.z) - (b.z - a.z) * (p.x - a.x))) / len < margin) return false;+ }+ return true;+}++/** Offset a convex polygon outwards by `d` (vertex normals averaged). */+export function offsetPolygon(points: readonly Vec2[], d: number): Vec2[] {+ const n = points.length;+ const area = points.reduce((s, p, i) => { const q = points[(i + 1) % n]; return s + (p.x * q.z - q.x * p.z); }, 0);+ // (e.z, -e.x) points out of a polygon wound with positive area.+ const sign = area > 0 ? 1 : -1;+ return points.map((p, i) => {+ const prev = points[(i + n - 1) % n], next = points[(i + 1) % n];+ const e1 = { x: p.x - prev.x, z: p.z - prev.z }, e2 = { x: next.x - p.x, z: next.z - p.z };+ const l1 = Math.hypot(e1.x, e1.z) || 1, l2 = Math.hypot(e2.x, e2.z) || 1;+ const n1 = { x: (e1.z / l1) * sign, z: (-e1.x / l1) * sign }, n2 = { x: (e2.z / l2) * sign, z: (-e2.x / l2) * sign };+ const bx = n1.x + n2.x, bz = n1.z + n2.z;+ const bl = Math.hypot(bx, bz) || 1;+ const cos = (n1.x * bx + n1.z * bz) / bl;+ const k = d / Math.max(0.35, cos);+ return { x: p.x + (bx / bl) * k, z: p.z + (bz / bl) * k };+ });+}++/** A band between two polygon outlines at two heights (the hull's sloping plates). */+function band(top: readonly Vec2[], topY: number, bottom: readonly Vec2[], bottomY: number): BufferGeometry {+ const positions: number[] = [];+ const uvs: number[] = [];+ let run = 0;+ for (let i = 0; i < top.length; i += 1) {+ const j = (i + 1) % top.length;+ const a = top[i], b = top[j], c = bottom[j], d = bottom[i];+ const len = Math.hypot(b.x - a.x, b.z - a.z);+ const quad = [[a, topY, 0], [b, topY, len], [c, bottomY, len], [a, topY, 0], [c, bottomY, len], [d, bottomY, 0]] as const;+ for (const [p, y, u] of quad) { positions.push(p.x, y, p.z); uvs.push((run + u) / 2.4, y / 2.4); }+ run += len;+ }+ const g = new BufferGeometry();+ g.setAttribute("position", new BufferAttribute(new Float32Array(positions), 3));+ g.setAttribute("uv", new BufferAttribute(new Float32Array(uvs), 2));+ g.computeVertexNormals();+ return g;+}++/** A wall-like box from a to b with uvs in metres along its length. */+function wallBox(len: number, h: number, t: number): BufferGeometry {+ const g = new BoxGeometry(len, h, t);+ g.translate(0, h / 2, 0);+ const uv = g.attributes.uv as BufferAttribute;+ for (let i = 0; i < uv.count; i += 1) uv.setXY(i, uv.getX(i) * (len / 1.2), uv.getY(i) * (h / WALL_H));+ return g;+}++function along(batch: GeoBatch, wall: Wall) {+ const dx = wall.b.x - wall.a.x, dz = wall.b.z - wall.a.z;+ const len = Math.hypot(dx, dz);+ const yaw = Math.atan2(dz, dx);+ const at = new Matrix4().makeRotationY(-yaw).setPosition((wall.a.x + wall.b.x) / 2, 0, (wall.a.z + wall.b.z) / 2);+ const cut: CutLine = { ax: wall.a.x, az: wall.a.z, bx: wall.b.x, bz: wall.b.z, kind: wall.kind === "hull" ? 1 : 2 };+ return { frame: batch.frame(at, cut), len };+}++/** The wall line a doorway sits in: its hull edge (same direction as the hull), or a line along the door. */+function doorCut(plan: DeckPlan, door: DeckPlan["doors"][number]): CutLine {+ const hull = plan.hull;+ for (let i = 0; i < hull.length; i += 1) {+ const a = hull[i], b = hull[(i + 1) % hull.length];+ const dx = b.x - a.x, dz = b.z - a.z, len = Math.hypot(dx, dz) || 1;+ const dist = Math.abs((door.at.x - a.x) * dz - (door.at.z - a.z) * dx) / len;+ if (dist < 0.3) return { ax: a.x, az: a.z, bx: b.x, bz: b.z, kind: 1 };+ }+ const half = door.width / 2 + 0.4;+ return door.axis === "x"+ ? { ax: door.at.x - half, az: door.at.z, bx: door.at.x + half, bz: door.at.z, kind: 2 }+ : { ax: door.at.x, az: door.at.z - half, bx: door.at.x, bz: door.at.z + half, kind: 2 };+}++export function buildStructure(plan: DeckPlan): GeoBatch {+ const batch = new GeoBatch();+ const root = batch.frame(new Matrix4());++ // ── slab and outer hull ────────────────────────────────────────────+ const outline = plan.hull;+ const slabShape = new Shape(outline.map((p) => ({ x: p.x, y: -p.z }) as never));+ const slab = new ExtrudeGeometry(slabShape, { depth: 0.5, bevelEnabled: false });+ slab.rotateX(-Math.PI / 2);+ slab.translate(0, -0.5, 0);+ root.geo("structure", slab, SHIP.hullDark);+ const o1 = offsetPolygon(outline, 0.32), o2 = offsetPolygon(outline, 2.6), o3 = offsetPolygon(outline, 1.2), o4 = offsetPolygon(outline, -3.5);+ root.geo("panel", band(o1, 0.08, o2, -1.6), SHIP.hullOuter);+ root.geo("structure", band(o2, -1.6, o3, -4.8), SHIP.hullDark);+ root.geo("structure", band(o3, -4.8, o4, -6.4), SHIP.graphite);+ // A lip between the wall and the sloping plates, and running lights along it.+ root.geo("structure", band(offsetPolygon(outline, 0.25), 0.1, o1, 0.08), SHIP.graphite);+ o2.forEach((p, i) => {+ const q = o2[(i + 1) % o2.length];+ const len = Math.hypot(q.x - p.x, q.z - p.z);+ const n = Math.floor(len / 6);+ for (let k = 1; k < n; k += 1) {+ const t = k / n;+ root.box("glow", 0.22, 0.08, 0.22, i % 2 ? SHIP.cyan : SHIP.lightWarm, { x: p.x + (q.x - p.x) * t, y: -1.62, z: p.z + (q.z - p.z) * t });+ }+ });++ // ── floors ─────────────────────────────────────────────────────────+ root.geo("deck", flatPolygon(outline, 0.0), "#9aa0a9");+ for (const room of plan.rooms) {+ if (room.floor === "deck") continue;+ const poly = clipPolygon(rectPoly(room.rect), outline);+ if (poly.length < 3) continue;+ const f = FLOOR_FINISH[room.floor];+ root.geo(f.finish, flatPolygon(poly, 0.012), f.color);+ }++ // ── light pools under the (cut-away) ceiling fittings ──────────────+ for (const room of plan.rooms) {+ const tone = POOL_TONE[room.kind] ?? "#2a3444";+ const r = room.rect;+ const w = r.x1 - r.x0, d = r.z1 - r.z0;+ const nx = Math.max(1, Math.round(w / 4.4)), nz = Math.max(1, Math.round(d / 4.4));+ for (let i = 0; i < nx; i += 1) for (let k = 0; k < nz; k += 1) {+ const x = r.x0 + (w * (i + 0.5)) / nx, z = r.z0 + (d * (k + 0.5)) / nz;+ if (!insideConvex(outline, { x, z }, 1.6)) continue;+ root.geo("pool", flatQuad(3.6), tone, { x, y: 0.03, z });+ }+ }++ // ── walls ──────────────────────────────────────────────────────────+ const holoRooms = plan.rooms.filter((r) => r.kind === "holodeck");+ for (const wall of plan.walls) {+ const { frame, len } = along(batch, wall);+ if (len < 0.05) continue;+ const t = wall.t;+ const mx = (wall.a.x + wall.b.x) / 2, mz = (wall.a.z + wall.b.z) / 2;+ const holo = holoRooms.some((r) => mx >= r.rect.x0 - 0.5 && mx <= r.rect.x1 + 0.5 && mz >= r.rect.z0 - 0.5 && mz <= r.rect.z1 + 0.5);+ if (holo && (wall.kind === "hull" || wall.kind === "bulkhead")) {+ // The holodeck's chamber: black walls with the floor's gold grid running up them.+ frame.geo("structure", wallBox(len, WALL_H, t), "#08090b");+ for (let k = 1; k < 3; k += 1) frame.box("glowSoft", len, 0.02, t + 0.02, "#7a5f22", { y: k * 0.9 });+ const n = Math.max(1, Math.round(len));+ for (let k = 0; k <= n; k += 1) frame.box("glowSoft", 0.02, WALL_H, t + 0.02, "#7a5f22", { x: -len / 2 + (len * k) / n });+ frame.box("structure", len, 0.1, t + 0.06, SHIP.charcoal, { y: WALL_H });+ continue;+ }+ if (wall.kind === "hull" || wall.kind === "bulkhead") {+ const hull = wall.kind === "hull";+ // A dark base band, ceramic panels above it, and the cap.+ frame.geo("structure", wallBox(len, BASE_H, t + 0.03), SHIP.panelDark);+ if (hull && wall.windows && len > 2) {+ frame.geo("panel", wallBox(len, WINDOW_LO - BASE_H, t), SHIP.panelCool, { y: BASE_H });+ frame.geo("panel", wallBox(len, WALL_H - WINDOW_HI, t), SHIP.panelCool, { y: WINDOW_HI });+ frame.box("structure", len, 0.07, t + 0.12, SHIP.graphite, { y: WINDOW_LO - 0.07 });+ frame.box("structure", len, 0.06, t + 0.08, SHIP.graphite, { y: WINDOW_HI });+ frame.box("glass", len, WINDOW_HI - WINDOW_LO, 0.03, "#9fd6ff", { y: WINDOW_LO });+ frame.box("glowSoft", len, 0.02, 0.05, SHIP.lightCool, { y: WINDOW_LO, z: t / 2 - 0.04 });+ } else {+ frame.geo("panel", wallBox(len, WALL_H - BASE_H, t), SHIP.panelCool, { y: BASE_H });+ }+ frame.box("structure", len, 0.12, t + 0.08, SHIP.graphite, { y: WALL_H - 0.02 });+ frame.box("glowSoft", len, 0.018, t + 0.1, SHIP.lightCool, { y: WALL_H + 0.1 });+ // Ribs every 2.4 m: graphite pilasters with a light slit on both faces.+ const ribs = Math.max(1, Math.round(len / 2.4));+ for (let k = 0; k <= ribs; k += 1) {+ const x = -len / 2 + (len * k) / ribs;+ frame.box("structure", 0.24, WALL_H + 0.06, t + 0.14, SHIP.graphite, { x });+ for (const s of hull ? [1] : [-1, 1]) frame.box("glowSoft", 0.035, 1.25, 0.02, SHIP.cyan, { x, y: 1.0, z: s * (t / 2 + 0.075) });+ }+ // A light line in the floor along each inner face.+ for (const s of hull ? [1] : [-1, 1]) frame.box("glowSoft", len, 0.006, 0.035, s < 0 ? SHIP.lightCool : SHIP.lightWarm, { y: 0.004, z: s * (t / 2 + 0.28) });+ } else if (wall.kind === "glass") {+ const n = Math.max(1, Math.round(len / 1.6));+ for (let k = 0; k <= n; k += 1) frame.box("structure", 0.08, WALL_H, 0.14, SHIP.graphite, { x: -len / 2 + (len * k) / n });+ frame.box("structure", len, 0.12, 0.16, SHIP.charcoal, {});+ frame.box("structure", len, 0.1, 0.16, SHIP.graphite, { y: WALL_H - 0.1 });+ frame.box("glass", len, WALL_H - 0.22, 0.02, "#bfe4ff", { y: 0.12 });+ frame.box("glowSoft", len, 0.12, 0.03, "#7fb6d9", { y: 1.35 });+ frame.box("glow", len, 0.02, 0.05, SHIP.cyan, { y: WALL_H });+ } else {+ // A rail: posts and a lit handrail.+ const n = Math.max(1, Math.round(len / 1.4));+ for (let k = 0; k <= n; k += 1) frame.box("metal", 0.05, 1.0, 0.05, SHIP.steelLight, { x: -len / 2 + (len * k) / n });+ frame.box("metal", len, 0.06, 0.08, SHIP.steelLight, { y: 1.0 });+ frame.box("glow", len, 0.015, 0.03, SHIP.gold, { y: 1.06 });+ }+ }++ // ── door frames ────────────────────────────────────────────────────+ for (const door of plan.doors) {+ const yaw = door.axis === "x" ? 0 : Math.PI / 2;+ const f = batch.frame(new Matrix4().makeRotationY(yaw).setPosition(door.at.x, 0, door.at.z), doorCut(plan, door));+ const half = door.width / 2;+ for (const s of [-1, 1]) {+ f.box("structure", 0.16, WALL_H, 0.42, SHIP.graphite, { x: s * (half + 0.08) });+ f.box("glow", 0.03, 2.2, 0.44, door.slides ? SHIP.cyan : SHIP.lightWarm, { x: s * (half + 0.0), y: 0.1 });+ }+ f.box("structure", door.width + 0.32, WALL_H - 2.35, 0.46, SHIP.graphite, { y: 2.35 });+ f.box("glow", door.width, 0.03, 0.44, door.slides ? SHIP.cyan : SHIP.lightWarm, { y: 2.33 });+ // Threshold plate.+ f.box("metal", door.width, 0.015, 0.5, SHIP.steel, { y: 0.0 });+ }+ return batch;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/render/kit/cutaway.ts b/dodaios/ui/web/frontend/src/components/society/starship/render/kit/cutaway.tsnew file mode 100644index 0000000000..07cfdc468d--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/render/kit/cutaway.ts@@ -0,0 +1,76 @@+/**+ * The cut-away: walls that would hide what the camera looks at sink to a+ * kerb, like an architect's model with its near walls lifted off. The hull+ * drops on every side the camera is outside of; an inner wall drops while it+ * stands between the camera and the captain. It happens in the vertex shader+ * of the shared finishes, from two attributes every merged part carries+ * (`cutAB`: the wall's line, `cutKind`: 0 never, 1 hull, 2 inner), so the+ * merged geometry stays merged.+ */+import type { Material } from "three";++export const CUTAWAY = {+ uCutCam: { value: [0, 0] as [number, number] },+ uCutFocus: { value: [0, 0] as [number, number] },+ /** 1 = on. */+ uCutOn: { value: 1 },+ /** 1 = inner walls too (off in the overview, where nothing stands in front). */+ uCutInner: { value: 1 },+};++const DECL = /* glsl */ `+attribute vec4 cutAB;+attribute float cutKind;+uniform vec2 uCutCam;+uniform vec2 uCutFocus;+uniform float uCutOn;+uniform float uCutInner;+uniform float uCutKeep;+uniform float uCutDrop;+varying float vShipCut;+bool shipCut() {+ if (cutKind < 0.5 || uCutOn < 0.5) return false;+ vec2 a = cutAB.xy, b = cutAB.zw;+ if (cutKind < 1.5) {+ vec2 d = b - a;+ // The hull runs clockwise from the bow, so (d.y, -d.x) points outwards.+ return dot(uCutCam - a, vec2(d.y, -d.x)) > 0.0;+ }+ if (uCutInner < 0.5) return false;+ vec2 r = uCutCam - uCutFocus, s = b - a;+ float den = r.x * s.y - r.y * s.x;+ if (abs(den) < 1e-5) return false;+ vec2 qp = a - uCutFocus;+ float t = (qp.x * s.y - qp.y * s.x) / den;+ float u = (qp.x * r.y - qp.y * r.x) / den;+ return t > 0.0 && t < 1.0 && u > -0.04 && u < 1.04;+}+`;++const patched = new WeakSet<Material>();++/**+ * Teach a shared finish the cut-away. Idempotent. A cut part keeps `keep` of+ * its height and sinks by `drop` (glass sinks out of sight instead of+ * squashing into a bright band).+ */+export function withCutaway<M extends Material>(material: M, keep = 0.14, drop = 0): M {+ if (patched.has(material)) return material;+ patched.add(material);+ const previous = material.onBeforeCompile;+ material.onBeforeCompile = (shader, renderer) => {+ previous?.call(material, shader, renderer);+ Object.assign(shader.uniforms, CUTAWAY, { uCutKeep: { value: keep }, uCutDrop: { value: drop } });+ shader.vertexShader = DECL + shader.vertexShader.replace(+ "#include <begin_vertex>",+ "#include <begin_vertex>\n vShipCut = 0.0;\n if (shipCut()) { transformed.y = transformed.y * uCutKeep - uCutDrop; vShipCut = 1.0; }",+ );+ // A cut wall reads as a dark kerb, not as a pale slab: its colour (and its lights) dim.+ shader.fragmentShader = "varying float vShipCut;\n" + shader.fragmentShader.replace(+ "#include <color_fragment>",+ "#include <color_fragment>\n diffuseColor.rgb *= mix(1.0, 0.32, vShipCut);",+ );+ };+ material.customProgramCacheKey = () => "ship-cutaway";+ return material;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/render/kit/geo.ts b/dodaios/ui/web/frontend/src/components/society/starship/render/kit/geo.tsnew file mode 100644index 0000000000..4933989886--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/render/kit/geo.ts@@ -0,0 +1,190 @@+/**+ * Static geometry is collected part by part and merged per finish, so a whole+ * deck's walls and furniture cost a handful of draw calls. Every part carries+ * its colour in its vertices; a finish (material) is shared by everything+ * made of it.+ */+import {+ BoxGeometry, BufferAttribute, BufferGeometry, Color, CylinderGeometry, ExtrudeGeometry, Matrix4, Quaternion,+ Shape, SphereGeometry, TorusGeometry, Vector3, type ColorRepresentation,+} from "three";+import { mergeGeometries } from "three/examples/jsm/utils/BufferGeometryUtils.js";++export type Finish =+ | "panel" | "structure" | "metal" | "deck" | "carpet" | "grate" | "ceramic" | "glass" | "glow" | "glowSoft" | "screen" | "fabric" | "holoFloor"+ /** A soft pool of light on the floor under a ceiling fitting (additive, radial). */+ | "pool";++const tmpColor = new Color();++/**+ * A wall line a part belongs to, for the cutaway (render/kit/cutaway.ts):+ * `kind` 1 = the hull (drops while the camera is outside it), 2 = an inner+ * wall (drops while it stands between the camera and the captain).+ */+export interface CutLine { ax: number; az: number; bx: number; bz: number; kind: 1 | 2 }++/** Bake a colour attribute into a non-indexed copy of `geo`. */+function prepared(geo: BufferGeometry, color: ColorRepresentation, cut?: CutLine): BufferGeometry {+ const g = geo.index ? geo.toNonIndexed() : geo.clone();+ geo.dispose();+ for (const name of Object.keys(g.attributes)) if (name !== "position" && name !== "normal" && name !== "uv") g.deleteAttribute(name);+ if (!g.attributes.uv) g.setAttribute("uv", new BufferAttribute(new Float32Array((g.attributes.position.count) * 2), 2));+ const n = g.attributes.position.count;+ const colors = new Float32Array(n * 3);+ tmpColor.set(color).convertSRGBToLinear();+ for (let i = 0; i < n; i += 1) { colors[i * 3] = tmpColor.r; colors[i * 3 + 1] = tmpColor.g; colors[i * 3 + 2] = tmpColor.b; }+ g.setAttribute("color", new BufferAttribute(colors, 3));+ // Every part carries the cutaway attributes (zero = never cut), so all of a finish merge together.+ const ab = new Float32Array(n * 4), kind = new Float32Array(n);+ if (cut) for (let i = 0; i < n; i += 1) { ab[i * 4] = cut.ax; ab[i * 4 + 1] = cut.az; ab[i * 4 + 2] = cut.bx; ab[i * 4 + 3] = cut.bz; kind[i] = cut.kind; }+ g.setAttribute("cutAB", new BufferAttribute(ab, 4));+ g.setAttribute("cutKind", new BufferAttribute(kind, 1));+ g.clearGroups();+ return g;+}++export interface Placement {+ x?: number; y?: number; z?: number;+ yaw?: number; pitch?: number; roll?: number;+}++const m4 = new Matrix4();+const q = new Quaternion();++/** Yaw about +y, then pitch about the turned x, then roll about the turned z. */+export function matrixOf(p: Placement, scale?: Vector3): Matrix4 {+ q.setFromAxisAngle(new Vector3(0, 1, 0), p.yaw ?? 0);+ if (p.pitch) q.multiply(new Quaternion().setFromAxisAngle(new Vector3(1, 0, 0), p.pitch));+ if (p.roll) q.multiply(new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), p.roll));+ return m4.clone().compose(new Vector3(p.x ?? 0, p.y ?? 0, p.z ?? 0), q, scale ?? new Vector3(1, 1, 1));+}++/**+ * A batch of parts, merged per finish. `frame` is the placement every part+ * added through `child()` is relative to.+ */+export class GeoBatch {+ private readonly parts = new Map<Finish, BufferGeometry[]>();+ private readonly castShadow = new Map<Finish, boolean>();++ add(finish: Finish, geo: BufferGeometry, color: ColorRepresentation, at: Matrix4, cut?: CutLine): this {+ const g = prepared(geo, color, cut);+ g.applyMatrix4(at);+ const list = this.parts.get(finish) ?? [];+ list.push(g);+ this.parts.set(finish, list);+ return this;+ }++ /** A frame to place parts in: `frame.box(...)` lands relative to `at`; `cut` ties them to a wall line. */+ frame(at: Matrix4, cut?: CutLine): Frame { return new Frame(this, at, cut); }++ merged(): { finish: Finish; geometry: BufferGeometry }[] {+ const out: { finish: Finish; geometry: BufferGeometry }[] = [];+ for (const [finish, list] of this.parts) {+ if (list.length === 0) continue;+ const geometry = mergeGeometries(list, false);+ for (const g of list) g.dispose();+ if (geometry) { geometry.computeBoundingSphere(); out.push({ finish, geometry }); }+ }+ this.parts.clear();+ return out;+ }++ noShadow(finish: Finish): this { this.castShadow.set(finish, false); return this; }+}++export class Frame {+ constructor(private readonly batch: GeoBatch, private readonly at: Matrix4, private readonly cut?: CutLine) {}++ private put(finish: Finish, geo: BufferGeometry, color: ColorRepresentation, p: Placement): this {+ this.batch.add(finish, geo, color, this.at.clone().multiply(matrixOf(p)), this.cut);+ return this;+ }++ /** A box whose bottom sits at `p.y` (default 0). */+ box(finish: Finish, w: number, h: number, d: number, color: ColorRepresentation, p: Placement = {}): this {+ const g = new BoxGeometry(w, h, d);+ g.translate(0, h / 2, 0);+ return this.put(finish, g, color, p);+ }++ /** A box with chamfered vertical edges (an extruded octagon), bottom at `p.y`. */+ chamfer(finish: Finish, w: number, h: number, d: number, c: number, color: ColorRepresentation, p: Placement = {}): this {+ const s = new Shape();+ const hw = w / 2, hd = d / 2, k = Math.min(c, hw * 0.9, hd * 0.9);+ s.moveTo(-hw + k, -hd); s.lineTo(hw - k, -hd); s.lineTo(hw, -hd + k); s.lineTo(hw, hd - k); s.lineTo(hw - k, hd);+ s.lineTo(-hw + k, hd); s.lineTo(-hw, hd - k); s.lineTo(-hw, -hd + k); s.closePath();+ const g = new ExtrudeGeometry(s, { depth: h, bevelEnabled: false });+ // Extrusion runs along +z; turned up, the shape's y lies along -z (the shapes are symmetric).+ g.rotateX(-Math.PI / 2);+ return this.put(finish, g, color, p);+ }++ /** A rounded slab: a box with rounded vertical edges and a small bevel on top. */+ rounded(finish: Finish, w: number, h: number, d: number, r: number, color: ColorRepresentation, p: Placement = {}): this {+ const s = new Shape();+ const hw = w / 2, hd = d / 2, k = Math.min(r, hw * 0.95, hd * 0.95);+ s.moveTo(-hw + k, -hd); s.lineTo(hw - k, -hd); s.quadraticCurveTo(hw, -hd, hw, -hd + k); s.lineTo(hw, hd - k);+ s.quadraticCurveTo(hw, hd, hw - k, hd); s.lineTo(-hw + k, hd); s.quadraticCurveTo(-hw, hd, -hw, hd - k);+ s.lineTo(-hw, -hd + k); s.quadraticCurveTo(-hw, -hd, -hw + k, -hd);+ const bevel = Math.min(0.02, h * 0.2);+ const g = new ExtrudeGeometry(s, { depth: Math.max(0.001, h - bevel * 2), bevelEnabled: true, bevelSize: bevel, bevelThickness: bevel, bevelSegments: 1, curveSegments: 4 });+ g.translate(0, 0, bevel);+ g.rotateX(-Math.PI / 2);+ return this.put(finish, g, color, p);+ }++ cylinder(finish: Finish, rTop: number, rBottom: number, h: number, color: ColorRepresentation, p: Placement = {}, segments = 24, open = false): this {+ const g = new CylinderGeometry(rTop, rBottom, h, segments, 1, open);+ g.translate(0, h / 2, 0);+ return this.put(finish, g, color, p);+ }++ ring(finish: Finish, radius: number, tube: number, color: ColorRepresentation, p: Placement = {}, arc = Math.PI * 2, segments = 48): this {+ const g = new TorusGeometry(radius, tube, 6, segments, arc);+ g.rotateX(Math.PI / 2);+ return this.put(finish, g, color, p);+ }++ sphere(finish: Finish, r: number, color: ColorRepresentation, p: Placement = {}, segments = 16): this {+ return this.put(finish, new SphereGeometry(r, segments, Math.max(6, segments / 2)), color, p);+ }++ /** Any prepared geometry. */+ geo(finish: Finish, geo: BufferGeometry, color: ColorRepresentation, p: Placement = {}): this {+ return this.put(finish, geo, color, p);+ }++ /** A child frame placed relative to this one. */+ child(p: Placement): Frame {+ return new Frame(this.batch, this.at.clone().multiply(matrixOf(p)), this.cut);+ }+}++/** A flat annulus sector lying on the floor (y up), for trims and floor lines. */+export function annulus(inner: number, outer: number, start = 0, length = Math.PI * 2, segments = 64): BufferGeometry {+ const positions: number[] = [], normals: number[] = [], uvs: number[] = [];+ for (let i = 0; i < segments; i += 1) {+ const a0 = start + (length * i) / segments, a1 = start + (length * (i + 1)) / segments;+ const p = (r: number, a: number) => [Math.sin(a) * r, 0, Math.cos(a) * r];+ const quad = [p(inner, a0), p(outer, a0), p(outer, a1), p(inner, a0), p(outer, a1), p(inner, a1)];+ for (const v of quad) { positions.push(...v); normals.push(0, 1, 0); uvs.push(0, 0); }+ }+ const g = new BufferGeometry();+ g.setAttribute("position", new BufferAttribute(new Float32Array(positions), 3));+ g.setAttribute("normal", new BufferAttribute(new Float32Array(normals), 3));+ g.setAttribute("uv", new BufferAttribute(new Float32Array(uvs), 2));+ return g;+}++/** A flat rectangle on the floor with uvs in metres (for tiling textures). */+export function floorQuad(w: number, d: number): BufferGeometry {+ const g = new BufferGeometry();+ const hw = w / 2, hd = d / 2;+ g.setAttribute("position", new BufferAttribute(new Float32Array([-hw, 0, -hd, -hw, 0, hd, hw, 0, hd, -hw, 0, -hd, hw, 0, hd, hw, 0, -hd]), 3));+ g.setAttribute("normal", new BufferAttribute(new Float32Array([0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0]), 3));+ g.setAttribute("uv", new BufferAttribute(new Float32Array([-hw, -hd, -hw, hd, hw, hd, -hw, -hd, hw, hd, hw, -hd]), 2));+ return g;+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/render/kit/materials.ts b/dodaios/ui/web/frontend/src/components/society/starship/render/kit/materials.tsnew file mode 100644index 0000000000..f1b4b90097--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/render/kit/materials.ts@@ -0,0 +1,192 @@+/**+ * The ship's finishes. One material per finish for the whole session; parts+ * carry their tint in vertex colours. Textures are drawn on canvases at+ * start-up (no image files): deck plating, wall panels with seams, a grate,+ * carpet and the holodeck grid.+ */+import {+ AdditiveBlending, CanvasTexture, Color, DoubleSide, MeshBasicMaterial, MeshPhysicalMaterial, MeshStandardMaterial, RepeatWrapping,+ SRGBColorSpace, type Material, type Texture,+} from "three";+import type { Finish } from "./geo";+import { withCutaway } from "./cutaway";++function canvas(size: number): [HTMLCanvasElement, CanvasRenderingContext2D] {+ const c = document.createElement("canvas");+ c.width = size; c.height = size;+ const ctx = c.getContext("2d");+ if (!ctx) throw new Error("2d canvas unavailable");+ return [c, ctx];+}++function rng(seed: number): () => number {+ let s = seed >>> 0;+ return () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; };+}++function tiled(c: HTMLCanvasElement, metres: number, color = true): Texture {+ const t = new CanvasTexture(c);+ t.wrapS = t.wrapT = RepeatWrapping;+ t.repeat.set(1 / metres, 1 / metres);+ t.anisotropy = 8;+ if (color) t.colorSpace = SRGBColorSpace;+ return t;+}++/** Deck plating: 1.2 m plates with recessed seams, a faint wear pattern and rivets at the corners. Tiles every 2.4 m. */+function deckPlates(): { map: Texture; rough: Texture } {+ const [c, ctx] = canvas(512);+ const [rc, rctx] = canvas(512);+ const r = rng(7);+ ctx.fillStyle = "#3a3f47"; ctx.fillRect(0, 0, 512, 512);+ rctx.fillStyle = "#9a9a9a"; rctx.fillRect(0, 0, 512, 512);+ const plate = 256;+ for (let py = 0; py < 2; py += 1) for (let px = 0; px < 2; px += 1) {+ const x = px * plate, y = py * plate;+ const tone = 52 + Math.floor(r() * 10);+ ctx.fillStyle = `rgb(${tone},${tone + 4},${tone + 10})`;+ ctx.fillRect(x + 3, y + 3, plate - 6, plate - 6);+ // Brushed streaks.+ for (let k = 0; k < 90; k += 1) {+ const a = r() * 0.06;+ ctx.fillStyle = `rgba(255,255,255,${a})`;+ ctx.fillRect(x + 4 + r() * (plate - 8), y + 4 + r() * (plate - 8), 30 + r() * 80, 1);+ rctx.fillStyle = `rgba(0,0,0,${a * 1.5})`;+ rctx.fillRect(x + 4 + r() * (plate - 8), y + 4 + r() * (plate - 8), 30 + r() * 80, 1);+ }+ // Inset panel in the middle of each plate.+ ctx.strokeStyle = "rgba(0,0,0,0.35)"; ctx.lineWidth = 2;+ ctx.strokeRect(x + 40, y + 40, plate - 80, plate - 80);+ ctx.strokeStyle = "rgba(255,255,255,0.05)"; ctx.lineWidth = 1;+ ctx.strokeRect(x + 42, y + 42, plate - 84, plate - 84);+ for (const [ox, oy] of [[14, 14], [plate - 14, 14], [14, plate - 14], [plate - 14, plate - 14]]) {+ ctx.fillStyle = "#23262b"; ctx.beginPath(); ctx.arc(x + ox, y + oy, 4, 0, Math.PI * 2); ctx.fill();+ ctx.fillStyle = "rgba(255,255,255,0.12)"; ctx.beginPath(); ctx.arc(x + ox - 1, y + oy - 1, 1.6, 0, Math.PI * 2); ctx.fill();+ }+ }+ // Seams.+ ctx.fillStyle = "#24272d";+ for (let k = 0; k <= 2; k += 1) { ctx.fillRect(k * plate - 1.5, 0, 3, 512); ctx.fillRect(0, k * plate - 1.5, 512, 3); }+ rctx.fillStyle = "#ffffff";+ for (let k = 0; k <= 2; k += 1) { rctx.fillRect(k * plate - 2, 0, 4, 512); rctx.fillRect(0, k * plate - 2, 512, 4); }+ return { map: tiled(c, 4.8), rough: tiled(rc, 4.8, false) };+}++/** Wall panels: 1.2 m wide, a horizontal seam at waist height and another near the top. */+function wallPanels(): Texture {+ const [c, ctx] = canvas(256);+ ctx.fillStyle = "#e9e6e0"; ctx.fillRect(0, 0, 256, 256);+ const g = ctx.createLinearGradient(0, 0, 0, 256);+ g.addColorStop(0, "rgba(0,0,0,0.05)"); g.addColorStop(1, "rgba(0,0,0,0.0)");+ ctx.fillStyle = g; ctx.fillRect(0, 0, 256, 256);+ ctx.fillStyle = "rgba(40,40,46,0.55)";+ ctx.fillRect(0, 0, 3, 256);+ ctx.fillRect(0, 160, 256, 2);+ ctx.fillRect(0, 40, 256, 2);+ ctx.fillStyle = "rgba(255,255,255,0.5)";+ ctx.fillRect(3, 0, 1, 256);+ ctx.fillRect(0, 162, 256, 1);+ const t = new CanvasTexture(c);+ t.wrapS = t.wrapT = RepeatWrapping;+ t.colorSpace = SRGBColorSpace;+ t.anisotropy = 8;+ return t;+}++function carpet(): Texture {+ const [c, ctx] = canvas(256);+ const r = rng(3);+ ctx.fillStyle = "#3b3f4e"; ctx.fillRect(0, 0, 256, 256);+ for (let k = 0; k < 9000; k += 1) {+ const v = r();+ ctx.fillStyle = v > 0.5 ? `rgba(255,255,255,${r() * 0.05})` : `rgba(0,0,0,${r() * 0.08})`;+ ctx.fillRect(r() * 256, r() * 256, 1.5, 1.5);+ }+ // A quiet geometric weave every half metre.+ ctx.strokeStyle = "rgba(255,255,255,0.035)"; ctx.lineWidth = 2;+ for (let k = 0; k < 4; k += 1) { ctx.beginPath(); ctx.moveTo(0, k * 64 + 32); ctx.lineTo(256, k * 64 + 32); ctx.stroke(); }+ return tiled(c, 2);+}++function grate(): Texture {+ const [c, ctx] = canvas(256);+ ctx.fillStyle = "#1d2025"; ctx.fillRect(0, 0, 256, 256);+ ctx.fillStyle = "#4a5059";+ for (let y = 0; y < 256; y += 16) for (let x = 0; x < 256; x += 16) ctx.fillRect(x + 2, y + 2, 12, 12);+ ctx.fillStyle = "#0b0c0f";+ for (let y = 0; y < 256; y += 16) for (let x = 0; x < 256; x += 16) ctx.fillRect(x + 5, y + 5, 6, 6);+ return tiled(c, 0.8);+}++function ceramic(): Texture {+ const [c, ctx] = canvas(256);+ ctx.fillStyle = "#cfd2d6"; ctx.fillRect(0, 0, 256, 256);+ ctx.fillStyle = "rgba(0,0,0,0.18)";+ for (let k = 0; k <= 4; k += 1) { ctx.fillRect(k * 64 - 1, 0, 2, 256); ctx.fillRect(0, k * 64 - 1, 256, 2); }+ return tiled(c, 2.4);+}++function holoGrid(): Texture {+ const [c, ctx] = canvas(256);+ ctx.fillStyle = "#050607"; ctx.fillRect(0, 0, 256, 256);+ ctx.fillStyle = "#e3b341";+ ctx.fillRect(0, 0, 256, 2); ctx.fillRect(0, 0, 2, 256);+ return tiled(c, 1.0);+}++function radial(): Texture {+ const [c, ctx] = canvas(128);+ const g = ctx.createRadialGradient(64, 64, 0, 64, 64, 64);+ g.addColorStop(0, "rgba(255,255,255,1)");+ g.addColorStop(0.35, "rgba(255,255,255,0.45)");+ g.addColorStop(1, "rgba(255,255,255,0)");+ ctx.fillStyle = g;+ ctx.fillRect(0, 0, 128, 128);+ const t = new CanvasTexture(c);+ t.colorSpace = SRGBColorSpace;+ return t;+}++let cache: Map<Finish, Material> | null = null;++export function finishMaterial(finish: Finish): Material {+ if (!cache) cache = buildMaterials();+ const m = cache.get(finish);+ if (!m) throw new Error(`unknown finish ${finish}`);+ return m;+}++function buildMaterials(): Map<Finish, Material> {+ const plates = deckPlates();+ const map = new Map<Finish, Material>();+ map.set("panel", new MeshStandardMaterial({ vertexColors: true, map: wallPanels(), roughness: 0.55, metalness: 0.05, envMapIntensity: 0.6 }));+ map.set("structure", new MeshStandardMaterial({ vertexColors: true, roughness: 0.45, metalness: 0.55, envMapIntensity: 0.9 }));+ map.set("metal", new MeshStandardMaterial({ vertexColors: true, roughness: 0.28, metalness: 0.9, envMapIntensity: 1.2 }));+ map.set("deck", new MeshStandardMaterial({ vertexColors: true, map: plates.map, roughnessMap: plates.rough, roughness: 0.7, metalness: 0.45, envMapIntensity: 0.8 }));+ map.set("carpet", new MeshStandardMaterial({ vertexColors: true, map: carpet(), roughness: 0.95, metalness: 0 }));+ map.set("grate", new MeshStandardMaterial({ vertexColors: true, map: grate(), roughness: 0.6, metalness: 0.7 }));+ map.set("ceramic", new MeshStandardMaterial({ vertexColors: true, map: ceramic(), roughness: 0.35, metalness: 0.0, envMapIntensity: 0.7 }));+ map.set("fabric", new MeshStandardMaterial({ vertexColors: true, roughness: 0.9, metalness: 0 }));+ map.set("glass", new MeshPhysicalMaterial({+ vertexColors: true, roughness: 0.05, metalness: 0, transmission: 0, transparent: true, opacity: 0.22,+ envMapIntensity: 1.4, side: DoubleSide, depthWrite: false,+ }));+ // Light sources: unlit, above 1 so the bloom pass picks them up.+ map.set("glow", new MeshBasicMaterial({ vertexColors: true, toneMapped: false, color: new Color(1.9, 1.9, 1.9) }));+ map.set("glowSoft", new MeshBasicMaterial({ vertexColors: true, toneMapped: false, color: new Color(0.95, 0.95, 0.95) }));+ map.set("screen", new MeshBasicMaterial({ vertexColors: true, toneMapped: false, color: new Color(1.0, 1.0, 1.0) }));+ map.set("holoFloor", new MeshStandardMaterial({ vertexColors: true, map: holoGrid(), emissiveMap: holoGrid(), emissive: new Color(0.62, 0.46, 0.16), roughness: 0.4, metalness: 0.3 }));+ map.set("pool", new MeshBasicMaterial({ vertexColors: true, map: radial(), transparent: true, blending: AdditiveBlending, depthWrite: false }));+ for (const [finish, m] of map) withCutaway(m, finish === "glass" ? 0 : 0.14, finish === "glass" ? 0.2 : 0);+ return map;+}++/** True for finishes that throw a shadow. */+export function castsShadow(finish: Finish): boolean {+ return finish !== "glow" && finish !== "glowSoft" && finish !== "glass" && finish !== "screen" && finish !== "deck" && finish !== "pool"+ && finish !== "carpet" && finish !== "grate" && finish !== "ceramic" && finish !== "holoFloor";+}++export function receivesShadow(finish: Finish): boolean {+ return finish !== "glow" && finish !== "glowSoft" && finish !== "screen" && finish !== "glass" && finish !== "pool";+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/render/kit/palette.ts b/dodaios/ui/web/frontend/src/components/society/starship/render/kit/palette.tsnew file mode 100644index 0000000000..8742f91599--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/render/kit/palette.ts@@ -0,0 +1,37 @@+/**+ * The ship's colours (sRGB hex). Charcoal and warm white carry the+ * architecture, gold marks command and everything the captain uses, cyan is+ * information. State colours appear only on real state.+ */+export const SHIP = {+ charcoal: "#24282f",+ graphite: "#30353d",+ steel: "#5d6672",+ steelLight: "#9aa3ae",+ hullOuter: "#aeb4bc",+ hullDark: "#3b4149",+ panel: "#e4e0d8",+ panelCool: "#d4d8dd",+ panelDark: "#2b3038",+ trim: "#c9ccd1",+ gold: "#d9a441",+ goldDeep: "#a8782a",+ cyan: "#5fd4ff",+ cyanDeep: "#1b7fb0",+ white: "#f4f6f8",+ lightWarm: "#ffe2b8",+ lightCool: "#cfe8ff",+ leather: "#3a2d29",+ fabric: "#3c4250",+ plant: "#3f7d4a",+ plantDark: "#2b5a36",+ soil: "#2d2421",+} as const;++export const STATE = {+ working: "#3fd27f",+ waiting: "#ffb020",+ idle: "#8a96a8",+ paused: "#6b6f8a",+ error: "#ff4d5e",+} as const;diff --git a/dodaios/ui/web/frontend/src/components/society/starship/shipStore.ts b/dodaios/ui/web/frontend/src/components/society/starship/shipStore.tsnew file mode 100644index 0000000000..39feca99de--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/shipStore.ts@@ -0,0 +1,140 @@+/**+ * The ship's interaction state, shared by the canvas and the HUD. What+ * changes every frame (the captain's position, the crew's bodies) lives in+ * plain mutable objects and never in React state; the store carries what the+ * HUD renders and what the world must react to.+ */+import { create } from "zustand";+import type { DeckId, Vec2 } from "./plan/types";+import { loadDestination, saveDestination, type DestinationId } from "./space/destinations";++export type Selection =+ | { kind: "agent"; id: string }+ | { kind: "station"; id: string };++export interface CaptainBody {+ x: number;+ z: number;+ yaw: number;+ /** Remaining route (world points). */+ path: Vec2[];+ moving: boolean;+ speed: number;+ /** Seated in a chair (the captain's chair), with its yaw and seat height. */+ seated: { x: number; z: number; yaw: number; seatY: number } | null;+}++/** The captain's body: mutable, read by the camera and the crew every frame. */+export const captain: CaptainBody = { x: 0, z: 0, yaw: Math.PI, path: [], moving: false, speed: 0, seated: null };++const DECK_KEY = "dodaios.ship.deck.v1";+const LOOK_KEY = "dodaios.ship.captain.v1";++/** The captain's suit, chosen at the quartermaster and kept per browser profile. */+export interface CaptainLook {+ suit: string;+ trim: string;+ visor: string;+}++export const DEFAULT_LOOK: CaptainLook = { suit: "#2c3340", trim: "#d9a441", visor: "#d6a440" };++function loadLook(): CaptainLook {+ try {+ const raw = localStorage.getItem(LOOK_KEY);+ if (raw) return { ...DEFAULT_LOOK, ...(JSON.parse(raw) as Partial<CaptainLook>) };+ } catch { /* storage unavailable or damaged */ }+ return DEFAULT_LOOK;+}++function loadDeck(): DeckId {+ try {+ const raw = localStorage.getItem(DECK_KEY);+ if (raw === "bridge" || raw === "ops" || raw === "engineering" || raw === "holodeck" || raw === "honors") return raw;+ } catch { /* storage unavailable */ }+ return "ops";+}++export interface Gathering {+ /** The division (room id) whose crew is called, or "mess" for a break. */+ place: string;+ agentIds: string[];+ untilMs: number;+}++interface ShipState {+ deck: DeckId;+ /** Increments on every deck change, so the captain is placed once per arrival. */+ arrivals: number;+ selection: Selection | null;+ /** The station the captain stands at (or the pointer rests on). */+ nearby: string | null;+ hovered: Selection | null;+ follow: boolean;+ /** Bumped to ask the camera for the overview. */+ overviewSeq: number;+ /** Bumped to glide the camera to `focus`. */+ focus: { at: Vec2; seq: number } | null;+ /** A walk the HUD asked for (walk there). */+ walkTo: { at: Vec2; seq: number } | null;+ /** Put the captain somewhere at once (development checks; a reduced-motion "walk there"). */+ placeAt: { at: Vec2; seq: number } | null;+ destination: DestinationId;+ /** 0..1 while the ship jumps to a new destination. */+ warpingTo: DestinationId | null;+ gathering: Gathering | null;+ captainLook: CaptainLook;+ setCaptainLook: (look: CaptainLook) => void;+ setDeck: (deck: DeckId) => void;+ select: (selection: Selection | null) => void;+ setNearby: (id: string | null) => void;+ hover: (selection: Selection | null) => void;+ setFollow: (follow: boolean) => void;+ overview: () => void;+ focusOn: (at: Vec2) => void;+ requestWalk: (at: Vec2) => void;+ place: (at: Vec2) => void;+ setDestination: (id: DestinationId) => void;+ setWarping: (id: DestinationId | null) => void;+ gather: (g: Gathering | null) => void;+}++export const useShip = create<ShipState>((set, get) => ({+ deck: loadDeck(),+ arrivals: 0,+ selection: null,+ nearby: null,+ hovered: null,+ follow: true,+ overviewSeq: 0,+ focus: null,+ walkTo: null,+ placeAt: null,+ destination: loadDestination(),+ warpingTo: null,+ gathering: null,+ captainLook: loadLook(),+ setCaptainLook: (captainLook) => {+ try { localStorage.setItem(LOOK_KEY, JSON.stringify(captainLook)); } catch { /* storage unavailable */ }+ set({ captainLook });+ },+ setDeck: (deck) => {+ try { localStorage.setItem(DECK_KEY, deck); } catch { /* storage unavailable */ }+ set({ deck, arrivals: get().arrivals + 1, selection: null, nearby: null, hovered: null, gathering: null, follow: true, walkTo: null, placeAt: null, focus: null });+ },+ select: (selection) => set({ selection }),+ setNearby: (nearby) => { if (get().nearby !== nearby) set({ nearby }); },+ hover: (hovered) => {+ const cur = get().hovered;+ if (cur?.kind === hovered?.kind && cur?.id === hovered?.id) return;+ set({ hovered });+ },+ setFollow: (follow) => { if (get().follow !== follow) set({ follow }); },+ overview: () => set({ overviewSeq: get().overviewSeq + 1, follow: false }),+ focusOn: (at) => set({ focus: { at, seq: (get().focus?.seq ?? 0) + 1 }, follow: false }),+ requestWalk: (at) => set({ walkTo: { at, seq: (get().walkTo?.seq ?? 0) + 1 }, follow: true }),+ place: (at) => set({ placeAt: { at, seq: (get().placeAt?.seq ?? 0) + 1 }, follow: true }),+ setDestination: (destination) => { saveDestination(destination); set({ destination }); },+ setWarping: (warpingTo) => set({ warpingTo }),+ gather: (gathering) => set({ gathering }),+}));diff --git a/dodaios/ui/web/frontend/src/components/society/starship/space/SpaceBackdrop.tsx b/dodaios/ui/web/frontend/src/components/society/starship/space/SpaceBackdrop.tsxnew file mode 100644index 0000000000..12a67c6845--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/space/SpaceBackdrop.tsx@@ -0,0 +1,299 @@+/**+ * Outside the hull: a procedural star field and nebula on a sky sphere, the+ * destination's planet below the ship (surface, night-side lights, clouds+ * and an atmosphere rim lit by the sun), its rings, the sun itself, and at+ * one destination a black hole. Everything is self-lit and cast no shadows;+ * with reduced motion the sky stands still.+ */+import { useFrame } from "@react-three/fiber";+import { useEffect, useMemo, useRef } from "react";+import {+ AdditiveBlending, BackSide, Color, DoubleSide, Mesh, PlaneGeometry, RingGeometry, ShaderMaterial, SphereGeometry, Vector3,+} from "three";+import type { Destination } from "./destinations";++const NOISE = /* glsl */ `+float hash13(vec3 p) { p = fract(p * 0.1031); p += dot(p, p.zyx + 31.32); return fract((p.x + p.y) * p.z); }+float noise3(vec3 x) {+ vec3 i = floor(x), f = fract(x); f = f * f * (3.0 - 2.0 * f);+ return mix(mix(mix(hash13(i), hash13(i + vec3(1,0,0)), f.x), mix(hash13(i + vec3(0,1,0)), hash13(i + vec3(1,1,0)), f.x), f.y),+ mix(mix(hash13(i + vec3(0,0,1)), hash13(i + vec3(1,0,1)), f.x), mix(hash13(i + vec3(0,1,1)), hash13(i + vec3(1,1,1)), f.x), f.y), f.z);+}+float fbm(vec3 p) { float v = 0.0, a = 0.5; for (int i = 0; i < 5; i++) { v += a * noise3(p); p = p * 2.03 + 17.1; a *= 0.5; } return v; }+`;++const SKY_VERT = /* glsl */ `+varying vec3 vDir;+void main() { vDir = normalize(position); vec4 p = projectionMatrix * modelViewMatrix * vec4(position, 1.0); gl_Position = p.xyww; }+`;++const SKY_FRAG = /* glsl */ `+uniform vec3 uNebulaA; uniform vec3 uNebulaB; uniform float uNebula; uniform float uStars; uniform float uBand; uniform float uTime;+varying vec3 vDir;+${NOISE}+vec3 starLayer(vec3 d, float scale, float threshold, float size) {+ vec3 p = d * scale; vec3 cell = floor(p); vec3 f = fract(p) - 0.5;+ float h = hash13(cell);+ if (h < threshold) return vec3(0.0);+ vec3 offset = vec3(hash13(cell + 1.7), hash13(cell + 7.3), hash13(cell + 3.1)) - 0.5;+ float dist = length(f - offset * 0.7);+ float b = smoothstep(size, 0.0, dist) * (h - threshold) / (1.0 - threshold);+ float tint = hash13(cell + 11.0);+ vec3 col = mix(vec3(0.7, 0.8, 1.0), vec3(1.0, 0.85, 0.7), tint);+ float tw = 0.75 + 0.25 * sin(uTime * (1.0 + h * 3.0) + h * 40.0);+ return col * b * tw;+}+void main() {+ vec3 d = normalize(vDir);+ // A galactic band across the sky.+ float band = exp(-pow(dot(d, normalize(vec3(0.3, 0.55, -0.78))) * 3.2, 2.0)) * uBand;+ float n = fbm(d * 2.2 + vec3(4.0));+ float n2 = fbm(d * 5.0 - vec3(2.0));+ float neb = smoothstep(0.42, 0.85, n) * uNebula;+ vec3 col = vec3(0.004, 0.006, 0.014);+ col += mix(uNebulaA, uNebulaB, smoothstep(0.3, 0.8, n2)) * neb * 0.55;+ col += vec3(0.55, 0.5, 0.62) * band * (0.08 + 0.12 * n2);+ // Dark dust lanes inside the band.+ col *= 1.0 - band * smoothstep(0.55, 0.75, n2) * 0.6;+ vec3 stars = starLayer(d, 180.0, 0.965, 0.22) * 2.2 + starLayer(d, 420.0, 0.975, 0.18) * 1.3 + starLayer(d, 900.0, 0.985, 0.16) * (0.8 + band * 2.0);+ col += stars * uStars;+ gl_FragColor = vec4(col, 1.0);+}+`;++const PLANET_VERT = /* glsl */ `+varying vec3 vNormal; varying vec3 vWorld; varying vec3 vLocal;+void main() {+ vLocal = position;+ vNormal = normalize(mat3(modelMatrix) * normal);+ vec4 w = modelMatrix * vec4(position, 1.0); vWorld = w.xyz;+ gl_Position = projectionMatrix * viewMatrix * w;+}+`;++const PLANET_FRAG = /* glsl */ `+uniform vec3 uSun; uniform vec3 uSunColour; uniform vec3 uC0; uniform vec3 uC1; uniform vec3 uC2; uniform vec3 uAtmo;+uniform float uKind; uniform float uCity; uniform float uTime; uniform float uRadius;+varying vec3 vNormal; varying vec3 vWorld; varying vec3 vLocal;+${NOISE}+void main() {+ vec3 n = normalize(vNormal);+ // The ship hangs over the planet's +y side: the poles lie along z, so it looks at the tropics, not an ice cap.+ vec3 p = normalize(vLocal).xzy;+ vec3 view = normalize(cameraPosition - vWorld);+ float light = dot(n, normalize(uSun));+ float day = smoothstep(-0.12, 0.25, light);+ vec3 surface;+ float clouds = 0.0;+ float night = 0.0;+ if (uKind < 0.5) {+ // Terran: oceans, continents, ice caps, clouds.+ float h = fbm(p * 7.5 + 1.3);+ float land = smoothstep(0.54, 0.58, h);+ vec3 ocean = mix(uC0, uC1, smoothstep(0.2, 0.52, h));+ vec3 ground = mix(vec3(0.16, 0.24, 0.12), vec3(0.42, 0.36, 0.24), smoothstep(0.56, 0.75, h));+ surface = mix(ocean, ground, land);+ surface = mix(surface, uC2, smoothstep(0.78, 0.9, abs(p.y)));+ clouds = smoothstep(0.6, 0.82, fbm(p * 13.0 + vec3(uTime * 0.004, 0.0, uTime * 0.002))) * 0.75;+ night = land * smoothstep(0.62, 0.8, fbm(p * 70.0)) * uCity;+ } else if (uKind < 1.5) {+ // Gas giant: latitude bands with turbulence.+ float lat = p.y + fbm(p * vec3(2.0, 8.0, 2.0) + vec3(uTime * 0.002, 0.0, 0.0)) * 0.18;+ float b = sin(lat * 26.0) * 0.5 + 0.5;+ surface = mix(uC0, uC1, b);+ surface = mix(surface, uC2, smoothstep(0.6, 1.0, sin(lat * 9.0 + 1.0)) * 0.6);+ } else if (uKind < 2.5) {+ // Ice: bright plains crossed by dark fractures.+ float c = abs(fbm(p * 7.0) - 0.5);+ surface = mix(uC1, uC2, smoothstep(0.3, 0.7, fbm(p * 2.5)));+ surface = mix(uC0, surface, smoothstep(0.0, 0.04, c));+ } else if (uKind < 3.5) {+ // Lava: dark crust and glowing seams that also show on the night side.+ float c = abs(fbm(p * 5.0) - 0.5);+ surface = mix(uC0, uC1, smoothstep(0.35, 0.75, fbm(p * 2.0)));+ night = smoothstep(0.05, 0.0, c) * 1.6;+ } else {+ // Aurora world: terran with a green aurora round both poles.+ float h = fbm(p * 3.0 + 4.2);+ float land = smoothstep(0.5, 0.55, h);+ surface = mix(mix(uC0, uC1, h), vec3(0.2, 0.3, 0.22), land);+ clouds = smoothstep(0.55, 0.8, fbm(p * 5.0 + uTime * 0.003));+ night = land * smoothstep(0.64, 0.8, fbm(p * 40.0)) * uCity;+ }+ vec3 col = surface * (0.06 + 0.94 * max(0.0, light)) * uSunColour;+ col = mix(col, vec3(1.0) * max(0.0, light) * uSunColour, clouds * 0.85);+ // City lights and lava glow live on the dark side.+ vec3 glow = uKind > 2.5 && uKind < 3.5 ? vec3(1.6, 0.55, 0.15) : vec3(1.4, 1.0, 0.55);+ col += glow * night * (1.0 - day) * (1.0 - clouds * 0.7);+ if (uKind > 3.5) {+ float aur = smoothstep(0.72, 0.82, abs(p.y)) * (1.0 - smoothstep(0.86, 0.95, abs(p.y)));+ aur *= 0.5 + 0.5 * sin(atan(p.z, p.x) * 18.0 + uTime * 0.25);+ col += vec3(0.25, 1.4, 0.7) * aur * (1.0 - day * 0.6);+ }+ // Atmosphere: a rim that glows where the sun reaches.+ float rim = pow(1.0 - max(0.0, dot(n, view)), 3.0);+ col += uAtmo * rim * (0.15 + 1.6 * smoothstep(-0.3, 0.4, light));+ gl_FragColor = vec4(col, 1.0);+}+`;++const HALO_FRAG = /* glsl */ `+uniform vec3 uAtmo; uniform vec3 uSun; varying vec3 vNormal; varying vec3 vWorld;+void main() {+ vec3 view = normalize(cameraPosition - vWorld);+ float facing = dot(normalize(vNormal), view);+ float a = pow(clamp(1.0 + facing, 0.0, 1.0), 6.0);+ float lit = smoothstep(-0.4, 0.5, dot(normalize(vNormal), normalize(uSun)));+ gl_FragColor = vec4(uAtmo * a * (0.2 + lit * 1.4), a * (0.25 + lit));+}+`;++const RING_FRAG = /* glsl */ `+uniform vec3 uColour; uniform float uInner; uniform float uOuter; varying vec3 vLocal;+${NOISE}+void main() {+ float r = length(vLocal.xy);+ float t = (r - uInner) / (uOuter - uInner);+ float bands = 0.55 + 0.45 * sin(t * 90.0) * sin(t * 23.0 + 1.0);+ float edge = smoothstep(0.0, 0.04, t) * smoothstep(1.0, 0.92, t);+ float gap = 1.0 - smoothstep(0.02, 0.0, abs(t - 0.62)) * 0.9;+ float a = edge * bands * gap * 0.75;+ gl_FragColor = vec4(uColour * (0.6 + bands * 0.6), a);+}+`;++const SUN_FRAG = /* glsl */ `+uniform vec3 uColour; varying vec2 vUv;+void main() {+ float d = length(vUv - 0.5) * 2.0;+ float core = smoothstep(0.12, 0.08, d);+ float glow = exp(-d * 5.0) * 0.9 + exp(-d * 14.0);+ float rays = pow(max(0.0, 1.0 - abs(vUv.x - 0.5) * 60.0), 2.0) * exp(-abs(vUv.y - 0.5) * 6.0) * 0.4+ + pow(max(0.0, 1.0 - abs(vUv.y - 0.5) * 60.0), 2.0) * exp(-abs(vUv.x - 0.5) * 6.0) * 0.4;+ vec3 col = uColour * (core * 6.0 + glow * 2.2 + rays * 2.0);+ gl_FragColor = vec4(col, 1.0);+}+`;++const DISC_FRAG = /* glsl */ `+uniform float uTime; varying vec3 vLocal;+${NOISE}+void main() {+ float r = length(vLocal.xy);+ float t = clamp((r - 60.0) / 260.0, 0.0, 1.0);+ float a = atan(vLocal.y, vLocal.x);+ float swirl = fbm(vec3(cos(a - uTime * 0.05 + t * 6.0) * 3.0, sin(a - uTime * 0.05 + t * 6.0) * 3.0, t * 8.0));+ float glow = (1.0 - t) * (1.0 - t) * (0.5 + swirl);+ vec3 col = mix(vec3(1.6, 0.7, 0.25), vec3(2.6, 2.1, 1.4), 1.0 - t) * glow * 2.0;+ gl_FragColor = vec4(col, smoothstep(0.0, 0.05, t) * glow);+}+`;++const VARY_VERT = /* glsl */ `+varying vec3 vLocal; varying vec2 vUv; varying vec3 vNormal; varying vec3 vWorld;+void main() { vLocal = position; vUv = uv; vNormal = normalize(mat3(modelMatrix) * normal); vec4 w = modelMatrix * vec4(position, 1.0); vWorld = w.xyz;+ gl_Position = projectionMatrix * viewMatrix * w; }+`;++function hex(colour: string): Color { return new Color(colour); }++const KIND: Record<Destination["planet"]["kind"], number> = { terran: 0, gas: 1, ice: 2, lava: 3, aurora: 4, none: -1 };++export function SpaceBackdrop({ destination, reduced }: { destination: Destination; reduced: boolean }) {+ const sunDir = useMemo(() => new Vector3(...destination.sun.direction).normalize(), [destination]);+ const sky = useMemo(() => new ShaderMaterial({+ vertexShader: SKY_VERT, fragmentShader: SKY_FRAG, side: BackSide, depthWrite: false, depthTest: false,+ uniforms: {+ uNebulaA: { value: hex(destination.sky.nebula[0]) }, uNebulaB: { value: hex(destination.sky.nebula[1]) },+ uNebula: { value: destination.sky.nebulaStrength }, uStars: { value: destination.sky.stars }, uBand: { value: destination.sky.band },+ uTime: { value: 0 },+ },+ }), [destination]);+ const planet = useMemo(() => destination.planet.kind === "none" ? null : new ShaderMaterial({+ vertexShader: PLANET_VERT, fragmentShader: PLANET_FRAG,+ uniforms: {+ uSun: { value: sunDir }, uSunColour: { value: hex(destination.sun.colour) },+ uC0: { value: hex(destination.planet.colours[0]) }, uC1: { value: hex(destination.planet.colours[1]) }, uC2: { value: hex(destination.planet.colours[2]) },+ uAtmo: { value: hex(destination.planet.atmosphere) }, uKind: { value: KIND[destination.planet.kind] },+ uCity: { value: destination.planet.cityLights ? 1 : 0 }, uTime: { value: 0 }, uRadius: { value: destination.planet.radius },+ },+ }), [destination, sunDir]);+ const halo = useMemo(() => destination.planet.kind === "none" ? null : new ShaderMaterial({+ vertexShader: PLANET_VERT, fragmentShader: HALO_FRAG, transparent: true, blending: AdditiveBlending, depthWrite: false, side: BackSide,+ uniforms: { uAtmo: { value: hex(destination.planet.atmosphere) }, uSun: { value: sunDir } },+ }), [destination, sunDir]);+ const rings = useMemo(() => destination.planet.rings ? new ShaderMaterial({+ vertexShader: VARY_VERT, fragmentShader: RING_FRAG, transparent: true, depthWrite: false, side: DoubleSide,+ uniforms: { uColour: { value: hex(destination.planet.rings.colour) }, uInner: { value: destination.planet.rings.inner }, uOuter: { value: destination.planet.rings.outer } },+ }) : null, [destination]);+ const sun = useMemo(() => new ShaderMaterial({+ vertexShader: VARY_VERT, fragmentShader: SUN_FRAG, transparent: true, blending: AdditiveBlending, depthWrite: false, toneMapped: false,+ uniforms: { uColour: { value: hex(destination.sun.colour) } },+ }), [destination]);+ const disc = useMemo(() => destination.singularity ? new ShaderMaterial({+ vertexShader: VARY_VERT, fragmentShader: DISC_FRAG, transparent: true, blending: AdditiveBlending, depthWrite: false, side: DoubleSide, toneMapped: false,+ uniforms: { uTime: { value: 0 } },+ }) : null, [destination]);+ const geos = useMemo(() => ({+ sky: new SphereGeometry(4000, 48, 24),+ planet: new SphereGeometry(1, 128, 64),+ ring: destination.planet.rings ? new RingGeometry(destination.planet.rings.inner, destination.planet.rings.outer, 160, 1) : null,+ sun: new PlaneGeometry(1, 1),+ disc: new RingGeometry(60, 320, 128, 1),+ }), [destination]);+ useEffect(() => () => {+ for (const m of [sky, planet, halo, rings, sun, disc]) m?.dispose();+ for (const g of Object.values(geos)) g?.dispose();+ }, [sky, planet, halo, rings, sun, disc, geos]);++ const planetRef = useRef<Mesh>(null);+ const sunRefs = useRef<(Mesh | null)[]>([]);+ useFrame(({ camera, clock }, dt) => {+ const t = reduced ? 0 : clock.elapsedTime;+ sky.uniforms.uTime.value = t;+ if (planet) planet.uniforms.uTime.value = t;+ if (disc) disc.uniforms.uTime.value = t;+ if (planetRef.current && !reduced) planetRef.current.rotation.y += dt * 0.004;+ for (const s of sunRefs.current) s?.lookAt(camera.position);+ });++ const p = destination.planet;+ const sunAt = sunDir.clone().multiplyScalar(3200);+ return (+ <group>+ <mesh geometry={geos.sky} material={sky} renderOrder={-10} frustumCulled={false} />+ {planet && halo && (+ <group position={p.centre}>+ <mesh ref={planetRef} geometry={geos.planet} material={planet} scale={p.radius} />+ <mesh geometry={geos.planet} material={halo} scale={p.radius * 1.06} />+ {rings && geos.ring && <mesh geometry={geos.ring} material={rings} rotation={[-Math.PI / 2 + (p.rings?.tilt ?? 0), 0, 0.2]} />}+ </group>+ )}+ <mesh ref={(m) => { sunRefs.current[0] = m; }} geometry={geos.sun} material={sun} position={sunAt} scale={900 * destination.sun.size} />+ {destination.sun.twin && (+ <mesh ref={(m) => { sunRefs.current[1] = m; }} geometry={geos.sun} material={sun}+ position={sunAt.clone().add(new Vector3(520, -160, 260))} scale={560 * destination.sun.size} />+ )}+ {destination.singularity && disc && <Singularity disc={disc} geometry={geos.disc} />}+ </group>+ );+}++function Singularity({ disc, geometry }: { disc: ShaderMaterial; geometry: RingGeometry }) {+ const core = useMemo(() => new SphereGeometry(58, 48, 24), []);+ const black = useMemo(() => new ShaderMaterial({+ vertexShader: VARY_VERT,+ fragmentShader: /* glsl */ `varying vec3 vNormal; varying vec3 vWorld;+ void main() { vec3 v = normalize(cameraPosition - vWorld); float rim = pow(1.0 - max(0.0, dot(normalize(vNormal), v)), 6.0);+ gl_FragColor = vec4(vec3(2.4, 1.7, 1.0) * rim, 1.0); }`,+ toneMapped: false,+ }), []);+ useEffect(() => () => { core.dispose(); black.dispose(); }, [core, black]);+ return (+ <group position={[-900, -380, -2200]} rotation={[0.35, 0.4, 0]}>+ <mesh geometry={core} material={black} />+ <mesh geometry={geometry} material={disc} rotation={[-Math.PI / 2 + 0.18, 0, 0]} />+ <mesh geometry={geometry} material={disc} rotation={[0.1, 0, 0]} scale={0.55} />+ </group>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/starship/space/destinations.ts b/dodaios/ui/web/frontend/src/components/society/starship/space/destinations.tsnew file mode 100644index 0000000000..913b30f2cd--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/starship/space/destinations.ts@@ -0,0 +1,109 @@+/**+ * Where the ship is. Every destination is a sky (stars and nebula), a body+ * below the ship and a sun; the bridge's helm sets course, and new+ * destinations open with the captain's rank (the level system's+ * `destination` rewards). Pure data, so tests and the helm share it.+ */++export type DestinationId =+ | "home" | "gas_giant" | "crimson_nebula" | "ice_moon" | "twin_suns" | "event_horizon" | "aurora_world" | "galactic_core";++export interface Destination {+ id: DestinationId;+ /** Captain's level that opens it (mirrors the rulebook's `destination` rewards). */+ level: number;+ /** The body below the ship. */+ planet: {+ kind: "terran" | "gas" | "ice" | "lava" | "none" | "aurora";+ /** Day-side colours, deep to bright. */+ colours: [string, string, string];+ atmosphere: string;+ radius: number;+ /** Where the body's centre lies relative to the deck (metres). */+ centre: [number, number, number];+ rings?: { inner: number; outer: number; colour: string; tilt: number };+ cityLights?: boolean;+ };+ sky: { nebula: [string, string]; nebulaStrength: number; stars: number; band: number };+ sun: { direction: [number, number, number]; colour: string; size: number; twin?: boolean };+ /** A black hole in the sky instead of a planet's company. */+ singularity?: boolean;+}++export const DESTINATIONS: readonly Destination[] = [+ {+ id: "home", level: 1,+ planet: { kind: "terran", colours: ["#0b2a55", "#1f6fb0", "#e8f2ff"], atmosphere: "#6fb8ff", radius: 1400, centre: [520, -1650, -260], cityLights: true },+ sky: { nebula: ["#1a2a6c", "#3b1f5e"], nebulaStrength: 0.35, stars: 1, band: 0.5 },+ sun: { direction: [-0.55, 0.42, -0.72], colour: "#fff1d6", size: 1 },+ },+ {+ id: "gas_giant", level: 5,+ planet: { kind: "gas", colours: ["#5a3418", "#c98a4b", "#f3dcb4"], atmosphere: "#ffcf8a", radius: 2200, centre: [-900, -2300, -900],+ rings: { inner: 2600, outer: 4100, colour: "#d9c3a0", tilt: 0.32 } },+ sky: { nebula: ["#2b1a0c", "#1a2440"], nebulaStrength: 0.25, stars: 0.9, band: 0.3 },+ sun: { direction: [0.6, 0.35, -0.7], colour: "#fff4e0", size: 0.9 },+ },+ {+ id: "crimson_nebula", level: 10,+ planet: { kind: "none", colours: ["#000000", "#000000", "#000000"], atmosphere: "#000000", radius: 1, centre: [0, -9000, 0] },+ sky: { nebula: ["#8c1c3a", "#ff7a4c"], nebulaStrength: 1.0, stars: 0.6, band: 0.1 },+ sun: { direction: [0.2, 0.5, -0.85], colour: "#ffd2c2", size: 0.7 },+ },+ {+ id: "ice_moon", level: 15,+ planet: { kind: "ice", colours: ["#5e7c9a", "#bcd6ea", "#ffffff"], atmosphere: "#cfeaff", radius: 1100, centre: [-380, -1350, -420] },+ sky: { nebula: ["#0f3a4a", "#1d2a5a"], nebulaStrength: 0.4, stars: 1.1, band: 0.6 },+ sun: { direction: [0.7, 0.3, -0.6], colour: "#e9f3ff", size: 1.1 },+ },+ {+ id: "twin_suns", level: 20,+ planet: { kind: "lava", colours: ["#2a0f08", "#a33a12", "#ffb347"], atmosphere: "#ff8a4c", radius: 1250, centre: [640, -1500, 120] },+ sky: { nebula: ["#40200a", "#2a0f30"], nebulaStrength: 0.45, stars: 0.8, band: 0.2 },+ sun: { direction: [-0.4, 0.5, -0.76], colour: "#ffe0a8", size: 1.2, twin: true },+ },+ {+ id: "event_horizon", level: 25,+ planet: { kind: "none", colours: ["#000000", "#000000", "#000000"], atmosphere: "#000000", radius: 1, centre: [0, -9000, 0] },+ sky: { nebula: ["#1b0f3a", "#0a2a4a"], nebulaStrength: 0.5, stars: 1.2, band: 0.4 },+ sun: { direction: [0.3, 0.4, -0.86], colour: "#ffdca8", size: 0.5 },+ singularity: true,+ },+ {+ id: "aurora_world", level: 30,+ planet: { kind: "aurora", colours: ["#0a2a2a", "#1f7a6a", "#cfffe9"], atmosphere: "#5bffb8", radius: 1500, centre: [-560, -1720, -320], cityLights: true },+ sky: { nebula: ["#0d3b2e", "#3a1f5e"], nebulaStrength: 0.55, stars: 1, band: 0.5 },+ sun: { direction: [0.5, 0.45, -0.74], colour: "#f2fff6", size: 0.9 },+ },+ {+ id: "galactic_core", level: 40,+ planet: { kind: "none", colours: ["#000000", "#000000", "#000000"], atmosphere: "#000000", radius: 1, centre: [0, -9000, 0] },+ sky: { nebula: ["#ffcf8a", "#7a3cff"], nebulaStrength: 0.85, stars: 2.2, band: 1.6 },+ sun: { direction: [-0.2, 0.3, -0.93], colour: "#fff3dd", size: 0.6 },+ },+];++export const DESTINATION_IDS = DESTINATIONS.map((d) => d.id);++export function destinationById(id: string | null | undefined): Destination {+ return DESTINATIONS.find((d) => d.id === id) ?? DESTINATIONS[0];+}++/** The destinations open at a captain's level, home first. */+export function openDestinations(level: number): Destination[] {+ return DESTINATIONS.filter((d) => d.level <= Math.max(1, level));+}++const KEY = "dodaios.ship.destination.v1";++export function loadDestination(): DestinationId {+ try {+ const raw = localStorage.getItem(KEY);+ if (raw && (DESTINATION_IDS as string[]).includes(raw)) return raw as DestinationId;+ } catch { /* storage unavailable */ }+ return "home";+}++export function saveDestination(id: DestinationId): void {+ try { localStorage.setItem(KEY, id); } catch { /* storage unavailable */ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/index.ts b/dodaios/ui/web/frontend/src/i18n/index.tsindex a7c2bd87cb..215ce6e0c7 100644--- a/dodaios/ui/web/frontend/src/i18n/index.ts+++ b/dodaios/ui/web/frontend/src/i18n/index.ts@@ -122,7 +122,33 @@ export type LocaleChunk =| "appshot_editor"| "providers"| "pane_review"- | "memory";+ | "memory"+ | "ship";++const SHIP_LOCALES = import.meta.glob("./locales/ship/*.json");++/** Keys that would reach an object's prototype instead of the object. */+const UNSAFE_KEYS = new Set(["__proto__", "constructor", "prototype"]);++function mergeDeep(target: Record<string, unknown>, source: Record<string, unknown>): Record<string, unknown> {+ for (const [key, value] of Object.entries(source)) {+ if (UNSAFE_KEYS.has(key)) continue;+ const prev = Object.prototype.hasOwnProperty.call(target, key) ? target[key] : undefined;+ if (value && typeof value === "object" && !Array.isArray(value) && prev && typeof prev === "object") {+ mergeDeep(prev as Record<string, unknown>, value as Record<string, unknown>);+ } else target[key] = value;+ }+ return target;+}++/** Every ship locale file of one language, merged. */+function shipLocale(lang: UiLanguage): () => Promise<unknown> {+ return () => Promise.all(+ Object.entries(SHIP_LOCALES)+ .filter(([path]) => path.endsWith(`/${lang}.json`) || path.endsWith(`.${lang}.json`))+ .map(([, load]) => load()),+ ).then((mods) => mods.reduce<Record<string, unknown>>((all, mod) => mergeDeep(all, unwrapModule(mod)), {}));+}const CHUNK_LOADERS: Record<LocaleChunk, Record<UiLanguage, () => Promise<unknown>>> = {marketplace: {@@ -185,6 +211,9 @@ const CHUNK_LOADERS: Record<LocaleChunk, Record<UiLanguage, () => Promise<unknowzh: () => import("./locales/pane_review/zh.json"),pt: () => import("./locales/pane_review/pt.json"),},+ // The Dodaios Verse starship (Agents > Dodaios Verse, the IDE's engineering tab).+ // Its strings live in several files per language (`ship/<lang>.json` and `ship/<area>.<lang>.json`).+ ship: { en: shipLocale("en"), de: shipLocale("de"), es: shipLocale("es"), zh: shipLocale("zh"), pt: shipLocale("pt") },// The Memory section (the vault reader, map and editor).memory: {en: () => import("./locales/memory/en.json"),diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/bridge.de.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/bridge.de.jsonnew file mode 100644index 0000000000..e55c9c1a8b--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/bridge.de.json@@ -0,0 +1,96 @@+{+ "ship": {+ "bridge": {+ "no_first_officer": "Noch kein Erster Offizier an Bord. Dein Assistent nimmt den Platz ein, sobald es ihn gibt.",+ "room": {+ "readyroom": "Bereitschaftsraum"+ },+ "viewscreen": {+ "destination": "Ziel",+ "warp": "Warpsprung"+ },+ "screen": {+ "helm": "Steuer",+ "ops": "Operationen",+ "personnel": "Personal",+ "comms": "Erster Offizier",+ "comms_hint": "Kanal offen",+ "science": "Wissenschaft",+ "navigation": "Navigation",+ "record": "Dienstakte",+ "course": "Kurs",+ "charted": "Kartiert",+ "next": "Nächstes",+ "all_charted": "Alle Ziele kartiert",+ "warp": "Warp",+ "holding": "Position gehalten",+ "live": "Live",+ "no_crew": "Keine Crew an Bord",+ "no_lead": "Kein Erster Offizier",+ "more": "+{count} weitere",+ "one_sun": "Eine Sonne",+ "twin_suns": "Zwei Sonnen",+ "rings": "Ringsystem",+ "cities": "Beleuchtete Städte auf der Nachtseite",+ "singularity": "Schwarzes Loch: Abstand halten"+ },+ "body": {+ "terran": "Ozeanwelt",+ "gas": "Gasriese",+ "ice": "Eismond",+ "lava": "Glühende Welt",+ "none": "Offener Raum",+ "aurora": "Polarlichtwelt"+ },+ "helm": {+ "eyebrow": "Steuer",+ "title": "Kurs setzen",+ "holding": "Position bei {place}",+ "captain_level": "Captain-Level {n}",+ "opens": "Level {n}",+ "here": "Hier",+ "open": "Offen",+ "locked": "Gesperrt",+ "locked_say": "{place} öffnet sich ab Captain-Level {n}.",+ "already": "Das Schiff ist bereits bei {place}.",+ "engaged": "Kurs auf {place} gesetzt. Energie.",+ "warping": "Sprung nach {place} …",+ "hint": "Pfeiltasten wählen, Enter springt, Escape schließt."+ },+ "destination": {+ "home": {+ "name": "Heimatorbit",+ "about": "Eine blaue Welt unter dir, ihre Städte leuchten auf der Nachtseite."+ },+ "gas_giant": {+ "name": "Gebänderter Riese",+ "about": "Ein sturmgestreifter Gasriese mit einem weiten Ringsystem."+ },+ "crimson_nebula": {+ "name": "Karmesinnebel",+ "about": "Tief in einer roten und bernsteinfarbenen Wolke, kein Planet, nur das Leuchten."+ },+ "ice_moon": {+ "name": "Eismond",+ "about": "Ein gefrorener Mond unter einer hellen, kalten Sonne."+ },+ "twin_suns": {+ "name": "Zwillingssonnen",+ "about": "Eine glühende Welt im Licht zweier Sonnen."+ },+ "event_horizon": {+ "name": "Ereignishorizont",+ "about": "Auf Position am Rand eines Schwarzen Lochs."+ },+ "aurora_world": {+ "name": "Polarlichtwelt",+ "about": "Eine grüne Welt unter wehenden Polarlichtern, ihre Städte wach."+ },+ "galactic_core": {+ "name": "Galaktischer Kern",+ "about": "Das dichte, helle Herz der Galaxis."+ }+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/bridge.en.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/bridge.en.jsonnew file mode 100644index 0000000000..4332535633--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/bridge.en.json@@ -0,0 +1,96 @@+{+ "ship": {+ "bridge": {+ "no_first_officer": "No first officer aboard yet. Your assistant takes the seat once it exists.",+ "room": {+ "readyroom": "Ready Room"+ },+ "viewscreen": {+ "destination": "Destination",+ "warp": "Warp jump"+ },+ "screen": {+ "helm": "Helm",+ "ops": "Operations",+ "personnel": "Personnel",+ "comms": "First officer",+ "comms_hint": "Channel open",+ "science": "Science",+ "navigation": "Navigation",+ "record": "Service record",+ "course": "Course",+ "charted": "Charted",+ "next": "Next",+ "all_charted": "Every destination charted",+ "warp": "Warp",+ "holding": "Holding",+ "live": "Live",+ "no_crew": "No crew aboard",+ "no_lead": "No first officer",+ "more": "+{count} more",+ "one_sun": "One sun",+ "twin_suns": "Two suns",+ "rings": "Ring system",+ "cities": "Lit cities on the night side",+ "singularity": "Black hole: hold distance"+ },+ "body": {+ "terran": "Ocean world",+ "gas": "Gas giant",+ "ice": "Ice moon",+ "lava": "Molten world",+ "none": "Open space",+ "aurora": "Aurora world"+ },+ "helm": {+ "eyebrow": "Helm",+ "title": "Set a course",+ "holding": "Holding at {place}",+ "captain_level": "Captain level {n}",+ "opens": "Level {n}",+ "here": "Here",+ "open": "Open",+ "locked": "Locked",+ "locked_say": "{place} opens at captain level {n}.",+ "already": "The ship is already at {place}.",+ "engaged": "Course laid in for {place}. Engaging.",+ "warping": "Jumping to {place}…",+ "hint": "Arrow keys choose, Enter engages, Escape closes."+ },+ "destination": {+ "home": {+ "name": "Home Orbit",+ "about": "A blue world below, its cities lit on the night side."+ },+ "gas_giant": {+ "name": "Banded Giant",+ "about": "A storm-banded gas giant with a wide ring system."+ },+ "crimson_nebula": {+ "name": "Crimson Nebula",+ "about": "Deep inside a red and amber cloud, no planet, only the glow."+ },+ "ice_moon": {+ "name": "Ice Moon",+ "about": "A frozen moon under a bright, cold sun."+ },+ "twin_suns": {+ "name": "Twin Suns",+ "about": "A molten world lit by two suns."+ },+ "event_horizon": {+ "name": "Event Horizon",+ "about": "Holding station at the edge of a black hole."+ },+ "aurora_world": {+ "name": "Aurora World",+ "about": "A green world under sweeping auroras, its cities awake."+ },+ "galactic_core": {+ "name": "Galactic Core",+ "about": "The dense, bright heart of the galaxy."+ }+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/bridge.es.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/bridge.es.jsonnew file mode 100644index 0000000000..53d18ba427--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/bridge.es.json@@ -0,0 +1,96 @@+{+ "ship": {+ "bridge": {+ "no_first_officer": "Todavía no hay primer oficial a bordo. Tu asistente ocupará el asiento en cuanto exista.",+ "room": {+ "readyroom": "Sala de mando"+ },+ "viewscreen": {+ "destination": "Destino",+ "warp": "Salto warp"+ },+ "screen": {+ "helm": "Timón",+ "ops": "Operaciones",+ "personnel": "Personal",+ "comms": "Primer oficial",+ "comms_hint": "Canal abierto",+ "science": "Ciencia",+ "navigation": "Navegación",+ "record": "Hoja de servicio",+ "course": "Rumbo",+ "charted": "Cartografiados",+ "next": "Siguiente",+ "all_charted": "Todos los destinos cartografiados",+ "warp": "Warp",+ "holding": "En posición",+ "live": "En vivo",+ "no_crew": "No hay tripulación a bordo",+ "no_lead": "Sin primer oficial",+ "more": "+{count} más",+ "one_sun": "Un sol",+ "twin_suns": "Dos soles",+ "rings": "Sistema de anillos",+ "cities": "Ciudades iluminadas en el lado nocturno",+ "singularity": "Agujero negro: mantener distancia"+ },+ "body": {+ "terran": "Mundo oceánico",+ "gas": "Gigante gaseoso",+ "ice": "Luna helada",+ "lava": "Mundo fundido",+ "none": "Espacio abierto",+ "aurora": "Mundo de auroras"+ },+ "helm": {+ "eyebrow": "Timón",+ "title": "Fijar un rumbo",+ "holding": "En posición en {place}",+ "captain_level": "Nivel de capitán {n}",+ "opens": "Nivel {n}",+ "here": "Aquí",+ "open": "Abierto",+ "locked": "Bloqueado",+ "locked_say": "{place} se abre con el nivel de capitán {n}.",+ "already": "La nave ya está en {place}.",+ "engaged": "Rumbo fijado a {place}. Adelante.",+ "warping": "Saltando a {place}…",+ "hint": "Las flechas eligen, Intro salta, Escape cierra."+ },+ "destination": {+ "home": {+ "name": "Órbita de origen",+ "about": "Un mundo azul abajo, con sus ciudades encendidas en el lado nocturno."+ },+ "gas_giant": {+ "name": "Gigante de bandas",+ "about": "Un gigante gaseoso surcado de tormentas, con un amplio sistema de anillos."+ },+ "crimson_nebula": {+ "name": "Nebulosa carmesí",+ "about": "En lo hondo de una nube roja y ámbar: ningún planeta, solo el resplandor."+ },+ "ice_moon": {+ "name": "Luna helada",+ "about": "Una luna congelada bajo un sol brillante y frío."+ },+ "twin_suns": {+ "name": "Soles gemelos",+ "about": "Un mundo fundido iluminado por dos soles."+ },+ "event_horizon": {+ "name": "Horizonte de sucesos",+ "about": "En posición al borde de un agujero negro."+ },+ "aurora_world": {+ "name": "Mundo de auroras",+ "about": "Un mundo verde bajo auroras ondulantes, con sus ciudades despiertas."+ },+ "galactic_core": {+ "name": "Núcleo galáctico",+ "about": "El corazón denso y brillante de la galaxia."+ }+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/bridge.pt.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/bridge.pt.jsonnew file mode 100644index 0000000000..09989e9fe0--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/bridge.pt.json@@ -0,0 +1,96 @@+{+ "ship": {+ "bridge": {+ "no_first_officer": "Ainda não há imediato a bordo. Seu assistente ocupa o assento assim que existir.",+ "room": {+ "readyroom": "Sala do capitão"+ },+ "viewscreen": {+ "destination": "Destino",+ "warp": "Salto de dobra"+ },+ "screen": {+ "helm": "Leme",+ "ops": "Operações",+ "personnel": "Pessoal",+ "comms": "Imediato",+ "comms_hint": "Canal aberto",+ "science": "Ciências",+ "navigation": "Navegação",+ "record": "Folha de serviço",+ "course": "Rumo",+ "charted": "Mapeados",+ "next": "Próximo",+ "all_charted": "Todos os destinos mapeados",+ "warp": "Dobra",+ "holding": "Em posição",+ "live": "Ao vivo",+ "no_crew": "Nenhuma tripulação a bordo",+ "no_lead": "Sem imediato",+ "more": "+{count} a mais",+ "one_sun": "Um sol",+ "twin_suns": "Dois sóis",+ "rings": "Sistema de anéis",+ "cities": "Cidades acesas no lado noturno",+ "singularity": "Buraco negro: manter distância"+ },+ "body": {+ "terran": "Mundo oceânico",+ "gas": "Gigante gasoso",+ "ice": "Lua gelada",+ "lava": "Mundo derretido",+ "none": "Espaço aberto",+ "aurora": "Mundo de auroras"+ },+ "helm": {+ "eyebrow": "Leme",+ "title": "Traçar um rumo",+ "holding": "Em posição em {place}",+ "captain_level": "Nível de capitão {n}",+ "opens": "Nível {n}",+ "here": "Aqui",+ "open": "Aberto",+ "locked": "Bloqueado",+ "locked_say": "{place} abre no nível de capitão {n}.",+ "already": "A nave já está em {place}.",+ "engaged": "Rumo traçado para {place}. Acionar.",+ "warping": "Saltando para {place}…",+ "hint": "As setas escolhem, Enter salta, Escape fecha."+ },+ "destination": {+ "home": {+ "name": "Órbita natal",+ "about": "Um mundo azul lá embaixo, com as cidades acesas no lado noturno."+ },+ "gas_giant": {+ "name": "Gigante listrado",+ "about": "Um gigante gasoso riscado de tempestades, com um amplo sistema de anéis."+ },+ "crimson_nebula": {+ "name": "Nebulosa carmesim",+ "about": "No fundo de uma nuvem vermelha e âmbar: nenhum planeta, só o brilho."+ },+ "ice_moon": {+ "name": "Lua gelada",+ "about": "Uma lua congelada sob um sol forte e frio."+ },+ "twin_suns": {+ "name": "Sóis gêmeos",+ "about": "Um mundo derretido iluminado por dois sóis."+ },+ "event_horizon": {+ "name": "Horizonte de eventos",+ "about": "Em posição à beira de um buraco negro."+ },+ "aurora_world": {+ "name": "Mundo de auroras",+ "about": "Um mundo verde sob auroras ondulantes, com as cidades acordadas."+ },+ "galactic_core": {+ "name": "Núcleo galáctico",+ "about": "O coração denso e brilhante da galáxia."+ }+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/bridge.zh.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/bridge.zh.jsonnew file mode 100644index 0000000000..2b555ec30b--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/bridge.zh.json@@ -0,0 +1,96 @@+{+ "ship": {+ "bridge": {+ "no_first_officer": "舰上还没有大副。你的助手一旦创建,就会坐上这个位置。",+ "room": {+ "readyroom": "舰长待命室"+ },+ "viewscreen": {+ "destination": "目的地",+ "warp": "曲速跃迁"+ },+ "screen": {+ "helm": "舵手",+ "ops": "作战",+ "personnel": "人员",+ "comms": "大副",+ "comms_hint": "频道已开启",+ "science": "科学",+ "navigation": "导航",+ "record": "服役记录",+ "course": "航向",+ "charted": "已绘制",+ "next": "下一个",+ "all_charted": "所有目的地均已绘制",+ "warp": "曲速",+ "holding": "保持位置",+ "live": "实时",+ "no_crew": "舰上没有船员",+ "no_lead": "没有大副",+ "more": "还有 {count} 位",+ "one_sun": "一颗恒星",+ "twin_suns": "两颗恒星",+ "rings": "行星环系统",+ "cities": "夜侧城市灯火通明",+ "singularity": "黑洞:保持距离"+ },+ "body": {+ "terran": "海洋世界",+ "gas": "气态巨行星",+ "ice": "冰卫星",+ "lava": "熔岩世界",+ "none": "开阔空间",+ "aurora": "极光世界"+ },+ "helm": {+ "eyebrow": "舵手",+ "title": "设定航向",+ "holding": "停泊于 {place}",+ "captain_level": "舰长等级 {n}",+ "opens": "等级 {n}",+ "here": "当前",+ "open": "已开放",+ "locked": "未解锁",+ "locked_say": "{place} 在舰长等级 {n} 时开放。",+ "already": "飞船已经在 {place}。",+ "engaged": "航向已设定:{place}。启动。",+ "warping": "正在跃迁至 {place}……",+ "hint": "方向键选择,Enter 跃迁,Escape 关闭。"+ },+ "destination": {+ "home": {+ "name": "母星轨道",+ "about": "下方是一颗蓝色星球,夜侧城市灯火闪烁。"+ },+ "gas_giant": {+ "name": "条纹巨星",+ "about": "风暴条纹密布的气态巨行星,环绕着宽阔的行星环。"+ },+ "crimson_nebula": {+ "name": "绯红星云",+ "about": "深入一片红色与琥珀色的云团,没有行星,只有光芒。"+ },+ "ice_moon": {+ "name": "冰月",+ "about": "明亮而寒冷的恒星下,一颗冰封的卫星。"+ },+ "twin_suns": {+ "name": "双日",+ "about": "被两颗恒星照亮的熔岩世界。"+ },+ "event_horizon": {+ "name": "事件视界",+ "about": "在黑洞边缘保持位置。"+ },+ "aurora_world": {+ "name": "极光世界",+ "about": "舞动极光下的绿色星球,城市依旧醒着。"+ },+ "galactic_core": {+ "name": "银河核心",+ "about": "银河系密集而明亮的心脏。"+ }+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/de.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/de.jsonnew file mode 100644index 0000000000..ec543c1f7f--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/de.json@@ -0,0 +1,110 @@+{+ "ship": {+ "title": "Dodaios Verse",+ "fallback": "Das Schiff braucht WebGL, das diese Ansicht gerade nicht starten kann.",+ "loading": "An Bord gehen …",+ "click": "Klick",+ "close": "Schließen",+ "level": "Level {n}",+ "help": "Laufen mit WASD oder per Klick aufs Deck. Ziehen zum Umsehen, scrollen zum Zoomen. E benutzt, wovor du stehst, O zeigt das ganze Deck.",+ "deck": {+ "label": "Deck {n}",+ "bridge": "Brücke",+ "bridge_about": "Kommando, Steuer und dein Erster Offizier",+ "ops": "Operationen",+ "ops_about": "Die Divisionen deiner Agents, Messe und Transporter",+ "engineering": "Maschinenraum",+ "engineering_about": "Coding-Agents bei der Arbeit rund um den Reaktor",+ "holodeck": "Holodeck",+ "holodeck_about": "Zehn spielbare Spiele",+ "honors": "Ehrenhalle",+ "honors_about": "Ränge, Beförderungen und deine Dienstakte"+ },+ "crew": {+ "working": "{count} arbeiten",+ "waiting": "{count} warten",+ "idle": "{count} dienstfrei"+ },+ "state": {+ "working": "Arbeitet",+ "waiting": "Braucht dich",+ "idle": "Dienstfrei",+ "paused": "Ruht",+ "error": "Fehlgeschlagen",+ "vacant": "Frei"+ },+ "room": {+ "lounge": "Aussichtslounge",+ "quartermaster": "Quartiermeister",+ "pods": "Ruhekapseln",+ "lift": "Turbolift",+ "garden": "Hydrokultur"+ },+ "division": {+ "pool": "Crew ohne Team",+ "free": "Freie Bucht"+ },+ "screen": {+ "standby": "Bereit",+ "vacant": "Frei"+ },+ "station": {+ "transporter": { "action": "Neuen Agent herbeamen", "name": "Transporter" },+ "lift": { "action": "Turbolift rufen", "name": "Turbolift" },+ "division": { "action": "Team öffnen", "name": "Holo-Tisch" },+ "newDivision": { "action": "Hier ein Team gründen", "name": "Freie Bucht" },+ "quartermaster": { "action": "Anzug wechseln", "name": "Quartiermeister", "soon": "Der Quartiermeister öffnet im nächsten Bauschritt." },+ "mess": {+ "action": "Crew in die Messe rufen",+ "name": "Kombüse",+ "called": "{count} dienstfreie Agents gehen in die Messe.",+ "nobody": "Gerade ist niemand dienstfrei.",+ "ended": "Pause vorbei: Alle gehen zurück."+ },+ "captain": { "action": "Im Kommandosessel Platz nehmen", "name": "Kommandosessel" },+ "firstOfficer": { "action": "Mit deinem Ersten Offizier sprechen", "name": "Erster Offizier" },+ "helm": { "action": "Kurs setzen", "name": "Steuer" },+ "ops": { "action": "Crew-Verzeichnis öffnen", "name": "Operationstisch" },+ "systems": { "action": "Coding-Agents starten", "name": "Hauptsystemanzeige" },+ "holoCabinet": { "action": "Spielen", "name": "Holo-Automat" },+ "rankWall": { "action": "Deine Dienstakte öffnen", "name": "Rangwand" },+ "honorCase": { "action": "Ansehen", "name": "Vitrine" },+ "pods": { "action": "Hineinsehen", "name": "Ruhekapseln" }+ },+ "agent": {+ "open_chat": "Chat öffnen",+ "walk_there": "Hingehen",+ "show": "Zeigen"+ },+ "lift": {+ "title": "Turbolift",+ "here": "Du bist hier"+ },+ "tools": {+ "label": "Schiffssteuerung",+ "follow": "Mir folgen",+ "overview": "Ganzes Deck",+ "lift": "Turbolift",+ "help": "Steuerung"+ },+ "rank": {+ "record_soon": "Deine Dienstakte öffnet sich in der Ehrenhalle.",+ "cadet": "Kadett",+ "crewman": "Crewman",+ "specialist": "Spezialist",+ "petty_officer": "Maat",+ "chief_petty_officer": "Obermaat",+ "warrant_officer": "Fähnrich zur See",+ "ensign": "Leutnant zur See",+ "lieutenant_junior_grade": "Oberleutnant zur See",+ "lieutenant": "Kapitänleutnant",+ "lieutenant_commander": "Korvettenkapitän",+ "commander": "Fregattenkapitän",+ "captain": "Kapitän zur See",+ "commodore": "Flottillenadmiral",+ "rear_admiral": "Konteradmiral",+ "vice_admiral": "Vizeadmiral",+ "admiral": "Admiral"+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/en.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/en.jsonnew file mode 100644index 0000000000..25675ccfb8--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/en.json@@ -0,0 +1,110 @@+{+ "ship": {+ "title": "Dodaios Verse",+ "fallback": "The ship needs WebGL, which this view cannot start right now.",+ "loading": "Boarding…",+ "click": "Click",+ "close": "Close",+ "level": "Level {n}",+ "help": "Walk with WASD or a click on the deck. Drag to look round, scroll to zoom. E uses what you stand at, O shows the whole deck.",+ "deck": {+ "label": "Deck {n}",+ "bridge": "Bridge",+ "bridge_about": "Command, the helm and your first officer",+ "ops": "Operations",+ "ops_about": "Your agents' divisions, the mess and the transporter",+ "engineering": "Engineering",+ "engineering_about": "Coding agents at work round the reactor",+ "holodeck": "Holodeck",+ "holodeck_about": "Ten playable games",+ "honors": "Hall of Honour",+ "honors_about": "Ranks, promotions and your service record"+ },+ "crew": {+ "working": "{count} working",+ "waiting": "{count} waiting",+ "idle": "{count} off duty"+ },+ "state": {+ "working": "Working",+ "waiting": "Needs you",+ "idle": "Off duty",+ "paused": "Resting",+ "error": "Failed",+ "vacant": "Vacant"+ },+ "room": {+ "lounge": "Observation Lounge",+ "quartermaster": "Quartermaster",+ "pods": "Rest Pods",+ "lift": "Turbolift",+ "garden": "Hydroponics"+ },+ "division": {+ "pool": "Crew without a team",+ "free": "Free bay"+ },+ "screen": {+ "standby": "Standing by",+ "vacant": "Vacant"+ },+ "station": {+ "transporter": { "action": "Beam in a new agent", "name": "Transporter" },+ "lift": { "action": "Call the turbolift", "name": "Turbolift" },+ "division": { "action": "Open the team", "name": "Holo-table" },+ "newDivision": { "action": "Start a team here", "name": "Free bay" },+ "quartermaster": { "action": "Change your suit", "name": "Quartermaster", "soon": "The quartermaster opens in the next step of the build." },+ "mess": {+ "action": "Call the crew to the mess",+ "name": "Galley",+ "called": "{count} off-duty agents are heading to the mess.",+ "nobody": "Nobody is off duty right now.",+ "ended": "Break over: everyone heads back."+ },+ "captain": { "action": "Take the captain's chair", "name": "Captain's chair" },+ "firstOfficer": { "action": "Talk to your first officer", "name": "First officer" },+ "helm": { "action": "Set a course", "name": "Helm" },+ "ops": { "action": "Open the crew directory", "name": "Operations table" },+ "systems": { "action": "Launch coding agents", "name": "Master systems display" },+ "holoCabinet": { "action": "Play", "name": "Holo cabinet" },+ "rankWall": { "action": "Open your service record", "name": "Rank wall" },+ "honorCase": { "action": "Look at it", "name": "Display case" },+ "pods": { "action": "Look in", "name": "Rest pods" }+ },+ "agent": {+ "open_chat": "Open chat",+ "walk_there": "Walk there",+ "show": "Show"+ },+ "lift": {+ "title": "Turbolift",+ "here": "You are here"+ },+ "tools": {+ "label": "Ship controls",+ "follow": "Follow me",+ "overview": "Whole deck",+ "lift": "Turbolift",+ "help": "Controls"+ },+ "rank": {+ "record_soon": "Your service record opens in the Hall of Honour.",+ "cadet": "Cadet",+ "crewman": "Crewman",+ "specialist": "Specialist",+ "petty_officer": "Petty Officer",+ "chief_petty_officer": "Chief Petty Officer",+ "warrant_officer": "Warrant Officer",+ "ensign": "Ensign",+ "lieutenant_junior_grade": "Lieutenant Junior Grade",+ "lieutenant": "Lieutenant",+ "lieutenant_commander": "Lieutenant Commander",+ "commander": "Commander",+ "captain": "Captain",+ "commodore": "Commodore",+ "rear_admiral": "Rear Admiral",+ "vice_admiral": "Vice Admiral",+ "admiral": "Admiral"+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/engineering.de.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/engineering.de.jsonnew file mode 100644index 0000000000..4fe400ff22--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/engineering.de.json@@ -0,0 +1,36 @@+{+ "ship": {+ "engineering": {+ "other": "Weitere Workspaces",+ "bay_free": "Bereitschaftsbucht",+ "nook": "Ruhebereich",+ "panel": {+ "title": "Coding-Agenten starten",+ "cli": "Agent",+ "workspace": "Workspace",+ "task": "Erste Aufgabe (optional)",+ "task_placeholder": "Woran sollen die neuen Agenten arbeiten?",+ "count": "Wie viele",+ "fewer": "Weniger",+ "more": "Mehr",+ "start_one": "Agent starten",+ "start_many": "{count} Agenten starten",+ "hint": "Strg+Enter startet. Neue Agenten nehmen eine freie Konsole in der Bucht ihres Workspaces.",+ "loading": "Lese die IDE …",+ "load_failed": "Die IDE hat nicht geantwortet: {error}",+ "no_clis": "Noch keine Coding-CLI installiert. Installiere eine in der Agentic IDE.",+ "no_workspace": "Noch kein Workspace geöffnet.",+ "open_ide": "Agentic IDE öffnen",+ "opening": "Öffne ein Pane …",+ "waiting": "{pane} startet …",+ "briefing": "Übergebe {pane} die Aufgabe …",+ "done_open": "{pane} ist offen.",+ "done_briefed": "{pane} hat die Aufgabe.",+ "not_started": "{pane} ist nicht rechtzeitig gestartet; die Aufgabe wurde nicht gesendet.",+ "failed": "Pane ließ sich nicht öffnen: {error}",+ "unconfirmed": "Die Aufgabe wurde eingetippt, aber der Agent hat sie nicht bestätigt.",+ "launched": "{count} neu auf dem Maschinendeck."+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/engineering.en.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/engineering.en.jsonnew file mode 100644index 0000000000..6ae425da9b--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/engineering.en.json@@ -0,0 +1,36 @@+{+ "ship": {+ "engineering": {+ "other": "Other workspaces",+ "bay_free": "Standby bay",+ "nook": "Crew Rest",+ "panel": {+ "title": "Launch coding agents",+ "cli": "Agent",+ "workspace": "Workspace",+ "task": "First task (optional)",+ "task_placeholder": "What should the new agents work on?",+ "count": "How many",+ "fewer": "Fewer",+ "more": "More",+ "start_one": "Start agent",+ "start_many": "Start {count} agents",+ "hint": "Ctrl+Enter starts. New agents take a free console in their workspace's bay.",+ "loading": "Reading the IDE…",+ "load_failed": "The IDE did not answer: {error}",+ "no_clis": "No coding CLI is installed yet. Install one in the Agentic IDE.",+ "no_workspace": "No workspace is open yet.",+ "open_ide": "Open the Agentic IDE",+ "opening": "Opening a pane…",+ "waiting": "{pane} is starting…",+ "briefing": "Handing {pane} its task…",+ "done_open": "{pane} is open.",+ "done_briefed": "{pane} has its task.",+ "not_started": "{pane} did not start in time; the task was not sent.",+ "failed": "Could not open a pane: {error}",+ "unconfirmed": "The task was typed in, but the agent did not confirm it.",+ "launched": "{count} new on the engineering deck."+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/engineering.es.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/engineering.es.jsonnew file mode 100644index 0000000000..7d9859915b--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/engineering.es.json@@ -0,0 +1,36 @@+{+ "ship": {+ "engineering": {+ "other": "Otros espacios de trabajo",+ "bay_free": "Bahía en espera",+ "nook": "Descanso",+ "panel": {+ "title": "Lanzar agentes de código",+ "cli": "Agente",+ "workspace": "Espacio de trabajo",+ "task": "Primera tarea (opcional)",+ "task_placeholder": "¿En qué deben trabajar los nuevos agentes?",+ "count": "Cuántos",+ "fewer": "Menos",+ "more": "Más",+ "start_one": "Iniciar agente",+ "start_many": "Iniciar {count} agentes",+ "hint": "Ctrl+Intro inicia. Los nuevos agentes ocupan una consola libre en la bahía de su espacio de trabajo.",+ "loading": "Leyendo el IDE…",+ "load_failed": "El IDE no respondió: {error}",+ "no_clis": "Aún no hay ninguna CLI de código instalada. Instala una en el Agentic IDE.",+ "no_workspace": "Aún no hay ningún espacio de trabajo abierto.",+ "open_ide": "Abrir el Agentic IDE",+ "opening": "Abriendo un panel…",+ "waiting": "{pane} está arrancando…",+ "briefing": "Entregando la tarea a {pane}…",+ "done_open": "{pane} está abierto.",+ "done_briefed": "{pane} tiene su tarea.",+ "not_started": "{pane} no arrancó a tiempo; la tarea no se envió.",+ "failed": "No se pudo abrir un panel: {error}",+ "unconfirmed": "La tarea se escribió, pero el agente no la confirmó.",+ "launched": "{count} nuevos en la cubierta de ingeniería."+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/engineering.pt.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/engineering.pt.jsonnew file mode 100644index 0000000000..0ee9d2ebbd--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/engineering.pt.json@@ -0,0 +1,36 @@+{+ "ship": {+ "engineering": {+ "other": "Outros espaços de trabalho",+ "bay_free": "Baia em espera",+ "nook": "Descanso",+ "panel": {+ "title": "Iniciar agentes de código",+ "cli": "Agente",+ "workspace": "Espaço de trabalho",+ "task": "Primeira tarefa (opcional)",+ "task_placeholder": "Em que os novos agentes devem trabalhar?",+ "count": "Quantos",+ "fewer": "Menos",+ "more": "Mais",+ "start_one": "Iniciar agente",+ "start_many": "Iniciar {count} agentes",+ "hint": "Ctrl+Enter inicia. Novos agentes ocupam um console livre na baia do seu espaço de trabalho.",+ "loading": "Lendo o IDE…",+ "load_failed": "O IDE não respondeu: {error}",+ "no_clis": "Ainda não há nenhuma CLI de código instalada. Instale uma no Agentic IDE.",+ "no_workspace": "Ainda não há nenhum espaço de trabalho aberto.",+ "open_ide": "Abrir o Agentic IDE",+ "opening": "Abrindo um painel…",+ "waiting": "{pane} está iniciando…",+ "briefing": "Entregando a tarefa a {pane}…",+ "done_open": "{pane} está aberto.",+ "done_briefed": "{pane} recebeu a tarefa.",+ "not_started": "{pane} não iniciou a tempo; a tarefa não foi enviada.",+ "failed": "Não foi possível abrir um painel: {error}",+ "unconfirmed": "A tarefa foi digitada, mas o agente não a confirmou.",+ "launched": "{count} novos no deck de engenharia."+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/engineering.zh.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/engineering.zh.jsonnew file mode 100644index 0000000000..c3b1845359--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/engineering.zh.json@@ -0,0 +1,36 @@+{+ "ship": {+ "engineering": {+ "other": "其他工作区",+ "bay_free": "待命舱位",+ "nook": "船员休息区",+ "panel": {+ "title": "启动编码代理",+ "cli": "代理",+ "workspace": "工作区",+ "task": "首个任务(可选)",+ "task_placeholder": "新代理应该做什么?",+ "count": "数量",+ "fewer": "减少",+ "more": "增加",+ "start_one": "启动代理",+ "start_many": "启动 {count} 个代理",+ "hint": "Ctrl+Enter 启动。新代理会坐到其工作区舱位中的空闲控制台。",+ "loading": "正在读取 IDE…",+ "load_failed": "IDE 没有响应:{error}",+ "no_clis": "尚未安装任何编码 CLI。请在 Agentic IDE 中安装一个。",+ "no_workspace": "尚未打开任何工作区。",+ "open_ide": "打开 Agentic IDE",+ "opening": "正在打开窗格…",+ "waiting": "{pane} 正在启动…",+ "briefing": "正在把任务交给 {pane}…",+ "done_open": "{pane} 已打开。",+ "done_briefed": "{pane} 已收到任务。",+ "not_started": "{pane} 未能及时启动;任务未发送。",+ "failed": "无法打开窗格:{error}",+ "unconfirmed": "任务已输入,但代理没有确认。",+ "launched": "工程甲板上新增 {count} 个。"+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/es.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/es.jsonnew file mode 100644index 0000000000..408df0e6a4--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/es.json@@ -0,0 +1,110 @@+{+ "ship": {+ "title": "Dodaios Verse",+ "fallback": "La nave necesita WebGL y esta vista no puede iniciarlo ahora.",+ "loading": "Subiendo a bordo…",+ "click": "Clic",+ "close": "Cerrar",+ "level": "Nivel {n}",+ "help": "Camina con WASD o con un clic en la cubierta. Arrastra para mirar, desplaza para acercar. E usa lo que tienes delante, O muestra toda la cubierta.",+ "deck": {+ "label": "Cubierta {n}",+ "bridge": "Puente",+ "bridge_about": "Mando, el timón y tu primer oficial",+ "ops": "Operaciones",+ "ops_about": "Las divisiones de tus agentes, el comedor y el transportador",+ "engineering": "Ingeniería",+ "engineering_about": "Agentes de código trabajando alrededor del reactor",+ "holodeck": "Holocubierta",+ "holodeck_about": "Diez juegos jugables",+ "honors": "Salón de Honor",+ "honors_about": "Rangos, ascensos y tu hoja de servicio"+ },+ "crew": {+ "working": "{count} trabajando",+ "waiting": "{count} esperando",+ "idle": "{count} libres"+ },+ "state": {+ "working": "Trabajando",+ "waiting": "Te necesita",+ "idle": "Libre",+ "paused": "Descansando",+ "error": "Falló",+ "vacant": "Libre"+ },+ "room": {+ "lounge": "Sala de observación",+ "quartermaster": "Intendencia",+ "pods": "Cápsulas de descanso",+ "lift": "Turboascensor",+ "garden": "Hidroponía"+ },+ "division": {+ "pool": "Tripulación sin equipo",+ "free": "Bahía libre"+ },+ "screen": {+ "standby": "En espera",+ "vacant": "Libre"+ },+ "station": {+ "transporter": { "action": "Transportar un agente nuevo", "name": "Transportador" },+ "lift": { "action": "Llamar al turboascensor", "name": "Turboascensor" },+ "division": { "action": "Abrir el equipo", "name": "Holomesa" },+ "newDivision": { "action": "Fundar un equipo aquí", "name": "Bahía libre" },+ "quartermaster": { "action": "Cambiar de traje", "name": "Intendencia", "soon": "La intendencia abre en el siguiente paso de la construcción." },+ "mess": {+ "action": "Llamar a la tripulación al comedor",+ "name": "Cocina",+ "called": "{count} agentes libres van al comedor.",+ "nobody": "Ahora mismo nadie está libre.",+ "ended": "Fin del descanso: todos vuelven."+ },+ "captain": { "action": "Sentarte en el sillón del capitán", "name": "Sillón del capitán" },+ "firstOfficer": { "action": "Hablar con tu primer oficial", "name": "Primer oficial" },+ "helm": { "action": "Fijar un rumbo", "name": "Timón" },+ "ops": { "action": "Abrir el directorio de la tripulación", "name": "Mesa de operaciones" },+ "systems": { "action": "Lanzar agentes de código", "name": "Pantalla de sistemas" },+ "holoCabinet": { "action": "Jugar", "name": "Holomáquina" },+ "rankWall": { "action": "Abrir tu hoja de servicio", "name": "Muro de rangos" },+ "honorCase": { "action": "Mirar", "name": "Vitrina" },+ "pods": { "action": "Asomarse", "name": "Cápsulas de descanso" }+ },+ "agent": {+ "open_chat": "Abrir chat",+ "walk_there": "Ir allí",+ "show": "Mostrar"+ },+ "lift": {+ "title": "Turboascensor",+ "here": "Estás aquí"+ },+ "tools": {+ "label": "Controles de la nave",+ "follow": "Seguirme",+ "overview": "Toda la cubierta",+ "lift": "Turboascensor",+ "help": "Controles"+ },+ "rank": {+ "record_soon": "Tu hoja de servicio se abre en el Salón de Honor.",+ "cadet": "Cadete",+ "crewman": "Tripulante",+ "specialist": "Especialista",+ "petty_officer": "Suboficial",+ "chief_petty_officer": "Suboficial mayor",+ "warrant_officer": "Oficial técnico",+ "ensign": "Alférez",+ "lieutenant_junior_grade": "Teniente de corbeta",+ "lieutenant": "Teniente de navío",+ "lieutenant_commander": "Capitán de corbeta",+ "commander": "Capitán de fragata",+ "captain": "Capitán de navío",+ "commodore": "Comodoro",+ "rear_admiral": "Contraalmirante",+ "vice_admiral": "Vicealmirante",+ "admiral": "Almirante"+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/holodeck.de.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/holodeck.de.jsonnew file mode 100644index 0000000000..e404accb1d--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/holodeck.de.json@@ -0,0 +1,10 @@+{+ "ship": {+ "holodeck": {+ "room": "Holodeck",+ "program": "Holodeck-Programm",+ "loading": "Das Programm wird geladen …",+ "missing": "Dieses Programm ist nicht in der Bibliothek des Holodecks."+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/holodeck.en.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/holodeck.en.jsonnew file mode 100644index 0000000000..bc71c64dfc--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/holodeck.en.json@@ -0,0 +1,10 @@+{+ "ship": {+ "holodeck": {+ "room": "Holodeck",+ "program": "Holodeck program",+ "loading": "Loading the program…",+ "missing": "This program is not in the holodeck’s library."+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/holodeck.es.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/holodeck.es.jsonnew file mode 100644index 0000000000..5917ea781a--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/holodeck.es.json@@ -0,0 +1,10 @@+{+ "ship": {+ "holodeck": {+ "room": "Holocubierta",+ "program": "Programa de la holocubierta",+ "loading": "Cargando el programa…",+ "missing": "Este programa no está en la biblioteca de la holocubierta."+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/holodeck.pt.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/holodeck.pt.jsonnew file mode 100644index 0000000000..e001f76f2b--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/holodeck.pt.json@@ -0,0 +1,10 @@+{+ "ship": {+ "holodeck": {+ "room": "Holodeck",+ "program": "Programa do holodeck",+ "loading": "Carregando o programa…",+ "missing": "Este programa não está na biblioteca do holodeck."+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/holodeck.zh.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/holodeck.zh.jsonnew file mode 100644index 0000000000..f6b44fa603--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/holodeck.zh.json@@ -0,0 +1,10 @@+{+ "ship": {+ "holodeck": {+ "room": "全息甲板",+ "program": "全息甲板程序",+ "loading": "正在载入程序…",+ "missing": "全息甲板的程序库里没有这个程序。"+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/honors.de.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/honors.de.jsonnew file mode 100644index 0000000000..77981d14bd--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/honors.de.json@@ -0,0 +1,8 @@+{+ "ship": {+ "honors": {+ "room": "Ehrenhalle",+ "wall_title": "Die Ränge der Dodaios"+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/honors.en.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/honors.en.jsonnew file mode 100644index 0000000000..4590285dda--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/honors.en.json@@ -0,0 +1,8 @@+{+ "ship": {+ "honors": {+ "room": "Hall of Honour",+ "wall_title": "Ranks of the Dodaios"+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/honors.es.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/honors.es.jsonnew file mode 100644index 0000000000..a2363dcda1--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/honors.es.json@@ -0,0 +1,8 @@+{+ "ship": {+ "honors": {+ "room": "Salón de Honor",+ "wall_title": "Rangos de la Dodaios"+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/honors.pt.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/honors.pt.jsonnew file mode 100644index 0000000000..cf1978a549--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/honors.pt.json@@ -0,0 +1,8 @@+{+ "ship": {+ "honors": {+ "room": "Salão de Honra",+ "wall_title": "Patentes da Dodaios"+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/honors.zh.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/honors.zh.jsonnew file mode 100644index 0000000000..ae5c63337e--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/honors.zh.json@@ -0,0 +1,8 @@+{+ "ship": {+ "honors": {+ "room": "荣誉殿堂",+ "wall_title": "Dodaios 号军衔"+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/levels.de.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/levels.de.jsonnew file mode 100644index 0000000000..f7cae3b382--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/levels.de.json@@ -0,0 +1,173 @@+{+ "ship": {+ "levels": {+ "record": "Dienstakte",+ "open_record": "Deine Dienstakte öffnen",+ "close": "Schließen",+ "unavailable": "Die Dienstakte ist gerade nicht erreichbar. Sie füllt sich, sobald das Schiff das Levelsystem lesen kann.",+ "tabs": {+ "label": "Seiten der Dienstakte",+ "record": "Akte",+ "ranks": "Ränge",+ "rewards": "Belohnungen",+ "earn": "So verdienst du XP",+ "crew": "Crew"+ },+ "who": {+ "captain": "Kapitän",+ "companion": "Begleiter",+ "crew": "Crew"+ },+ "level": "Level {n}",+ "xp": "{n} XP",+ "xp_progress": "{have} von {need} XP",+ "xp_missing": "Noch {n} XP bis Level {level}",+ "at_cap": "Höchstes Level erreicht",+ "next_promotion": "Nächste Beförderung",+ "next_promotion_line": "{rank} ab Level {level}",+ "top_rank": "Du trägst den höchsten Rang an Bord.",+ "next_reward": "Als Nächstes frei",+ "next_reward_line": "{reward} ab Level {level}",+ "all_open": "Alle Belohnungen sind frei.",+ "log": "Logbuch",+ "log_empty": "Noch nichts eingetragen. Sprich mit {name} oder gib der Crew Arbeit, dann steht es hier.",+ "log_promoted": "Befördert: {rank}",+ "log_level": "Level {n} erreicht",+ "log_warp": "Sprung nach {place}",+ "log_deck": "Erster Besuch: {deck}",+ "yesterday": "Gestern",+ "sound": "Klang bei Beförderungen",+ "tier": {+ "enlisted": "Mannschaften",+ "warrant": "Warrant-Ränge",+ "officer": "Offiziere",+ "flag": "Flaggoffiziere"+ },+ "tier_about": {+ "enlisted": "Silberne Winkel. Hier fangen alle an.",+ "warrant": "Ein goldener Rangpunkt: die Brücke zwischen Crew und Kommando.",+ "officer": "Goldene Rangpunkte, vom Ensign bis zum Captain.",+ "flag": "Ein goldener Balken und Sterne. Führt eine Flotte."+ },+ "rank_current": "Dein Rang",+ "rank_held": "Erreicht",+ "to_go": "Noch {n} XP",+ "rewards": {+ "suit": "Anzüge",+ "suit_about": "Was du an Bord trägst. Getragen wird der beste freie Anzug, außer du wählst einen anderen.",+ "destination": "Ziele",+ "destination_about": "Wohin das Steuer Kurs setzen kann. Jedes Ziel öffnet sich mit deinem Level.",+ "decoration": "Auszeichnungen",+ "decoration_about": "Auf der Brust getragen. Auch die Crew verdient sie."+ },+ "suit_choice": "Anzug zum Tragen",+ "auto": "Automatisch",+ "auto_about": "Dein bester Anzug",+ "own": "Eigene Kleidung",+ "own_about": "Keine Uniform",+ "wearing": "Getragen",+ "open_state": "Frei",+ "opens_at": "Frei ab Level {n}",+ "current_course": "Aktueller Kurs",+ "home": "Heimatorbit",+ "earn": {+ "lead": "XP gibt es nur für Echtes: erledigte Arbeit, gewechselte Worte, Zeit an Bord. Jede Grenze hält das Schiff selbst ein.",+ "captain": "Du, der Kapitän",+ "pet": "Dein Begleiter",+ "agent": "Jeder Android der Crew",+ "per_day": "bis zu {n} XP am Tag",+ "every": "höchstens alle {t}",+ "once_day": "einmal am Tag",+ "once_deck": "einmal pro Deck",+ "seconds": "{n} s",+ "minutes": "{n} min"+ },+ "crew": {+ "empty": "Noch keine Androiden an Bord. Stell am Transporter einen ein.",+ "about": "Androiden steigen auf derselben Leiter wie du, indem sie Arbeit erledigen."+ },+ "promotion": {+ "promoted": "Beförderung",+ "level_up": "Level-Aufstieg",+ "away": "Während du weg warst",+ "now_open": "Jetzt frei",+ "continue": "Weiter",+ "agent_promoted": "{agent} wurde befördert: {rank}",+ "agent_level": "{agent} hat Level {n} erreicht"+ },+ "rule": {+ "chat_turn": "Mit {name} im Chat sprechen",+ "voice_turn": "Mit {name} per Sprache sprechen",+ "quest_posted": "Einen Auftrag für die Crew ausschreiben",+ "quest_completed": "Ein Auftrag von dir wird erledigt",+ "agent_hired": "Einen neuen Androiden einstellen",+ "mission_completed": "Eine Mission von dir wird abgenommen",+ "daily_visit": "An Bord kommen",+ "deck_discovered": "Ein Deck zum ersten Mal besuchen",+ "holodeck_round": "Eine gewertete Runde auf dem Holodeck beenden",+ "holodeck_record": "Einen neuen Bestwert auf dem Holodeck aufstellen",+ "team_briefing": "Eine Division zur Besprechung rufen",+ "warp_jump": "Kurs setzen und zu einem Ziel springen",+ "task_done": "Eine Aufgabe erledigen",+ "task_blocked": "Eine Aufgabe mit Grund als blockiert melden",+ "quest_done": "Einen Auftrag erfüllen",+ "answered_teammate": "Die Frage eines Crewmitglieds beantworten",+ "jarvis_answered": "Jede Antwort, die {name} dir gibt",+ "delegated": "Eine Aufgabe an einen Androiden übergeben",+ "walk_together": "Neben dir über die Decks gehen"+ },+ "source": {+ "chat_turn": "Mit {name} geschrieben",+ "voice_turn": "Mit {name} gesprochen",+ "quest_posted": "Auftrag ausgeschrieben",+ "quest_completed": "Auftrag erledigt",+ "agent_hired": "Androiden eingestellt",+ "mission_completed": "Mission abgenommen",+ "daily_visit": "An Bord gekommen",+ "deck_discovered": "Neues Deck besucht",+ "holodeck_round": "Runde auf dem Holodeck gespielt",+ "holodeck_record": "Holodeck-Rekord aufgestellt",+ "team_briefing": "Besprechung abgehalten",+ "warp_jump": "Warpsprung gemacht",+ "task_done": "Aufgabe erledigt",+ "task_blocked": "Blockierte Aufgabe gemeldet",+ "quest_done": "Auftrag erfüllt",+ "answered_teammate": "Einem Crewmitglied geantwortet",+ "jarvis_answered": "Dir geantwortet",+ "delegated": "Aufgabe übergeben",+ "walk_together": "Mit dir gegangen"+ },+ "legacy_source": {+ "floor_discovered": "Eine Etage des alten Büros erkundet",+ "dog_petted": "Den Bürohund gestreichelt",+ "dog_treat": "Dem Bürohund ein Leckerli gegeben",+ "arcade_round": "Eine Runde in der Spielhalle gespielt",+ "arcade_record": "Einen Rekord in der Spielhalle aufgestellt",+ "team_meeting": "Ein Teamtreffen abgehalten",+ "other": "XP verdient"+ },+ "slot": {+ "suit": "Anzug",+ "destination": "Ziel",+ "decoration": "Auszeichnung"+ },+ "reward": {+ "suit_field_armor": "Feldpanzer",+ "suit_command_coat": "Kommandomantel",+ "suit_dress_whites": "Weiße Galauniform",+ "suit_admiral_coat": "Admiralsmantel",+ "destination_gas_giant": "Gebänderter Riese",+ "destination_crimson_nebula": "Karmesinnebel",+ "destination_ice_moon": "Eismond",+ "destination_twin_suns": "Zwillingssonnen",+ "destination_event_horizon": "Ereignishorizont",+ "destination_aurora_world": "Polarlichtwelt",+ "destination_galactic_core": "Galaktischer Kern",+ "decoration_service_ribbon": "Dienstband",+ "decoration_commendation": "Belobigung",+ "decoration_star_medal": "Sternmedaille",+ "decoration_legion_of_merit": "Verdienstlegion"+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/levels.en.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/levels.en.jsonnew file mode 100644index 0000000000..d6aec1d6ae--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/levels.en.json@@ -0,0 +1,173 @@+{+ "ship": {+ "levels": {+ "record": "Service record",+ "open_record": "Open your service record",+ "close": "Close",+ "unavailable": "The service record is out of reach right now. It fills in as soon as the ship can read the level system.",+ "tabs": {+ "label": "Service record pages",+ "record": "Record",+ "ranks": "Ranks",+ "rewards": "Rewards",+ "earn": "How to earn",+ "crew": "Crew"+ },+ "who": {+ "captain": "Captain",+ "companion": "Companion",+ "crew": "Crew"+ },+ "level": "Level {n}",+ "xp": "{n} XP",+ "xp_progress": "{have} of {need} XP",+ "xp_missing": "{n} XP to level {level}",+ "at_cap": "Highest level reached",+ "next_promotion": "Next promotion",+ "next_promotion_line": "{rank} at level {level}",+ "top_rank": "You hold the highest rank aboard.",+ "next_reward": "Opens next",+ "next_reward_line": "{reward} at level {level}",+ "all_open": "Every reward is open.",+ "log": "Ship's log",+ "log_empty": "Nothing logged yet. Talk to {name} or give the crew work, and it is written here.",+ "log_promoted": "Promoted to {rank}",+ "log_level": "Reached level {n}",+ "log_warp": "Jumped to {place}",+ "log_deck": "First visit to the {deck}",+ "yesterday": "Yesterday",+ "sound": "Promotion sound",+ "tier": {+ "enlisted": "Enlisted",+ "warrant": "Warrant",+ "officer": "Officers",+ "flag": "Flag officers"+ },+ "tier_about": {+ "enlisted": "Silver chevrons. Everyone starts here.",+ "warrant": "One gold pip: the bridge between crew and command.",+ "officer": "Gold pips, from ensign to captain.",+ "flag": "A gold bar and stars. Commands a fleet."+ },+ "rank_current": "Your rank",+ "rank_held": "Held",+ "to_go": "{n} XP to go",+ "rewards": {+ "suit": "Suits",+ "suit_about": "What you wear aboard. The finest one open is worn unless you choose another.",+ "destination": "Destinations",+ "destination_about": "Where the helm can set course. Each one opens with your level.",+ "decoration": "Decorations",+ "decoration_about": "Worn on the chest. The crew earns them too."+ },+ "suit_choice": "Suit to wear",+ "auto": "Automatic",+ "auto_about": "The finest suit you have",+ "own": "Own clothes",+ "own_about": "No uniform",+ "wearing": "Wearing",+ "open_state": "Open",+ "opens_at": "Opens at level {n}",+ "current_course": "Current course",+ "home": "Home Orbit",+ "earn": {+ "lead": "XP only comes from real things: work done, words exchanged, time aboard. Every limit is kept by the ship itself.",+ "captain": "You, the captain",+ "pet": "Your companion",+ "agent": "Every android of the crew",+ "per_day": "up to {n} XP a day",+ "every": "at most every {t}",+ "once_day": "once a day",+ "once_deck": "once per deck",+ "seconds": "{n} s",+ "minutes": "{n} min"+ },+ "crew": {+ "empty": "No androids aboard yet. Hire one at the transporter.",+ "about": "Androids climb the same ladder as you, by finishing work."+ },+ "promotion": {+ "promoted": "Promotion",+ "level_up": "Level up",+ "away": "While you were away",+ "now_open": "Now open",+ "continue": "Continue",+ "agent_promoted": "{agent} was promoted to {rank}",+ "agent_level": "{agent} reached level {n}"+ },+ "rule": {+ "chat_turn": "Talk with {name} in the chat",+ "voice_turn": "Talk with {name} by voice",+ "quest_posted": "Post a quest for the crew",+ "quest_completed": "A quest you posted is completed",+ "agent_hired": "Hire a new android",+ "mission_completed": "A mission you started is approved",+ "daily_visit": "Come aboard",+ "deck_discovered": "Visit a deck for the first time",+ "holodeck_round": "Finish a scored round on the holodeck",+ "holodeck_record": "Set a new best on the holodeck",+ "team_briefing": "Call a division to a briefing",+ "warp_jump": "Set course and jump to a destination",+ "task_done": "Finish a task",+ "task_blocked": "Report a task as blocked, with the reason",+ "quest_done": "Complete a quest",+ "answered_teammate": "Answer a crewmate's question",+ "jarvis_answered": "Every answer {name} gives you",+ "delegated": "Hand a task to an android",+ "walk_together": "Walk the decks beside you"+ },+ "source": {+ "chat_turn": "Talked with {name}",+ "voice_turn": "Spoke with {name}",+ "quest_posted": "Posted a quest",+ "quest_completed": "A quest was completed",+ "agent_hired": "Hired an android",+ "mission_completed": "A mission was approved",+ "daily_visit": "Came aboard",+ "deck_discovered": "Visited a new deck",+ "holodeck_round": "Played a round on the holodeck",+ "holodeck_record": "Set a holodeck record",+ "team_briefing": "Held a briefing",+ "warp_jump": "Made a warp jump",+ "task_done": "Finished a task",+ "task_blocked": "Reported a blocked task",+ "quest_done": "Completed a quest",+ "answered_teammate": "Answered a crewmate",+ "jarvis_answered": "Answered you",+ "delegated": "Handed over a task",+ "walk_together": "Walked with you"+ },+ "legacy_source": {+ "floor_discovered": "Explored a floor of the old office",+ "dog_petted": "Petted the office dog",+ "dog_treat": "Gave the office dog a treat",+ "arcade_round": "Played a round in the arcade",+ "arcade_record": "Set an arcade record",+ "team_meeting": "Held a team meeting",+ "other": "Earned XP"+ },+ "slot": {+ "suit": "Suit",+ "destination": "Destination",+ "decoration": "Decoration"+ },+ "reward": {+ "suit_field_armor": "Field Armour",+ "suit_command_coat": "Command Coat",+ "suit_dress_whites": "Dress Whites",+ "suit_admiral_coat": "Admiral's Coat",+ "destination_gas_giant": "Banded Giant",+ "destination_crimson_nebula": "Crimson Nebula",+ "destination_ice_moon": "Ice Moon",+ "destination_twin_suns": "Twin Suns",+ "destination_event_horizon": "Event Horizon",+ "destination_aurora_world": "Aurora World",+ "destination_galactic_core": "Galactic Core",+ "decoration_service_ribbon": "Service Ribbon",+ "decoration_commendation": "Commendation",+ "decoration_star_medal": "Star Medal",+ "decoration_legion_of_merit": "Legion of Merit"+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/levels.es.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/levels.es.jsonnew file mode 100644index 0000000000..b80824c81b--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/levels.es.json@@ -0,0 +1,173 @@+{+ "ship": {+ "levels": {+ "record": "Hoja de servicio",+ "open_record": "Abrir tu hoja de servicio",+ "close": "Cerrar",+ "unavailable": "La hoja de servicio no está disponible ahora mismo. Se completará en cuanto la nave pueda leer el sistema de niveles.",+ "tabs": {+ "label": "Páginas de la hoja de servicio",+ "record": "Hoja",+ "ranks": "Rangos",+ "rewards": "Recompensas",+ "earn": "Cómo ganar XP",+ "crew": "Tripulación"+ },+ "who": {+ "captain": "Capitán",+ "companion": "Compañero",+ "crew": "Tripulación"+ },+ "level": "Nivel {n}",+ "xp": "{n} XP",+ "xp_progress": "{have} de {need} XP",+ "xp_missing": "Faltan {n} XP para el nivel {level}",+ "at_cap": "Nivel máximo alcanzado",+ "next_promotion": "Próximo ascenso",+ "next_promotion_line": "{rank} en el nivel {level}",+ "top_rank": "Tienes el rango más alto a bordo.",+ "next_reward": "Lo próximo que se abre",+ "next_reward_line": "{reward} en el nivel {level}",+ "all_open": "Todas las recompensas están abiertas.",+ "log": "Cuaderno de bitácora",+ "log_empty": "Aún no hay nada anotado. Habla con {name} o dale trabajo a la tripulación y aparecerá aquí.",+ "log_promoted": "Ascendido a {rank}",+ "log_level": "Nivel {n} alcanzado",+ "log_warp": "Salto a {place}",+ "log_deck": "Primera visita: {deck}",+ "yesterday": "Ayer",+ "sound": "Sonido de ascenso",+ "tier": {+ "enlisted": "Marinería",+ "warrant": "Suboficiales mayores",+ "officer": "Oficiales",+ "flag": "Oficiales de bandera"+ },+ "tier_about": {+ "enlisted": "Galones de plata. Todos empiezan aquí.",+ "warrant": "Un punto dorado: el puente entre la tripulación y el mando.",+ "officer": "Puntos dorados, de alférez a capitán.",+ "flag": "Una barra dorada y estrellas. Manda una flota."+ },+ "rank_current": "Tu rango",+ "rank_held": "Conseguido",+ "to_go": "Faltan {n} XP",+ "rewards": {+ "suit": "Trajes",+ "suit_about": "Lo que llevas a bordo. Se viste el mejor traje abierto, salvo que elijas otro.",+ "destination": "Destinos",+ "destination_about": "Hacia dónde puede fijar rumbo el timón. Cada uno se abre con tu nivel.",+ "decoration": "Condecoraciones",+ "decoration_about": "Se llevan en el pecho. La tripulación también las gana."+ },+ "suit_choice": "Traje que llevas",+ "auto": "Automático",+ "auto_about": "Tu mejor traje",+ "own": "Ropa propia",+ "own_about": "Sin uniforme",+ "wearing": "Puesto",+ "open_state": "Abierto",+ "opens_at": "Se abre en el nivel {n}",+ "current_course": "Rumbo actual",+ "home": "Órbita de origen",+ "earn": {+ "lead": "La XP solo llega por cosas reales: trabajo hecho, palabras cruzadas, tiempo a bordo. La propia nave vigila cada límite.",+ "captain": "Tú, el capitán",+ "pet": "Tu compañero",+ "agent": "Cada androide de la tripulación",+ "per_day": "hasta {n} XP al día",+ "every": "como mucho cada {t}",+ "once_day": "una vez al día",+ "once_deck": "una vez por cubierta",+ "seconds": "{n} s",+ "minutes": "{n} min"+ },+ "crew": {+ "empty": "Aún no hay androides a bordo. Contrata uno en el transportador.",+ "about": "Los androides suben la misma escala que tú, terminando trabajo."+ },+ "promotion": {+ "promoted": "Ascenso",+ "level_up": "Subida de nivel",+ "away": "Mientras no estabas",+ "now_open": "Ya abierto",+ "continue": "Continuar",+ "agent_promoted": "{agent} ha ascendido a {rank}",+ "agent_level": "{agent} ha alcanzado el nivel {n}"+ },+ "rule": {+ "chat_turn": "Hablar con {name} en el chat",+ "voice_turn": "Hablar con {name} por voz",+ "quest_posted": "Publicar una misión para la tripulación",+ "quest_completed": "Se completa una misión que publicaste",+ "agent_hired": "Contratar un androide nuevo",+ "mission_completed": "Se aprueba una misión que iniciaste",+ "daily_visit": "Subir a bordo",+ "deck_discovered": "Visitar una cubierta por primera vez",+ "holodeck_round": "Terminar una ronda con puntuación en la holocubierta",+ "holodeck_record": "Batir tu récord en la holocubierta",+ "team_briefing": "Convocar a una división a una reunión",+ "warp_jump": "Fijar rumbo y saltar a un destino",+ "task_done": "Terminar una tarea",+ "task_blocked": "Informar de una tarea bloqueada, con el motivo",+ "quest_done": "Completar una misión",+ "answered_teammate": "Responder a la pregunta de un compañero",+ "jarvis_answered": "Cada respuesta que te da {name}",+ "delegated": "Pasar una tarea a un androide",+ "walk_together": "Recorrer las cubiertas a tu lado"+ },+ "source": {+ "chat_turn": "Habló con {name}",+ "voice_turn": "Conversó con {name} por voz",+ "quest_posted": "Publicó una misión",+ "quest_completed": "Se completó una misión",+ "agent_hired": "Contrató un androide",+ "mission_completed": "Se aprobó una misión",+ "daily_visit": "Subió a bordo",+ "deck_discovered": "Visitó una cubierta nueva",+ "holodeck_round": "Jugó una ronda en la holocubierta",+ "holodeck_record": "Batió un récord en la holocubierta",+ "team_briefing": "Celebró una reunión",+ "warp_jump": "Hizo un salto warp",+ "task_done": "Terminó una tarea",+ "task_blocked": "Informó de una tarea bloqueada",+ "quest_done": "Completó una misión",+ "answered_teammate": "Respondió a un compañero",+ "jarvis_answered": "Te respondió",+ "delegated": "Pasó una tarea",+ "walk_together": "Caminó contigo"+ },+ "legacy_source": {+ "floor_discovered": "Exploró una planta de la antigua oficina",+ "dog_petted": "Acarició al perro de la oficina",+ "dog_treat": "Dio un premio al perro de la oficina",+ "arcade_round": "Jugó una ronda en la sala de juegos",+ "arcade_record": "Batió un récord en la sala de juegos",+ "team_meeting": "Celebró una reunión de equipo",+ "other": "Ganó XP"+ },+ "slot": {+ "suit": "Traje",+ "destination": "Destino",+ "decoration": "Condecoración"+ },+ "reward": {+ "suit_field_armor": "Armadura de campaña",+ "suit_command_coat": "Abrigo de mando",+ "suit_dress_whites": "Uniforme blanco de gala",+ "suit_admiral_coat": "Abrigo de almirante",+ "destination_gas_giant": "Gigante de bandas",+ "destination_crimson_nebula": "Nebulosa carmesí",+ "destination_ice_moon": "Luna helada",+ "destination_twin_suns": "Soles gemelos",+ "destination_event_horizon": "Horizonte de sucesos",+ "destination_aurora_world": "Mundo de auroras",+ "destination_galactic_core": "Núcleo galáctico",+ "decoration_service_ribbon": "Cinta de servicio",+ "decoration_commendation": "Mención de honor",+ "decoration_star_medal": "Medalla de la estrella",+ "decoration_legion_of_merit": "Legión al mérito"+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/levels.pt.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/levels.pt.jsonnew file mode 100644index 0000000000..61cfbbd5f2--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/levels.pt.json@@ -0,0 +1,173 @@+{+ "ship": {+ "levels": {+ "record": "Folha de serviço",+ "open_record": "Abrir a tua folha de serviço",+ "close": "Fechar",+ "unavailable": "A folha de serviço não está disponível neste momento. Fica completa assim que a nave conseguir ler o sistema de níveis.",+ "tabs": {+ "label": "Páginas da folha de serviço",+ "record": "Folha",+ "ranks": "Postos",+ "rewards": "Recompensas",+ "earn": "Como ganhar XP",+ "crew": "Tripulação"+ },+ "who": {+ "captain": "Capitão",+ "companion": "Companheiro",+ "crew": "Tripulação"+ },+ "level": "Nível {n}",+ "xp": "{n} XP",+ "xp_progress": "{have} de {need} XP",+ "xp_missing": "Faltam {n} XP para o nível {level}",+ "at_cap": "Nível máximo atingido",+ "next_promotion": "Próxima promoção",+ "next_promotion_line": "{rank} no nível {level}",+ "top_rank": "Tens o posto mais alto a bordo.",+ "next_reward": "A seguir abre",+ "next_reward_line": "{reward} no nível {level}",+ "all_open": "Todas as recompensas estão abertas.",+ "log": "Diário de bordo",+ "log_empty": "Ainda nada registado. Fala com o {name} ou dá trabalho à tripulação e fica escrito aqui.",+ "log_promoted": "Promovido a {rank}",+ "log_level": "Nível {n} atingido",+ "log_warp": "Salto para {place}",+ "log_deck": "Primeira visita: {deck}",+ "yesterday": "Ontem",+ "sound": "Som de promoção",+ "tier": {+ "enlisted": "Praças",+ "warrant": "Subalternos",+ "officer": "Oficiais",+ "flag": "Oficiais-generais"+ },+ "tier_about": {+ "enlisted": "Divisas de prata. Todos começam aqui.",+ "warrant": "Um ponto dourado: a ponte entre a tripulação e o comando.",+ "officer": "Pontos dourados, de guarda-marinha a capitão.",+ "flag": "Uma barra dourada e estrelas. Comanda uma frota."+ },+ "rank_current": "O teu posto",+ "rank_held": "Conquistado",+ "to_go": "Faltam {n} XP",+ "rewards": {+ "suit": "Fatos",+ "suit_about": "O que vestes a bordo. Usa-se o melhor fato aberto, a menos que escolhas outro.",+ "destination": "Destinos",+ "destination_about": "Para onde o leme pode traçar rumo. Cada um abre com o teu nível.",+ "decoration": "Condecorações",+ "decoration_about": "Usadas ao peito. A tripulação também as ganha."+ },+ "suit_choice": "Fato a vestir",+ "auto": "Automático",+ "auto_about": "O teu melhor fato",+ "own": "Roupa própria",+ "own_about": "Sem farda",+ "wearing": "Vestido",+ "open_state": "Aberto",+ "opens_at": "Abre no nível {n}",+ "current_course": "Rumo atual",+ "home": "Órbita natal",+ "earn": {+ "lead": "O XP só vem de coisas reais: trabalho feito, palavras trocadas, tempo a bordo. É a própria nave que cumpre cada limite.",+ "captain": "Tu, o capitão",+ "pet": "O teu companheiro",+ "agent": "Cada androide da tripulação",+ "per_day": "até {n} XP por dia",+ "every": "no máximo a cada {t}",+ "once_day": "uma vez por dia",+ "once_deck": "uma vez por convés",+ "seconds": "{n} s",+ "minutes": "{n} min"+ },+ "crew": {+ "empty": "Ainda não há androides a bordo. Contrata um no teletransportador.",+ "about": "Os androides sobem a mesma escada que tu, terminando trabalho."+ },+ "promotion": {+ "promoted": "Promoção",+ "level_up": "Subida de nível",+ "away": "Enquanto estiveste fora",+ "now_open": "Agora aberto",+ "continue": "Continuar",+ "agent_promoted": "{agent} foi promovido a {rank}",+ "agent_level": "{agent} atingiu o nível {n}"+ },+ "rule": {+ "chat_turn": "Falar com o {name} no chat",+ "voice_turn": "Falar com o {name} por voz",+ "quest_posted": "Publicar uma missão para a tripulação",+ "quest_completed": "Uma missão que publicaste é concluída",+ "agent_hired": "Contratar um novo androide",+ "mission_completed": "Uma missão que iniciaste é aprovada",+ "daily_visit": "Subir a bordo",+ "deck_discovered": "Visitar um convés pela primeira vez",+ "holodeck_round": "Terminar uma ronda com pontuação no holodeck",+ "holodeck_record": "Bater o teu recorde no holodeck",+ "team_briefing": "Chamar uma divisão para uma reunião",+ "warp_jump": "Traçar rumo e saltar para um destino",+ "task_done": "Terminar uma tarefa",+ "task_blocked": "Comunicar uma tarefa bloqueada, com o motivo",+ "quest_done": "Concluir uma missão",+ "answered_teammate": "Responder à pergunta de um colega",+ "jarvis_answered": "Cada resposta que o {name} te dá",+ "delegated": "Passar uma tarefa a um androide",+ "walk_together": "Percorrer os conveses ao teu lado"+ },+ "source": {+ "chat_turn": "Falou com o {name}",+ "voice_turn": "Conversou com o {name} por voz",+ "quest_posted": "Publicou uma missão",+ "quest_completed": "Uma missão foi concluída",+ "agent_hired": "Contratou um androide",+ "mission_completed": "Uma missão foi aprovada",+ "daily_visit": "Subiu a bordo",+ "deck_discovered": "Visitou um convés novo",+ "holodeck_round": "Jogou uma ronda no holodeck",+ "holodeck_record": "Bateu um recorde no holodeck",+ "team_briefing": "Fez uma reunião",+ "warp_jump": "Fez um salto warp",+ "task_done": "Terminou uma tarefa",+ "task_blocked": "Comunicou uma tarefa bloqueada",+ "quest_done": "Concluiu uma missão",+ "answered_teammate": "Respondeu a um colega",+ "jarvis_answered": "Respondeu-te",+ "delegated": "Passou uma tarefa",+ "walk_together": "Caminhou contigo"+ },+ "legacy_source": {+ "floor_discovered": "Explorou um piso do antigo escritório",+ "dog_petted": "Fez festas ao cão do escritório",+ "dog_treat": "Deu um biscoito ao cão do escritório",+ "arcade_round": "Jogou uma ronda na sala de jogos",+ "arcade_record": "Bateu um recorde na sala de jogos",+ "team_meeting": "Fez uma reunião de equipa",+ "other": "Ganhou XP"+ },+ "slot": {+ "suit": "Fato",+ "destination": "Destino",+ "decoration": "Condecoração"+ },+ "reward": {+ "suit_field_armor": "Armadura de campanha",+ "suit_command_coat": "Casaco de comando",+ "suit_dress_whites": "Farda branca de gala",+ "suit_admiral_coat": "Casaco de almirante",+ "destination_gas_giant": "Gigante listrado",+ "destination_crimson_nebula": "Nebulosa carmesim",+ "destination_ice_moon": "Lua gelada",+ "destination_twin_suns": "Sóis gêmeos",+ "destination_event_horizon": "Horizonte de eventos",+ "destination_aurora_world": "Mundo de auroras",+ "destination_galactic_core": "Núcleo galáctico",+ "decoration_service_ribbon": "Fita de serviço",+ "decoration_commendation": "Louvor",+ "decoration_star_medal": "Medalha da estrela",+ "decoration_legion_of_merit": "Legião de mérito"+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/levels.zh.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/levels.zh.jsonnew file mode 100644index 0000000000..e416fb3ef5--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/levels.zh.json@@ -0,0 +1,173 @@+{+ "ship": {+ "levels": {+ "record": "服役档案",+ "open_record": "打开你的服役档案",+ "close": "关闭",+ "unavailable": "服役档案暂时无法读取。飞船一旦能读取等级系统,就会自动补全。",+ "tabs": {+ "label": "服役档案页面",+ "record": "档案",+ "ranks": "军衔",+ "rewards": "奖励",+ "earn": "如何获得经验",+ "crew": "船员"+ },+ "who": {+ "captain": "舰长",+ "companion": "伙伴",+ "crew": "船员"+ },+ "level": "{n} 级",+ "xp": "{n} 经验",+ "xp_progress": "{have} / {need} 经验",+ "xp_missing": "距 {level} 级还差 {n} 经验",+ "at_cap": "已达最高等级",+ "next_promotion": "下次晋升",+ "next_promotion_line": "{level} 级晋升为{rank}",+ "top_rank": "你已是舰上最高军衔。",+ "next_reward": "下一项解锁",+ "next_reward_line": "{level} 级解锁{reward}",+ "all_open": "所有奖励均已解锁。",+ "log": "航海日志",+ "log_empty": "日志里还没有记录。和 {name} 聊聊,或给船员派活,就会写在这里。",+ "log_promoted": "晋升为{rank}",+ "log_level": "达到 {n} 级",+ "log_warp": "跃迁至{place}",+ "log_deck": "首次到访:{deck}",+ "yesterday": "昨天",+ "sound": "晋升音效",+ "tier": {+ "enlisted": "士兵",+ "warrant": "准尉",+ "officer": "军官",+ "flag": "将官"+ },+ "tier_about": {+ "enlisted": "银色臂章。人人从这里起步。",+ "warrant": "一枚金色衔星:船员与指挥层之间的桥梁。",+ "officer": "金色衔星,从少尉到舰长。",+ "flag": "一道金条加星。统领一支舰队。"+ },+ "rank_current": "你的军衔",+ "rank_held": "已获得",+ "to_go": "还差 {n} 经验",+ "rewards": {+ "suit": "服装",+ "suit_about": "你在舰上的穿着。默认穿最好的已解锁服装,也可以自己选。",+ "destination": "目的地",+ "destination_about": "舵手可以设定航向的地方。每个目的地随你的等级解锁。",+ "decoration": "勋章",+ "decoration_about": "佩戴在胸前。船员也能获得。"+ },+ "suit_choice": "要穿的服装",+ "auto": "自动",+ "auto_about": "你最好的服装",+ "own": "自己的衣服",+ "own_about": "不穿制服",+ "wearing": "穿着中",+ "open_state": "已解锁",+ "opens_at": "{n} 级解锁",+ "current_course": "当前航向",+ "home": "母星轨道",+ "earn": {+ "lead": "经验只来自真实的事:完成的工作、交流的话语、在舰上的时间。每条限制都由飞船自己把关。",+ "captain": "你,舰长",+ "pet": "你的伙伴",+ "agent": "每一位仿生船员",+ "per_day": "每天最多 {n} 经验",+ "every": "最多每 {t} 一次",+ "once_day": "每天一次",+ "once_deck": "每层甲板一次",+ "seconds": "{n} 秒",+ "minutes": "{n} 分钟"+ },+ "crew": {+ "empty": "舰上还没有仿生人。去传送台雇一位吧。",+ "about": "仿生人和你爬同一架军衔梯,靠的是完成工作。"+ },+ "promotion": {+ "promoted": "晋升",+ "level_up": "升级",+ "away": "你不在时",+ "now_open": "现已解锁",+ "continue": "继续",+ "agent_promoted": "{agent} 晋升为{rank}",+ "agent_level": "{agent} 达到 {n} 级"+ },+ "rule": {+ "chat_turn": "在聊天中和 {name} 交谈",+ "voice_turn": "用语音和 {name} 交谈",+ "quest_posted": "给船员发布任务",+ "quest_completed": "你发布的任务被完成",+ "agent_hired": "雇用一位新的仿生人",+ "mission_completed": "你发起的行动获批通过",+ "daily_visit": "登舰",+ "deck_discovered": "首次到访一层甲板",+ "holodeck_round": "在全息甲板完成一局计分游戏",+ "holodeck_record": "在全息甲板刷新最好成绩",+ "team_briefing": "召集一个分队开简报会",+ "warp_jump": "设定航向并跃迁到目的地",+ "task_done": "完成一项工作",+ "task_blocked": "报告一项受阻的工作并说明原因",+ "quest_done": "完成一个任务",+ "answered_teammate": "回答船员同伴的问题",+ "jarvis_answered": "{name} 给你的每一次回答",+ "delegated": "把工作交给一位仿生人",+ "walk_together": "在你身边走过各层甲板"+ },+ "source": {+ "chat_turn": "和 {name} 聊天",+ "voice_turn": "和 {name} 语音交谈",+ "quest_posted": "发布了任务",+ "quest_completed": "任务已完成",+ "agent_hired": "雇用了仿生人",+ "mission_completed": "行动获批",+ "daily_visit": "登舰",+ "deck_discovered": "到访新甲板",+ "holodeck_round": "在全息甲板玩了一局",+ "holodeck_record": "刷新全息甲板纪录",+ "team_briefing": "开了简报会",+ "warp_jump": "完成一次跃迁",+ "task_done": "完成了工作",+ "task_blocked": "报告了受阻的工作",+ "quest_done": "完成了任务",+ "answered_teammate": "回答了同伴",+ "jarvis_answered": "回答了你",+ "delegated": "交出了工作",+ "walk_together": "陪你散步"+ },+ "legacy_source": {+ "floor_discovered": "探索了旧办公楼的一层",+ "dog_petted": "摸了摸办公室的狗",+ "dog_treat": "给办公室的狗喂了零食",+ "arcade_round": "在游戏厅玩了一局",+ "arcade_record": "刷新游戏厅纪录",+ "team_meeting": "开了团队会议",+ "other": "获得经验"+ },+ "slot": {+ "suit": "服装",+ "destination": "目的地",+ "decoration": "勋章"+ },+ "reward": {+ "suit_field_armor": "野战护甲",+ "suit_command_coat": "指挥大衣",+ "suit_dress_whites": "白色礼服",+ "suit_admiral_coat": "上将大衣",+ "destination_gas_giant": "条纹巨星",+ "destination_crimson_nebula": "绯红星云",+ "destination_ice_moon": "冰月",+ "destination_twin_suns": "双日",+ "destination_event_horizon": "事件视界",+ "destination_aurora_world": "极光世界",+ "destination_galactic_core": "银河核心",+ "decoration_service_ribbon": "服役绶带",+ "decoration_commendation": "嘉奖令",+ "decoration_star_medal": "星章",+ "decoration_legion_of_merit": "功勋军团勋章"+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/ops.de.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/ops.de.jsonnew file mode 100644index 0000000000..a8ba38ee2d--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/ops.de.json@@ -0,0 +1,37 @@+{+ "ship": {+ "ops": {+ "quartermaster": {+ "title": "Dein Anzug",+ "cut": "Schnitt",+ "suit": "Anzug",+ "trim": "Besatz",+ "visor": "Visier",+ "open": "Verfügbar",+ "at_level": "Ab Level {n}",+ "note": "Änderungen siehst du sofort an deinem Captain; sie bleiben auf diesem Computer gespeichert.",+ "cuts": {+ "duty": "Dienstanzug",+ "field_armor": "Feldpanzerung",+ "command_coat": "Kommandomantel",+ "dress_whites": "Galauniform",+ "admiral_coat": "Admiralsmantel",+ "auto": "Bester verfügbarer"+ }+ },+ "division": {+ "eyebrow": "Division",+ "lead": "Lead",+ "empty": "Hier sitzt noch niemand.",+ "open_chat": "Team-Chat öffnen",+ "open_agents": "Agent-Liste öffnen",+ "briefing": "Briefing einberufen",+ "end_briefing": "Briefing beenden",+ "briefing_called": "{count} aus {team} kommen an den Tisch.",+ "briefing_over": "Briefing vorbei: Alle gehen zurück.",+ "nobody_free": "Gerade arbeiten alle in dieser Division.",+ "note": "Ein Briefing versammelt das Team nur auf dem Schiff an seinem Tisch; ans Team wird nichts geschickt und niemand beginnt zu arbeiten."+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/ops.en.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/ops.en.jsonnew file mode 100644index 0000000000..9c7c9f6bbc--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/ops.en.json@@ -0,0 +1,37 @@+{+ "ship": {+ "ops": {+ "quartermaster": {+ "title": "Your suit",+ "cut": "Cut",+ "suit": "Suit",+ "trim": "Trim",+ "visor": "Visor",+ "open": "Open",+ "at_level": "Opens at level {n}",+ "note": "Changes show on your captain at once and are kept on this computer.",+ "cuts": {+ "duty": "Duty suit",+ "field_armor": "Field armour",+ "command_coat": "Command coat",+ "dress_whites": "Dress whites",+ "admiral_coat": "Admiral's coat",+ "auto": "Finest open"+ }+ },+ "division": {+ "eyebrow": "Division",+ "lead": "Lead",+ "empty": "Nobody sits here yet.",+ "open_chat": "Open team chat",+ "open_agents": "Open the agents list",+ "briefing": "Call a briefing",+ "end_briefing": "End the briefing",+ "briefing_called": "{count} of {team} are coming to the table.",+ "briefing_over": "Briefing over: everyone heads back.",+ "nobody_free": "Everyone in this division is working right now.",+ "note": "A briefing only gathers the team at its table on the ship; nothing is sent to the team and nobody starts work."+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/ops.es.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/ops.es.jsonnew file mode 100644index 0000000000..235ba72cad--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/ops.es.json@@ -0,0 +1,37 @@+{+ "ship": {+ "ops": {+ "quartermaster": {+ "title": "Tu traje",+ "cut": "Corte",+ "suit": "Traje",+ "trim": "Ribete",+ "visor": "Visor",+ "open": "Disponible",+ "at_level": "Se abre en el nivel {n}",+ "note": "Los cambios se ven en tu capitán al instante y se guardan en este ordenador.",+ "cuts": {+ "duty": "Traje de servicio",+ "field_armor": "Armadura de campo",+ "command_coat": "Abrigo de mando",+ "dress_whites": "Uniforme de gala",+ "admiral_coat": "Abrigo de almirante",+ "auto": "El mejor disponible"+ }+ },+ "division": {+ "eyebrow": "División",+ "lead": "Líder",+ "empty": "Aquí aún no se sienta nadie.",+ "open_chat": "Abrir el chat del equipo",+ "open_agents": "Abrir la lista de agentes",+ "briefing": "Convocar una reunión",+ "end_briefing": "Terminar la reunión",+ "briefing_called": "{count} de {team} vienen a la mesa.",+ "briefing_over": "Fin de la reunión: todos vuelven.",+ "nobody_free": "Ahora mismo todos en esta división están trabajando.",+ "note": "Una reunión solo reúne al equipo en su mesa de la nave; no se envía nada al equipo y nadie empieza a trabajar."+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/ops.pt.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/ops.pt.jsonnew file mode 100644index 0000000000..7eb1f56211--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/ops.pt.json@@ -0,0 +1,37 @@+{+ "ship": {+ "ops": {+ "quartermaster": {+ "title": "O teu fato",+ "cut": "Corte",+ "suit": "Fato",+ "trim": "Debrum",+ "visor": "Viseira",+ "open": "Disponível",+ "at_level": "Abre no nível {n}",+ "note": "As alterações aparecem logo no teu capitão e ficam guardadas neste computador.",+ "cuts": {+ "duty": "Fato de serviço",+ "field_armor": "Armadura de campo",+ "command_coat": "Casaco de comando",+ "dress_whites": "Uniforme de gala",+ "admiral_coat": "Casaco de almirante",+ "auto": "O melhor disponível"+ }+ },+ "division": {+ "eyebrow": "Divisão",+ "lead": "Líder",+ "empty": "Ainda ninguém se senta aqui.",+ "open_chat": "Abrir o chat da equipa",+ "open_agents": "Abrir a lista de agentes",+ "briefing": "Convocar um briefing",+ "end_briefing": "Terminar o briefing",+ "briefing_called": "{count} de {team} vêm à mesa.",+ "briefing_over": "Fim do briefing: todos voltam.",+ "nobody_free": "Agora todos nesta divisão estão a trabalhar.",+ "note": "Um briefing só reúne a equipa à sua mesa na nave; nada é enviado à equipa e ninguém começa a trabalhar."+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/ops.zh.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/ops.zh.jsonnew file mode 100644index 0000000000..7d197b7077--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/ops.zh.json@@ -0,0 +1,37 @@+{+ "ship": {+ "ops": {+ "quartermaster": {+ "title": "你的制服",+ "cut": "款式",+ "suit": "制服",+ "trim": "饰边",+ "visor": "面罩",+ "open": "可用",+ "at_level": "{n} 级开放",+ "note": "更改会立即显示在你的舰长身上,并保存在这台电脑上。",+ "cuts": {+ "duty": "值勤服",+ "field_armor": "野战装甲",+ "command_coat": "指挥大衣",+ "dress_whites": "礼服",+ "admiral_coat": "上将大衣",+ "auto": "最佳可用"+ }+ },+ "division": {+ "eyebrow": "分部",+ "lead": "负责人",+ "empty": "这里还没有人。",+ "open_chat": "打开团队聊天",+ "open_agents": "打开智能体列表",+ "briefing": "召开简报会",+ "end_briefing": "结束简报会",+ "briefing_called": "{team} 的 {count} 名成员正前往桌边。",+ "briefing_over": "简报结束:大家都回去了。",+ "nobody_free": "这个分部现在所有人都在工作。",+ "note": "简报只是在飞船上把团队聚到桌边;不会向团队发送任何内容,也不会有人开始工作。"+ }+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/pt.jsonnew file mode 100644index 0000000000..eac2b15a8b--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/pt.json@@ -0,0 +1,110 @@+{+ "ship": {+ "title": "Dodaios Verse",+ "fallback": "A nave precisa de WebGL, que esta vista não consegue iniciar agora.",+ "loading": "A embarcar…",+ "click": "Clique",+ "close": "Fechar",+ "level": "Nível {n}",+ "help": "Caminha com WASD ou com um clique no convés. Arrasta para olhar, desliza para fazer zoom. E usa o que tens à frente, O mostra o convés inteiro.",+ "deck": {+ "label": "Convés {n}",+ "bridge": "Ponte",+ "bridge_about": "Comando, o leme e o teu primeiro oficial",+ "ops": "Operações",+ "ops_about": "As divisões dos teus agentes, o refeitório e o transportador",+ "engineering": "Engenharia",+ "engineering_about": "Agentes de código a trabalhar à volta do reator",+ "holodeck": "Holodeck",+ "holodeck_about": "Dez jogos para jogar",+ "honors": "Salão de Honra",+ "honors_about": "Patentes, promoções e a tua folha de serviço"+ },+ "crew": {+ "working": "{count} a trabalhar",+ "waiting": "{count} à espera",+ "idle": "{count} de folga"+ },+ "state": {+ "working": "A trabalhar",+ "waiting": "Precisa de ti",+ "idle": "De folga",+ "paused": "A descansar",+ "error": "Falhou",+ "vacant": "Livre"+ },+ "room": {+ "lounge": "Sala de observação",+ "quartermaster": "Intendência",+ "pods": "Cápsulas de descanso",+ "lift": "Turboelevador",+ "garden": "Hidroponia"+ },+ "division": {+ "pool": "Tripulação sem equipa",+ "free": "Baía livre"+ },+ "screen": {+ "standby": "Em espera",+ "vacant": "Livre"+ },+ "station": {+ "transporter": { "action": "Transportar um novo agente", "name": "Transportador" },+ "lift": { "action": "Chamar o turboelevador", "name": "Turboelevador" },+ "division": { "action": "Abrir a equipa", "name": "Holomesa" },+ "newDivision": { "action": "Fundar uma equipa aqui", "name": "Baía livre" },+ "quartermaster": { "action": "Mudar de fato", "name": "Intendência", "soon": "A intendência abre no próximo passo da construção." },+ "mess": {+ "action": "Chamar a tripulação ao refeitório",+ "name": "Cozinha",+ "called": "{count} agentes de folga vão para o refeitório.",+ "nobody": "Ninguém está de folga agora.",+ "ended": "Fim da pausa: todos voltam."+ },+ "captain": { "action": "Sentar-te na cadeira do capitão", "name": "Cadeira do capitão" },+ "firstOfficer": { "action": "Falar com o teu primeiro oficial", "name": "Primeiro oficial" },+ "helm": { "action": "Definir um rumo", "name": "Leme" },+ "ops": { "action": "Abrir o diretório da tripulação", "name": "Mesa de operações" },+ "systems": { "action": "Lançar agentes de código", "name": "Ecrã de sistemas" },+ "holoCabinet": { "action": "Jogar", "name": "Holomáquina" },+ "rankWall": { "action": "Abrir a tua folha de serviço", "name": "Parede de patentes" },+ "honorCase": { "action": "Ver", "name": "Vitrine" },+ "pods": { "action": "Espreitar", "name": "Cápsulas de descanso" }+ },+ "agent": {+ "open_chat": "Abrir chat",+ "walk_there": "Ir até lá",+ "show": "Mostrar"+ },+ "lift": {+ "title": "Turboelevador",+ "here": "Estás aqui"+ },+ "tools": {+ "label": "Controlos da nave",+ "follow": "Seguir-me",+ "overview": "Convés inteiro",+ "lift": "Turboelevador",+ "help": "Controlos"+ },+ "rank": {+ "record_soon": "A tua folha de serviço abre-se no Salão de Honra.",+ "cadet": "Cadete",+ "crewman": "Tripulante",+ "specialist": "Especialista",+ "petty_officer": "Sargento",+ "chief_petty_officer": "Sargento-chefe",+ "warrant_officer": "Subtenente",+ "ensign": "Guarda-marinha",+ "lieutenant_junior_grade": "Segundo-tenente",+ "lieutenant": "Primeiro-tenente",+ "lieutenant_commander": "Capitão-tenente",+ "commander": "Capitão-de-fragata",+ "captain": "Capitão-de-mar-e-guerra",+ "commodore": "Comodoro",+ "rear_admiral": "Contra-almirante",+ "vice_admiral": "Vice-almirante",+ "admiral": "Almirante"+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/locales/ship/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/ship/zh.jsonnew file mode 100644index 0000000000..83617ef606--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/locales/ship/zh.json@@ -0,0 +1,110 @@+{+ "ship": {+ "title": "Dodaios Verse",+ "fallback": "飞船需要 WebGL,此视图目前无法启动它。",+ "loading": "正在登船…",+ "click": "点击",+ "close": "关闭",+ "level": "等级 {n}",+ "help": "用 WASD 或点击甲板行走。拖动环顾四周,滚动缩放。E 使用面前的设施,O 显示整层甲板。",+ "deck": {+ "label": "甲板 {n}",+ "bridge": "舰桥",+ "bridge_about": "指挥、舵位和你的大副",+ "ops": "作战甲板",+ "ops_about": "你的智能体分部、餐厅和传送器",+ "engineering": "轮机舱",+ "engineering_about": "编程智能体围绕反应堆工作",+ "holodeck": "全息甲板",+ "holodeck_about": "十款可玩的游戏",+ "honors": "荣誉殿堂",+ "honors_about": "军衔、晋升和你的服役记录"+ },+ "crew": {+ "working": "{count} 工作中",+ "waiting": "{count} 等待中",+ "idle": "{count} 休息中"+ },+ "state": {+ "working": "工作中",+ "waiting": "需要你",+ "idle": "休息中",+ "paused": "休眠中",+ "error": "失败",+ "vacant": "空闲"+ },+ "room": {+ "lounge": "观景休息室",+ "quartermaster": "军需处",+ "pods": "休眠舱",+ "lift": "涡轮电梯",+ "garden": "水培区"+ },+ "division": {+ "pool": "无团队的船员",+ "free": "空闲舱位"+ },+ "screen": {+ "standby": "待命",+ "vacant": "空闲"+ },+ "station": {+ "transporter": { "action": "传送一个新智能体", "name": "传送器" },+ "lift": { "action": "呼叫涡轮电梯", "name": "涡轮电梯" },+ "division": { "action": "打开团队", "name": "全息桌" },+ "newDivision": { "action": "在这里组建团队", "name": "空闲舱位" },+ "quartermaster": { "action": "更换制服", "name": "军需处", "soon": "军需处将在下一个构建步骤开放。" },+ "mess": {+ "action": "召集船员去餐厅",+ "name": "厨房",+ "called": "{count} 名休息中的智能体正前往餐厅。",+ "nobody": "现在没有人在休息。",+ "ended": "休息结束:大家都回去了。"+ },+ "captain": { "action": "坐上舰长席", "name": "舰长席" },+ "firstOfficer": { "action": "与你的大副交谈", "name": "大副" },+ "helm": { "action": "设定航向", "name": "舵位" },+ "ops": { "action": "打开船员名册", "name": "作战桌" },+ "systems": { "action": "启动编程智能体", "name": "主系统显示屏" },+ "holoCabinet": { "action": "开始游戏", "name": "全息游戏机" },+ "rankWall": { "action": "打开你的服役记录", "name": "军衔墙" },+ "honorCase": { "action": "查看", "name": "展示柜" },+ "pods": { "action": "看一看", "name": "休眠舱" }+ },+ "agent": {+ "open_chat": "打开聊天",+ "walk_there": "走过去",+ "show": "显示"+ },+ "lift": {+ "title": "涡轮电梯",+ "here": "你在这里"+ },+ "tools": {+ "label": "飞船控制",+ "follow": "跟随我",+ "overview": "整层甲板",+ "lift": "涡轮电梯",+ "help": "操作说明"+ },+ "rank": {+ "record_soon": "你的服役记录在荣誉殿堂中打开。",+ "cadet": "学员",+ "crewman": "水兵",+ "specialist": "专业军士",+ "petty_officer": "下士",+ "chief_petty_officer": "上士",+ "warrant_officer": "准尉",+ "ensign": "少尉",+ "lieutenant_junior_grade": "中尉",+ "lieutenant": "上尉",+ "lieutenant_commander": "少校",+ "commander": "中校",+ "captain": "上校",+ "commodore": "准将",+ "rear_admiral": "少将",+ "vice_admiral": "中将",+ "admiral": "上将"+ }+ }+}diff --git a/dodaios/ui/web/frontend/src/i18n/ship-locale-parity.test.ts b/dodaios/ui/web/frontend/src/i18n/ship-locale-parity.test.tsnew file mode 100644index 0000000000..b66b1505d7--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/ship-locale-parity.test.ts@@ -0,0 +1,44 @@+import { readdirSync, readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++/** Every ship locale file exists in all five languages with the same keys. */+const DIR = join(__dirname, "locales", "ship");+const LANGS = ["en", "de", "es", "pt", "zh"] as const;++function keys(value: unknown, prefix = ""): string[] {+ if (!value || typeof value !== "object") return [prefix];+ return Object.entries(value as Record<string, unknown>).flatMap(([k, v]) => keys(v, prefix ? `${prefix}.${k}` : k));+}++function areas(): string[] {+ const names = readdirSync(DIR).filter((f) => f.endsWith(".json"));+ const found = new Set<string>();+ for (const name of names) {+ const parts = name.replace(/\.json$/, "").split(".");+ found.add(parts.length === 1 ? "" : parts.slice(0, -1).join("."));+ }+ return [...found];+}++describe("ship locale parity", () => {+ it.each(areas())("area '%s' has the same keys in every language", (area) => {+ const file = (lang: string) => join(DIR, area ? `${area}.${lang}.json` : `${lang}.json`);+ const english = keys(JSON.parse(readFileSync(file("en"), "utf8"))).sort();+ for (const lang of LANGS) {+ const other = keys(JSON.parse(readFileSync(file(lang), "utf8"))).sort();+ expect(other, `${area || "core"} ${lang}`).toEqual(english);+ }+ });++ it("never uses {name} for anything but the assistant (the resolver fills it with the assistant's name)", () => {+ for (const f of readdirSync(DIR).filter((n) => n.endsWith(".json") && !n.startsWith("levels."))) {+ expect(readFileSync(join(DIR, f), "utf8"), f).not.toContain("{name}");+ }+ });++ it("keeps German umlauts real", () => {+ const text = readdirSync(DIR).filter((f) => f.endsWith("de.json")).map((f) => readFileSync(join(DIR, f), "utf8")).join("\n");+ expect(text).not.toMatch(/\b(fuer|ueber|Schliessen|Bruecke|zurueck|oeffnen)\b/);+ });+});diff --git a/dodaios/ui/web/frontend/src/views/JarvisAgentsView.test.tsx b/dodaios/ui/web/frontend/src/views/JarvisAgentsView.test.tsxindex 1b47fd9ccd..7f95c80ae2 100644--- a/dodaios/ui/web/frontend/src/views/JarvisAgentsView.test.tsx+++ b/dodaios/ui/web/frontend/src/views/JarvisAgentsView.test.tsx@@ -5,32 +5,32 @@ import { JarvisAgentsView } from "./JarvisAgentsView";vi.mock("@/i18n", () => ({ useLocaleChunk: () => true }));vi.mock("@/components/society/world/WorldStage", () => ({ WorldStage: () => { throw new Error("Legacy world must not mount"); } }));vi.mock("@/components/society/mars/MarsWorldStage", () => ({ MarsWorldStage: () => { throw new Error("Mars must not mount as the map"); } }));-vi.mock("@/components/society/office/OfficeStage", () => ({ OfficeStage: ({ active, onOpenLedger, onSelectAgent }: any) => <div data-testid="office-map" data-active={active}><button onClick={onOpenLedger}>Open agents</button><button onClick={() => onSelectAgent("a1")}>Agent a1</button></div> }));+vi.mock("@/components/society/starship/ShipStage", () => ({ ShipStage: ({ active, onOpenLedger, onSelectAgent }: any) => <div data-testid="ship-map" data-active={active}><button onClick={onOpenLedger}>Open agents</button><button onClick={() => onSelectAgent("a1")}>Agent a1</button></div> }));const initialUrl = window.location.href;afterEach(() => { cleanup(); window.history.replaceState(null, "", initialUrl); });-it.each(["?view=agents", "?view=agents&world=legacy", "?view=agents&world=mars"])("mounts only the office for %s", async (url) => {+it.each(["?view=agents", "?view=agents&world=legacy", "?view=agents&world=mars"])("mounts only the ship for %s", async (url) => {window.history.replaceState(null, "", url);const openAgents = vi.fn();render(<JarvisAgentsView onOpenAgents={openAgents} />);- expect(await screen.findByTestId("office-map")).toBeTruthy();+ expect(await screen.findByTestId("ship-map")).toBeTruthy();expect(screen.queryByRole("button", { name: /previous|preview/i })).toBeNull();fireEvent.click(screen.getByText("Open agents"));expect(openAgents).toHaveBeenCalledOnce();});-it("forwards an agent picked in the office", async () => {+it("forwards an agent picked on the ship", async () => {const onSelect = vi.fn();render(<JarvisAgentsView onOpenAgents={() => undefined} onSelectAgent={onSelect} />);fireEvent.click(await screen.findByText("Agent a1"));expect(onSelect).toHaveBeenCalledWith("a1");});-it("forwards visibility without replacing the office", () => {+it("forwards visibility without replacing the ship", () => {const view = render(<JarvisAgentsView onOpenAgents={() => undefined} />);- const office = screen.getByTestId("office-map");- expect(office.dataset.active).toBe("true");+ const ship = screen.getByTestId("ship-map");+ expect(ship.dataset.active).toBe("true");view.rerender(<JarvisAgentsView active={false} onOpenAgents={() => undefined} />);- expect(screen.getByTestId("office-map")).toBe(office);- expect(office.dataset.active).toBe("false");+ expect(screen.getByTestId("ship-map")).toBe(ship);+ expect(ship.dataset.active).toBe("false");});diff --git a/dodaios/ui/web/frontend/src/views/JarvisAgentsView.tsx b/dodaios/ui/web/frontend/src/views/JarvisAgentsView.tsxindex 494970e1cf..0fb76042de 100644--- a/dodaios/ui/web/frontend/src/views/JarvisAgentsView.tsx+++ b/dodaios/ui/web/frontend/src/views/JarvisAgentsView.tsx@@ -1,7 +1,7 @@/** Lazy map surface; the parent keeps the existing Agents workspace mounted. */import { useLocaleChunk } from "@/i18n";import type { PlaceId } from "@/components/society/world/islandLayout";-import { OfficeStage } from "@/components/society/office/OfficeStage";+import { ShipStage } from "@/components/society/starship/ShipStage";export interface JarvisAgentsViewProps {onSelectAgent?: (agentId: string | null) => void;@@ -17,7 +17,7 @@ export function JarvisAgentsView({ onSelectAgent, onOpenAgents, onCreateAgent, oif (!ready) return null;return (<div className="h-full min-h-0">- <OfficeStage active={active} onOpenLedger={onOpenAgents} onSelectAgent={onSelectAgent} onCreateAgent={onCreateAgent} onOpenGroup={onOpenGroup} />+ <ShipStage active={active} onOpenLedger={onOpenAgents} onSelectAgent={onSelectAgent} onCreateAgent={onCreateAgent} onOpenGroup={onOpenGroup} /></div>);}diff --git a/dodaios/ui/web/progression_routes.py b/dodaios/ui/web/progression_routes.pyindex 52cd6b41a8..cf82b6f59b 100644--- a/dodaios/ui/web/progression_routes.py+++ b/dodaios/ui/web/progression_routes.py@@ -1,4 +1,4 @@-"""REST API of the Jarvis Verse level system (``dodaios/progression``).+"""REST API of the Dodaios Verse level system (``dodaios/progression``).- ``GET /api/progression`` → every subject's level, the rulebook and recent awards- ``POST /api/progression/actions`` → report a world action from the Verse (metered server-side)@@ -18,6 +18,7 @@ from pydantic import BaseModel, Fieldfrom dodaios.progression.rules import (LOOK_UNLOCKS,MAX_LEVEL,+ RANKS,REWARDS,RULES,TITLES,@@ -58,6 +59,7 @@ def _rulebook() -> dict[str, Any]:}for r in REWARDS],+ "ranks": [{"id": rank, "level": level, "tier": tier} for level, rank, tier in RANKS],"looks": [{"look_id": look, "agent": level} for look, level in LOOK_UNLOCKS.items()],"titles": {kind: [{"level": lvl, "title": t} for lvl, t in bands]@@ -89,7 +91,7 @@ async def get_progression(class WorldAction(BaseModel):action: str = Field(..., max_length=40, description="A world-action source from the rulebook")ref: str = Field(- "", max_length=40, description="The action's subject, e.g. the floor discovered"+ "", max_length=40, description="The action's subject, a deck or a destination")diff --git a/tests/unit/progression/test_frontend_parity.py b/tests/unit/progression/test_frontend_parity.pyindex e6c4eda8bd..59f2df1225 100644--- a/tests/unit/progression/test_frontend_parity.py+++ b/tests/unit/progression/test_frontend_parity.py@@ -1,8 +1,10 @@-"""The Verse's copy of the level-system ids matches the Python rulebook (AP-4).+"""The ship's copy of the level-system ids matches the Python rulebook (AP-4).-``levelCatalog.ts`` only knows what each id looks like; the server owns the-numbers. A reward, title, source or slot added on one side without the other-would render nothing or show a raw key, so the lists must be equal.+``levelCatalog.ts`` names the ids, ``starship/levels/ranks.ts`` draws the+ladder and ``starship/space/destinations.ts`` paints the destinations; the+server owns the numbers. An id added on one side without the other would+render nothing, show a raw key or open a destination at the wrong level, so+the lists must be equal."""from __future__ import annotations@@ -12,18 +14,22 @@ import refrom pathlib import Pathfrom dodaios.progression.rules import (+ DESTINATION_IDS,LOOK_UNLOCKS,+ RANKS,REWARDS,RULES,SLOTS,SUBJECT_KINDS,- TITLES,WORLD_ACTIONS,)+from dodaios.progression.service import VERSE_DECKS_FRONTEND = Path(__file__).resolve().parents[3] / "dodaios/ui/web/frontend/src"_CATALOG = _FRONTEND / "components/society/progression/levelCatalog.ts"-_LOCALES = _FRONTEND / "i18n/locales/society"+_STARSHIP = _FRONTEND / "components/society/starship"+_SHIP_LOCALES = _FRONTEND / "i18n/locales/ship"+_LANGS = ("en", "de", "es", "pt", "zh")def _ts_list(name: str) -> list[str]:@@ -40,26 +46,58 @@ def _ts_union(name: str) -> set[str]:return set(re.findall(r'"([a-z_]+)"', match.group(1)))-def test_kinds_slots_rewards_titles_and_sources_match():+def test_kinds_slots_rewards_ranks_and_sources_match():assert _ts_list("SUBJECT_KINDS") == list(SUBJECT_KINDS)assert _ts_list("SLOTS") == list(SLOTS)assert _ts_list("REWARD_IDS") == [r.reward_id for r in REWARDS]- assert set(_ts_list("TITLE_IDS")) == {t for bands in TITLES.values() for _, t in bands}+ assert _ts_list("RANK_IDS") == [rank for _, rank, _ in RANKS]assert _ts_list("XP_SOURCES") == [r.source for r in RULES]assert _ts_union("WorldAction") == set(WORLD_ACTIONS)-def test_every_id_has_a_label_in_every_language():- titles = {t for bands in TITLES.values() for _, t in bands}- for lang in ("en", "de", "es"):- chunk = json.loads((_LOCALES / f"{lang}.json").read_text(encoding="utf-8"))- level = chunk["society"]["level"]- assert set(level["reward"]) == {r.reward_id for r in REWARDS}, lang- assert set(level["title"]) == titles, lang- assert set(level["source"]) == {r.source for r in RULES}, lang- assert set(level["slot"]) == set(SLOTS), lang- for kind in SUBJECT_KINDS:- assert f"rules_{kind}" in level, (lang, kind)+def test_the_ship_draws_the_same_ladder():+ text = (_STARSHIP / "levels/ranks.ts").read_text(encoding="utf-8")+ ladder = [+ (int(level), rank, tier)+ for rank, level, tier in re.findall(+ r'\{ id: "([a-z_]+)", level: (\d+), tier: "([a-z]+)"', text+ )+ ]+ assert ladder == list(RANKS)+++def test_destinations_open_at_the_rulebooks_levels():+ text = (_STARSHIP / "space/destinations.ts").read_text(encoding="utf-8")+ found = re.findall(r'id: "([a-z_]+)", level: (\d+)', text)+ painted = [(dest, int(level)) for dest, level in found]+ expected = [("home", 1)] + [+ (r.reward_id.removeprefix("destination_"), r.person)+ for r in REWARDS if r.slot == "destination"+ ]+ assert painted == expected+ assert tuple(dest for dest, _ in painted) == DESTINATION_IDS+++def test_the_decks_the_server_pays_are_the_ships_decks():+ text = (_STARSHIP / "plan/types.ts").read_text(encoding="utf-8")+ match = re.search(r"export const DECKS: readonly DeckId\[\] = \[(.*?)\];", text, re.S)+ assert match, "DECKS not found in starship/plan/types.ts"+ assert set(re.findall(r'"([a-z_]+)"', match.group(1))) == set(VERSE_DECKS)+++def test_every_id_has_words_in_every_language():+ ranks = {rank for _, rank, _ in RANKS}+ sources = {r.source for r in RULES}+ for lang in _LANGS:+ chunk = json.loads((_SHIP_LOCALES / f"levels.{lang}.json").read_text(encoding="utf-8"))+ levels = chunk["ship"]["levels"]+ assert set(levels["reward"]) == {r.reward_id for r in REWARDS}, lang+ assert set(levels["source"]) == sources, lang+ assert set(levels["rule"]) == sources, lang+ assert set(levels["slot"]) == set(SLOTS), lang+ assert set(levels["tier"]) == {tier for _, _, tier in RANKS}, lang+ core = json.loads((_SHIP_LOCALES / f"{lang}.json").read_text(encoding="utf-8"))+ assert ranks <= set(core["ship"]["rank"]), langdef test_every_agent_look_is_a_real_accessory():diff --git a/tests/unit/progression/test_routes.py b/tests/unit/progression/test_routes.pyindex a53fce76e3..ddc9824117 100644--- a/tests/unit/progression/test_routes.py+++ b/tests/unit/progression/test_routes.py@@ -8,7 +8,7 @@ import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient-from dodaios.progression.rules import MAX_LEVEL, REWARDS, RULES+from dodaios.progression.rules import MAX_LEVEL, RANKS, REWARDS, RULESfrom dodaios.progression.service import ProgressionServicefrom dodaios.ui.web.progression_routes import router@@ -32,11 +32,14 @@ def test_the_first_read_carries_the_whole_rulebook(client: TestClient):assert len(body["level_xp"]) == MAX_LEVEL and body["level_xp"][0] == 0assert {r["source"] for r in body["rules"]} == {r.source for r in RULES}assert {r["reward_id"] for r in body["rewards"]} == {r.reward_id for r in REWARDS}- assert body["titles"]["person"][0] == {"level": 1, "title": "private"}+ assert body["titles"]["person"][0] == {"level": 1, "title": "cadet"}+ assert body["ranks"][0] == {"id": "cadet", "level": 1, "tier": "enlisted"}+ assert [(r["level"], r["id"], r["tier"]) for r in body["ranks"]] == list(RANKS)+ assert body["looks"] and all(look["agent"] == 1 for look in body["looks"])def test_a_world_action_pays_and_shows_up_in_the_next_read(client: TestClient):- action = {"action": "floor_discovered", "ref": "arcade"}+ action = {"action": "deck_discovered", "ref": "holodeck"}paid = client.post("/api/progression/actions", json=action)assert paid.status_code == 200award = paid.json()["awarded"]@@ -53,8 +56,10 @@ def test_a_world_action_pays_and_shows_up_in_the_next_read(client: TestClient):def test_server_only_and_unknown_actions_are_refused(client: TestClient):- for action in ("chat_turn", "level_up_now"):+ for action in ("chat_turn", "level_up_now", "arcade_round"):assert client.post("/api/progression/actions", json={"action": action}).status_code == 422+ unknown_deck = {"action": "deck_discovered", "ref": "hall"}+ assert client.post("/api/progression/actions", json=unknown_deck).status_code == 422def test_without_the_service_the_api_says_unavailable():diff --git a/tests/unit/progression/test_rules.py b/tests/unit/progression/test_rules.pyindex 3685fbcfc3..198bf5f276 100644--- a/tests/unit/progression/test_rules.py+++ b/tests/unit/progression/test_rules.py@@ -1,13 +1,16 @@-"""The rulebook of the Jarvis Verse level system is consistent and well paced."""+"""The ship's rulebook is consistent and well paced."""from __future__ import annotationsfrom dodaios.progression.rules import (+ DESTINATION_IDS,LOOK_UNLOCKS,MAX_LEVEL,+ RANK_TIERS,RANKS,REWARDS,RULES,+ RULES_BY_SOURCE,SLOTS,SUBJECT_KINDS,TITLES,@@ -38,6 +41,11 @@ def test_every_step_costs_more_than_the_one_before_and_reads_in_fives():assert xp_to_next(MAX_LEVEL) == 0+def test_the_curve_is_unchanged_so_existing_xp_keeps_its_meaning():+ assert [xp_to_next(level) for level in (1, 2, 10, 49)] == [40, 65, 320, 1805]+ assert total_xp_for_level(MAX_LEVEL) == 43_230++def test_pacing_matches_the_design_targets():# ~200 XP on an ordinary day: level 10 inside two weeks, the cap after months.assert total_xp_for_level(10) < 200 * 14@@ -66,10 +74,66 @@ def test_rules_have_unique_sources_and_pay_a_known_kind():# A world action is reported by the client: it must be metered.if rule.trigger == "world":assert rule.cooldown_s > 0 or rule.once_per_ref, rule.source- assert "daily_visit" in WORLD_ACTIONS and "chat_turn" not in WORLD_ACTIONS-def test_rewards_are_unique_and_unlock_on_a_promotion():+def test_the_world_actions_are_the_ships():+ assert WORLD_ACTIONS == {+ "daily_visit", "deck_discovered", "holodeck_round", "holodeck_record",+ "team_briefing", "warp_jump", "walk_together",+ }+ limits = {+ source: (r.xp, r.cooldown_s, r.daily_cap, r.once_per_ref, r.kind)+ for source, r in RULES_BY_SOURCE.items() if source in WORLD_ACTIONS+ }+ assert limits == {+ "daily_visit": (25, 0, 0, True, "person"),+ "deck_discovered": (20, 0, 0, True, "person"),+ "holodeck_round": (8, 45, 80, False, "person"),+ "holodeck_record": (15, 45, 60, False, "person"),+ "team_briefing": (10, 600, 40, False, "person"),+ "warp_jump": (5, 600, 30, False, "person"),+ "walk_together": (3, 20, 60, False, "pet"),+ }+ # The office tower's actions are gone (old ledger rows keep their source strings).+ for gone in ("floor_discovered", "dog_petted", "dog_treat", "arcade_round", "team_meeting"):+ assert gone not in RULES_BY_SOURCE+++def test_the_server_rules_keep_their_amounts():+ amounts = {r.source: r.xp for r in RULES if r.trigger == "server"}+ assert amounts == {+ "chat_turn": 5, "voice_turn": 5, "quest_posted": 15, "quest_completed": 20,+ "agent_hired": 50, "mission_completed": 30, "task_done": 40, "task_blocked": 8,+ "quest_done": 60, "answered_teammate": 5, "jarvis_answered": 4, "delegated": 10,+ }+++def test_the_rank_ladder_climbs_from_cadet_to_admiral():+ levels = [level for level, _, _ in RANKS]+ assert levels[0] == 1 and levels[-1] == MAX_LEVEL+ assert levels == sorted(set(levels))+ assert len(RANKS) == 16+ assert RANKS[0][1] == "cadet" and RANKS[-1][1] == "admiral"+ # Tiers come in order: enlisted, warrant, officer, flag; none is skipped.+ tiers = [tier for _, _, tier in RANKS]+ order = [RANK_TIERS.index(tier) for tier in tiers]+ assert order == sorted(order) and set(tiers) == set(RANK_TIERS)+ ids = [rank for _, rank, _ in RANKS]+ assert len(ids) == len(set(ids))+ for kind in SUBJECT_KINDS:+ assert [rank for _, rank in TITLES[kind]] == ids+++def test_titles_follow_the_ladder():+ assert title_for("person", 1) == "cadet"+ assert title_for("person", 2) == "cadet"+ assert title_for("agent", 3) == "crewman"+ assert title_for("person", 15) == "warrant_officer"+ assert title_for("pet", 34) == "captain"+ assert title_for("pet", MAX_LEVEL) == "admiral"+++def test_rewards_are_unique_named_by_their_slot_and_within_the_cap():ids = [reward.reward_id for reward in REWARDS]assert len(ids) == len(set(ids))for reward in REWARDS:@@ -78,47 +142,46 @@ def test_rewards_are_unique_and_unlock_on_a_promotion():for kind in SUBJECT_KINDS:level = reward.level_for(kind)assert level is None or 2 <= level <= MAX_LEVEL- # The person can dress in every slot; agents earn decorations; the pet wears its rank only.+++def test_rewards_per_kind():+ def by_slot(kind, slot):+ return [+ (r.reward_id, r.level_for(kind))+ for r in REWARDS if r.slot == slot and r.level_for(kind)+ ]++ assert by_slot("person", "suit") == [+ ("suit_field_armor", 6), ("suit_command_coat", 16),+ ("suit_dress_whites", 26), ("suit_admiral_coat", 42),+ ]+ assert [lvl for _, lvl in by_slot("person", "destination")] == [5, 10, 15, 20, 25, 30, 40]+ assert by_slot("person", "decoration") == [+ ("decoration_service_ribbon", 8), ("decoration_commendation", 18),+ ("decoration_star_medal", 36), ("decoration_legion_of_merit", 47),+ ]+ assert [lvl for _, lvl in by_slot("agent", "decoration")] == [3, 16, 32, 44]+ # Androids earn decorations only; the pet wears its rank only.+ assert by_slot("agent", "suit") == [] and by_slot("agent", "destination") == []assert {r.slot for r in unlocked_rewards("person", MAX_LEVEL)} == set(SLOTS)assert {r.slot for r in unlocked_rewards("agent", MAX_LEVEL)} == {"decoration"}assert unlocked_rewards("pet", MAX_LEVEL) == []- # A person's piece unlocks exactly on a promotion, so the banner can name the new rank with it.- promotions = {level for level, _, _ in RANKS}- for reward in REWARDS:- assert reward.person in promotions, reward.reward_id---def test_rewards_between_names_only_what_the_climb_crossed():- assert rewards_between("person", 1, 2) == []- assert [r.reward_id for r in rewards_between("person", 3, 4)] == ["uniform_service_shirt"]- at_ten = {r.reward_id for r in rewards_between("person", 7, 10)}- assert at_ten == {"uniform_field_jacket", "decoration_ribbon_bar"}- assert rewards_between("person", 10, 10) == []-def test_titles_start_at_level_one_and_climb():- for kind in SUBJECT_KINDS:- bands = TITLES[kind]- assert bands[0][0] == 1- assert [lvl for lvl, _ in bands] == sorted(lvl for lvl, _ in bands)- assert title_for("person", 1) == "private"- assert title_for("person", 11) == "sergeant"- assert title_for("agent", 26) == "second_lieutenant"- assert title_for("pet", MAX_LEVEL) == "general_of_the_army"+def test_every_destination_reward_is_a_helm_destination():+ assert DESTINATION_IDS[0] == "home"+ assert DESTINATION_IDS[1:] == tuple(+ r.reward_id.removeprefix("destination_") for r in REWARDS if r.slot == "destination"+ )-def test_the_rank_ladder_climbs_from_enlisted_to_general():- levels = [level for level, _, _ in RANKS]- assert levels[0] == 1 and levels[-1] == MAX_LEVEL- assert levels == sorted(set(levels))- grades = [grade for _, _, grade in RANKS]- assert grades[0] == "E-1" and grades[-1] == "O-11"- # Enlisted first, then commissioned: no officer grade before the last enlisted one.- first_officer = next(i for i, g in enumerate(grades) if g.startswith("O-"))- assert all(g.startswith("E-") for g in grades[:first_officer])- assert all(g.startswith("O-") for g in grades[first_officer:])- for kind in SUBJECT_KINDS:- assert [rank for _, rank in TITLES[kind]] == [rank for _, rank, _ in RANKS]+def test_rewards_between_names_only_what_the_climb_crossed():+ assert rewards_between("person", 1, 4) == []+ assert [r.reward_id for r in rewards_between("person", 4, 5)] == ["destination_gas_giant"]+ at_ten = {r.reward_id for r in rewards_between("person", 5, 10)}+ assert at_ten == {"suit_field_armor", "decoration_service_ribbon", "destination_crimson_nebula"}+ assert rewards_between("person", 10, 10) == []+ assert [r.reward_id for r in rewards_between("agent", 1, 3)] == ["decoration_service_ribbon"]def test_subject_ids_name_their_kind():diff --git a/tests/unit/progression/test_service.py b/tests/unit/progression/test_service.pyindex d62b868f00..0e993714ec 100644--- a/tests/unit/progression/test_service.py+++ b/tests/unit/progression/test_service.py@@ -116,8 +116,8 @@ async def test_agents_level_from_finished_work_and_quests(setup):assert levels["person"] == (15 + 20, 1)up = [e for e in seen if e.subject_id == "agent:scout" and e.level > e.previous_level]assert up and up[-1].level == 3- assert "decoration_ribbon_bar" in up[-1].unlocked- assert up[-1].title == "private_second_class"+ assert "decoration_service_ribbon" in up[-1].unlocked+ assert up[-1].title == "crewman"async def test_the_lead_is_the_pet_never_an_agent(setup):@@ -169,28 +169,74 @@ async def test_a_hired_agent_pays_the_person_once(setup):async def test_world_actions_are_metered_on_the_server(setup, clock):service, _, _, _ = setup- assert await service.report_action("dog_petted") is not None- assert await service.report_action("dog_petted") is None # cooldown- clock.now += 61_000- assert await service.report_action("dog_petted") is not None+ assert await service.report_action("holodeck_round") is not None+ assert await service.report_action("holodeck_round") is None # cooldown+ clock.now += 46_000+ assert await service.report_action("holodeck_round") is not Noneassert await service.report_action("daily_visit", ref="anything") is not Noneassert await service.report_action("daily_visit") is None # once per day- assert await service.report_action("floor_discovered", ref="arcade") is not None- assert await service.report_action("floor_discovered", ref="arcade") is None- # The Level Hall is a floor of its own and pays its first visit like the others.- assert await service.report_action("floor_discovered", ref="hall") is not None- assert await service.report_action("floor_discovered", ref="hall") is None+ for deck in ("bridge", "ops", "engineering", "holodeck", "honors"):+ assert await service.report_action("deck_discovered", ref=deck) is not None, deck+ assert await service.report_action("deck_discovered", ref=deck) is None, deckwalked = await service.report_action("walk_together")assert walked is not None and walked.subject_id == "pet:ember"+async def test_a_warp_jump_repeats_after_its_cooldown_and_keeps_its_destination(setup, clock):+ service, _, _, _ = setup+ first = await service.report_action("warp_jump", ref="home")+ assert first is not None and first.xp == 5 and first.ref.startswith("home@")+ assert await service.report_action("warp_jump", ref="home") is None # cooldown+ clock.now += 601_000+ again = await service.report_action("warp_jump", ref="home")+ assert again is not None and again.ref != first.ref+++async def test_a_warp_jump_only_reaches_destinations_the_rank_has_opened(setup):+ service, _, _, _ = setup+ # A new captain (level 1) has only the home orbit; the ice moon opens at level 15.+ with pytest.raises(UnknownAction):+ await service.report_action("warp_jump", ref="ice_moon")+++async def test_the_daily_caps_of_world_actions_hold(setup, clock):+ service, _, _, _ = setup+ paid = 0+ for _ in range(12):+ award = await service.report_action("team_briefing")+ paid += award.xp if award else 0+ clock.now += 601_000+ assert paid == RULES_BY_SOURCE["team_briefing"].daily_cap++async def test_unknown_or_server_only_actions_are_refused(setup):service, _, _, _ = setup- for action, ref in (("chat_turn", ""), ("cheat", ""), ("floor_discovered", "roof")):+ refused = (+ ("chat_turn", ""), ("cheat", ""), ("deck_discovered", "roof"), ("deck_discovered", ""),+ ("warp_jump", "andromeda"), ("warp_jump", ""),+ # The office tower's actions are gone.+ ("floor_discovered", "agents"), ("dog_petted", ""), ("arcade_round", ""),+ )+ for action, ref in refused:with pytest.raises(UnknownAction):await service.report_action(action, ref=ref)+async def test_old_ledger_rows_with_retired_sources_still_read(setup):+ service, _, _, _ = setup+ await service.award("person", "chat_turn", ref="x")+ conn = service.store._connection()+ conn.execute(+ "INSERT INTO progression_awards"+ " (subject_id, source, xp, level_before, level_after, ref, ts_ms)"+ " VALUES ('person', 'dog_petted', 3, 1, 1, '', 1)"+ )+ conn.execute("UPDATE progression_subjects SET xp = xp + 3 WHERE subject_id = 'person'")+ assert {row["source"] for row in service.store.recent()} == {"chat_turn", "dog_petted"}+ assert service.snapshot()[0]["xp"] == 8+ assert service.snapshot()[0]["title"] == "cadet"++def test_the_store_refuses_a_rule_for_the_wrong_kind(tmp_path: Path):store = ProgressionStore(tmp_path / "p.db")with pytest.raises(ValueError):