@homie-rocks/studio 0.24.5 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +54 -1
  2. package/README.md +56 -6
  3. package/assets/animate.ts +521 -0
  4. package/assets/render-page.ts +77 -4
  5. package/bin/homie-studio.mjs +13 -4
  6. package/lib/art-cli.mjs +105 -5
  7. package/lib/art-tools.mjs +168 -1
  8. package/lib/asset-check.mjs +72 -5
  9. package/lib/characters.mjs +380 -0
  10. package/lib/clips.mjs +417 -0
  11. package/lib/decisions.mjs +38 -8
  12. package/lib/mcp-tools.mjs +1 -1
  13. package/lib/mcp.mjs +2 -2
  14. package/lib/optimise.mjs +79 -3
  15. package/lib/perf.mjs +15 -7
  16. package/lib/render3d.mjs +2 -0
  17. package/lib/rig.mjs +431 -0
  18. package/lib/scaffold.mjs +7 -0
  19. package/lib/site.mjs +14 -3
  20. package/lib/studio.mjs +18 -3
  21. package/lib/style-board.mjs +3 -1
  22. package/lib/template-history.json +78 -0
  23. package/mcp/ui/animation.js +56 -0
  24. package/mcp/ui/card.css +4 -0
  25. package/mcp/ui/cast.js +36 -2
  26. package/mcp/ui/lineup.js +7 -7
  27. package/netplay/NETPLAY.md +38 -2
  28. package/netplay/netplay.ts +58 -3
  29. package/package.json +5 -1
  30. package/site/SITE.md +19 -1
  31. package/starters/gem-rush/game.json +2 -1
  32. package/starters/gem-rush-3d/game.json +2 -1
  33. package/starters/hero-rush-3d/assets/RIGHTS.md +163 -0
  34. package/starters/hero-rush-3d/assets/manifest.json +1471 -0
  35. package/starters/hero-rush-3d/credits.json +40 -0
  36. package/starters/hero-rush-3d/game.json +12 -0
  37. package/starters/hero-rush-3d/index.html +20 -0
  38. package/starters/hero-rush-3d/lab.json +32 -0
  39. package/starters/hero-rush-3d/src/main.ts +2588 -0
  40. package/starters/hero-rush-3d/style.json +68 -0
  41. package/starters/hero-rush-3d/tunables.json +32 -0
  42. package/worker/arrival.mjs +207 -0
  43. package/worker/pages.mjs +23 -5
  44. package/worker/site.mjs +26 -4
  45. package/worker/version.mjs +1 -1
@@ -0,0 +1,2588 @@
1
+ /*
2
+ * HERO RUSH 3D — Gem Rush's arena with ANIMATED HEROES: knights, barbarians, mages and rogues run for the coins, JUMP,
3
+ * and SWING to knock each other's run loose; skeletons fill the empty seats. The start for a 3D game with characters.
4
+ *
5
+ * THE RULES are Gem Rush's (the netplay v1 reference game): move, collect coins, score; 60 s rounds that cycle forever;
6
+ * the round starts the moment the first browser arrives, with two bots, and every human who arrives takes a bot's body.
7
+ * One browser hosts (pickups, scoring, bots, the clock) and broadcasts snapshots; everyone else moves their own hero
8
+ * locally and draws the rest from interpolated snapshots; a promoted host continues the same round. Two verbs on top:
9
+ * JUMP (Space, or the Jump button): a hero in the air is out of a swing's reach. Its height rides in the avatar and
10
+ * the snapshot, so every screen draws the jump, and the host decides what a swing hits by it.
11
+ * SWING (F, a click, or the Swing button): every screen plays the swing at once; the host lands it T.windupMs later
12
+ * (the anticipation), knocking every body in front of the swinger and within reach that is on the ground.
13
+ * The hot zone (keyed state) scores double; a watcher follows any player (`net.viewSeat`, `net.spotlight`); the swing
14
+ * and the jump are tuned in the Game Lab (tunables.json, lab.json). The world is in metres, a 26 x 16 m clearing, x
15
+ * across and y deep (y is three.js's z).
16
+ *
17
+ * THE BOTS never swamp a new player. They play at the room's skill dial (NETPLAY.md section 17; they jump a swing they
18
+ * see coming), with two things on top (THE BOTS, below, says exactly how):
19
+ * - In somebody's first round in the room, when nobody set the dial (no vote, no owner), they play a level easier.
20
+ * - A RUBBER BAND: a bot ahead of the best person in the room by more than its dial allows eases off (it walks,
21
+ * reacts later, swings less) and comes to race near the people, so a rival is on their screen; otherwise it plays
22
+ * at its dial. The lead it may hold grows with the dial; at Maxed there is no rubber band (a party that voted
23
+ * Maxed asked for it).
24
+ * Scores stay honest: nobody's score is ever changed, no coin is given, taken or faked; the bots just play softer.
25
+ * And a bot is always labelled a bot (an AI agent "· AI") wherever its name or score shows, the phone's board too.
26
+ *
27
+ * THE ARRIVAL: the play page shows the game's arrival card (its title, art and a progress line this game feeds with
28
+ * `net.loading`) until the game says `net.playable()`: the round's state is in and your own hero is drawn in its real
29
+ * model (THE ARRIVAL, by the HUD). So the round opens on your hero, with no title card over it. On a phone held
30
+ * upright the camera follows low and close (30 degrees, about 5.5 m across: the camera's comment says why), so every
31
+ * hero reads as a character, a mage too, and your name chip says which you are ("You · Mage").
32
+ *
33
+ * THE CHARACTERS are KayKit's CC0 adventurers and skeletons from the Homie starter library, made phone-sized by `game new`
34
+ * (lib/characters.mjs): each one skinned mesh, one draw call, its joints named by the skeleton standard, and every clip
35
+ * in one shared clip library per skeleton (public/anims/<skeleton>.glb). They move through @homie-rocks/studio/animate:
36
+ * idle, walk and run blended by ground speed, the swing on the upper body while running, an additive flinch and a
37
+ * hit-stop when hit, jump, fall and land with squash and stretch, a lean into turns, a cheer for the round's winner.
38
+ * Every number of that is a Game Lab tunable (the "Motion" group of tunables.json).
39
+ *
40
+ * THE LOOK comes from files beside game.json:
41
+ * style.json the palette, fonts, light and camera (the art direction's tokens: `homie-studio style` writes it);
42
+ * everything the code draws takes its colours from it
43
+ * public/models/ the heroes, the skeletons, the coin, the chest, trees, rocks and barrels: KayKit's CC0 packs from the
44
+ * Homie starter library (one family, so they fit), fetched by `game new` (the repository keeps no model
45
+ * files). assets/manifest.json names each library item and its SHA-256; assets/RIGHTS.md and
46
+ * credits.json say what its licence allows.
47
+ * public/anims/ the clip libraries, baked by `game new` from the characters' own CC0 clips.
48
+ * Every model loads through @homie-rocks/studio/assets (createModels: each file is checked before three.js reads a
49
+ * byte). A model that is refused or not there is drawn as a stand-in in the same colours: a round never waits on, or
50
+ * breaks for, a model.
51
+ *
52
+ * PHONE BUDGETS: under 100 draw calls and 150k triangles a frame (the `drawCalls` and `triangles` probes read
53
+ * renderer.info), the pixel ratio at most 1.5 on a phone and 2 on a computer, and no shadow map on a phone: a soft
54
+ * disc under each body, coin, tree and rock (a computer draws the sun's real shadows). Repeated things are one
55
+ * InstancedMesh per model; far heroes pose less often (animate's crowd()).
56
+ *
57
+ * The HUD (clock, scores, names, results, "Reconnecting…", the controls hint and the touch buttons) is a 2D canvas over
58
+ * the world, in style.json's fonts and colours.
59
+ */
60
+ import {
61
+ AmbientLight, Box3, BoxGeometry, BufferAttribute, BufferGeometry, CanvasTexture, CircleGeometry, Color, ConeGeometry, CylinderGeometry,
62
+ DodecahedronGeometry, IcosahedronGeometry,
63
+ DirectionalLight, DoubleSide, DynamicDrawUsage, Euler, ExtrudeGeometry, Fog, Group, HemisphereLight, InstancedMesh, LineBasicMaterial,
64
+ LineSegments, Matrix4, Mesh, MeshBasicMaterial, MeshLambertMaterial, MeshStandardMaterial, NoToneMapping, Object3D, Path,
65
+ PCFSoftShadowMap, PerspectiveCamera, PlaneGeometry, Quaternion, RingGeometry, Scene, Shape, SRGBColorSpace, Vector3, WebGLRenderer,
66
+ type Material,
67
+ } from 'three';
68
+ import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js';
69
+ // The one model loader every studio game uses: checks each file, decodes meshopt and WebP, copies for placing.
70
+ import { createModels, instancedCopies, placeCopy, repaint, stylize, type Copies } from '@homie-rocks/studio/assets';
71
+ // Characters that move well: clips from the skeleton's clip library, blended, layered and tuned (Game Lab tunables).
72
+ import { crowd, loadCharacter, type Character } from '@homie-rocks/studio/animate';
73
+ import { createNetplay, Roster, q, lerp, capMove, skillPreset, PALETTE, AI_MARK, type RoleChange, type RoundInfo, type RoundResult, type Skill, type Slot, type Snapshot } from '@homie-rocks/studio/netplay';
74
+ // The port toolkit: its probe (what `homie-studio port check` and `perf` read, and sandbox + audio shims), and name
75
+ // labels that never pile up (port/view.ts).
76
+ import { createBubbles, createLabels, exposePort, paintBubbles, type BubbleIn, type BubbleOut, type LabelIn, type LabelOut } from '@homie-rocks/studio/port';
77
+ // The Game Lab: tunables, phases, tracks and overlays (no-ops outside the lab).
78
+ import { lab } from '@homie-rocks/studio/lab';
79
+ import tuning from '../tunables.json';
80
+ import styleFile from '../style.json';
81
+ import gameFile from '../game.json';
82
+
83
+ /* ------------------------------------------------------------------ rules */
84
+ const W = 26;
85
+ const H = 16;
86
+ const R_AV = 0.44;
87
+ /**
88
+ * The clearing's own features, solid (rules coordinates, metres): bodies slide round them, gems never land in them.
89
+ * Away from the middle row, where bodies start and the Game Lab stages its knock.
90
+ */
91
+ const OBSTACLES: readonly { x: number; y: number; r: number; kind: 'camp' | 'bush' | 'rock' | 'stone' | 'tree' }[] = [
92
+ // The clearing's heart: a campfire ring with log seats (a game makes it its den, its camp, its well).
93
+ { x: 13.0, y: 4.0, r: 1.05, kind: 'camp' },
94
+ { x: 4.6, y: 3.8, r: 0.75, kind: 'bush' }, { x: 21.4, y: 4.6, r: 0.55, kind: 'rock' }, { x: 6.0, y: 12.6, r: 0.5, kind: 'rock' },
95
+ { x: 20.2, y: 12.2, r: 0.75, kind: 'bush' }, { x: 9.6, y: 13.4, r: 0.45, kind: 'stone' }, { x: 23.6, y: 2.0, r: 0.5, kind: 'tree' },
96
+ ];
97
+ /** A position kept in the clearing and out of its features (pushed to their edge, so a body slides round them). */
98
+ function bound(x: number, y: number): { x: number; y: number } {
99
+ x = Math.max(R_AV, Math.min(W - R_AV, x)); y = Math.max(R_AV, Math.min(H - R_AV, y));
100
+ for (const o of OBSTACLES) {
101
+ const dx = x - o.x; const dy = y - o.y; const d = Math.hypot(dx, dy); const min = o.r + R_AV;
102
+ if (d >= min) continue;
103
+ if (d > 1e-6) { x = o.x + (dx / d) * min; y = o.y + (dy / d) * min; } else x = o.x + min;
104
+ }
105
+ return { x, y };
106
+ }
107
+ const R_GEM = 0.3;
108
+ const SPEED = 6.2;
109
+ const BOT_SPEED = 4.2; // a player runs 6.2: a person who chases the coins out-runs a Fair bot
110
+ /** A hero this high or higher is in the air: a swing passes under it. */
111
+ const CLEAR_M = 0.3;
112
+ const ROUND_MS = 60_000;
113
+ const BREAK_MS = 7_000;
114
+ const GEM_COUNT = 14;
115
+ const MIN_SLOTS = 3; // 1 human + 2 bots from the first frame
116
+ const MAX_SLOTS = 8;
117
+ /** The swing's, the jump's and the motion's numbers (tunables.json): the file's values, or the Game Lab's sliders. */
118
+ const T = lab.tunables(tuning);
119
+ /** The jump as a curve of time: up at the speed that reaches T.jumpHeight in T.jumpRise seconds, down T.fallFaster harder. */
120
+ const jumpGravity = (): number => (2 * T.jumpHeight) / Math.max(0.05, T.jumpRise) ** 2;
121
+ const jumpSpeed = (): number => jumpGravity() * Math.max(0.05, T.jumpRise);
122
+ /** One jump step for anything with a height (h, metres up) and a vertical speed (vh): the same rule on every screen. */
123
+ function fall(o: { h: number; vh: number }, dt: number): boolean {
124
+ if (o.h <= 0 && o.vh <= 0) { o.h = 0; o.vh = 0; return false; }
125
+ const g = jumpGravity() * (o.vh < 0 ? T.fallFaster : 1);
126
+ o.vh -= g * dt; o.h += o.vh * dt;
127
+ if (o.h <= 0) { o.h = 0; o.vh = 0; return true; } // landed this step
128
+ return false;
129
+ }
130
+ const ZONE_MS = 12_000;
131
+ /** The contract's 12 colours (PALETTE, NETPLAY.md section 3): a person wears their seat's, so the watch page's strip matches. */
132
+ const colourOf = (slot: number, seat: number | null): string => PALETTE[(seat ?? slot) % PALETTE.length] as string;
133
+ const BOT_NAMES = ['Rook', 'Vex', 'Moth', 'Kilo', 'Juno', 'Pike', 'Nyx', 'Ash'];
134
+ const botName = (slot: number): string => BOT_NAMES[slot % BOT_NAMES.length] as string;
135
+ /** An AI's name already ends in " · AI" (the relay sees to it); a plain bot says bot. */
136
+ const label = (name: string, bot: boolean): string => (name.endsWith(AI_MARK) ? name : bot ? `${name} · bot` : name);
137
+
138
+ /* ------------------------------------------------------------ wire shapes */
139
+ /** Snapshot: compact arrays, quantized to the centimetre. (Reset epochs ride in the helper's `c` table.) */
140
+ type P = [slot: number, seat: number, x: number, y: number, score: number, vx: number, vy: number, h: number];
141
+ type G = [id: number, x: number, y: number];
142
+ interface Snap { r: [n: number, phase: number, startedAt: number, endsAt: number]; p: P[]; g: G[] }
143
+ /**
144
+ * Replica input: the avatar (owner movement) AND the stick intent (host movement), so either mode reads the same
145
+ * frame. The helper stamps the reset epoch the replica has adopted.
146
+ */
147
+ type Avatar = [x: number, y: number, vx: number, vy: number, mx: number, my: number, h: number];
148
+ /** A body's bump, while it lasts: its direction (kvx, kvy), where its slide starts (kx, ky) and when (kat, after the hit-stop). */
149
+ interface Knock { kvx: number; kvy: number; kx: number; ky: number; kat: number; knockUntil: number }
150
+ /** A body: where it is, its height off the ground (h) and vertical speed (vh), and which way it faces (fa, radians). */
151
+ interface Body extends Knock { slot: number; seat: number | null; name: string; bot: boolean; x: number; y: number; vx: number; vy: number; h: number; vh: number; fa: number; score: number; tx: number; ty: number }
152
+ interface Gem { id: number; x: number; y: number }
153
+ /** Slow state, on the keyed state channel (net.state('zone', ...)), not in the 20 Hz snapshot. */
154
+ interface Zone { n: number; x: number; y: number; r: number; until: number }
155
+ /** `firstRound`: each person's first whole round here (seat, round), so a promoted host eases the same round. */
156
+ interface Ckpt { round: RoundInfo; bodies: Body[]; gems: Gem[]; roster: Slot[]; tick: number; gemSeq: number; firstRound?: [number, number][] }
157
+
158
+ /* --------------------------------------------------------------- the net */
159
+ /**
160
+ * `?movement=host` plays host movement: the host moves every body from the seats' stick intents (its rules own
161
+ * movement), and each replica PREDICTS its own body by replaying its unacknowledged intents on the host's position.
162
+ * Default `owner`: each browser moves its own body and the host bounds it.
163
+ */
164
+ const MOVEMENT: 'owner' | 'host' = (() => { try { return new URLSearchParams(location.search).get('movement') === 'host' ? 'host' : 'owner'; } catch { return 'owner'; } })();
165
+ // caps: its bots read the dial ('skill'), and its Roster takes an AI's slot for it ('agents': the join passes p.agent).
166
+ // arrival 'game': the play page's arrival card stays until this game says it is playable (THE ARRIVAL, by the HUD).
167
+ const net = createNetplay<Snap, Avatar, Ckpt>({ game: 'hero-rush-3d', maxPlayers: MAX_SLOTS, movement: MOVEMENT, snapshotHz: 20, inputHz: 20, checkpointMs: 1000, caps: ['skill', 'agents'], arrival: 'game', checkpoint: () => checkpoint() });
168
+ /** The Roster keeps the server's AI seats (revision 6): the policy is read whenever it fills. */
169
+ const policy = () => net.policy;
170
+
171
+ /* ------------------------------------------------------------ host state */
172
+ let roster = new Roster({ min: MIN_SLOTS, max: MAX_SLOTS, botName, policy });
173
+ let bodies = new Map<number, Body>();
174
+ let gems: Gem[] = [];
175
+ let gemSeq = 0;
176
+ let round: RoundInfo | null = null;
177
+ let zone: Zone | null = null;
178
+ let tick = 0;
179
+ let hosting = false;
180
+ let cheatResets = 0;
181
+ let controlResets = 0;
182
+ let predictionError = 0;
183
+ /** Gems each slot picked up this round (a gem, whatever it scored): the dial's numbers (`pickups` probe). */
184
+ let pickups = new Map<number, number>();
185
+
186
+ /* ------------------------------------------------ this browser's avatar */
187
+ const me = { x: W / 2, y: H / 2, vx: 0, vy: 0, h: 0, vh: 0, kvx: 0, kvy: 0, kx: 0, ky: 0, kat: 0, knockUntil: 0, has: false };
188
+ /** Offline (no shell) plays as a local seat 0, with keys or touch. */
189
+ const mySeat = (): number | null => (net.offline ? 0 : net.seat);
190
+ /** Whose view to draw: my own seat, or for a watcher the player it follows (null: the whole arena). */
191
+ const viewSeat = (): number | null => (net.offline ? 0 : net.viewSeat);
192
+
193
+ /* ------------------------------------------------------- replica view */
194
+ const drawn = new Map<number, { x: number; y: number; h: number; seat: number; score: number; slot: number }>();
195
+ const waves: { x: number; y: number; at: number; colour: string; knock?: boolean; fa?: number; slot?: number }[] = [];
196
+ let wavesSeen = 0;
197
+ let knocksSeen = 0;
198
+ let jumpsSeen = 0;
199
+ let dodgesSeen = 0;
200
+ let firstStateAt = 0;
201
+ let firstSnapAt = 0;
202
+ let frames = 0;
203
+
204
+ const rnd = (a: number, b: number): number => a + Math.random() * (b - a);
205
+ const spawnPoint = (i: number): { x: number; y: number } => {
206
+ const a = (i / MAX_SLOTS) * Math.PI * 2;
207
+ return { x: W / 2 + Math.cos(a) * 6.6, y: H / 2 + Math.sin(a) * 5 };
208
+ };
209
+ const newGem = (): Gem => {
210
+ let x = rnd(1.2, W - 1.2); let y = rnd(1.2, H - 1.2);
211
+ for (let i = 0; i < 12 && OBSTACLES.some((o) => Math.hypot(o.x - x, o.y - y) < o.r + 0.7); i += 1) { x = rnd(1.2, W - 1.2); y = rnd(1.2, H - 1.2); }
212
+ return { id: ++gemSeq, x, y };
213
+ };
214
+
215
+ function bodyFor(slot: Slot): Body {
216
+ const sp = spawnPoint(slot.slot);
217
+ return { slot: slot.slot, seat: slot.seat, name: slot.name, bot: slot.bot, x: sp.x, y: sp.y, vx: 0, vy: 0, h: 0, vh: 0, fa: 0, score: 0, tx: sp.x, ty: sp.y, kvx: 0, kvy: 0, kx: sp.x, ky: sp.y, kat: 0, knockUntil: 0 };
218
+ }
219
+
220
+ function syncBodiesFromRoster(): void {
221
+ const seen = new Set<number>();
222
+ for (const s of roster.slots) {
223
+ seen.add(s.slot);
224
+ const b = bodies.get(s.slot);
225
+ if (!b) { bodies.set(s.slot, bodyFor(s)); continue; }
226
+ b.seat = s.seat; b.name = s.name; b.bot = s.bot;
227
+ }
228
+ for (const k of [...bodies.keys()]) if (!seen.has(k)) bodies.delete(k);
229
+ }
230
+
231
+ function publishRoster(): void { net.roster(roster.toJSON()); }
232
+
233
+ /** The host moved body `b` itself: tell its owner (a replica adopts it; the host's own body is `me`). */
234
+ function hostMoved(b: Body): void {
235
+ if (b.bot || b.seat === null) return;
236
+ if (b.seat === mySeat()) { me.x = b.x; me.y = b.y; me.vx = 0; me.vy = 0; me.h = 0; me.vh = 0; me.has = true; return; }
237
+ net.reset(b.seat);
238
+ }
239
+
240
+ function newZone(n: number): Zone {
241
+ return { n, x: rnd(4.4, W - 4.4), y: rnd(4, H - 4), r: 3, until: net.now() + ZONE_MS };
242
+ }
243
+ function setZone(z: Zone): void { zone = z; net.state('zone', z); }
244
+
245
+ /** A round starts with every hero on its spawn ring facing the camera (fa 0): a line-up the hero intro opens on. */
246
+ function startRound(n: number): void {
247
+ const now = net.now();
248
+ roster.trim();
249
+ syncBodiesFromRoster();
250
+ let i = 0;
251
+ for (const b of [...bodies.values()].sort((a, c) => a.slot - c.slot)) {
252
+ const sp = spawnPoint(i++);
253
+ b.x = sp.x; b.y = sp.y; b.vx = 0; b.vy = 0; b.h = 0; b.vh = 0; b.fa = 0; b.score = 0; b.tx = sp.x; b.ty = sp.y; b.kvx = 0; b.kvy = 0; b.knockUntil = 0;
254
+ hostMoved(b);
255
+ }
256
+ gems = Array.from({ length: GEM_COUNT }, newGem);
257
+ pickups = new Map();
258
+ sight.clear();
259
+ swings.length = 0;
260
+ round = { n, phase: 'live', startedAt: now, endsAt: now + ROUND_MS };
261
+ if (lab.stage === 'dummy' || lab.stage === 'jump') stageDummy();
262
+ setZone(newZone((zone?.n ?? 0) + 1));
263
+ net.round(round);
264
+ publishRoster();
265
+ net.snapshot(buildSnap(), tick, true);
266
+ }
267
+
268
+ function endRound(): void {
269
+ if (!round) return;
270
+ const now = net.now();
271
+ const ranked = [...bodies.values()].sort((a, b) => b.score - a.score || Number(a.bot) - Number(b.bot) || a.slot - b.slot);
272
+ const agentSlot = (slot: number): boolean => Boolean(roster.slots.find((x) => x.slot === slot)?.agent);
273
+ const results: RoundResult[] = ranked.map((b, i) => ({ slot: b.slot, seat: b.seat, name: b.name, score: b.score, bot: b.bot, place: i + 1, ...(agentSlot(b.slot) ? { agent: true as const } : {}) }));
274
+ round = { n: round.n, phase: 'over', startedAt: now, endsAt: now + BREAK_MS, results };
275
+ net.round(round);
276
+ }
277
+
278
+ /* ---------------------------------------------------- becoming the host */
279
+ function becomeHost(e: RoleChange<Snap, Ckpt>): void {
280
+ hosting = true;
281
+ if (e.promoted) restore(e);
282
+ else {
283
+ roster = new Roster({ min: MIN_SLOTS, max: MAX_SLOTS, botName, policy });
284
+ bodies = new Map();
285
+ const seat = mySeat();
286
+ if (seat !== null) roster.claim(seat, net.offline ? 'You' : net.name);
287
+ syncBodiesFromRoster();
288
+ firstRound = new Map();
289
+ startRound((e.round?.n ?? 0) + 1);
290
+ welcome(seat);
291
+ }
292
+ // Whoever is connected now is who plays: seats that left during the gap become bots.
293
+ const peers = net.offline ? [{ seat: 0, name: 'You' }] : [...net.peers.values()].filter((p) => p.seat !== null).map((p) => ({ seat: p.seat, name: p.name, agent: p.agent ?? null }));
294
+ const { claimed } = roster.reconcile(peers);
295
+ syncBodiesFromRoster();
296
+ for (const s of claimed) welcome(s.seat);
297
+ for (const s of claimed) { const b = bodies.get(s.slot); if (b && b.seat !== mySeat()) hostMoved(b); }
298
+ // My own body is wherever my local avatar is: it was client-owned a moment ago and still is.
299
+ const mine = mySeat() !== null ? [...bodies.values()].find((b) => b.seat === mySeat()) : undefined;
300
+ if (mine && me.has) { mine.x = me.x; mine.y = me.y; }
301
+ else if (mine) { me.x = mine.x; me.y = mine.y; me.has = true; }
302
+ // The hot zone is keyed state: the relay handed it over with the role.
303
+ zone = net.stateOf<Zone>('zone') ?? zone;
304
+ if (!zone && round) setZone(newZone(1));
305
+ publishRoster();
306
+ }
307
+
308
+ function restore(e: RoleChange<Snap, Ckpt>): void {
309
+ const ck = e.ckpt?.d ?? null;
310
+ if (ck) {
311
+ roster = Roster.from(ck.roster, { min: MIN_SLOTS, max: MAX_SLOTS, botName, policy });
312
+ bodies = new Map(ck.bodies.map((b) => [b.slot, { ...b }]));
313
+ gems = ck.gems.map((g) => ({ ...g }));
314
+ gemSeq = ck.gemSeq;
315
+ round = ck.round;
316
+ tick = ck.tick;
317
+ firstRound = new Map(Array.isArray(ck.firstRound) ? ck.firstRound : []);
318
+ } else {
319
+ roster = Roster.from(e.roster ?? [], { min: MIN_SLOTS, max: MAX_SLOTS, botName, policy });
320
+ bodies = new Map();
321
+ syncBodiesFromRoster();
322
+ }
323
+ // The snapshot is newer than the checkpoint (20 Hz vs 1 Hz): positions, scores and gems from it.
324
+ const s = e.snap;
325
+ if (s && (!e.ckpt || s.st >= e.ckpt.st)) {
326
+ for (const [slot, seat, x, y, score, , , h] of s.d.p) {
327
+ let b = bodies.get(slot);
328
+ if (!b) {
329
+ const rs0 = roster.slots.find((r) => r.slot === slot) ?? { slot, seat: seat >= 0 ? seat : null, name: seat >= 0 ? `Player ${seat + 1}` : botName(slot), bot: seat < 0 };
330
+ b = bodyFor(rs0);
331
+ bodies.set(slot, b);
332
+ }
333
+ b.x = x; b.y = y; b.h = Number(h) || 0; b.score = score; b.tx = x; b.ty = y;
334
+ }
335
+ gems = s.d.g.map(([id, x, y]) => ({ id, x, y }));
336
+ gemSeq = Math.max(gemSeq, ...gems.map((g) => g.id));
337
+ const [n, ph, startedAt, endsAt] = s.d.r;
338
+ round = { n, phase: ph ? 'over' : 'live', startedAt, endsAt, ...(round?.n === n && round.results ? { results: round.results } : {}) };
339
+ tick = Math.max(tick, s.k);
340
+ }
341
+ // A round message the relay kept is at least as authoritative as the checkpoint's copy.
342
+ if (e.round && (!round || e.round.n > round.n || (e.round.n === round.n && e.round.phase === 'over' && round.phase === 'live'))) round = e.round;
343
+ // Anyone already playing whose first round the checkpoint does not say is no newcomer: the dial stays exact for them.
344
+ for (const r of roster.slots) if (!r.bot && r.seat !== null && !firstRound.has(r.seat)) firstRound.set(r.seat, 0);
345
+ if (!round) { startRound(1); return; }
346
+ net.round(round);
347
+ }
348
+
349
+ function checkpoint(): Ckpt {
350
+ return {
351
+ round: round ?? { n: 0, phase: 'live', startedAt: 0, endsAt: 0 },
352
+ bodies: [...bodies.values()].map((b) => ({ ...b })),
353
+ gems: gems.map((g) => ({ ...g })),
354
+ roster: roster.toJSON(),
355
+ tick,
356
+ gemSeq,
357
+ firstRound: [...firstRound],
358
+ };
359
+ }
360
+
361
+ net.on('role', (e) => {
362
+ if (e.role === 'host') becomeHost(e);
363
+ else { hosting = false; }
364
+ });
365
+ net.on('join', (p) => {
366
+ if (!hosting || p.seat === null) return;
367
+ // An AI takes a seat kept for AI, a person never does (revision 6: the Roster needs p.agent for that).
368
+ const c = roster.claim(p.seat, p.name, p.agent ? { role: p.agent.role, hands: p.agent.hands } : null);
369
+ if (!c) return; // full: they watch
370
+ welcome(p.seat);
371
+ syncBodiesFromRoster();
372
+ const b = bodies.get(c.slot.slot);
373
+ // The arriving human takes over the bot's body where it stands, score and all (reset = "adopt this position").
374
+ if (b) { b.vx = 0; b.vy = 0; b.kvx = 0; b.kvy = 0; b.knockUntil = 0; hostMoved(b); }
375
+ publishRoster();
376
+ net.snapshot(buildSnap(), tick, true);
377
+ });
378
+ net.on('leave', (p) => {
379
+ if (!hosting || p.seat === null) return;
380
+ roster.release(p.seat); // their body stays, driven by a bot
381
+ firstRound.delete(p.seat); // whoever sits in this seat next is new here
382
+ syncBodiesFromRoster();
383
+ publishRoster();
384
+ });
385
+ // The server's policy changed: its AI seats come (or go between rounds) at once.
386
+ net.on('policy', () => { if (!hosting) return; roster.fill(); syncBodiesFromRoster(); publishRoster(); });
387
+ net.on('event', (e) => {
388
+ if (e.k === 'swing') addWave(e.d as { slot: number; fa?: number });
389
+ if (e.k === 'knock') addWave(e.d as { slot: number }, true);
390
+ if (e.k === 'jump') {
391
+ const slot = Number((e.d as { slot?: number })?.slot);
392
+ // A player's jump comes to the host from its own screen (its height is its own): the host passes it on to everyone,
393
+ // only for that player's own body.
394
+ if (hosting && e.from !== null) { const b = bodies.get(slot); if (!b || b.bot || b.seat !== e.from) return; net.send('jump', { slot }); }
395
+ jumped(slot);
396
+ }
397
+ if (e.k === 'dodge') dodged((e.d as { slot: number }).slot);
398
+ });
399
+ net.on('round', (r) => { round = hosting ? round : r; });
400
+ net.on('state', (e) => { if (e.k === 'zone' && !hosting) zone = (e.d as Zone | null) ?? null; if (!firstStateAt) firstStateAt = performance.now(); });
401
+ net.on('snapshot', () => { if (!firstSnapAt) firstSnapAt = performance.now(); });
402
+ /** My body's control changed: on a reset, stand where the host put me (a new round, a takeover, a knockback's end). */
403
+ net.on('control', (e) => {
404
+ if (!e.reset) return;
405
+ controlResets += 1;
406
+ const p = (e.snap as Snapshot<Snap>).d.p.find((x) => x[1] === net.seat);
407
+ if (p) { me.x = p[2]; me.y = p[3]; me.vx = 0; me.vy = 0; me.h = Number(p[7]) || 0; me.vh = 0; me.has = true; }
408
+ });
409
+
410
+ /* ----------------------------------------------------------------- input */
411
+ // The camera looks across the meadow from its near edge, square to it: screen right is +x and screen down is +y, so
412
+ // keys and the stick move a body exactly as in Gem Rush. Space jumps; F (or J, Enter, a click) swings. On a phone the
413
+ // first finger anywhere is the stick, and two buttons at the bottom right jump and swing (a second finger anywhere
414
+ // else swings too).
415
+ const keys = new Set<string>();
416
+ addEventListener('keydown', (e) => {
417
+ if (['KeyW', 'KeyA', 'KeyS', 'KeyD', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Space', 'KeyF', 'KeyJ', 'Enter'].includes(e.code)) e.preventDefault();
418
+ if (e.code === 'Space' && !keys.has('Space')) jump();
419
+ if (['KeyF', 'KeyJ', 'Enter'].includes(e.code) && !keys.has(e.code)) swing();
420
+ keys.add(e.code);
421
+ });
422
+ addEventListener('keyup', (e) => keys.delete(e.code));
423
+ addEventListener('blur', () => keys.clear());
424
+
425
+ const stick = { id: -1, ox: 0, oy: 0, x: 0, y: 0, active: false };
426
+ const canvas = document.getElementById('c') as HTMLCanvasElement;
427
+ const hudCanvas = document.getElementById('hud') as HTMLCanvasElement;
428
+ const ctx = hudCanvas.getContext('2d') as CanvasRenderingContext2D;
429
+ /** The touch buttons (CSS px, set by the HUD each frame); shown once a finger has touched the screen. */
430
+ const buttons: { id: 'jump' | 'swing'; x: number; y: number; r: number; at: number }[] = [];
431
+ let touched = (() => { try { return matchMedia('(pointer: coarse)').matches; } catch { return false; } })();
432
+ const buttonAt = (x: number, y: number): (typeof buttons)[number] | null => buttons.find((b) => Math.hypot(x - b.x, y - b.y) <= b.r * 1.15) ?? null;
433
+ canvas.addEventListener('pointerdown', (e) => {
434
+ if (e.pointerType === 'mouse') { if (e.button === 0) swing(); return; }
435
+ touched = true;
436
+ const b = buttonAt(e.clientX, e.clientY);
437
+ if (b) { b.at = performance.now(); if (b.id === 'jump') jump(); else swing(); return; }
438
+ if (stick.active && e.pointerId !== stick.id) { swing(); return; } // a second finger swings
439
+ stick.id = e.pointerId; stick.ox = e.clientX; stick.oy = e.clientY; stick.x = e.clientX; stick.y = e.clientY; stick.active = true;
440
+ canvas.setPointerCapture(e.pointerId);
441
+ });
442
+ canvas.addEventListener('pointermove', (e) => { if (e.pointerId === stick.id) { stick.x = e.clientX; stick.y = e.clientY; } });
443
+ const endStick = (e: PointerEvent): void => { if (e.pointerId === stick.id) { stick.active = false; stick.id = -1; } };
444
+ canvas.addEventListener('pointerup', endStick);
445
+ canvas.addEventListener('pointercancel', endStick);
446
+
447
+ function moveVector(): { x: number; y: number } {
448
+ let x = 0; let y = 0;
449
+ if (keys.has('KeyA') || keys.has('ArrowLeft')) x -= 1;
450
+ if (keys.has('KeyD') || keys.has('ArrowRight')) x += 1;
451
+ if (keys.has('KeyW') || keys.has('ArrowUp')) y -= 1;
452
+ if (keys.has('KeyS') || keys.has('ArrowDown')) y += 1;
453
+ if (stick.active) {
454
+ const dx = stick.x - stick.ox; const dy = stick.y - stick.oy;
455
+ const len = Math.hypot(dx, dy);
456
+ if (len > 6) { const m = Math.min(1, len / 56); x += (dx / len) * m; y += (dy / len) * m; }
457
+ }
458
+ const len = Math.hypot(x, y);
459
+ return len > 1 ? { x: x / len, y: y / len } : { x, y };
460
+ }
461
+
462
+ /** My jump: my body's height is mine (it rides in my avatar), so it starts here at once; every screen is told. */
463
+ function jump(): void {
464
+ const seat = mySeat();
465
+ if (seat === null || !me.has || me.h > 0 || me.knockUntil > net.now()) return;
466
+ me.vh = jumpSpeed(); me.h = 1e-3;
467
+ const mine = hosting ? [...bodies.values()].find((x) => x.seat === seat) : [...drawn.values()].find((x) => x.seat === seat);
468
+ if (mine) { jumped(mine.slot); net.send('jump', { slot: mine.slot }); }
469
+ if (!hosting && MOVEMENT === 'host') net.press('jump');
470
+ }
471
+
472
+ /** My swing: the host lands it; every screen sees it start at once. */
473
+ function swing(): void {
474
+ const seat = mySeat();
475
+ if (seat === null) return;
476
+ if (hosting) {
477
+ const b = [...bodies.values()].find((x) => x.seat === seat);
478
+ if (b) startSwing(b);
479
+ } else net.press('swing');
480
+ }
481
+ /**
482
+ * Host: a swing starts. Every screen plays it now (the swing event); it LANDS T.windupMs later (the anticipation the
483
+ * Game Lab tunes): every other body within T.knockRange, in front of the swinger (within T.swingArc degrees of where it
484
+ * faces) and on the ground then, is knocked back. A body in the air is missed: it dodged.
485
+ */
486
+ const swings: { slot: number; at: number }[] = [];
487
+ const swingReady = new Map<number, number>();
488
+ function startSwing(from: Body): void {
489
+ const now = net.now();
490
+ if ((swingReady.get(from.slot) ?? 0) > now || from.knockUntil > now) return;
491
+ swingReady.set(from.slot, now + T.windupMs + T.swingRestMs);
492
+ const d = { slot: from.slot, fa: q(from.fa, 2) };
493
+ addWave(d); net.send('swing', d);
494
+ swings.push({ slot: from.slot, at: now + T.windupMs });
495
+ botsSee(from);
496
+ }
497
+ function landSwings(): void {
498
+ const now = net.now();
499
+ for (let i = swings.length - 1; i >= 0; i -= 1) {
500
+ const s = swings[i] as (typeof swings)[number];
501
+ if (now < s.at) continue;
502
+ swings.splice(i, 1);
503
+ const from = bodies.get(s.slot);
504
+ if (!from || from.knockUntil > now) continue;
505
+ const half = (T.swingArc * Math.PI) / 360;
506
+ for (const b of bodies.values()) {
507
+ if (b === from) continue;
508
+ const dx = b.x - from.x; const dy = b.y - from.y; const d = Math.hypot(dx, dy);
509
+ if (d > T.knockRange) continue;
510
+ let off = Math.atan2(dx, dy) - from.fa; off = Math.atan2(Math.sin(off), Math.cos(off));
511
+ if (d > R_AV * 1.5 && Math.abs(off) > half) continue;
512
+ const h = !b.bot && b.seat !== null && b.seat === mySeat() ? me.h : b.h;
513
+ if (h >= CLEAR_M) { dodged(b.slot); net.send('dodge', { slot: b.slot }); continue; }
514
+ knock(b, from.x, from.y, from.slot);
515
+ }
516
+ }
517
+ }
518
+ /**
519
+ * Host: knock a body back. The hit LANDS first: for T.hitStopMs the body holds where it was hit (it flashes, flinches
520
+ * and shakes on every screen), then it SLIDES T.knockDistance along the hit, fast at first and easing into the stop
521
+ * (T.knockEase), so it arrives at rest, the same distance at any frame rate, and its owner steers again with no pop.
522
+ * A replica's body is TAKEN for the whole bump (its owner's avatar frames are ignored; the host drives it; the owner
523
+ * draws its body from snapshots), then the helper GIVES it back with a reset, so the owner stands where it ended.
524
+ */
525
+ function knock(b: Body, fx: number, fy: number, by: number): void {
526
+ let dx = b.x - fx; let dy = b.y - fy;
527
+ const len = Math.hypot(dx, dy);
528
+ if (len < 0.02) { const a = Math.random() * Math.PI * 2; dx = Math.cos(a); dy = Math.sin(a); } else { dx /= len; dy /= len; }
529
+ const at = net.now() + T.hitStopMs;
530
+ const o: Knock & { x: number; y: number } = !b.bot && b.seat !== null && b.seat === mySeat() ? me : b;
531
+ o.kvx = dx; o.kvy = dy; o.kx = o.x; o.ky = o.y; o.kat = at; o.knockUntil = at + T.knockMs;
532
+ if (o === b && !b.bot && b.seat !== null) net.take(b.seat, T.hitStopMs + T.knockMs);
533
+ labKnock(b);
534
+ const d = { slot: b.slot, dx: q(dx, 2), dy: q(dy, 2), by };
535
+ addWave(d, true); net.send('knock', d);
536
+ }
537
+
538
+ /** Where a bumped body is now: held through the hit-stop, then eased out along the hit. Sets its velocity too. */
539
+ function slide(o: Knock & { x: number; y: number; vx: number; vy: number }, now: number, dt: number): void {
540
+ const u = Number.isFinite(o.kat) ? Math.max(0, Math.min(1, (now - o.kat) / Math.max(1, T.knockMs))) : 1;
541
+ const e = 1 - (1 - u) ** Math.max(1, T.knockEase);
542
+ const { x, y } = bound(o.kx + o.kvx * T.knockDistance * e, o.ky + o.kvy * T.knockDistance * e);
543
+ if (u >= 1) { o.vx = 0; o.vy = 0; } else if (dt > 0) { o.vx = (x - o.x) / dt; o.vy = (y - o.y) / dt; }
544
+ o.x = x; o.y = y;
545
+ }
546
+ /** The frame a bump is over: the body lands exactly where its slide ends, at rest (at 12 fps the last step is long). */
547
+ function landed(o: Knock & { x: number; y: number; vx: number; vy: number }): void {
548
+ if (!o.kat) return;
549
+ slide(o, o.kat + T.knockMs, 0);
550
+ o.kat = 0;
551
+ }
552
+ function addWave(d: { slot: number; dx?: number; dy?: number; by?: number; fa?: number }, isKnock = false): void {
553
+ const pos = hosting ? bodies.get(d.slot) : [...drawn.values()].find((x) => x.slot === d.slot);
554
+ // The action, for a watcher on Auto: whoever swung (a person, never a bot).
555
+ const waver = pos && 'bot' in pos ? (pos.bot ? null : pos.seat) : pos && pos.seat >= 0 ? pos.seat : null;
556
+ if (!isKnock) net.spotlight(waver);
557
+ const mineSlot = hosting ? [...bodies.values()].find((x) => x.seat !== null && x.seat === mySeat())?.slot : [...drawn.values()].find((x) => x.seat === net.seat)?.slot;
558
+ const at = mineSlot === d.slot && me.has ? me : pos;
559
+ if (!at) return;
560
+ waves.push({ x: at.x, y: at.y, at: performance.now(), colour: isKnock ? '#ffffff' : PALETTE[d.slot % PALETTE.length] as string, knock: isKnock, fa: d.fa, slot: d.slot });
561
+ if (isKnock) knocksSeen += 1; else wavesSeen += 1;
562
+ if (isKnock) bumped(d, at); else swung(d.slot);
563
+ }
564
+
565
+ /* ---------------------------------------------------------------- simulate */
566
+ /** The one movement rule, shared by the owner, the host (host movement) and a replica's prediction. */
567
+ function integrate(o: { x: number; y: number; vx: number; vy: number }, mx: number, my: number, dt: number): void {
568
+ mx = Number(mx) || 0; my = Number(my) || 0;
569
+ const len = Math.hypot(mx, my);
570
+ if (len > 1) { mx /= len; my /= len; } // an intent is at most full stick: no speed hack through intents
571
+ const k = Math.min(1, dt * 14);
572
+ o.vx += (mx * SPEED - o.vx) * k;
573
+ o.vy += (my * SPEED - o.vy) * k;
574
+ const p = bound(o.x + o.vx * dt, o.y + o.vy * dt);
575
+ o.x = p.x; o.y = p.y;
576
+ }
577
+
578
+ function stepMe(dt: number): void {
579
+ const seat = mySeat();
580
+ if (seat === null) { me.has = false; return; }
581
+ // Host-driven (host movement, or knocked back on a replica): stepReplica predicts me instead.
582
+ if (!net.owned) { fall(me, dt); return; }
583
+ fall(me, dt);
584
+ if (me.knockUntil > net.now()) { slide(me, net.now(), dt); return; }
585
+ landed(me);
586
+ const v = moveVector();
587
+ integrate(me, v.x, v.y, dt);
588
+ }
589
+ /** Which way a body faces: where it goes, once it moves (a knocked body keeps its facing: it flies backwards). */
590
+ function faceOf(o: { vx: number; vy: number; fa: number; knockUntil: number }, now: number): void {
591
+ if (o.knockUntil > now) return;
592
+ if (Math.hypot(o.vx, o.vy) > 0.6) o.fa = Math.atan2(o.vx, o.vy);
593
+ }
594
+
595
+ /**
596
+ * Replica, host-driven body. My stick moves me locally every frame (instant response), with the same rule the host
597
+ * runs. When a new snapshot lands: start from where the host has me, replay every intent it had not acknowledged,
598
+ * and pull toward that by 30% (or jump, if it is far). The host stays the truth; I never wait for it.
599
+ */
600
+ let predictedK = -1;
601
+ function predictMe(dt: number): void {
602
+ const v = moveVector();
603
+ integrate(me, v.x, v.y, dt);
604
+ const snap = net.latest();
605
+ if (!snap || snap.k === predictedK) return;
606
+ predictedK = snap.k;
607
+ const p = snap.d.p.find((x) => x[1] === net.seat);
608
+ if (!p) return;
609
+ const pred = { x: p[2], y: p[3], vx: p[5] ?? 0, vy: p[6] ?? 0 };
610
+ for (const f of net.pending()) {
611
+ let left = Math.min(0.25, f.dt / 1000);
612
+ while (left > 0) { const h = Math.min(left, 1 / 60); integrate(pred, f.a[4], f.a[5], h); left -= h; }
613
+ }
614
+ const err = Math.hypot(pred.x - me.x, pred.y - me.y);
615
+ predictionError = err;
616
+ if (!me.has || err > 3) { me.x = pred.x; me.y = pred.y; me.vx = pred.vx; me.vy = pred.vy; }
617
+ else { me.x += (pred.x - me.x) * 0.3; me.y += (pred.y - me.y) * 0.3; }
618
+ me.has = true;
619
+ }
620
+
621
+ function stepKnocked(b: Body, dt: number): void { slide(b, net.now(), dt); }
622
+
623
+ /**
624
+ * THE BOTS, AT THE ROOM'S DIAL (NETPLAY.md section 17), AND NEVER RUNNING AWAY WITH A NEW PLAYER'S ROUND.
625
+ *
626
+ * The dial: a bot re-reads the world only every `reactionMs` (what it last noticed is where it heads, and a miss costs
627
+ * it that long again), aims up to 4 m off at aimNoise 1, leaves the hot zone to the people at positioning 0 and fights
628
+ * for it at 1, and swings at a rival in reach about `aggression x 0.8` times a second. Rookie is beatable by anyone,
629
+ * Maxed by few.
630
+ *
631
+ * On top of the dial, in plain words:
632
+ * A PLAYER'S FIRST ROUND. While somebody plays their first round in this room and nobody has set the dial (no vote,
633
+ * no owner: `net.policy.by` is absent), every bot plays one level easier for that round (Fair plays as Steady). A
634
+ * dial somebody set is always kept exactly.
635
+ * THE RUBBER BAND. Each bot compares its score with the best person's in the room (people only: never a bot, never
636
+ * an AI). Up to LEAD[level] points ahead of them it plays at its dial (2 at Fair, 5 at Strong; a Rookie eases off
637
+ * even a point behind them). Further ahead it eases off, the more the further (LEAD_BAND points more and it is all
638
+ * the way soft): it slows to a walk, notices things later, swings less, and races for the coins near the nearest
639
+ * person rather than the far ones. All the way soft it goes for no coin at all: it keeps near that person, a step
640
+ * up their screen, where a rival is seen (jogging after them when they run off), and goes round the coins on its
641
+ * way. The lead allowed grows with the dial; Maxed has no rubber band (a party that voted Maxed asked for the real
642
+ * thing). Within its lead, a bot always plays at its dial.
643
+ * HONEST. No score is ever changed: no coin is given, taken or faked, and a soft bot still picks up any coin it is
644
+ * knocked or walks onto, like anyone. Bots only play softer. Every bot is labelled where its name or score shows
645
+ * ("· bot"; an AI agent's name ends in "· AI"), on the phone's compact board too.
646
+ */
647
+ const sight = new Map<number, { at: number; tx: number; ty: number; arrived?: boolean; near?: number }>();
648
+ /**
649
+ * The lead (points over the best person) a bot may hold before it eases off, by level: Rookie (it eases off a point
650
+ * BEHIND them: beatable by anyone), Steady, Fair, Strong, Maxed (no rubber band at all).
651
+ */
652
+ const LEAD = [-1, 1, 2, 5, Infinity] as const;
653
+ /** Points past that lead over which a bot goes from its dial to all the way soft. */
654
+ const LEAD_BAND = 2;
655
+ /**
656
+ * Each seated person and the first round they play whole in this room (the round they sat down in, or the next when
657
+ * less than half of it was left). While one of them is in it, nobody set the dial and the bots play a level easier.
658
+ * Kept in the checkpoint, so a promoted host goes on easing the same round.
659
+ */
660
+ let firstRound = new Map<number, number>();
661
+ /** How each bot plays now (its level this round, and how soft the rubber band has it): the `pickups` probe. */
662
+ const botPlay = new Map<number, { level: number; soft: number }>();
663
+
664
+ /** A person sat down: their first whole round here is this one, or the next if less than half of this one is left. */
665
+ function welcome(seat: number | null): void {
666
+ if (seat === null || firstRound.has(seat)) return;
667
+ const live = round?.phase === 'live';
668
+ firstRound.set(seat, !round ? 1 : live && round.endsAt - net.now() > ROUND_MS / 2 ? round.n : round.n + 1);
669
+ }
670
+ /** The people in the room: seated, not a bot, not an AI (an agent that plays its own seat is labelled · AI). */
671
+ function people(): Body[] {
672
+ return [...bodies.values()].filter((b) => !b.bot && b.seat !== null && !b.name.endsWith(AI_MARK) && !roster.slots.find((x) => x.slot === b.slot)?.agent);
673
+ }
674
+ /** Somebody is playing their first round in this room now. */
675
+ function newcomerRound(folk: Body[]): boolean {
676
+ return Boolean(round) && folk.some((b) => (firstRound.get(b.seat as number) ?? 0) >= (round as RoundInfo).n);
677
+ }
678
+ /** The dial a bot plays at this round: the room's, or a level easier in a newcomer's first round when nobody set it. */
679
+ function dialOf(slot: number, easy: boolean): Skill {
680
+ const s: Skill = net.skillOf(slot); // Fair when nobody set a dial
681
+ return easy && !net.policy.by && s.level > 1 ? skillPreset(s.level - 1, net.policy.kids) : s;
682
+ }
683
+ /** The rubber band: 0 plays at the dial, 1 all the way soft, from how far this bot leads the best person. */
684
+ function softness(b: Body, s: Skill, best: number | null): number {
685
+ const allowed = LEAD[Math.max(1, Math.min(5, s.level)) - 1] as number;
686
+ if (best === null || !Number.isFinite(allowed)) return 0;
687
+ return Math.max(0, Math.min(1, (b.score - best - allowed) / LEAD_BAND));
688
+ }
689
+ /** The nearest of `list` to `b`, or null. */
690
+ function nearestOf(list: Body[], b: Body): Body | null {
691
+ let best: Body | null = null; let bd = Infinity;
692
+ for (const o of list) { const d = Math.hypot(o.x - b.x, o.y - b.y); if (d < bd) { bd = d; best = o; } }
693
+ return best;
694
+ }
695
+ /**
696
+ * All the way soft: a spot near person `p`, 2.2 to 3 m off (just past a swing's reach) and a step up their screen
697
+ * (where even a phone held upright shows a rival), turned a little each time it looks, so it keeps round them like a
698
+ * rival waiting for a chance. It leaves the coins to them: of a few such spots, the first it can walk to without
699
+ * running over a coin.
700
+ */
701
+ function beside(b: Body, p: Body): { x: number; y: number } {
702
+ const clear = R_AV + R_GEM + 0.15;
703
+ let spot = { x: b.x, y: b.y };
704
+ for (let i = 0; i < 6; i += 1) {
705
+ let a = Math.atan2(Math.min(b.y - p.y, -0.6), b.x - p.x) + (Math.random() - 0.5) * (1.2 + i * 0.5);
706
+ a = Math.max(-Math.PI + 0.7, Math.min(-0.7, a));
707
+ const r = 2.2 + Math.random() * 0.8;
708
+ spot = bound(p.x + Math.cos(a) * r, p.y + Math.sin(a) * r);
709
+ const dx = spot.x - b.x; const dy = spot.y - b.y; const len2 = dx * dx + dy * dy || 1;
710
+ // The nearest point of the walk to each coin: none closer than a pickup.
711
+ if (!gems.some((g) => { const u = Math.max(0, Math.min(1, ((g.x - b.x) * dx + (g.y - b.y) * dy) / len2)); return Math.hypot(b.x + dx * u - g.x, b.y + dy * u - g.y) < clear; })) break;
712
+ }
713
+ return spot;
714
+ }
715
+
716
+ function stepBots(dt: number): void {
717
+ const taken = new Set<number>();
718
+ const now = net.now();
719
+ const folk = people();
720
+ const best = folk.length ? Math.max(...folk.map((p) => p.score)) : null;
721
+ const easy = newcomerRound(folk);
722
+ for (const b of bodies.values()) {
723
+ if (!b.bot) continue;
724
+ fall(b, dt);
725
+ const leap = dodgeAt.get(b.slot);
726
+ if (leap !== undefined && now >= leap) { dodgeAt.delete(b.slot); if (b.h <= 0 && b.knockUntil <= now) { b.vh = jumpSpeed(); b.h = 1e-3; jumped(b.slot); net.send('jump', { slot: b.slot }); } }
727
+ if (b.knockUntil > now) { stepKnocked(b, dt); continue; }
728
+ landed(b);
729
+ if (lab.stage === 'dummy' || lab.stage === 'jump') { standStill(b, dt); continue; }
730
+ const s = dialOf(b.slot, easy);
731
+ const soft = softness(b, s, best); // THE RUBBER BAND
732
+ botPlay.set(b.slot, { level: s.level, soft });
733
+ let eye = sight.get(b.slot);
734
+ // REACTION TIME: later when soft (it notices coins late); all the way soft it only keeps up with its person.
735
+ if (!eye || now - eye.at >= s.reactionMs * (soft >= 1 ? 1 : 1 + 2.5 * soft)) {
736
+ const near = soft > 0 ? nearestOf(folk, b) : null;
737
+ let g: Gem | null = null;
738
+ let tx = b.tx; let ty = b.ty;
739
+ if (near && soft >= 1) { const at = beside(b, near); tx = at.x; ty = at.y; } // all the way soft: no coin, near them
740
+ else {
741
+ g = pickGem(b, taken, s, near, soft); // POSITIONING (soft: the coins near the nearest person)
742
+ const miss = 4 * s.aimNoise; // AIM NOISE: up to 4 m off at 1
743
+ if (g) { tx = g.x + (Math.random() - 0.5) * miss; ty = g.y + (Math.random() - 0.5) * miss; }
744
+ }
745
+ eye = { at: now, tx, ty, ...(near && soft >= 1 ? { near: near.slot } : {}) };
746
+ sight.set(b.slot, eye);
747
+ if (g) taken.add(g.id);
748
+ }
749
+ b.tx = eye.tx; b.ty = eye.ty;
750
+ const rival = nearestBody(b, T.knockRange * 0.9); // AGGRESSION: swings at a rival in reach, turning to it (less when soft)
751
+ if (rival && round?.phase === 'live' && Math.random() < s.aggression * (1 - 0.75 * soft) * 0.8 * dt) { b.fa = Math.atan2(rival.x - b.x, rival.y - b.y); startSwing(b); }
752
+ const dx = b.tx - b.x; const dy = b.ty - b.y; const dist = Math.hypot(dx, dy);
753
+ const len = dist || 1;
754
+ // Arrived where it aimed: it stands there, and notices what it missed only a reaction later.
755
+ if (dist < 0.12 && !eye.arrived) { eye.arrived = true; eye.at = now; }
756
+ // Soft: down to a walk; all the way soft it jogs back to its person when they have run off (a rival in view).
757
+ const kept = eye.near !== undefined ? bodies.get(eye.near) : undefined;
758
+ const far = kept ? Math.hypot(kept.x - b.x, kept.y - b.y) > 3.5 : false;
759
+ const speed = dist < 0.12 ? 0 : BOT_SPEED * (far ? 1 : 1 - 0.5 * soft);
760
+ const k = Math.min(1, dt * 5);
761
+ b.vx += ((dx / len) * speed - b.vx) * k;
762
+ b.vy += ((dy / len) * speed - b.vy) * k;
763
+ // All the way soft it steps round a coin in its way (turning a little, or a lot, or it waits): it leaves them to
764
+ // the people. It still takes one it is knocked onto, or one that lands under it: the rules' pickups are anyone's.
765
+ if (kept) sidestep(b, dt);
766
+ const p = bound(b.x + b.vx * dt, b.y + b.vy * dt);
767
+ b.x = p.x; b.y = p.y;
768
+ faceOf(b, now);
769
+ }
770
+ }
771
+ /** A soft bot's step that would touch a coin turns aside (60, then 120 degrees, either way), or it stands this frame. */
772
+ function sidestep(b: Body, dt: number): void {
773
+ const reach = R_AV + R_GEM + 0.06;
774
+ const look = Math.max(0.25, Math.hypot(b.vx, b.vy) * dt * 4); // a few frames ahead
775
+ const touches = (vx: number, vy: number): boolean => {
776
+ const sp = Math.hypot(vx, vy) || 1; const x = b.x + (vx / sp) * look; const y = b.y + (vy / sp) * look;
777
+ return gems.some((g) => Math.hypot(g.x - x, g.y - y) < reach && Math.hypot(g.x - x, g.y - y) < Math.hypot(g.x - b.x, g.y - b.y));
778
+ };
779
+ if (Math.hypot(b.vx, b.vy) < 0.05 || !touches(b.vx, b.vy)) return;
780
+ for (const a of [1.05, -1.05, 2.1, -2.1]) {
781
+ const c = Math.cos(a); const sn = Math.sin(a);
782
+ const vx = b.vx * c - b.vy * sn; const vy = b.vx * sn + b.vy * c;
783
+ if (!touches(vx, vy)) { b.vx = vx; b.vy = vy; return; }
784
+ }
785
+ b.vx = 0; b.vy = 0;
786
+ }
787
+ /**
788
+ * A bot sees a swing start near it: it may JUMP it, after its reaction time (half of it: a swing is loud), the more
789
+ * likely the better its aim at the dial (a Rookie is caught, a Maxed bot hops most of them; a soft one less often).
790
+ */
791
+ const dodgeAt = new Map<number, number>();
792
+ function botsSee(from: Body): void {
793
+ const easy = newcomerRound(people());
794
+ for (const b of bodies.values()) {
795
+ if (!b.bot || b === from || lab.stage === 'dummy' || lab.stage === 'jump') continue;
796
+ if (Math.hypot(b.x - from.x, b.y - from.y) > T.knockRange + 0.6) continue;
797
+ const s = dialOf(b.slot, easy);
798
+ const soft = botPlay.get(b.slot)?.soft ?? 0;
799
+ if (Math.random() < (0.15 + 0.6 * (1 - s.aimNoise)) * (1 - 0.5 * soft)) dodgeAt.set(b.slot, net.now() + Math.max(40, s.reactionMs * 0.5 - 60));
800
+ }
801
+ }
802
+
803
+ /**
804
+ * Positioning: 0 leaves the hot zone to the people, 1 fights for it. A soft bot (`pull` 0 to 1) weighs how far each
805
+ * coin is from the person `near` it too, so it races for theirs, where they can see it and beat it to them.
806
+ */
807
+ function pickGem(b: Body, taken: Set<number>, s: Skill, near: Body | null = null, pull = 0): Gem | null {
808
+ let best: Gem | null = null; let bd = Infinity;
809
+ for (const g of gems) {
810
+ if (taken.has(g.id)) continue;
811
+ const hot = zone !== null && Math.hypot(g.x - zone.x, g.y - zone.y) < zone.r;
812
+ const d = Math.hypot(g.x - b.x, g.y - b.y) * (hot ? 1.5 - s.positioning : 1) + (near ? 2 * pull * Math.hypot(g.x - near.x, g.y - near.y) : 0);
813
+ if (d < bd) { bd = d; best = g; }
814
+ }
815
+ return best;
816
+ }
817
+
818
+ /** The nearest other body within `range` (a bot's rival), or null. */
819
+ function nearestBody(b: Body, range: number): Body | null {
820
+ let best: Body | null = null; let bd = range;
821
+ for (const o of bodies.values()) {
822
+ if (o === b) continue;
823
+ const d = Math.hypot(o.x - b.x, o.y - b.y);
824
+ if (d < bd) { bd = d; best = o; }
825
+ }
826
+ return best;
827
+ }
828
+
829
+ function stepHost(dt: number): void {
830
+ tick += 1;
831
+ const seat = mySeat();
832
+ const now0 = net.now();
833
+ for (const b of bodies.values()) {
834
+ if (b.bot) continue;
835
+ if (b.seat === seat) {
836
+ me.has = true;
837
+ b.x = me.x; b.y = me.y; b.vx = me.vx; b.vy = me.vy; b.h = me.h; b.vh = me.vh;
838
+ faceOf(b, now0);
839
+ continue;
840
+ }
841
+ if (b.seat === null) continue;
842
+ const ctl = net.control(b.seat);
843
+ if (ctl.taken || b.knockUntil > now0) { stepKnocked(b, dt); fall(b, dt); if (net.takePresses(b.seat)['swing']) startSwing(b); continue; } // the host drives the knockback
844
+ if (MOVEMENT === 'host') {
845
+ // Host movement: the seat sends intents; the rules move the body (and jump it).
846
+ const f = net.inputOf(b.seat);
847
+ integrate(b, f ? Number(f.a?.[4]) : 0, f ? Number(f.a?.[5]) : 0, dt);
848
+ const pr = net.takePresses(b.seat);
849
+ if (pr['jump'] && b.h <= 0) { b.vh = jumpSpeed(); b.h = 1e-3; }
850
+ fall(b, dt);
851
+ faceOf(b, now0);
852
+ if (pr['swing']) startSwing(b);
853
+ continue;
854
+ }
855
+ const a = net.avatar(b.seat); // null while taken, or until the owner has adopted the last reset
856
+ if (a && Array.isArray(a)) {
857
+ // Client-owned movement, bounded: to the arena, and to 1.3x top speed per frame. A legitimate avatar catches
858
+ // up within a frame; a teleport crawls, and a claim more than half a second of running away is reset.
859
+ const claim = bound(Number(a[0]) || 0, Number(a[1]) || 0);
860
+ const m = capMove(b, claim, SPEED * 1.3 * dt + 0.12);
861
+ if (m.over > SPEED * 0.5) { net.reset(b.seat); cheatResets += 1; }
862
+ else { b.x = m.x; b.y = m.y; b.vx = Number(a[2]) || 0; b.vy = Number(a[3]) || 0; }
863
+ // Its height is the owner's too, bounded by how high a jump goes.
864
+ b.h = Math.max(0, Math.min(T.jumpHeight * 1.15 + 0.05, Number(a[6]) || 0));
865
+ faceOf(b, now0);
866
+ }
867
+ if (net.takePresses(b.seat)['swing']) startSwing(b);
868
+ }
869
+ stepBots(dt);
870
+ landSwings();
871
+ const now = net.now();
872
+ if (round && round.phase === 'live') {
873
+ if (!zone || now >= zone.until) setZone(newZone((zone?.n ?? 0) + 1));
874
+ for (const b of bodies.values()) {
875
+ for (let i = 0; i < gems.length; i += 1) {
876
+ const g = gems[i] as Gem;
877
+ if (Math.hypot(g.x - b.x, g.y - b.y) < R_AV + R_GEM) {
878
+ b.score += zone && Math.hypot(g.x - zone.x, g.y - zone.y) < zone.r ? 2 : 1;
879
+ pickups.set(b.slot, (pickups.get(b.slot) ?? 0) + 1);
880
+ gems[i] = newGem();
881
+ }
882
+ }
883
+ }
884
+ if (now >= round.endsAt) endRound();
885
+ } else if (round && round.phase === 'over' && now >= round.endsAt) startRound(round.n + 1);
886
+ if (net.snapshotDue()) net.snapshot(buildSnap(), tick);
887
+ }
888
+
889
+ function buildSnap(): Snap {
890
+ const r = round ?? { n: 0, phase: 'live', startedAt: 0, endsAt: 0 };
891
+ return {
892
+ r: [r.n, r.phase === 'over' ? 1 : 0, r.startedAt, r.endsAt],
893
+ p: [...bodies.values()].map((b) => [b.slot, b.seat ?? -1, q(b.x, 2), q(b.y, 2), b.score, q(b.vx, 1), q(b.vy, 1), q(b.h, 2)] as P),
894
+ g: gems.map((g) => [g.id, q(g.x, 2), q(g.y, 2)] as G),
895
+ };
896
+ }
897
+
898
+ function stepReplica(dt: number): void {
899
+ const seat = net.seat;
900
+ if (seat !== null) {
901
+ // Host-driven (host movement, or taken for a knockback): predict from the host's position and my intents.
902
+ if (!net.owned) predictMe(dt);
903
+ // Only once I have a body (the first control event adopts it): before that my position is nobody's.
904
+ if (me.has) {
905
+ const v = moveVector();
906
+ // Stick direction as held "buttons": a new direction is a press edge, so it is sent within 16 ms.
907
+ const held = [v.x > 0.2 ? 'R' : v.x < -0.2 ? 'L' : '', v.y > 0.2 ? 'D' : v.y < -0.2 ? 'U' : ''].filter(Boolean);
908
+ net.input([q(me.x, 2), q(me.y, 2), q(me.vx, 1), q(me.vy, 1), q(v.x, 2), q(v.y, 2), q(me.h, 2)], held);
909
+ }
910
+ }
911
+ const smp = net.sample();
912
+ drawn.clear();
913
+ if (!smp) return;
914
+ const bySlot = new Map<number, P>(smp.a.d.p.map((p) => [p[0], p]));
915
+ for (const pb of smp.b.d.p) {
916
+ const pa = bySlot.get(pb[0]) ?? pb;
917
+ drawn.set(pb[0], { slot: pb[0], seat: pb[1], x: lerp(pa[2], pb[2], smp.alpha), y: lerp(pa[3], pb[3], smp.alpha), h: Math.max(0, lerp(Number(pa[7]) || 0, Number(pb[7]) || 0, smp.alpha)), score: pb[4] });
918
+ }
919
+ const [n, ph, startedAt, endsAt] = smp.b.d.r;
920
+ if (!round || round.n !== n || (round.phase === 'over') !== (ph === 1)) {
921
+ const kept = net.roundInfo && net.roundInfo.n === n ? net.roundInfo : null;
922
+ round = kept ?? { n, phase: ph ? 'over' : 'live', startedAt, endsAt };
923
+ }
924
+ }
925
+
926
+ /* -------------------------------------------------------------- how a swing, a hit and a jump look */
927
+ /*
928
+ * Every screen draws a swing from the swing event (the host's own, or the one it sends): the hero plays its attack (on
929
+ * the upper body when it runs) and a slash arcs in front of it. A bump comes from the knock event: the hit lands (the
930
+ * hero flashes white, flinches and holds through the hit-stop, shaking), flies (stretched along the hit, less as it
931
+ * slows), stops (squashed, then a wobble that dies away: overlap), throws sparks, and kicks the camera of whoever was
932
+ * in it. A jump plays from the jump event and the height in the snapshot; a dodge (a swing passing under a jumper)
933
+ * pops a word. Sparks and the camera's kick roll lab.random(): their own dice, so the world's (Math.random) stay the
934
+ * same as a build without them, which the Game Lab needs to compare two.
935
+ */
936
+ const bumps = new Map<number, { at: number; dx: number; dy: number }>();
937
+ const pushes = new Map<number, number>();
938
+ const sparks: { x: number; y: number; h: number; vx: number; vy: number; vh: number; at: number; life: number; gold?: boolean }[] = [];
939
+ let kickAt = -1e9;
940
+ function bumped(d: { slot: number; dx?: number; dy?: number; by?: number }, at: { x: number; y: number }): void {
941
+ const now = performance.now();
942
+ const dx = Number(d.dx) || 0; const dy = Number(d.dy) || 0;
943
+ bumps.set(d.slot, { at: now, dx, dy });
944
+ const base = Math.atan2(dy, dx);
945
+ for (let i = 0; i < T.sparks; i += 1) {
946
+ const a = base + (lab.random() - 0.5) * 1.6;
947
+ const v = 8.4 + lab.random() * 10.4;
948
+ sparks.push({ x: at.x - dx * R_AV * 0.6, y: at.y - dy * R_AV * 0.6, h: 0.45, vx: Math.cos(a) * v, vy: Math.sin(a) * v, vh: 1 + lab.random() * 3, at: now, life: 170 + lab.random() * 170 });
949
+ }
950
+ if (sparks.length > 160) sparks.splice(0, sparks.length - 160);
951
+ // The camera kicks for whoever was in it: the body bumped, or the one who waved.
952
+ const mine = hosting ? [...bodies.values()].find((x) => x.seat !== null && x.seat === mySeat())?.slot : [...drawn.values()].find((x) => x.seat === net.seat)?.slot;
953
+ if (mine !== undefined && (d.slot === mine || d.by === mine)) kickAt = now;
954
+ const hero = heroes.get(d.slot)?.char;
955
+ if (hero) hero.hit(dx, dy, 1);
956
+ }
957
+ /** A swing started: its hero plays its action (the mage casts, the rest strike). */
958
+ function swung(slot: number): void {
959
+ const h = heroes.get(slot);
960
+ if (!h?.char) return;
961
+ h.char.act(h.char.has(HERO_ACTION[h.kind] ?? 'attack') ? (HERO_ACTION[h.kind] ?? 'attack') : 'attack', { from: T.swingSkip });
962
+ labSwing(slot);
963
+ }
964
+ /** A jump started (its own owner jumped it; bots by the host). */
965
+ function jumped(slot: number): void {
966
+ jumpsSeen += 1;
967
+ heroes.get(slot)?.char?.jump();
968
+ }
969
+ /** A swing passed under a jumper: a word pops over it. */
970
+ const pops: { slot: number; at: number; text: string }[] = [];
971
+ function dodged(slot: number): void {
972
+ dodgesSeen += 1;
973
+ pops.push({ slot, at: performance.now(), text: 'Dodged!' });
974
+ if (pops.length > 12) pops.shift();
975
+ }
976
+ /** A gem taken: a little gold burst where it was (drawn on every screen from the gem list; the rules never see it). */
977
+ function sparkle(x: number, y: number): void {
978
+ const now = performance.now();
979
+ for (let i = 0; i < 7; i += 1) {
980
+ const a = lab.random() * Math.PI * 2; const v = 1.5 + lab.random() * 2.5;
981
+ sparks.push({ x, y, h: 0.35, vx: Math.cos(a) * v, vy: Math.sin(a) * v, vh: 3 + lab.random() * 3, at: now, life: 260 + lab.random() * 200, gold: true });
982
+ }
983
+ if (sparks.length > 160) sparks.splice(0, sparks.length - 160);
984
+ }
985
+ /**
986
+ * A body's look this frame: offset (m), stretch along the hit (sx) and across it (sy), height (up), the hit's angle
987
+ * on the ground, and how white it flashes.
988
+ */
989
+ function bodyFx(slot: number, t: number): { ox: number; oy: number; sx: number; sy: number; up: number; ang: number; flash: number } {
990
+ const out = { ox: 0, oy: 0, sx: 1, sy: 1, up: 1, ang: 0, flash: 0 };
991
+ const p = pushes.get(slot);
992
+ if (p !== undefined) { const u = (t - p) / 170; if (u >= 0 && u < 1) { const k = 0.14 * Math.sin(Math.PI * u); out.sx = 1 + k; out.sy = 1 + k; out.up = 1 + k; } }
993
+ const b = bumps.get(slot);
994
+ if (!b) return out;
995
+ const age = t - b.at;
996
+ const hs = T.hitStopMs; const end = hs + T.knockMs;
997
+ if (age > end + T.settleMs + 200) { bumps.delete(slot); return out; }
998
+ out.ang = Math.atan2(b.dy, b.dx);
999
+ out.flash = T.flashMs > 0 ? Math.max(0, 1 - age / T.flashMs) : 0;
1000
+ let k = 0;
1001
+ if (age < hs) { k = -T.squash * 0.45; out.ox = Math.sin(age * 0.9) * 0.06; out.oy = Math.cos(age * 1.3) * 0.06; }
1002
+ else if (age < end) k = T.squash * (1 - (age - hs) / T.knockMs) ** Math.max(0, T.knockEase - 1);
1003
+ else if (T.settleMs > 0 && age < end + T.settleMs) { const w = (age - end) / T.settleMs; k = -T.squash * 0.8 * Math.exp(-3 * w) * Math.sin(2.5 * Math.PI * w); }
1004
+ out.sx *= 1 + k; out.sy *= 1 / (1 + k); out.up *= 1 / Math.sqrt(Math.max(0.2, 1 + k));
1005
+ return out;
1006
+ }
1007
+
1008
+ /* -------------------------------------------------------------- the Game Lab */
1009
+ /*
1010
+ * What the lab shows (lab.json's takes):
1011
+ * "swing" stage dummy: you swing at the dummy beside you. WINDUP (from the press to the moment it lands: the
1012
+ * anticipation), then the dummy's HIT-STOP, LAUNCH, SLIDE and SETTLE. Tracks its speed and distance.
1013
+ * "jump" stage jump: you jump in an empty space. TAKE-OFF, RISE, HANG (near the top), FALL, LAND. Tracks the height
1014
+ * and the body's stretch (the animator's squash and stretch).
1015
+ * The onion skin and the spacing arc (dots far apart: fast; close together: slow) are drawn as lines on the meadow.
1016
+ * Only in the lab: outside it, labKnock, labSwing and labReport never run.
1017
+ */
1018
+ type Pose = { x: number; y: number; sx?: number; sy?: number; a?: number };
1019
+ /**
1020
+ * The take's stage "dummy" (lab.stage, only ever set by the lab): you stand left of the middle, facing a bot a short
1021
+ * step to your right, and every bot stands still unless it is bumped, like a training dummy. Stage "jump": you stand in
1022
+ * the middle with nobody near.
1023
+ */
1024
+ function stageDummy(): void {
1025
+ const seat = mySeat();
1026
+ const list = [...bodies.values()].sort((a, c) => a.slot - c.slot);
1027
+ const mine = list.find((b) => !b.bot && b.seat === seat);
1028
+ const bots = list.filter((b) => b.bot);
1029
+ const jumpStage = lab.stage === 'jump';
1030
+ if (mine) { mine.x = W / 2 - (jumpStage ? 0 : 3.2); mine.y = H / 2; mine.fa = Math.PI / 2; hostMoved(mine); }
1031
+ bots.forEach((b, i) => { b.x = i === 0 && !jumpStage ? W / 2 - 3.2 + 1.5 : W - 3.6; b.y = i === 0 && !jumpStage ? H / 2 : 3 + i * 5; b.tx = b.x; b.ty = b.y; b.fa = -Math.PI / 2; });
1032
+ }
1033
+ /** A dummy at rest: it eases to a stop wherever the last bump left it. */
1034
+ function standStill(b: Body, dt: number): void {
1035
+ const k = Math.min(1, dt * 5);
1036
+ b.vx -= b.vx * k; b.vy -= b.vy * k;
1037
+ const p = bound(b.x + b.vx * dt, b.y + b.vy * dt); b.x = p.x; b.y = p.y;
1038
+ }
1039
+ const subject = { slot: -1, at: 0, x0: 0, y0: 0, px: 0, py: 0, has: false };
1040
+ const swinger = { slot: -1, at: 0 };
1041
+ function labKnock(b: Body): void {
1042
+ if (!lab.on) return;
1043
+ subject.slot = b.slot; subject.at = net.now(); subject.x0 = b.x; subject.y0 = b.y; subject.px = b.x; subject.py = b.y; subject.has = true;
1044
+ }
1045
+ function labSwing(slot: number): void { if (lab.on) { swinger.slot = slot; swinger.at = net.now(); } }
1046
+ /** Where the subject is now (the host's own body is `me`), or null. */
1047
+ function subjectAt(): Pose | null {
1048
+ if (!subject.has) return null;
1049
+ const b = bodies.get(subject.slot);
1050
+ if (!b) return null;
1051
+ return !b.bot && b.seat !== null && b.seat === mySeat() ? me : b;
1052
+ }
1053
+ let apex = 0;
1054
+ function labReport(dt: number): void {
1055
+ if (dt <= 0) return;
1056
+ if (lab.stage === 'jump') {
1057
+ const hero = [...heroes.values()].find((x) => x.mine)?.char ?? null;
1058
+ lab.track('height', me.h, 'm');
1059
+ lab.track('stretch', hero ? (hero.root.children[0]?.scale.y ?? 1) * 100 - 100 : 0, '%');
1060
+ if (me.h <= 0) { lab.phase(hero?.state === 'LAND' ? 'LAND' : null, 'Squash on touch-down, then back to the run'); apex = 0; }
1061
+ else if (me.vh > jumpSpeed() * 0.55) lab.phase('TAKE-OFF', 'Leaves fast and stretched');
1062
+ else if (me.vh > jumpSpeed() * 0.15) lab.phase('RISE', 'Slows as it climbs');
1063
+ else if (me.vh > -jumpSpeed() * 0.25) { lab.phase('HANG', 'A moment at the top to read it'); apex = Math.max(apex, me.h); }
1064
+ else lab.phase('FALL', `Down ${T.fallFaster.toFixed(1)}x harder than up: weight`);
1065
+ lab.pose('subject', { x: me.x, y: me.y - me.h, sx: 1, sy: 1, a: 0 });
1066
+ return;
1067
+ }
1068
+ const at = subjectAt();
1069
+ const sinceSwing = net.now() - swinger.at;
1070
+ if (swinger.slot >= 0 && sinceSwing < T.windupMs && (!at || net.now() - subject.at > T.hitStopMs + T.knockMs + T.settleMs)) {
1071
+ lab.phase('WINDUP', 'The swing gathers: what you see before it lands');
1072
+ lab.track('speed', 0, 'm/s');
1073
+ return;
1074
+ }
1075
+ if (!at) { lab.phase(null); return; }
1076
+ const age = net.now() - subject.at;
1077
+ lab.track('speed', Math.hypot(at.x - subject.px, at.y - subject.py) / dt, 'm/s');
1078
+ lab.track('distance', Math.hypot(at.x - subject.x0, at.y - subject.y0), 'm');
1079
+ subject.px = at.x; subject.py = at.y;
1080
+ const fx = bodyFx(subject.slot, performance.now());
1081
+ lab.track('stretch', (fx.sx - 1) * 100, '%');
1082
+ if (age < T.hitStopMs) lab.phase('HIT-STOP', 'The hit lands: hold, flash, flinch');
1083
+ else if (age < T.hitStopMs + T.knockMs * 0.3) lab.phase('LAUNCH', 'Leaves fast, stretched along the hit');
1084
+ else if (age < T.hitStopMs + T.knockMs) lab.phase('SLIDE', 'Eases into the stop: no creep, no pop');
1085
+ else if (age < T.hitStopMs + T.knockMs + T.settleMs) lab.phase('SETTLE', 'Squash on the stop, overlap on the way out');
1086
+ else lab.phase(null);
1087
+ lab.pose('subject', { x: at.x, y: at.y, sx: fx.sx, sy: fx.sy, a: fx.ang });
1088
+ }
1089
+ /** The lab's views: the game's own camera, close on the action, the whole arena. */
1090
+ const labView = lab.camera<{ zoom?: number; whole?: boolean } | null>({ game: null, close: { zoom: 2.4 }, arena: { whole: true } });
1091
+
1092
+ /* ================================================================== THE LOOK */
1093
+
1094
+ /* ------------------------------------------------------------------ style.json */
1095
+ interface StyleTokens {
1096
+ palette: { bg: string; ink: string; accent: string; accent2: string; danger: string; good: string; gold: string; ramp?: string[] };
1097
+ fonts?: { display?: string; body?: string } | null;
1098
+ light?: { time?: string; key?: number[]; intensity?: number; hardness?: number; sky?: string; ground?: string; fog?: number } | null;
1099
+ camera?: { pitch?: number; distance?: number; fov?: number } | null;
1100
+ render?: string;
1101
+ materials?: { model?: string; outline?: boolean } | null;
1102
+ }
1103
+ const STYLE = styleFile as unknown as StyleTokens & { materials?: { model?: string; outline?: boolean } };
1104
+ /**
1105
+ * How the room scores (game.json "scoring"): "rivals" (the default: a ranking, a winner) or "together" (one total the
1106
+ * whole room fills, each player's share shown without places: a cozy game's room works as one). The rules are the
1107
+ * same; only what the HUD and the results card say changes.
1108
+ */
1109
+ const TOGETHER = (gameFile as { scoring?: string }).scoring === 'together';
1110
+ const PAL = STYLE.palette;
1111
+ const LIGHT = { key: [-0.5, -1, -0.35], intensity: 2.2, hardness: 0.35, sky: PAL.bg, ground: PAL.accent2, fog: 0.35, ...(STYLE.light ?? {}) };
1112
+ const CAM = { pitch: 52, distance: 22, fov: 38, ...(STYLE.camera ?? {}) };
1113
+ /** Two colours mixed in sRGB (k = 0: a, 1: b), as a hex string. */
1114
+ function mixHex(a: string, b: string, k: number): string {
1115
+ const pa = new Color(a).getHex(); const pb = new Color(b).getHex();
1116
+ const ch = (v: number, s: number): number => (v >> s) & 255;
1117
+ const m = (s: number): number => Math.round(ch(pa, s) + (ch(pb, s) - ch(pa, s)) * k);
1118
+ return `#${((m(16) << 16) | (m(8) << 8) | m(0)).toString(16).padStart(6, '0')}`;
1119
+ }
1120
+ /** sRGB luminance, 0 to 1. */
1121
+ function lumOf(hex: string): number { const c = new Color(hex).getHex(); return (0.2126 * ((c >> 16) & 255) + 0.7152 * ((c >> 8) & 255) + 0.0722 * (c & 255)) / 255; }
1122
+ /**
1123
+ * The HUD's paper and its text: the palette's light colour as paper (cream cards, like the title card) and its dark
1124
+ * one as text, whichever way round the palette has them, so every chip and card reads and they are one UI.
1125
+ */
1126
+ const PAPER = lumOf(PAL.ink) >= lumOf(PAL.bg) ? PAL.ink : PAL.bg;
1127
+ const TEXT = lumOf(PAL.ink) >= lumOf(PAL.bg) ? mixHex(PAL.bg, '#000000', 0.25) : PAL.ink;
1128
+ const HOT = lumOf(PAL.accent) > 0.62 ? mixHex(PAL.accent, TEXT, 0.35) : PAL.accent;
1129
+ /** A night light (style.json light.time): the grass goes dark with it. */
1130
+ const NIGHT = LIGHT.time === 'night';
1131
+ /** The world's own colours, all from the palette: so a new style.json repaints everything the code draws. */
1132
+ const COL = {
1133
+ sky: LIGHT.sky ?? PAL.bg,
1134
+ // The ground of the style board when the light names one (a night grove is dark grass), else the palette's greens.
1135
+ // Grass is the palette's greens, a little shaded, tinted by the light's ground colour (a night grove is darker, a
1136
+ // golden hour warmer): never the light's ground alone, which can be mud.
1137
+ meadow: mixHex(mixHex(mixHex(PAL.good, PAL.accent2, 0.55), PAL.bg, NIGHT ? 0.55 : 0.08), STYLE.light?.ground ?? PAL.accent2, NIGHT ? 0.3 : 0.06),
1138
+ meadowSpot: mixHex(mixHex(mixHex(PAL.good, PAL.accent2, 0.55), NIGHT ? PAL.bg : PAL.gold, NIGHT ? 0.45 : 0.14), STYLE.light?.ground ?? PAL.accent2, NIGHT ? 0.25 : 0.1),
1139
+ floor: mixHex(mixHex(mixHex(PAL.good, PAL.accent2, 0.4), NIGHT ? PAL.bg : PAL.gold, NIGHT ? 0.45 : 0.12), STYLE.light?.ground ?? PAL.good, STYLE.light?.ground ? 0.2 : 0),
1140
+ floorStripe: mixHex(mixHex(mixHex(mixHex(PAL.good, PAL.accent2, 0.4), NIGHT ? PAL.bg : PAL.gold, NIGHT ? 0.45 : 0.12), STYLE.light?.ground ?? PAL.good, STYLE.light?.ground ? 0.2 : 0), PAL.bg, 0.08),
1141
+ // The arena's edge: a worn earth-and-moss path, a step from the grass, never a painted stripe.
1142
+ path: mixHex(mixHex(PAL.good, PAL.accent2, 0.5), mixHex(PAL.accent, PAL.ink, 0.55), 0.38),
1143
+ shadow: mixHex(PAL.ink, PAL.accent2, 0.25),
1144
+ zone: PAL.accent,
1145
+ gem: PAL.gold,
1146
+ };
1147
+ const fontStack = (f: string | undefined, rest: string): string => (f && /^[A-Za-z0-9 ]{1,40}$/.test(f) ? `"${f}", ${rest}` : rest);
1148
+ const FONT_DISPLAY = fontStack(STYLE.fonts?.display, 'ui-rounded, system-ui, sans-serif');
1149
+ const FONT_BODY = fontStack(STYLE.fonts?.body, 'ui-rounded, system-ui, sans-serif');
1150
+ /**
1151
+ * style.json's fonts are Google Fonts (OFL): asked for once, without waiting. Until they arrive (or if they never do,
1152
+ * offline or blocked) the HUD draws in the system's rounded face; nothing in a round waits on a font.
1153
+ */
1154
+ function loadFonts(): void {
1155
+ const fams = [STYLE.fonts?.display, STYLE.fonts?.body].filter((f): f is string => typeof f === 'string' && /^[A-Za-z0-9 ]{1,40}$/.test(f));
1156
+ if (!fams.length) return;
1157
+ try {
1158
+ const l = document.createElement('link');
1159
+ l.rel = 'stylesheet';
1160
+ l.href = `https://fonts.googleapis.com/css2?${[...new Set(fams)].map((f) => `family=${f.replace(/ /g, '+')}:wght@600;700`).join('&')}&display=swap`;
1161
+ document.head.appendChild(l);
1162
+ } catch { /* the system's face, then */ }
1163
+ }
1164
+ loadFonts();
1165
+
1166
+ /* ------------------------------------------------------------------ the characters, asked for first */
1167
+ /*
1168
+ * THE CHARACTERS, your own first: the play page's arrival card waits for your own hero's real model (THE ARRIVAL,
1169
+ * below), and your seat (so your hero's kind) is known at the welcome, so the moment it comes your own hero is asked for
1170
+ * alone, followed by its skeleton's clip library; then the other heroes. The bots' skeletons (drawn as stand-ins until
1171
+ * they are in) come after the heroes, or after 4 s at most, so on a slow phone they never share the line with your own
1172
+ * hero. A watcher asks for every hero at once. About 0.67 MB for the heroes and their clips, 0.47 MB for the skeletons
1173
+ * and theirs, 0.15 MB for the meadow's props: the same files as ever, in this order.
1174
+ */
1175
+ const models = createModels();
1176
+ /**
1177
+ * The heroes people play (one a seat, in turn) and the skeletons bots play (one a slot): KayKit's adventurers and
1178
+ * skeletons, one rig family, so one clip library each and one look. Each is drawn HERO_M tall (`game new` made them so).
1179
+ */
1180
+ const HEROES = ['knight', 'barbarian', 'mage', 'rogue', 'rogue-hooded'] as const;
1181
+ const SKELETONS = ['skeleton-minion', 'skeleton-warrior', 'skeleton-rogue', 'skeleton-mage'] as const;
1182
+ const HERO_BUDGET = { triangles: 8000, texturePx: 1024, materials: 2, bytes: 1536 * 1024 };
1183
+ const heroUrl = (kind: string): string => `./models/${kind}.glb`;
1184
+ /** Models that are not there (refused or missing): drawn as stand-ins. */
1185
+ const standIns = new Set<string>();
1186
+ /** THE ARRIVAL's progress line: the files asked for while the game loads, and how many have come (or failed). */
1187
+ const loads = { all: 0, done: 0, heroes: 0, heroesDone: 0, said: 0 };
1188
+ function sayLoading(): void {
1189
+ loads.said = Math.max(loads.said, loads.all ? loads.done / loads.all : 0);
1190
+ net.loading(loads.said, loads.heroesDone < loads.heroes ? 'the heroes' : 'the clearing');
1191
+ }
1192
+ /** One more file on the line (`hero`: a character or its clips); the function it returns says it came or failed. */
1193
+ function expect(hero: boolean): () => void {
1194
+ loads.all += 1; if (hero) loads.heroes += 1;
1195
+ let settled = false;
1196
+ return () => { if (settled) return; settled = true; loads.done += 1; if (hero) loads.heroesDone += 1; sayLoading(); };
1197
+ }
1198
+ function track<T>(p: Promise<T>, hero: boolean): Promise<T> { const done = expect(hero); p.then(done, done); return p; }
1199
+ /** Each kind's model and its clip library, loaded once (loadCharacter finds both in hand); copies are made per body. */
1200
+ const heroLoads = new Map<string, Promise<boolean>>();
1201
+ const clipLoads = new Map<string, Promise<unknown>>();
1202
+ let heroesIn = (): void => {};
1203
+ const afterHeroes = new Promise<void>((done) => { heroesIn = done; setTimeout(done, 4000); });
1204
+ function loadHero(kind: string): Promise<boolean> {
1205
+ let p = heroLoads.get(kind);
1206
+ if (!p) {
1207
+ const url = heroUrl(kind);
1208
+ const came = expect(true);
1209
+ const go = (): Promise<boolean> => models.load(url, { budget: HERO_BUDGET }).then((m) => {
1210
+ came();
1211
+ // Its skeleton's clip library at once (the model names it), at loadCharacter's own address and budget.
1212
+ const named = (m.scene.userData?.homie as { anims?: string } | undefined)?.anims;
1213
+ if (!named) return true;
1214
+ const href = new URL(named, new URL(url, location.href)).href;
1215
+ let clips = clipLoads.get(href);
1216
+ if (!clips) { clips = track(models.load(href, { budget: { triangles: 0, bytes: 3 * 1024 * 1024 } }), true).catch(() => null); clipLoads.set(href, clips); }
1217
+ return clips.then(() => true);
1218
+ }, () => { came(); standIns.add(url); return false; });
1219
+ p = (SKELETONS as readonly string[]).includes(kind) ? afterHeroes.then(go) : go();
1220
+ heroLoads.set(kind, p);
1221
+ }
1222
+ return p;
1223
+ }
1224
+ /** Every hero in (your own first, at the welcome): the skeletons wait for it, and so does the Game Lab. */
1225
+ const allHeroes: Promise<boolean[]> = net.ready.then(() => {
1226
+ const seat = mySeat();
1227
+ const own = seat !== null && !net.watching ? (HEROES[seat % HEROES.length] as string) : null;
1228
+ return (own ? loadHero(own) : Promise.resolve(true)).then(() => Promise.all(HEROES.map(loadHero)));
1229
+ });
1230
+ void allHeroes.then(() => heroesIn());
1231
+ sayLoading();
1232
+ for (const k of SKELETONS) void loadHero(k);
1233
+
1234
+ /* ------------------------------------------------------------------ renderer, scene, light */
1235
+ const renderer = new WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' });
1236
+ // Flat low-poly colours read true without a film curve (the style board renders the same way).
1237
+ renderer.toneMapping = NoToneMapping;
1238
+ const scene = new Scene();
1239
+ scene.background = new Color(COL.sky);
1240
+ scene.fog = new Fog(COL.sky, 40, 90);
1241
+ const camera = new PerspectiveCamera(CAM.fov, 1, 1, 320);
1242
+ // The light of the style board (assets/render-page.ts): a sun along style.json's key, a sky-to-ground fill, a little ambient.
1243
+ /*
1244
+ * Shadows: real ones on a computer (a sun's shadow map that follows the camera, as the style board draws them), soft
1245
+ * discs under things on a phone (the phone budgets: one less pass). Decided once, by the screen the game opens on.
1246
+ */
1247
+ const REAL_SHADOWS = Math.min(innerWidth, innerHeight) > 540;
1248
+ if (REAL_SHADOWS) { renderer.shadowMap.enabled = true; renderer.shadowMap.type = PCFSoftShadowMap; }
1249
+ const SUN_DIR = new Vector3(-(LIGHT.key[0] ?? -0.5), -(LIGHT.key[1] ?? -1), -(LIGHT.key[2] ?? -0.35)).normalize();
1250
+ let sun: DirectionalLight;
1251
+ {
1252
+ const night = LIGHT.time === 'night';
1253
+ sun = new DirectionalLight(night ? mixHex(PAL.accent2, '#ffffff', 0.55) : LIGHT.time === 'golden' ? mixHex(PAL.gold, '#ffffff', 0.62) : '#ffffff', (LIGHT.intensity ?? 2.2) * 1.05);
1254
+ sun.position.copy(SUN_DIR).multiplyScalar(30);
1255
+ if (REAL_SHADOWS) {
1256
+ sun.castShadow = true;
1257
+ sun.shadow.mapSize.set(2048, 2048);
1258
+ Object.assign(sun.shadow.camera, { left: -22, right: 22, top: 22, bottom: -22, near: 1, far: 90 });
1259
+ sun.shadow.bias = -0.0006; sun.shadow.normalBias = 0.03; sun.shadow.radius = 3;
1260
+ scene.add(sun.target);
1261
+ }
1262
+ scene.add(sun, new HemisphereLight(new Color(night ? mixHex(LIGHT.sky ?? PAL.bg, '#9fb4ff', 0.5) : LIGHT.sky), new Color(LIGHT.ground), night ? 1.6 : 1.3), new AmbientLight(0xffffff, night ? 0.35 : 0.25));
1263
+ }
1264
+ const XZ = (x: number, y: number): [number, number] => [x - W / 2, y - H / 2]; // rules (x, y) to three.js (x, z)
1265
+ const EDGE = 0.55; // the path around the arena, metres
1266
+ /**
1267
+ * A clearing (false: the meadow runs on, a ring of bushes and rocks marks the edge) or a fenced, mown pitch (true: the
1268
+ * fence, the striped lawn and the path round it). A cozy game is a clearing; a sport is a pitch.
1269
+ */
1270
+ const FENCED = false;
1271
+
1272
+ /* ------------------------------------------------------------------ the meadow and the arena (procedural) */
1273
+ /** A small seeded dice for the dressing: never Math.random (the world's dice, which the Game Lab keeps the same in both builds). */
1274
+ function dice(seed: number): () => number {
1275
+ let s = seed >>> 0;
1276
+ return () => { s = (s + 0x6d2b79f5) >>> 0; let t = s; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
1277
+ }
1278
+ function canvasTexture(w: number, h: number, paint: (g: CanvasRenderingContext2D) => void): CanvasTexture {
1279
+ const c = document.createElement('canvas'); c.width = w; c.height = h;
1280
+ paint(c.getContext('2d') as CanvasRenderingContext2D);
1281
+ const t = new CanvasTexture(c); t.colorSpace = SRGBColorSpace;
1282
+ return t;
1283
+ }
1284
+ /**
1285
+ * The ground is faceted low poly, like everything standing on it: every triangle its own shade of the palette's greens,
1286
+ * crisp at any distance (no blurred texture). Inside the arena it is flat and mown in broad stripes, so it reads as a
1287
+ * pitch; outside it rolls a little, more the farther it is. heightAt is the one place the ground's height comes from,
1288
+ * so the trees, rocks and shadows stand on it.
1289
+ */
1290
+ const FLAT = EDGE + 5; // metres past the arena's edge that stay flat: the path, the fence, the flowers
1291
+ function heightAt(x: number, z: number): number {
1292
+ const dx = Math.max(0, Math.abs(x) - (W / 2 + FLAT)); const dz = Math.max(0, Math.abs(z) - (H / 2 + FLAT));
1293
+ const away = Math.min(1, Math.hypot(dx, dz) / 14);
1294
+ return away * 0.55 * (0.5 + 0.5 * Math.sin(x * 0.23 + z * 0.11) * Math.cos(z * 0.19 - x * 0.08));
1295
+ }
1296
+ /** A non-indexed triangle list, one colour per triangle (flat faces: each its own normal). */
1297
+ function facets(tris: number[][], colours: string[]): BufferGeometry {
1298
+ const pos = new Float32Array(tris.length * 9); const col = new Float32Array(tris.length * 9); const c = new Color();
1299
+ tris.forEach((t, i) => { pos.set(t, i * 9); c.set(colours[i] as string); for (let k = 0; k < 3; k += 1) col.set([c.r, c.g, c.b], i * 9 + k * 3); });
1300
+ const g = new BufferGeometry();
1301
+ g.setAttribute('position', new BufferAttribute(pos, 3)); g.setAttribute('color', new BufferAttribute(col, 3));
1302
+ g.computeVertexNormals();
1303
+ return g;
1304
+ }
1305
+ {
1306
+ // The meadow: a jittered 2.2 m grid, gently rolling away from the arena.
1307
+ const roll = dice(11);
1308
+ const cell = 2.2; const x0 = -110; const z0 = -120; const nx = 100; const nz = 82;
1309
+ const vx: number[] = []; const vz: number[] = [];
1310
+ for (let j = 0; j <= nz; j += 1) for (let i = 0; i <= nx; i += 1) {
1311
+ const edge = i === 0 || j === 0 || i === nx || j === nz;
1312
+ vx.push(x0 + i * cell + (edge ? 0 : (roll() - 0.5) * cell * 0.6)); vz.push(z0 + j * cell + (edge ? 0 : (roll() - 0.5) * cell * 0.6));
1313
+ }
1314
+ const at = (i: number, j: number): [number, number, number] => { const k = j * (nx + 1) + i; const x = vx[k] as number; const z = vz[k] as number; return [x, heightAt(x, z) - 0.01, z]; };
1315
+ // Shades a step apart, never a patchwork: the faces read as facets, not as tiles.
1316
+ const tones = [COL.meadow, COL.meadow, mixHex(COL.meadow, mixHex(PAL.good, PAL.ink, 0.25), 0.18), mixHex(COL.meadow, COL.meadowSpot, 0.3), mixHex(COL.meadow, PAL.ink, 0.04), mixHex(COL.meadow, PAL.bg, 0.07)];
1317
+ const tris: number[][] = []; const cols: string[] = [];
1318
+ for (let j = 0; j < nz; j += 1) for (let i = 0; i < nx; i += 1) {
1319
+ const a = at(i, j); const b = at(i + 1, j); const c = at(i + 1, j + 1); const d = at(i, j + 1);
1320
+ const flip = roll() < 0.5;
1321
+ for (const t of flip ? [[a, d, b], [b, d, c]] : [[a, d, c], [a, c, b]]) { tris.push(t.flat()); cols.push(tones[Math.floor(roll() * tones.length)] as string); }
1322
+ }
1323
+ const meadow = new Mesh(facets(tris, cols), new MeshLambertMaterial({ vertexColors: true }));
1324
+ meadow.receiveShadow = REAL_SHADOWS;
1325
+ stylize(meadow, STYLE);
1326
+ scene.add(meadow);
1327
+ // The arena: a mown lawn, stripes 4 m wide so it reads as a pitch at a glance, faceted in 1 m triangles whose
1328
+ // shades differ a little (the same hand as the meadow, never a painted texture).
1329
+ const lawn = dice(5);
1330
+ const ltris: number[][] = []; const lcols: string[] = [];
1331
+ for (let j = 0; j < H; j += 1) for (let i = 0; i < W; i += 1) {
1332
+ const [ax, az] = XZ(i, j); const y = 0.004;
1333
+ const a = [ax, y, az]; const b = [ax + 1, y, az]; const c = [ax + 1, y, az + 1]; const d = [ax, y, az + 1];
1334
+ const base = Math.floor(i / 4) % 2 ? COL.floorStripe : COL.floor;
1335
+ for (const t of lawn() < 0.5 ? [[a, d, b], [b, d, c]] : [[a, d, c], [a, c, b]]) {
1336
+ ltris.push(t.flat());
1337
+ const r = lawn();
1338
+ lcols.push(r < 0.3 ? mixHex(base, PAL.ink, 0.035) : r < 0.6 ? mixHex(base, PAL.bg, 0.04) : base);
1339
+ }
1340
+ }
1341
+ const floor = new Mesh(facets(ltris, lcols), new MeshLambertMaterial({ vertexColors: true }));
1342
+ floor.receiveShadow = REAL_SHADOWS;
1343
+ stylize(floor, STYLE);
1344
+ if (FENCED) scene.add(floor);
1345
+ // Its edge: a pale path, a hand's height above the grass (inked like the models when the style draws lines).
1346
+ const outer = new Shape();
1347
+ outer.moveTo(-W / 2 - EDGE, -H / 2 - EDGE); outer.lineTo(W / 2 + EDGE, -H / 2 - EDGE); outer.lineTo(W / 2 + EDGE, H / 2 + EDGE); outer.lineTo(-W / 2 - EDGE, H / 2 + EDGE); outer.closePath();
1348
+ const hole = new Path();
1349
+ hole.moveTo(-W / 2, -H / 2); hole.lineTo(-W / 2, H / 2); hole.lineTo(W / 2, H / 2); hole.lineTo(W / 2, -H / 2); hole.closePath();
1350
+ outer.holes.push(hole);
1351
+ const path = new Mesh(new ExtrudeGeometry(outer, { depth: 0.07, bevelEnabled: false }), new MeshLambertMaterial({ color: COL.path }));
1352
+ path.rotation.x = -Math.PI / 2;
1353
+ stylize(path, STYLE);
1354
+ if (FENCED) scene.add(path);
1355
+ }
1356
+
1357
+ /* ------------------------------------------------------------------ models */
1358
+ /*
1359
+ * THE MODELS come from the Homie starter library: `game new` copied each into public/models/ (assets/manifest.json
1360
+ * names the library item, its SHA-256 and its CC0 licence). The library keeps each at its own size and in its pack's
1361
+ * colours, so the game decides here how tall each stands (metres) and repaints the flat-coloured ones into style.json's
1362
+ * palette (repaint: a palette swap by colour family). A model that is not there (no library when the game was made, a
1363
+ * refused file) is drawn as a stand-in made here in the same colours, or left out when it is only a flower or a tuft of
1364
+ * grass: a round never waits on, or breaks for, a model.
1365
+ */
1366
+ // `models`, HEROES and SKELETONS are above (the characters, asked for first).
1367
+ /** The verb a hero's swing plays: a mage casts; everyone else strikes. */
1368
+ const HERO_ACTION: Record<string, string> = { mage: 'cast', 'skeleton-mage': 'cast' };
1369
+ /** What your own name chip says you are ("You · Mage"): which hero is yours reads at a glance, even from above. */
1370
+ const HERO_NAME: Record<string, string> = { knight: 'Knight', barbarian: 'Barbarian', mage: 'Mage', rogue: 'Rogue', 'rogue-hooded': 'Rogue' };
1371
+ const heroName = (kind: string): string => HERO_NAME[kind] ?? kind.replace(/[-_]+/g, ' ').replace(/^./, (c) => c.toUpperCase());
1372
+ const HERO_M = 1.45;
1373
+ const heroKind = (slot: number, seat: number | null, bot: boolean): string => (bot ? SKELETONS[slot % SKELETONS.length] : HEROES[(seat ?? slot) % HEROES.length]) as string;
1374
+
1375
+ type RGB = [number, number, number];
1376
+ const PAINT = {
1377
+ leaf: mixHex(PAL.good, PAL.ink, 0.25), wood: mixHex(PAL.accent, PAL.ink, 0.45), blade: mixHex(PAL.good, PAL.accent2, 0.5),
1378
+ stone: mixHex(mixHex(PAL.bg, PAL.ink, 0.5), '#8c8f96', 0.35),
1379
+ };
1380
+
1381
+ /** Stand-ins, drawn in the same colours when a model is not there: low-poly shapes, one draw call each. */
1382
+ type Stand = 'gem' | 'tree' | 'pine' | 'bush' | 'rock' | 'stone' | 'fence' | 'hero' | 'chest';
1383
+ function standIn(kind: Stand, colour = PAL.accent): Mesh {
1384
+ const parts: BufferGeometry[] = [];
1385
+ const add = (geo: BufferGeometry, hex: string, x: number, y: number, z: number, sx = 1, sy = 1, sz = 1): void => {
1386
+ const g = geo.index ? geo.toNonIndexed() : geo;
1387
+ g.scale(sx, sy, sz); g.translate(x, y, z);
1388
+ const c = new Color(hex); const n = (g.attributes.position as BufferAttribute).count; const col = new Float32Array(n * 3);
1389
+ for (let i = 0; i < n; i += 1) col.set([c.r, c.g, c.b], i * 3);
1390
+ g.setAttribute('color', new BufferAttribute(col, 3));
1391
+ parts.push(g);
1392
+ };
1393
+ if (kind === 'gem') add(new CylinderGeometry(0.22, 0.22, 0.06, 10), PAL.gold, 0, 0.28, 0);
1394
+ if (kind === 'tree') { add(new CylinderGeometry(0.12, 0.17, 1.5, 6), PAINT.wood, 0, 0.75, 0); add(new IcosahedronGeometry(1.05, 0), PAINT.leaf, 0, 2.45, 0); }
1395
+ if (kind === 'pine') { add(new CylinderGeometry(0.1, 0.14, 0.9, 6), PAINT.wood, 0, 0.45, 0); add(new ConeGeometry(1, 2.2, 7), PAINT.leaf, 0, 1.9, 0); add(new ConeGeometry(0.72, 1.6, 7), PAINT.leaf, 0, 2.95, 0); }
1396
+ if (kind === 'bush') add(new CylinderGeometry(0.42, 0.38, 0.8, 8), PAINT.wood, 0, 0.4, 0);
1397
+ if (kind === 'rock') add(new DodecahedronGeometry(0.5, 0), PAINT.stone, 0, 0.3, 0, 1.3, 0.75, 1.1);
1398
+ if (kind === 'stone') add(new BoxGeometry(0.9, 0.55, 0.7), PAINT.stone, 0, 0.27, 0);
1399
+ if (kind === 'fence') { for (const x of [-0.96, 0.96]) add(new BoxGeometry(0.1, 0.7, 0.1), PAINT.wood, x, 0.35, 0); for (const y of [0.3, 0.55]) add(new BoxGeometry(2.03, 0.08, 0.05), PAINT.wood, 0, y, 0); }
1400
+ if (kind === 'chest') { add(new BoxGeometry(1.1, 0.6, 0.7), PAINT.wood, 0, 0.3, 0); add(new BoxGeometry(1.12, 0.12, 0.72), PAL.gold, 0, 0.62, 0); }
1401
+ if (kind === 'hero') {
1402
+ // A hero-shaped stand-in in its seat's colour while its model loads: a body, a head, a sword arm.
1403
+ add(new CylinderGeometry(0.26, 0.3, 0.62, 8), colour, 0, 0.46, 0);
1404
+ add(new IcosahedronGeometry(0.3, 1), mixHex(colour, '#ffffff', 0.35), 0, 1.02, 0);
1405
+ for (const x of [-0.17, 0.17]) add(new BoxGeometry(0.16, 0.2, 0.18), mixHex(colour, PAL.ink, 0.4), x, 0.1, 0);
1406
+ add(new BoxGeometry(0.07, 0.62, 0.07), PAINT.stone, 0.42, 0.62, 0.12);
1407
+ }
1408
+ const mesh = new Mesh(mergeGeometries(parts) as BufferGeometry, new MeshLambertMaterial({ vertexColors: true, flatShading: true }));
1409
+ mesh.name = 'stand-in';
1410
+ return mesh;
1411
+ }
1412
+
1413
+ /** Every model the game draws: its file, how big it is drawn (m: its height, or its width with `wide`) and its stand-in. */
1414
+ interface Spec { url: string; m: number; swap: ((r: number, g: number, b: number) => RGB | null) | null; stand: Stand | null; tint?: string; px?: number; wide?: boolean }
1415
+ // The coin: KayKit's gold coin, drawn standing on its edge and spinning (its width is its size).
1416
+ const GEM: Spec = { url: './models/coin.glb', m: 0.56, swap: null, stand: 'gem', wide: true };
1417
+ const FENCE: Spec = { url: './models/fence.glb', m: 0.7, swap: null, stand: 'fence' };
1418
+ // The clearing's heart: the treasure chest, two lit torches beside it, barrels and crates round it.
1419
+ const CHEST: Spec = { url: './models/chest.glb', m: 0.95, swap: null, stand: 'chest' };
1420
+ const TORCH: Spec = { url: './models/torch.glb', m: 1.6, swap: null, stand: null };
1421
+ const BARREL: Spec = { url: './models/barrel.glb', m: 0.8, swap: null, stand: 'bush' };
1422
+ const CRATE: Spec = { url: './models/crate.glb', m: 0.72, swap: null, stand: 'stone' };
1423
+ /** The dressing: how many, where, its footprint in metres (for spacing), its shadow's radius and its size range. */
1424
+ type Where = 'far' | 'any' | 'low' | 'inside' | 'edge';
1425
+ const DRESSING: (Spec & { count: number; where: Where; foot: number; shadow: number; scale: [number, number] })[] = [
1426
+ { url: './models/pine.glb', m: 3.8, swap: null, stand: 'pine', count: 22, where: 'far', foot: 1.6, shadow: 1.0, scale: [0.8, 1.3] },
1427
+ { url: './models/pine-round.glb', m: 3.3, swap: null, stand: 'tree', count: 18, where: 'far', foot: 1.6, shadow: 1.0, scale: [0.8, 1.25] },
1428
+ { url: './models/grove.glb', m: 3.4, swap: null, stand: 'pine', count: 7, where: 'far', foot: 4.2, shadow: 2.4, scale: [0.9, 1.2] },
1429
+ { url: './models/rock.glb', m: 0.75, swap: null, stand: 'rock', count: 14, where: 'any', foot: 1.3, shadow: 0.7, scale: [0.6, 1.15] },
1430
+ { url: './models/rocks.glb', m: 0.55, swap: null, stand: 'rock', count: 10, where: 'any', foot: 1.2, shadow: 0.6, scale: [0.7, 1.2] },
1431
+ { url: './models/pine.glb', m: 3.8, swap: null, stand: 'pine', count: 8, where: 'any', foot: 1.6, shadow: 1.0, scale: [0.55, 0.85] },
1432
+ // The clearing's edge: rocks, barrels and crates just outside it (never on the camera's side).
1433
+ { url: './models/rock.glb', m: 0.75, swap: null, stand: 'rock', count: FENCED ? 0 : 12, where: 'edge', foot: 1.1, shadow: 0.6, scale: [0.6, 1] },
1434
+ { url: './models/barrel.glb', m: 0.8, swap: null, stand: 'bush', count: FENCED ? 0 : 6, where: 'edge', foot: 0.9, shadow: 0.45, scale: [0.9, 1.1] },
1435
+ { url: './models/crate.glb', m: 0.72, swap: null, stand: 'stone', count: FENCED ? 0 : 5, where: 'edge', foot: 1, shadow: 0.5, scale: [0.85, 1.15] },
1436
+ ];
1437
+
1438
+ /** A model loaded once, repainted and measured: `fit` scales it to its height, `size` is its box at that height. */
1439
+ interface Ready { scene: Object3D; fit: number; size: Vector3 }
1440
+ const ready = new Map<string, Promise<Ready | null>>();
1441
+ function prepare(spec: Pick<Spec, 'url' | 'm' | 'swap' | 'tint' | 'px' | 'wide'>): Promise<Ready | null> {
1442
+ let p = ready.get(spec.url);
1443
+ if (!p) {
1444
+ p = track(models.load(spec.url), false).then((m) => {
1445
+ if (spec.swap) repaint(m.scene, spec.swap, spec.px ? { maxPx: spec.px } : undefined);
1446
+ const size = new Box3().setFromObject(m.scene).getSize(new Vector3());
1447
+ const along = spec.wide ? Math.max(size.x, size.z) : size.y;
1448
+ const fit = along > 1e-3 ? spec.m / along : 1;
1449
+ // The art direction's material model and ink line (style.json), as the style board drew them.
1450
+ stylize(m.scene, STYLE, { scale: fit });
1451
+ return { scene: m.scene, fit, size: size.multiplyScalar(fit) };
1452
+ }, () => { standIns.add(spec.url); return null; });
1453
+ ready.set(spec.url, p);
1454
+ }
1455
+ return p;
1456
+ }
1457
+ // The Game Lab plays a take only once the models have settled (loaded or not there), so both builds start alike:
1458
+ // held here, released below once every model (the heroes too) has loaded or failed.
1459
+ lab.hold();
1460
+
1461
+ /**
1462
+ * A model as instanced copies (instancedCopies: one InstancedMesh per mesh, placed with placeCopy, never by baking into
1463
+ * the file's geometry), and the scale that makes it its height; its stand-in when it is not there, or nothing.
1464
+ */
1465
+ async function instancedFrom(spec: Spec, count: number): Promise<{ parts: Copies[]; fit: number; size: Vector3 | null }> {
1466
+ const r = await prepare(spec);
1467
+ if (r) return { parts: instancedCopies(r.scene, count), fit: r.fit, size: r.size };
1468
+ return { parts: spec.stand ? instancedCopies(standIn(spec.stand), count) : [], fit: 1, size: null };
1469
+ }
1470
+
1471
+ /* ------------------------------------------------------------------ soft discs: shadows, glows */
1472
+ const discTexture = canvasTexture(64, 64, (g) => {
1473
+ const gr = g.createRadialGradient(32, 32, 0, 32, 32, 32);
1474
+ gr.addColorStop(0, 'rgba(255,255,255,1)'); gr.addColorStop(0.45, 'rgba(255,255,255,0.75)'); gr.addColorStop(1, 'rgba(255,255,255,0)');
1475
+ g.fillStyle = gr; g.fillRect(0, 0, 64, 64);
1476
+ });
1477
+ const flatDisc = (): PlaneGeometry => { const g = new PlaneGeometry(2, 2); g.rotateX(-Math.PI / 2); return g; };
1478
+ const shadowMaterial = new MeshBasicMaterial({ map: discTexture, color: COL.shadow, transparent: true, opacity: 0.32, depthWrite: false });
1479
+ /** Shadows that move: one disc per body and per gem. */
1480
+ const blobs = new InstancedMesh(flatDisc(), shadowMaterial, MAX_SLOTS + 40);
1481
+ blobs.frustumCulled = false; blobs.count = 0; blobs.position.y = 0.012;
1482
+ scene.add(blobs);
1483
+ /** The glow under each gem: it says "take me" before the gem is near. */
1484
+ const glows = new InstancedMesh(flatDisc(), new MeshBasicMaterial({ map: discTexture, color: COL.gem, transparent: true, opacity: 0.32, depthWrite: false }), 40);
1485
+ glows.frustumCulled = false; glows.count = 0; glows.position.y = 0.016;
1486
+ scene.add(glows);
1487
+
1488
+ /* ------------------------------------------------------------------ the dressing around the arena */
1489
+ const placed: { x: number; z: number; r: number }[] = [];
1490
+ /**
1491
+ * A spot for a piece of dressing (three.js x, z): on a band round the arena, `out` metres past its path, most of them
1492
+ * near the fence (where the camera sees them), clear of the others. Trees and standing stones only behind the arena
1493
+ * and beside its far half: never between the camera and the play.
1494
+ */
1495
+ function spotFor(roll: () => number, where: Where, r: number, tall = false): { x: number; z: number } | null {
1496
+ if (where === 'inside') {
1497
+ // A few small flowers on the lawn itself, so a phone's close view is never bare grass (they never block a move).
1498
+ for (let tries = 0; tries < 60; tries += 1) {
1499
+ const x = (roll() - 0.5) * (W - 1.6); const z = (roll() - 0.5) * (H - 1.6);
1500
+ if (placed.some((p) => Math.hypot(p.x - x, p.z - z) < p.r + r)) continue;
1501
+ placed.push({ x, z, r });
1502
+ return { x, z };
1503
+ }
1504
+ return null;
1505
+ }
1506
+ const [lo, hi] = where === 'edge' ? [0.5, 1.6] : where === 'low' ? [1.2, 7] : where === 'any' ? [1.5, 9] : [1.8, 16];
1507
+ for (let tries = 0; tries < 60; tries += 1) {
1508
+ const out = lo + (hi - lo) * roll() ** 1.5;
1509
+ const hw = W / 2 + EDGE + out; const hh = H / 2 + EDGE + out;
1510
+ let u = roll() * (4 * hw + 4 * hh); let x: number; let z: number;
1511
+ if (u < 2 * hw) { x = -hw + u; z = -hh; } else if ((u -= 2 * hw) < 2 * hh) { x = hw; z = -hh + u; } else if ((u -= 2 * hh) < 2 * hw) { x = hw - u; z = hh; } else { u -= 2 * hw; x = -hw; z = hh - u; }
1512
+ if (where === 'far' && z > 0) continue;
1513
+ if (where === 'edge' && z > H / 2) continue; // the near side stays open to the camera
1514
+ if (where === 'any' && z > H / 2 && (out > 4 || tall)) continue; // little on the camera's side, and nothing tall:
1515
+ // a tree there would stand between a phone's close camera and its hero
1516
+ if (placed.some((p) => Math.hypot(p.x - x, p.z - z) < p.r + r)) continue;
1517
+ placed.push({ x, z, r });
1518
+ return { x, z };
1519
+ }
1520
+ return null;
1521
+ }
1522
+ const shadowSpots: { x: number; z: number; r: number }[] = [];
1523
+ /** The torches' flames at the clearing's heart (flickered in draw): two cones in the palette's gold and accent, a glow. */
1524
+ const flames: Object3D[] = [];
1525
+ async function buildCamp(o: { x: number; y: number; r: number }): Promise<void> {
1526
+ const [x, z] = XZ(o.x, o.y);
1527
+ const camp = new Group(); camp.position.set(x, 0, z); scene.add(camp);
1528
+ const chest = await prepare(CHEST);
1529
+ const box = chest ? chest.scene.clone(true) : standIn('chest');
1530
+ if (chest) box.scale.setScalar(chest.fit);
1531
+ box.rotation.y = 0.15; // turned a little toward the camera's side
1532
+ camp.add(box);
1533
+ const torch = await prepare(TORCH);
1534
+ for (const [tx, tz] of [[-1.05, -0.35], [1.05, -0.3]] as [number, number][]) {
1535
+ const t = new Group(); t.position.set(tx, 0, tz); camp.add(t);
1536
+ if (torch) { const obj = torch.scene.clone(true); obj.scale.setScalar(torch.fit); t.add(obj); }
1537
+ else { const pole = new Mesh(new CylinderGeometry(0.05, 0.06, 1.5, 6), new MeshLambertMaterial({ color: PAINT.wood })); pole.position.y = 0.75; t.add(pole); }
1538
+ const f = new Group(); f.position.y = TORCH.m * 0.92;
1539
+ const outer = new Mesh(new ConeGeometry(0.13, 0.42, 6), new MeshBasicMaterial({ color: PAL.accent }));
1540
+ const inner = new Mesh(new ConeGeometry(0.08, 0.28, 6), new MeshBasicMaterial({ color: PAL.gold }));
1541
+ outer.position.y = 0.2; inner.position.y = 0.15; f.add(outer, inner);
1542
+ t.add(f); flames.push(f);
1543
+ }
1544
+ const glow = new Mesh(new CircleGeometry(2.2, 28), new MeshBasicMaterial({ map: discTexture, color: PAL.gold, transparent: true, opacity: 0.3, depthWrite: false }));
1545
+ glow.rotation.x = -Math.PI / 2; glow.position.y = 0.02; camp.add(glow);
1546
+ for (const [spec, bx, bz, rot] of [[BARREL, -1.55, 0.55, 0.3], [CRATE, 1.6, 0.6, -0.4], [BARREL, 1.95, -0.25, 1]] as [Spec, number, number, number][]) {
1547
+ const r = await prepare(spec);
1548
+ const obj = r ? r.scene.clone(true) : spec.stand ? standIn(spec.stand) : null;
1549
+ if (!obj) continue;
1550
+ if (r) obj.scale.setScalar(r.fit * 0.85);
1551
+ obj.position.set(bx, 0, bz); obj.rotation.y = rot; camp.add(obj);
1552
+ }
1553
+ if (REAL_SHADOWS) camp.traverse((n) => { const mm = n as Mesh; if (mm.isMesh && mm.name !== 'hull' && n !== glow && !flames.some((f) => f.children.includes(n))) mm.castShadow = true; });
1554
+ }
1555
+
1556
+ /** The clearing's solid features (OBSTACLES), drawn with the dressing's own models. */
1557
+ const OBSTACLE_SPEC = {
1558
+ camp: null,
1559
+ bush: BARREL,
1560
+ rock: DRESSING.find((d) => d.url.endsWith('/rock.glb')),
1561
+ stone: CRATE,
1562
+ tree: DRESSING.find((d) => d.url.endsWith('/pine-round.glb')),
1563
+ } as const;
1564
+ async function dressMeadow(): Promise<void> {
1565
+ const roll = dice(2024);
1566
+ const m = new Matrix4(); const qt = new Quaternion(); const e = new Euler(); const p = new Vector3(); const s = new Vector3();
1567
+ // The clearing's features first: the dressing keeps clear of them, and each gets its shadow.
1568
+ for (const o of OBSTACLES) { const [x, z] = XZ(o.x, o.y); placed.push({ x, z, r: o.r + 0.3 }); shadowSpots.push({ x, z, r: o.r * 1.4 }); }
1569
+ // Decided before any model arrives, so the meadow is the same on every screen whatever loads first.
1570
+ const plans = DRESSING.map((d) => {
1571
+ const spots: { x: number; z: number; rot: number; sc: number }[] = [];
1572
+ for (let i = 0; i < d.count; i += 1) {
1573
+ const sc = d.scale[0] + roll() * (d.scale[1] - d.scale[0]);
1574
+ const at = spotFor(roll, d.where, d.foot * 0.5 * sc + 0.15, d.m * sc > 1.6);
1575
+ if (at) spots.push({ ...at, rot: roll() * Math.PI * 2, sc });
1576
+ }
1577
+ return { d, spots };
1578
+ });
1579
+ for (const { d, spots } of plans) if (d.shadow) for (const sp of spots) shadowSpots.push({ x: sp.x, z: sp.z, r: d.shadow * sp.sc });
1580
+ // Their shadows: one draw call for the lot.
1581
+ const still = new InstancedMesh(flatDisc(), shadowMaterial, shadowSpots.length || 1);
1582
+ shadowSpots.forEach((sp, i) => still.setMatrixAt(i, m.compose(p.set(sp.x, heightAt(sp.x, sp.z) + 0.008, sp.z), qt.identity(), s.set(sp.r, 1, sp.r))));
1583
+ still.count = shadowSpots.length;
1584
+ still.computeBoundingSphere();
1585
+ still.visible = !REAL_SHADOWS; // a computer draws the real shadows
1586
+ scene.add(still);
1587
+ await Promise.all(plans.map(async ({ d, spots }) => {
1588
+ const { parts, fit } = await instancedFrom(d, Math.max(1, spots.length));
1589
+ for (const c of parts) {
1590
+ spots.forEach((sp, i) => placeCopy(c, i, m.compose(p.set(sp.x, heightAt(sp.x, sp.z) - 0.02, sp.z), qt.setFromEuler(e.set(0, sp.rot, 0)), s.setScalar(sp.sc * fit))));
1591
+ c.mesh.count = spots.length;
1592
+ c.mesh.computeBoundingSphere();
1593
+ c.mesh.castShadow = REAL_SHADOWS && c.mesh.name !== 'hull'; c.mesh.receiveShadow = REAL_SHADOWS;
1594
+ scene.add(c.mesh);
1595
+ }
1596
+ }));
1597
+ // The features themselves: a copy of each model (or its stand-in) where the rules put it.
1598
+ const turn = dice(77);
1599
+ await Promise.all(OBSTACLES.map(async (o) => {
1600
+ if (o.kind === 'camp') { await buildCamp(o); return; }
1601
+ const spec = OBSTACLE_SPEC[o.kind];
1602
+ if (!spec) return;
1603
+ const r = await prepare(spec);
1604
+ const obj = r ? r.scene.clone(true) : spec.stand ? standIn(spec.stand) : null;
1605
+ if (!obj) return;
1606
+ const [x, z] = XZ(o.x, o.y);
1607
+ obj.position.set(x, 0, z); obj.rotation.y = turn() * Math.PI * 2;
1608
+ // Drawn as wide as it is solid (its footprint a little over o.r), so a hero stops at what it sees, never inside it.
1609
+ const half = r ? Math.max(r.size.x, r.size.z) / 2 : 0;
1610
+ const k = o.kind === 'tree' || !half ? (o.kind === 'tree' ? 0.8 : 1.1) : Math.max(0.6, Math.min(1.6, (o.r + 0.08) / half));
1611
+ obj.scale.setScalar((r?.fit ?? 1) * k);
1612
+ if (REAL_SHADOWS) obj.traverse((n) => { const mm = n as Mesh; if (mm.isMesh && mm.name !== 'hull') mm.castShadow = true; });
1613
+ scene.add(obj);
1614
+ }));
1615
+ }
1616
+ /** The fence just outside the path: a ring of the same piece, each stretched a little to fit its side; one draw call. */
1617
+ async function buildFence(): Promise<void> {
1618
+ const { parts, fit, size } = await instancedFrom(FENCE, 120);
1619
+ const piece = size?.x ?? 2.03; // metres along x at its height (the stand-in's is 2.03)
1620
+ const runs: { x: number; z: number; rot: number; stretch: number }[] = [];
1621
+ const nx = Math.ceil((W + 2 * EDGE) / piece); const nz = Math.ceil((H + 2 * EDGE) / piece);
1622
+ const sx = (W + 2 * EDGE) / nx; const sz = (H + 2 * EDGE) / nz;
1623
+ const off = 0.18;
1624
+ for (let i = 0; i < nx; i += 1) {
1625
+ const x = -W / 2 - EDGE + (i + 0.5) * sx;
1626
+ runs.push({ x, z: -H / 2 - EDGE - off, rot: 0, stretch: sx / piece }, { x, z: H / 2 + EDGE + off, rot: Math.PI, stretch: sx / piece });
1627
+ }
1628
+ for (let i = 0; i < nz; i += 1) {
1629
+ const z = -H / 2 - EDGE + (i + 0.5) * sz;
1630
+ runs.push({ x: -W / 2 - EDGE - off, z, rot: Math.PI / 2, stretch: sz / piece }, { x: W / 2 + EDGE + off, z, rot: -Math.PI / 2, stretch: sz / piece });
1631
+ }
1632
+ const m = new Matrix4(); const qt = new Quaternion(); const e = new Euler(); const p = new Vector3(); const s = new Vector3();
1633
+ for (const c of parts) {
1634
+ runs.forEach((r, i) => placeCopy(c, i, m.compose(p.set(r.x, 0, r.z), qt.setFromEuler(e.set(0, r.rot, 0)), s.set(r.stretch * fit, fit, fit))));
1635
+ c.mesh.count = runs.length;
1636
+ c.mesh.computeBoundingSphere();
1637
+ c.mesh.castShadow = REAL_SHADOWS;
1638
+ scene.add(c.mesh);
1639
+ }
1640
+ }
1641
+ /**
1642
+ * Tufts of grass in and around the clearing, made here (procedural, free): three thin blades in the palette's greens,
1643
+ * one InstancedMesh for all of them, so a phone's close view is never a bare board (they never block a move).
1644
+ */
1645
+ function grassTufts(): void {
1646
+ const roll = dice(311);
1647
+ const blades: BufferGeometry[] = [];
1648
+ for (let i = 0; i < 3; i += 1) {
1649
+ const g = new ConeGeometry(0.035, 0.26 + i * 0.05, 3); g.translate(0, 0.13 + i * 0.025, 0);
1650
+ g.rotateZ((i - 1) * 0.35); g.rotateY(i * 2.1); g.translate((i - 1) * 0.05, 0, (i % 2) * 0.04);
1651
+ blades.push(g.toNonIndexed());
1652
+ }
1653
+ const geo = mergeGeometries(blades) as BufferGeometry;
1654
+ const tufts = new InstancedMesh(geo, new MeshLambertMaterial({ color: PAINT.blade, flatShading: true }), 220);
1655
+ const m = new Matrix4(); const qt = new Quaternion(); const e = new Euler(); const p = new Vector3(); const sc = new Vector3();
1656
+ let n = 0;
1657
+ for (let i = 0; i < 220; i += 1) {
1658
+ const inside = i < 110;
1659
+ const x = inside ? (roll() - 0.5) * (W - 1) : (roll() - 0.5) * (W + 16); const z = inside ? (roll() - 0.5) * (H - 1) : -H / 2 - roll() * 9 + (roll() < 0.3 ? H + 4 : 0);
1660
+ if (OBSTACLES.some((o) => { const [ox, oz] = XZ(o.x, o.y); return Math.hypot(ox - x, oz - z) < o.r + 0.3; })) continue;
1661
+ const k = 0.8 + roll() * 0.8;
1662
+ tufts.setMatrixAt(n, m.compose(p.set(x, heightAt(x, z) - 0.01, z), qt.setFromEuler(e.set(0, roll() * Math.PI * 2, 0)), sc.set(k, k * (0.8 + roll() * 0.5), k)));
1663
+ tufts.setColorAt(n, new Color(mixHex(PAINT.blade, roll() < 0.5 ? PAL.good : PAL.gold, roll() * 0.25)));
1664
+ n += 1;
1665
+ }
1666
+ tufts.count = n; tufts.computeBoundingSphere();
1667
+ tufts.receiveShadow = REAL_SHADOWS;
1668
+ scene.add(tufts);
1669
+ }
1670
+ void dressMeadow();
1671
+ grassTufts();
1672
+ if (FENCED) void buildFence();
1673
+
1674
+ /* ------------------------------------------------------------------ gems */
1675
+ const GEM_CAP = 40;
1676
+ /** Gems are drawn a third bigger than the model's 0.42 m, so they read on a phone; picking one up is the rules' R_GEM. */
1677
+ const GEM_DRAWN = 1.35;
1678
+ let gemParts: Copies[] = [];
1679
+ let gemFit = 1;
1680
+ function setGemParts(parts: Copies[], fit = 1): void {
1681
+ for (const c of gemParts) scene.remove(c.mesh);
1682
+ gemParts = parts; gemFit = fit;
1683
+ for (const { mesh: im } of parts) {
1684
+ im.frustumCulled = false; im.count = 0;
1685
+ im.instanceMatrix.setUsage(DynamicDrawUsage);
1686
+ // A little light of their own (a copy of the file's material), so gems read as treasure in any light.
1687
+ const own = (im.material as MeshStandardMaterial).clone();
1688
+ if (own.emissive) { own.emissive = new Color(COL.gem); own.emissiveIntensity = 0.3; }
1689
+ im.material = own;
1690
+ scene.add(im);
1691
+ }
1692
+ }
1693
+ {
1694
+ // Until the gem arrives (a few hundred ms) its stand-in, which stays if it never does: the round has already started.
1695
+ setGemParts(instancedCopies(standIn('gem'), GEM_CAP));
1696
+ void prepare(GEM).then((r) => { if (r) setGemParts(instancedCopies(r.scene, GEM_CAP), r.fit); });
1697
+ }
1698
+ const lastGems = new Map<number, { x: number; y: number }>();
1699
+ let lastGemRound = -1;
1700
+
1701
+ /* ------------------------------------------------------------------ the hot zone, rings, waves, sparks */
1702
+ const zoneFill = new Mesh(new CircleGeometry(1, 48), new MeshBasicMaterial({ color: COL.zone, transparent: true, opacity: 0.16, depthWrite: false }));
1703
+ zoneFill.rotation.x = -Math.PI / 2; zoneFill.position.y = 0.014; zoneFill.visible = false;
1704
+ const zoneRing = (() => {
1705
+ // A dashed ring, as Gem Rush draws it: 18 dashes in one geometry.
1706
+ const dashes: BufferGeometry[] = [];
1707
+ for (let i = 0; i < 18; i += 1) dashes.push(new RingGeometry(0.93, 1, 6, 1, (i / 18) * Math.PI * 2, (Math.PI * 2) / 18 * 0.6));
1708
+ const g = mergeGeometries(dashes) as BufferGeometry; g.rotateX(-Math.PI / 2);
1709
+ return new Mesh(g, new MeshBasicMaterial({ color: COL.zone, transparent: true, opacity: 0.9, depthWrite: false }));
1710
+ })();
1711
+ zoneRing.position.y = 0.02; zoneRing.visible = false;
1712
+ scene.add(zoneFill, zoneRing);
1713
+
1714
+ /** Every body's seat colour, a ring on the grass under it (people bright; bots greyed, as Gem Rush dims them). */
1715
+ const ringGeo = new RingGeometry(R_AV + 0.02, R_AV + 0.14, 40); ringGeo.rotateX(-Math.PI / 2);
1716
+ const seatRings = new InstancedMesh(ringGeo, new MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.95, depthWrite: false }), MAX_SLOTS + 4);
1717
+ seatRings.frustumCulled = false; seatRings.count = 0; seatRings.position.y = 0.022;
1718
+ seatRings.setColorAt(0, new Color(0xffffff));
1719
+ const edgeGeo = new RingGeometry(R_AV - 0.02, R_AV + 0.18, 40); edgeGeo.rotateX(-Math.PI / 2);
1720
+ const seatEdges = new InstancedMesh(edgeGeo, new MeshBasicMaterial({ color: COL.shadow, transparent: true, opacity: 0.4, depthWrite: false }), MAX_SLOTS + 4);
1721
+ seatEdges.frustumCulled = false; seatEdges.count = 0; seatEdges.position.y = 0.018;
1722
+ scene.add(seatEdges, seatRings);
1723
+ /** The ring that says "you" (or the player a watcher follows). */
1724
+ const youGeo = new RingGeometry(R_AV + 0.2, R_AV + 0.3, 48); youGeo.rotateX(-Math.PI / 2);
1725
+ const youRing = new Mesh(youGeo, new MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.95, depthWrite: false }));
1726
+ youRing.position.y = 0.024; youRing.visible = false;
1727
+ scene.add(youRing);
1728
+
1729
+ const waveGeo = new RingGeometry(0.9, 1, 48); waveGeo.rotateX(-Math.PI / 2);
1730
+ const wavePool: Mesh[] = [];
1731
+ function waveMesh(i: number): Mesh {
1732
+ let w = wavePool[i];
1733
+ if (!w) { w = new Mesh(waveGeo, new MeshBasicMaterial({ color: 0xffffff, transparent: true, depthWrite: false })); w.position.y = 0.03; scene.add(w); wavePool[i] = w; }
1734
+ return w;
1735
+ }
1736
+
1737
+ /**
1738
+ * A swing's slash: a flat band of T.swingArc degrees in front of the swinger at waist height, sweeping out to its reach
1739
+ * (what a swing can hit, drawn). Its geometry follows the tunable (the Game Lab's slider redraws it).
1740
+ */
1741
+ let slashArc = -1;
1742
+ let slashGeo = new BufferGeometry();
1743
+ const slashPool: Mesh[] = [];
1744
+ function slashMesh(i: number): Mesh {
1745
+ if (slashArc !== T.swingArc) {
1746
+ slashArc = T.swingArc;
1747
+ const half = (Math.min(359, Math.max(10, T.swingArc)) * Math.PI) / 360;
1748
+ const g = new RingGeometry(0.82, 1, 28, 1, -Math.PI / 2 - half, half * 2); g.rotateX(-Math.PI / 2);
1749
+ slashGeo.dispose(); slashGeo = g;
1750
+ for (const m of slashPool) m.geometry = g;
1751
+ }
1752
+ let w = slashPool[i];
1753
+ if (!w) { w = new Mesh(slashGeo, new MeshBasicMaterial({ color: 0xffffff, transparent: true, depthWrite: false, side: DoubleSide })); scene.add(w); slashPool[i] = w; }
1754
+ return w;
1755
+ }
1756
+
1757
+ /** Sparks: little bars flying off a hit (white, then gold) and up off a taken gem; one draw call. */
1758
+ const sparkMesh = new InstancedMesh(new BoxGeometry(1, 0.07, 0.07), new MeshBasicMaterial({ color: 0xffffff }), 160);
1759
+ sparkMesh.frustumCulled = false; sparkMesh.count = 0; sparkMesh.instanceMatrix.setUsage(DynamicDrawUsage);
1760
+ sparkMesh.setColorAt(0, new Color(0xffffff));
1761
+ scene.add(sparkMesh);
1762
+
1763
+ /* ------------------------------------------------------------------ the heroes */
1764
+ /*
1765
+ * Each body is a hero (people) or a skeleton (bots): its model and its clips come through @homie-rocks/studio/animate
1766
+ * (loadCharacter finds the clip library the model names). The game moves the body; the character only shows it: it
1767
+ * faces where it goes, blends idle, walk and run by its speed, plays the swing, the jump and the hit from the same
1768
+ * events every screen gets, flashes white when hit, and cheers when it won the round.
1769
+ *
1770
+ * root (where, and how high it jumped) > tilt (the hit's angle) > squash (stretch along the hit) > untilt > character
1771
+ */
1772
+ interface Hero {
1773
+ slot: number; kind: string; mine: boolean;
1774
+ root: Group; tilt: Group; squash: Group; untilt: Group;
1775
+ char: Character | null; stand: Mesh | null; mats: MeshStandardMaterial[];
1776
+ px: number; py: number; ph: number; speed: number; seen: number; yaw: number; held: string | null;
1777
+ }
1778
+ const heroes = new Map<number, Hero>();
1779
+ function heroFor(slot: number, kind: string, colour: string): Hero {
1780
+ let h = heroes.get(slot);
1781
+ if (h && h.kind === kind) return h;
1782
+ if (!h) {
1783
+ const root = new Group(); const tilt = new Group(); const squash = new Group(); const untilt = new Group();
1784
+ root.add(tilt); tilt.add(squash); squash.add(untilt);
1785
+ scene.add(root);
1786
+ h = { slot, kind, mine: false, root, tilt, squash, untilt, char: null, stand: null, mats: [], px: NaN, py: NaN, ph: 0, speed: 0, seen: 0, yaw: 0, held: null };
1787
+ heroes.set(slot, h);
1788
+ }
1789
+ h.kind = kind;
1790
+ dressHero(h, colour);
1791
+ return h;
1792
+ }
1793
+ function clearHero(h: Hero): void {
1794
+ if (h.char) { h.char.dispose(); h.char = null; }
1795
+ if (h.stand) { h.untilt.remove(h.stand); h.stand.geometry.dispose(); h.stand = null; }
1796
+ for (const m of h.mats) m.dispose();
1797
+ h.mats = []; h.held = null;
1798
+ }
1799
+ /** The hero's model: a stand-in in its seat's colour at once (a round never waits), then its own character when it is in. */
1800
+ function dressHero(h: Hero, colour: string): void {
1801
+ clearHero(h);
1802
+ h.stand = standIn('hero', colour);
1803
+ h.untilt.add(h.stand);
1804
+ const want = h.kind;
1805
+ void loadHero(want).then(async (ok) => {
1806
+ if (!ok || h.kind !== want || heroes.get(h.slot) !== h) return;
1807
+ const char = await loadCharacter(models, heroUrl(want), { tune: T }).catch(() => null);
1808
+ if (!char || h.kind !== want || heroes.get(h.slot) !== h) { char?.dispose(); return; }
1809
+ clearHero(h);
1810
+ // Its own materials (a copy shares the file's), so a hit flashes this one hero; the art direction's material model.
1811
+ const own = new Map<Material, MeshStandardMaterial>();
1812
+ char.model.traverse((o) => {
1813
+ const mesh = o as Mesh;
1814
+ if (!mesh.isMesh) return;
1815
+ const m = mesh.material as MeshStandardMaterial;
1816
+ let c = own.get(m);
1817
+ if (!c) { c = m.clone(); own.set(m, c); h.mats.push(c); }
1818
+ mesh.material = c;
1819
+ mesh.castShadow = REAL_SHADOWS;
1820
+ // A skinned body moves out of its bind-pose box: never culled by it.
1821
+ mesh.frustumCulled = false;
1822
+ });
1823
+ char.root.rotation.y = h.yaw;
1824
+ h.char = char;
1825
+ h.untilt.add(char.root);
1826
+ });
1827
+ }
1828
+ /** Place, turn, squash, flash and animate one hero this frame. */
1829
+ function poseHero(h: Hero, at: { x: number; y: number; h: number }, t: number, dt: number, fx: ReturnType<typeof bodyFx>, place: number | null, over: boolean): void {
1830
+ const [x, z] = XZ(at.x + fx.ox, at.y + fx.oy);
1831
+ h.root.position.set(x, at.h, z);
1832
+ // How fast it moves, from where it is drawn (the same for its owner, the host and every replica).
1833
+ const dx = at.x - h.px; const dy = at.y - h.py; const step = Math.hypot(dx, dy);
1834
+ const sp = !Number.isFinite(step) || step > 2 || dt <= 0 ? 0 : step / dt; // a jump in place (a new round, a takeover) is not a run
1835
+ h.speed += (Math.min(sp, 12) - h.speed) * Math.min(1, dt * 10);
1836
+ const vh = dt > 0 ? (at.h - h.ph) / dt : 0;
1837
+ h.px = at.x; h.py = at.y; h.ph = at.h;
1838
+ // It faces where it goes, but not while flying from a bump (it is knocked backwards, not turned round).
1839
+ if (sp > 0.6 && !bumps.has(h.slot) && Number.isFinite(step)) h.yaw = Math.atan2(dx, dy);
1840
+ h.tilt.rotation.y = -fx.ang; h.untilt.rotation.y = fx.ang;
1841
+ h.squash.scale.set(fx.sx, fx.up, fx.sy);
1842
+ for (const m of h.mats) if (m.emissive) m.emissive.setScalar(fx.flash * 0.9);
1843
+ const c = h.char;
1844
+ if (!c) { if (h.stand) h.stand.rotation.y = h.yaw; return; }
1845
+ c.face(h.yaw, dt);
1846
+ c.move(bumps.has(h.slot) ? 0 : h.speed);
1847
+ c.air(at.h <= 0.001, vh);
1848
+ // The round's end: its winner cheers (held until the next round), everyone else stands.
1849
+ const want = over && place === 1 ? 'win' : null;
1850
+ if (want !== h.held) { if (want) c.hold(want); else if (h.held) c.hold(''); h.held = want; }
1851
+ c.update(dt);
1852
+ }
1853
+
1854
+ // The Game Lab starts its take once everything is in (the heroes in their order above: never all at once at boot).
1855
+ void Promise.all([allHeroes, ...SKELETONS.map((k) => loadHero(k)), prepare(GEM), ...(FENCED ? [prepare(FENCE)] : []), prepare(CHEST), prepare(TORCH), prepare(BARREL), prepare(CRATE), ...DRESSING.map(prepare)]).then(() => lab.ready());
1856
+
1857
+ /* ------------------------------------------------------------------ the Game Lab's overlays, as lines on the meadow */
1858
+ const pen = (() => {
1859
+ const cap = 6000;
1860
+ const pos = new Float32Array(cap * 3); const col = new Float32Array(cap * 3);
1861
+ const geo = new BufferGeometry();
1862
+ geo.setAttribute('position', new BufferAttribute(pos, 3).setUsage(DynamicDrawUsage));
1863
+ geo.setAttribute('color', new BufferAttribute(col, 3).setUsage(DynamicDrawUsage));
1864
+ const lines = new LineSegments(geo, new LineBasicMaterial({ vertexColors: true, depthTest: false, transparent: true }));
1865
+ lines.frustumCulled = false; lines.renderOrder = 10; lines.visible = false;
1866
+ if (lab.on) scene.add(lines);
1867
+ let n = 0; const c = new Color();
1868
+ const put = (x: number, y: number, hex: string): void => { const [px, pz] = XZ(x, y); pos.set([px, 0.06, pz], n * 3); c.set(hex); col.set([c.r, c.g, c.b], n * 3); n += 1; };
1869
+ return {
1870
+ begin(): void { n = 0; },
1871
+ seg(x1: number, y1: number, x2: number, y2: number, hex: string): void { if (n + 2 > cap) return; put(x1, y1, hex); put(x2, y2, hex); },
1872
+ ellipse(x: number, y: number, rx: number, ry: number, a: number, hex: string, dashed = false): void {
1873
+ const N = 32; const ca = Math.cos(a); const sa = Math.sin(a);
1874
+ const at = (i: number): [number, number] => { const th = (i / N) * Math.PI * 2; const ex = Math.cos(th) * rx; const ey = Math.sin(th) * ry; return [x + ex * ca - ey * sa, y + ex * sa + ey * ca]; };
1875
+ for (let i = 0; i < N; i += 1) { if (dashed && i % 2) continue; const [x1, y1] = at(i); const [x2, y2] = at(i + 1); this.seg(x1, y1, x2, y2, hex); }
1876
+ },
1877
+ end(): void {
1878
+ geo.setDrawRange(0, n);
1879
+ (geo.attributes.position as BufferAttribute).needsUpdate = true; (geo.attributes.color as BufferAttribute).needsUpdate = true;
1880
+ lines.visible = n > 0;
1881
+ },
1882
+ };
1883
+ })();
1884
+ type Pen = typeof pen;
1885
+ lab.overlay('onion', (c) => {
1886
+ const g = c as Pen;
1887
+ const ghosts = lab.past<Pose>('subject', 8, 3);
1888
+ ghosts.forEach((p) => g.ellipse(p.x, p.y, R_AV * (p.sx ?? 1), R_AV * (p.sy ?? 1), p.a ?? 0, '#ffad3b'));
1889
+ });
1890
+ lab.overlay('arcs', (c) => {
1891
+ const g = c as Pen;
1892
+ const pts = lab.past<Pose>('subject', 90, 1);
1893
+ for (let i = 1; i < pts.length; i += 1) { const a = pts[i - 1] as Pose; const b = pts[i] as Pose; g.seg(a.x, a.y, b.x, b.y, '#7cc4ff'); }
1894
+ for (const p of pts) { g.seg(p.x - 0.05, p.y, p.x + 0.05, p.y, '#7cc4ff'); g.seg(p.x, p.y - 0.05, p.x, p.y + 0.05, '#7cc4ff'); }
1895
+ });
1896
+ lab.overlay('reach', (c) => {
1897
+ if (!me.has) return;
1898
+ (c as Pen).ellipse(me.x, me.y, T.knockRange, T.knockRange, 0, '#ffffff', true);
1899
+ });
1900
+
1901
+ /* ------------------------------------------------------------------ the camera */
1902
+ /*
1903
+ * style.json's camera: high three-quarter (its pitch and field of view), square to the arena so the stick's up is
1904
+ * the screen's up. How close: the screen's short side about 13.5 m of meadow at the player on a computer and 9.5 m on
1905
+ * a phone (style.json's distance scales both: 22 is these), so a hero reads at about the same size in the hand.
1906
+ * It follows the body whose view this is and never looks past the arena's edge (beyond the path and the fence, as
1907
+ * far as the perspective allows); following nobody, it frames the whole arena (turned on a tall screen, so the
1908
+ * arena's long side runs up it).
1909
+ */
1910
+ const PITCH0 = (CAM.pitch * Math.PI) / 180;
1911
+ const HALF = (CAM.fov * Math.PI) / 360;
1912
+ /*
1913
+ * A phone held upright sees the ground through a slit: its width is the short side. Followed from style.json's pitch
1914
+ * and distance it shows a long strip of mostly empty grass with a small hero in it. So, like the port kit's fitView
1915
+ * (fill a phone held upright and follow the player), it frames the action instead: closer (about 5.5 m across at the
1916
+ * player, a hero a quarter of the screen's width) and LOWER, 28 to 32 degrees (8 under style.json's pitch): from the
1917
+ * 40 it once was, a hero is the top of its hat (a mage's brim hides the whole mage), and its legs, so its run, never
1918
+ * show. At 30 the face, the body and the legs read on every kind, and the far side of the clearing and the woods fill
1919
+ * the top of the screen, where the rivals ahead are. The player stands in the lower half. No tall dressing stands on
1920
+ * the camera's side, so nothing comes between the camera and its hero.
1921
+ */
1922
+ const UPRIGHT_PITCH = Math.max((28 * Math.PI) / 180, Math.min((32 * Math.PI) / 180, PITCH0 - (8 * Math.PI) / 180));
1923
+ let PITCH = PITCH0;
1924
+ const MARGIN = EDGE + 3; // how far past the arena's near side and ends the camera may look: the path, the fence, the flowers
1925
+ // Past its far side it may look into the woods (the trees stand 3 to 18 m out): the clearing reads as a place.
1926
+ const MARGIN_FAR = EDGE + 18;
1927
+ const WHOLE_MARGIN = EDGE + 1.2; // the whole arena: the path and the fence round it
1928
+ const view3 = { x: W / 2, y: H / 2, dist: 0, yaw: 0 };
1929
+ /** Ground reach from the point looked at, toward the camera (near, the screen's bottom) and away (far, its top), per metre of distance. */
1930
+ let NEAR_K = 0; let FAR_K = 0;
1931
+ /** The pitch this frame looks down at (style.json's, or an upright phone's steeper one), and the ground reach it gives. */
1932
+ function setPitch(p: number): void {
1933
+ if (p === PITCH && NEAR_K) return;
1934
+ PITCH = p;
1935
+ NEAR_K = Math.cos(PITCH) - Math.sin(PITCH) / Math.tan(PITCH + HALF);
1936
+ FAR_K = PITCH > HALF + 0.05 ? Math.sin(PITCH) / Math.tan(PITCH - HALF) - Math.cos(PITCH) : 4;
1937
+ }
1938
+ setPitch(PITCH0);
1939
+ function followDistance(cw: number, ch: number, phone: boolean, upright = false): number {
1940
+ // style.json's distance scales the view (22 is these spans); an upright phone's stays between 5.5 and 8 m whatever
1941
+ // it says, or a close camera would show one hero and nothing round it.
1942
+ const k = (CAM.distance ?? 22) / 22;
1943
+ const span = upright ? 6.1 * Math.max(0.9, Math.min(1.3, k)) : (phone ? 9.5 : 13.5) * k;
1944
+ return span / (2 * Math.tan(HALF) * Math.min(1, cw / ch));
1945
+ }
1946
+ /** How far away the whole arena fits; `turned`: seen from its side, its 32 m running up the screen (a tall screen). */
1947
+ function wholeDistance(cw: number, ch: number, turned: boolean): number {
1948
+ const aspect = cw / ch;
1949
+ const deep = turned ? W : H; const wide = turned ? H : W;
1950
+ const byDepth = (deep + 2 * WHOLE_MARGIN) / (NEAR_K + FAR_K);
1951
+ // The arena's near edge is the narrowest part of the view: it has to fit there.
1952
+ const byWidth = (wide / 2 + WHOLE_MARGIN) * Math.sin(PITCH + HALF) / (Math.sin(PITCH) * Math.cos(HALF) * Math.tan(HALF) * aspect);
1953
+ return Math.max(byDepth, byWidth);
1954
+ }
1955
+ /** How far from its far edge to look so a `deep` metres arena sits in the middle of the screen (on the screen, not in metres). */
1956
+ function middleOf(deep: number, d: number): number {
1957
+ let a = -20; let b = deep + 20;
1958
+ for (let i = 0; i < 30; i += 1) { const m = (a + b) / 2; if (screenY(deep - m, d) + screenY(-m, d) < 0) a = m; else b = m; }
1959
+ return (a + b) / 2;
1960
+ }
1961
+ /** How high on the screen (-1 bottom, 1 top) a ground point `s` metres nearer the camera than the point looked at sits. */
1962
+ function screenY(s: number, d: number): number {
1963
+ const along = d * Math.cos(PITCH) - s;
1964
+ return along <= 0 ? -1e3 : Math.tan(Math.atan2(d * Math.sin(PITCH), along) * -1 + PITCH) / Math.tan(HALF);
1965
+ }
1966
+ /**
1967
+ * Where to look (rules coordinates) at distance d, following `focus`, kept from looking past the arena (its path,
1968
+ * fence and a strip of meadow). Where the view is deeper than all that, the arena sits in the middle of the screen:
1969
+ * its near and far edges equally far from the screen's bottom and top (on the screen, not in metres: the near side of
1970
+ * a three-quarter view is the bigger).
1971
+ */
1972
+ function aimAt(focus: { x: number; y: number } | null, d: number, cw: number, ch: number, whole: boolean, turned = false, upright = false): { x: number; y: number } {
1973
+ // Turned (the whole arena on a tall screen, seen from its left side): its far edge is x = W.
1974
+ if (turned) return { x: W - middleOf(W, d), y: H / 2 };
1975
+ // An upright phone follows its player everywhere (past the edge it sees the fence and the woods), looking a little
1976
+ // ahead so the player stands in the lower half and what is coming fills the top.
1977
+ if (upright && focus) return { x: focus.x, y: focus.y - d * 0.27 };
1978
+ const loY = FAR_K * d - MARGIN_FAR; const hiY = H + MARGIN - NEAR_K * d;
1979
+ let y: number;
1980
+ if (whole || loY > hiY) y = middleOf(H, d);
1981
+ // Following: a little ahead of the player, so it stands below the middle and the clearing and the woods it is
1982
+ // heading into fill the top.
1983
+ else y = !focus ? (loY + hiY) / 2 : Math.max(loY, Math.min(hiY, focus.y - d * 0.12));
1984
+ const hw = d * Math.tan(HALF) * (cw / ch); // half the view's width where it looks
1985
+ const loX = hw - MARGIN; const hiX = W - hw + MARGIN;
1986
+ const x = whole || !focus || loX > hiX ? W / 2 : Math.max(loX, Math.min(hiX, focus.x));
1987
+ return { x, y };
1988
+ }
1989
+ function placeCamera(want: { x: number; y: number; dist: number; yaw: number; lift?: number }, dt: number, kick: number): void {
1990
+ if (!view3.dist) Object.assign(view3, want);
1991
+ // A watcher's switch glides, never a cut; the zoom and the turn ease a little slower than the pan.
1992
+ const kp = 1 - Math.exp(-dt * 12); const kd = 1 - Math.exp(-dt * 7);
1993
+ view3.x += (want.x - view3.x) * kp; view3.y += (want.y - view3.y) * kp; view3.dist += (want.dist - view3.dist) * kd; view3.yaw += (want.yaw - view3.yaw) * kd;
1994
+ const [tx, tz] = XZ(view3.x, view3.y);
1995
+ const kx = kick ? (lab.random() - 0.5) * 2 * kick : 0; const kz = kick ? (lab.random() - 0.5) * 2 * kick : 0;
1996
+ const back = Math.cos(PITCH) * view3.dist;
1997
+ // `lift`: the point looked at stands this high (the hero intro looks at a hero's chest, not its feet).
1998
+ const lift = want.lift ?? 0;
1999
+ camera.position.set(tx + kx + Math.sin(view3.yaw) * back, Math.sin(PITCH) * view3.dist + lift, tz + kz + Math.cos(view3.yaw) * back);
2000
+ camera.lookAt(tx + kx, lift, tz + kz);
2001
+ camera.updateMatrixWorld();
2002
+ // The sun's shadow box follows what the camera looks at (a little toward the far side, where the view widens).
2003
+ if (REAL_SHADOWS) { sun.target.position.set(tx, 0, tz - view3.dist * 0.25); sun.position.copy(sun.target.position).addScaledVector(SUN_DIR, 40); }
2004
+ const fog = LIGHT.fog ?? 0.35;
2005
+ const f = scene.fog as Fog;
2006
+ // A light haze far off only: the woods beyond the clearing stay clear.
2007
+ f.near = view3.dist * (2.6 - fog * 0.6); f.far = view3.dist * (6 - fog * 1.5);
2008
+ }
2009
+
2010
+ /* ------------------------------------------------------------------ size */
2011
+ let dpr = 1;
2012
+ function resize(): void {
2013
+ const phone = Math.min(innerWidth, innerHeight) <= 540;
2014
+ // Pixel budgets: 1.5 on a phone, 2 on a computer; the HUD's text stays sharp at the screen's own.
2015
+ renderer.setPixelRatio(Math.min(devicePixelRatio || 1, phone ? 1.5 : 2));
2016
+ renderer.setSize(innerWidth, innerHeight, false);
2017
+ camera.aspect = innerWidth / Math.max(1, innerHeight); camera.updateProjectionMatrix();
2018
+ dpr = Math.min(2, devicePixelRatio || 1);
2019
+ hudCanvas.width = Math.round(innerWidth * dpr); hudCanvas.height = Math.round(innerHeight * dpr);
2020
+ }
2021
+ addEventListener('resize', resize);
2022
+ resize();
2023
+
2024
+ /* ------------------------------------------------------------------ draw */
2025
+ /** Where the hot zone's "×2" sits on the screen this frame: names keep off it. */
2026
+ let zoneMark: { left: number; top: number; right: number; bottom: number } | null = null;
2027
+ const labels = createLabels({ screen: () => ({ w: innerWidth, h: innerHeight }), avoid: () => (zoneMark ? [zoneMark] : []) });
2028
+ let shownLabels: LabelOut[] = [];
2029
+ // Room chat (NETPLAY.md section 19): what a player says in the room's chat shows over their hero for a few seconds,
2030
+ // on the HUD's own paper (one UI with the names, the clock and the board). The studio taking a message down takes it too.
2031
+ const BUBBLE_TYPE = `600 14px ${FONT_BODY}`;
2032
+ const bubbles = createBubbles({ measure: (t) => { ctx.font = BUBBLE_TYPE; return ctx.measureText(t).width; }, screen: () => ({ w: innerWidth, h: innerHeight }), avoid: () => (zoneMark ? [zoneMark] : []) });
2033
+ net.on('say', (s) => bubbles.say(s.seat, s.text, { id: s.id, kind: s.kind }));
2034
+ net.on('unchat', (e) => { for (const id of e.ids) bubbles.remove(id); });
2035
+ let shownBubbles: BubbleOut[] = [];
2036
+ let lastDraw = 0;
2037
+ /** Where a seat's body is drawn now (host: the real body; replica: interpolated), or null. */
2038
+ function seatPos(seat: number): { x: number; y: number } | null {
2039
+ if (seat === mySeat() && me.has && !net.watching) return me;
2040
+ if (hosting) { const b = [...bodies.values()].find((x) => !x.bot && x.seat === seat); return b ? { x: b.x, y: b.y } : null; }
2041
+ const d = [...drawn.values()].find((x) => x.seat === seat);
2042
+ return d ? { x: d.x, y: d.y } : null;
2043
+ }
2044
+ /** The hero intro: how long, and how close it starts (a share of the game's own distance). */
2045
+ const INTRO_MS = 2600;
2046
+ const INTRO_CLOSE = 0.38;
2047
+ const INTRO_PITCH = (24 * Math.PI) / 180;
2048
+ let introAt = 0;
2049
+ const v3 = new Vector3();
2050
+ /** A point on the meadow (rules x, y, h metres up) on the screen, CSS px. */
2051
+ function onScreen(x: number, y: number, h: number, cw: number, ch: number): { x: number; y: number; ok: boolean } {
2052
+ const [px, pz] = XZ(x, y);
2053
+ v3.set(px, h, pz).project(camera);
2054
+ return { x: ((v3.x + 1) / 2) * cw, y: ((1 - v3.y) / 2) * ch, ok: v3.z < 1 };
2055
+ }
2056
+ const mtx = new Matrix4(); const quat = new Quaternion(); const eul = new Euler(); const vpos = new Vector3(); const vscl = new Vector3(); const tint = new Color();
2057
+
2058
+ function draw(t: number, dt: number): void {
2059
+ const cw = innerWidth; const ch = innerHeight;
2060
+ const phone = Math.min(cw, ch) <= 540;
2061
+ // The view: my own body, or (a watcher) the followed player's, drawn exactly as their own browser frames it.
2062
+ const view = viewSeat();
2063
+ const followed = net.watching && view !== null ? seatPos(view) : null;
2064
+ const overview = net.watching ? !followed : mySeat() === null;
2065
+ const focus = net.watching ? followed : overview || !me.has ? null : me;
2066
+ // The Game Lab's views (outside the lab: the game's own camera, always).
2067
+ const lv = labView();
2068
+ const whole = overview || Boolean(lv?.whole);
2069
+ // Only a watcher's overview on a tall screen turns (nobody steers there): the arena's long side runs up the screen.
2070
+ const turned = overview && ch > cw * 1.15;
2071
+ // A player's own phone held upright: steeper and closer, so the action fills it (the overview keeps style.json's).
2072
+ const upright = phone && !whole && ch > cw * 1.15;
2073
+ setPitch(upright ? UPRIGHT_PITCH : PITCH0);
2074
+ const dist = whole ? wholeDistance(cw, ch, turned) : followDistance(cw, ch, phone, upright) / (lv?.zoom ?? 1);
2075
+ const aim = aimAt(lv?.zoom ? subjectAt() ?? focus : focus, dist, cw, ch, whole, turned, upright);
2076
+ // The camera's kick (a bump you were in): a few centimetres, gone in a fifth of a second.
2077
+ const kick = t - kickAt < 200 ? T.shake * (1 - (t - kickAt) / 200) ** 2 : 0;
2078
+ // A seat taken: the camera opens close on your own hero (its idle, its face, the clip library at work) and pulls
2079
+ // back to the game's view over INTRO_MS. Never in the Game Lab, never for a watcher.
2080
+ let want: { x: number; y: number; dist: number; lift?: number } = { ...aim, dist };
2081
+ if (focus && !net.watching && !lab.on) {
2082
+ // It starts with a live round (a seat taken during the results waits for the next one, under the results card)
2083
+ // the moment the game is playable: the arrival card lifts on the hero's own model (its stand-in only when the model
2084
+ // is still not in after about five seconds), so the close-up is the first thing the player sees.
2085
+ if (!introAt && round?.phase === 'live' && playableAt) introAt = t;
2086
+ const u = introAt ? Math.min(1, (t - introAt) / INTRO_MS) : 1;
2087
+ if (u < 1) {
2088
+ const e = u < 0.35 ? 0 : (u - 0.35) / 0.65; const k = e * e * (3 - 2 * e);
2089
+ // Looking at the hero's chest: the whole hero, head to feet, in the middle of the screen.
2090
+ const fy = focus.y - 0.2;
2091
+ want = { x: focus.x + (aim.x - focus.x) * k, y: fy + (aim.y - fy) * k, dist: dist * (INTRO_CLOSE + (1 - INTRO_CLOSE) * k), lift: HERO_M * 0.55 * (1 - k) };
2092
+ // Lower too, at first: its face, not the top of its hat.
2093
+ setPitch(PITCH + (INTRO_PITCH - PITCH) * (1 - k));
2094
+ if (u === 0 || !view3.dist) Object.assign(view3, want, { yaw: 0 });
2095
+ }
2096
+ } else if (!focus) introAt = 0;
2097
+ placeCamera({ ...want, yaw: turned ? -Math.PI / 2 : 0 }, dt, kick);
2098
+ flames.forEach((f, i) => { const k = 1 + 0.14 * Math.sin(t / 95 + i * 2) + 0.06 * Math.sin(t / 37 + i); f.children[0]?.scale.set(1, k, 1); f.children[1]?.scale.set(1, 2 - k, 1); });
2099
+
2100
+ // hot zone (keyed state): gems inside score double
2101
+ zoneFill.visible = zoneRing.visible = Boolean(zone);
2102
+ if (zone) {
2103
+ const pulse = 0.5 + 0.5 * Math.sin(t / 300);
2104
+ const [zx, zz] = XZ(zone.x, zone.y);
2105
+ zoneFill.position.set(zx, 0.014, zz); zoneFill.scale.setScalar(zone.r);
2106
+ (zoneFill.material as MeshBasicMaterial).opacity = 0.14 + 0.1 * pulse;
2107
+ zoneRing.position.set(zx, 0.02, zz); zoneRing.scale.setScalar(zone.r); zoneRing.rotation.y = t / 4000;
2108
+ }
2109
+
2110
+ // gems: spinning, bobbing, glowing; a taken one bursts into gold where it was
2111
+ const gemList: { x: number; y: number; id: number }[] = hosting ? gems : (net.latest()?.d.g ?? []).map(([id, x, y]) => ({ id, x, y }));
2112
+ const rn = round?.n ?? -1;
2113
+ const seenNow = new Set<number>();
2114
+ let nb = 0;
2115
+ for (const g of gemList) seenNow.add(g.id);
2116
+ if (rn === lastGemRound) for (const [id, p] of lastGems) if (!seenNow.has(id)) sparkle(p.x, p.y);
2117
+ lastGems.clear(); lastGemRound = rn;
2118
+ for (let i = 0; i < Math.min(gemList.length, GEM_CAP); i += 1) {
2119
+ const g = gemList[i] as { x: number; y: number; id: number };
2120
+ lastGems.set(g.id, { x: g.x, y: g.y });
2121
+ const [gx, gz] = XZ(g.x, g.y);
2122
+ const bob = 0.5 + 0.5 * Math.sin(t / 300 + g.id);
2123
+ const sc = 1 + 0.12 * Math.sin(t / 200 + g.id);
2124
+ // A coin stands on its edge and spins (the model lies flat: up on its edge first, then turned about the up axis).
2125
+ mtx.compose(vpos.set(gx, 0.42 + 0.14 * bob, gz), quat.setFromEuler(eul.set(Math.PI / 2, t / 420 + g.id, 0, 'YXZ')), vscl.setScalar(sc * GEM_DRAWN * gemFit));
2126
+ for (const c of gemParts) placeCopy(c, i, mtx);
2127
+ glows.setMatrixAt(i, mtx.compose(vpos.set(gx, 0, gz), quat.identity(), vscl.set(0.75 + 0.1 * bob, 1, 0.75 + 0.1 * bob)));
2128
+ blobs.setMatrixAt(nb++, mtx.compose(vpos.set(gx, 0, gz), quat.identity(), vscl.set(0.32 - 0.06 * bob, 1, 0.32 - 0.06 * bob)));
2129
+ }
2130
+ const ng = Math.min(gemList.length, GEM_CAP);
2131
+ for (const { mesh: im } of gemParts) { im.count = ng; im.instanceMatrix.needsUpdate = true; }
2132
+ glows.count = ng; glows.instanceMatrix.needsUpdate = true;
2133
+
2134
+ // swings: a slash arcs in front of the swinger as the swing lands (after its windup); a hit rings white
2135
+ let nw = 0; let ns2 = 0;
2136
+ for (let i = waves.length - 1; i >= 0; i -= 1) {
2137
+ const w = waves[i] as (typeof waves)[number];
2138
+ const lead = w.knock ? 0 : T.windupMs * 0.75;
2139
+ const age = (t - w.at - lead) / T.ringMs;
2140
+ if (age > 1) { waves.splice(i, 1); continue; }
2141
+ if (age < 0) continue;
2142
+ const [wx, wz] = XZ(w.x, w.y);
2143
+ if (w.knock) {
2144
+ const m = waveMesh(nw++);
2145
+ const r = R_AV + 0.12 + age * 0.8;
2146
+ m.visible = true; m.position.set(wx, 0.03, wz); m.scale.set(r, 1, r);
2147
+ const mat = m.material as MeshBasicMaterial; mat.color.set(w.colour); mat.opacity = 1 - age;
2148
+ } else {
2149
+ const m = slashMesh(ns2++);
2150
+ const pos = hosting ? bodies.get(w.slot ?? -1) : null;
2151
+ const fa = w.fa ?? pos?.fa ?? 0;
2152
+ const r = 0.55 + Math.min(1, age * 2.2) * (T.knockRange - 0.55);
2153
+ m.visible = true; m.position.set(wx, 0.55, wz); m.rotation.set(0, fa, 0); m.scale.set(r, 1, r);
2154
+ const mat = m.material as MeshBasicMaterial; mat.color.set(w.colour); mat.opacity = 0.85 * (1 - age) ** 1.5;
2155
+ }
2156
+ }
2157
+ for (let i = nw; i < wavePool.length; i += 1) (wavePool[i] as Mesh).visible = false;
2158
+ for (let i = ns2; i < slashPool.length; i += 1) (slashPool[i] as Mesh).visible = false;
2159
+
2160
+ // the heroes
2161
+ const names = new Map<number, Slot>((net.slots ?? roster.slots).map((s) => [s.slot, s]));
2162
+ // `mine`: the body whose view this is: my own, or the player a watcher follows (named, never "You").
2163
+ const list: { slot: number; seat: number | null; x: number; y: number; h: number; bot: boolean; name: string; mine: boolean }[] = [];
2164
+ const isView = (seat: number | null, bot: boolean): boolean => !bot && seat !== null && seat === view;
2165
+ if (hosting) {
2166
+ for (const b of bodies.values()) {
2167
+ const own = !b.bot && b.seat !== null && b.seat === mySeat() && me.has;
2168
+ list.push({ slot: b.slot, seat: b.seat, x: own ? me.x : b.x, y: own ? me.y : b.y, h: own ? me.h : b.h, bot: b.bot, name: b.name, mine: isView(b.seat, b.bot) });
2169
+ }
2170
+ } else {
2171
+ for (const d of drawn.values()) {
2172
+ const own = !net.watching && d.seat >= 0 && d.seat === net.seat;
2173
+ const s = names.get(d.slot);
2174
+ list.push({ slot: d.slot, seat: d.seat >= 0 ? d.seat : null, x: own && me.has ? me.x : d.x, y: own && me.has ? me.y : d.y, h: own && me.has ? me.h : d.h, bot: d.seat < 0, name: s?.name ?? (d.seat >= 0 ? `Player ${d.seat + 1}` : botName(d.slot)), mine: isView(d.seat >= 0 ? d.seat : null, d.seat < 0) });
2175
+ }
2176
+ }
2177
+ const over = round?.phase === 'over';
2178
+ const places = new Map<number, number>((over ? round?.results ?? [] : []).map((r) => [r.slot, r.place]));
2179
+ let nr = 0;
2180
+ youRing.visible = false;
2181
+ for (const a of list) {
2182
+ const colour = colourOf(a.slot, a.bot ? null : a.seat);
2183
+ const fx = bodyFx(a.slot, t);
2184
+ const hero = heroFor(a.slot, heroKind(a.slot, a.seat, a.bot), colour);
2185
+ hero.seen = frames; hero.mine = a.mine;
2186
+ poseHero(hero, a, t, dt, fx, places.get(a.slot) ?? null, over);
2187
+ const [bx, bz] = XZ(a.x + fx.ox, a.y + fx.oy);
2188
+ seatRings.setMatrixAt(nr, mtx.compose(vpos.set(bx, 0, bz), quat.identity(), vscl.setScalar(1)));
2189
+ seatEdges.setMatrixAt(nr, mtx);
2190
+ seatRings.setColorAt(nr, tint.set(a.bot ? mixHex(colour, '#9aa3ad', 0.55) : colour));
2191
+ nr += 1;
2192
+ // The shadow stays on the ground and shrinks as the hero rises.
2193
+ const lift = Math.max(0.45, 1 - a.h * 0.45);
2194
+ blobs.setMatrixAt(nb++, mtx.compose(vpos.set(bx, 0, bz), quat.identity(), vscl.set(0.55 * fx.sx * lift, 1, 0.55 * fx.sy * lift)));
2195
+ if (a.mine) { youRing.visible = true; youRing.position.set(bx, 0.024, bz); youRing.scale.setScalar(1 + 0.05 * Math.sin(t / 220)); }
2196
+ }
2197
+ // Far and off-screen heroes pose less often (a room of many on a phone).
2198
+ crowd([...heroes.values()].map((x) => x.char).filter((c): c is Character => Boolean(c)), camera, { near: 16, far: 30 });
2199
+ // Bodies that left: their heroes go.
2200
+ for (const [slot, hero] of heroes) if (hero.seen !== frames) { clearHero(hero); scene.remove(hero.root); heroes.delete(slot); }
2201
+ seatRings.count = nr; seatRings.instanceMatrix.needsUpdate = true; seatEdges.count = nr; seatEdges.instanceMatrix.needsUpdate = true; if (seatRings.instanceColor) seatRings.instanceColor.needsUpdate = true;
2202
+ blobs.count = nb; blobs.instanceMatrix.needsUpdate = true;
2203
+
2204
+ // sparks
2205
+ let ns = 0;
2206
+ for (let i = sparks.length - 1; i >= 0; i -= 1) {
2207
+ const sp = sparks[i] as (typeof sparks)[number];
2208
+ const age = t - sp.at;
2209
+ if (age > sp.life) { sparks.splice(i, 1); continue; }
2210
+ if (!sp.gold && age < T.hitStopMs * 0.5) continue;
2211
+ const u = age / sp.life; const s = (age / 1000) * (1 - u * 0.5);
2212
+ const [sx, sz] = XZ(sp.x + sp.vx * s, sp.y + sp.vy * s);
2213
+ const h = sp.h + sp.vh * s - 4.9 * s * s;
2214
+ const len = Math.hypot(sp.vx, sp.vy) * 0.022 * (1 - u) + 0.05;
2215
+ mtx.compose(vpos.set(sx, Math.max(0.05, h), sz), quat.setFromEuler(eul.set(0, Math.atan2(-sp.vy, sp.vx), 0)), vscl.set(len, 1.6 * (1 - u) + 0.3, 1.6 * (1 - u) + 0.3));
2216
+ sparkMesh.setMatrixAt(ns, mtx);
2217
+ sparkMesh.setColorAt(ns, tint.set(sp.gold ? (u < 0.3 ? '#ffffff' : COL.gem) : u < 0.4 ? '#ffffff' : '#ffd166'));
2218
+ ns += 1;
2219
+ if (ns >= 160) break;
2220
+ }
2221
+ sparkMesh.count = ns; sparkMesh.instanceMatrix.needsUpdate = true; if (sparkMesh.instanceColor) sparkMesh.instanceColor.needsUpdate = true;
2222
+
2223
+ if (lab.on) { pen.begin(); lab.draw(pen); pen.end(); }
2224
+ renderer.render(scene, camera);
2225
+ arrival(t);
2226
+
2227
+ // ---- the HUD, over the world
2228
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
2229
+ ctx.clearRect(0, 0, cw, ch);
2230
+ // the hot zone's "×2", on the screen over its middle; over its far or near edge instead when the hero whose view
2231
+ // this is stands under its middle (the mark never covers your own hero)
2232
+ zoneMark = null;
2233
+ if (zone) {
2234
+ const size = phone ? 20 : 24;
2235
+ const own = list.find((a) => a.mine);
2236
+ const covers = (p: { x: number; y: number }): boolean => {
2237
+ if (!own) return false;
2238
+ const head = onScreen(own.x, own.y, HERO_M + own.h, cw, ch); const foot = onScreen(own.x, own.y, 0, cw, ch);
2239
+ const r = Math.max(14, Math.abs(onScreen(own.x + 0.5, own.y, 0, cw, ch).x - foot.x));
2240
+ return Math.abs(p.x - foot.x) < r + size && p.y > head.y - size && p.y < foot.y + size;
2241
+ };
2242
+ let z = onScreen(zone.x, zone.y, 0, cw, ch);
2243
+ for (const dy of [-0.72, 0.72]) { if (!covers(z)) break; z = onScreen(zone.x, zone.y + dy * zone.r, 0, cw, ch); }
2244
+ if (z.ok) {
2245
+ ctx.font = `700 ${size}px ${FONT_DISPLAY}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.lineJoin = 'round'; ctx.lineWidth = 4;
2246
+ ctx.strokeStyle = 'rgba(255,255,255,0.85)'; ctx.strokeText('×2', z.x, z.y); ctx.fillStyle = PAL.accent; ctx.fillText('×2', z.x, z.y);
2247
+ const half = ctx.measureText('×2').width / 2 + 3;
2248
+ zoneMark = { left: z.x - half, top: z.y - size * 0.6, right: z.x + half, bottom: z.y + size * 0.6 };
2249
+ }
2250
+ }
2251
+ // Names go on the screen, so they read at one size on any screen and never pile up.
2252
+ const fs = Math.round(Math.max(15, Math.min(22, (15 * Math.min(cw, ch)) / 720)));
2253
+ ctx.font = `700 ${fs}px ${FONT_BODY}`;
2254
+ const tags: LabelIn[] = [];
2255
+ const heads = new Map<number, { x: number; y: number; seat: number; mine: boolean }>();
2256
+ const viewAt = list.find((a) => a.mine) ?? null;
2257
+ for (const a of list) {
2258
+ const text = a.mine && !net.watching ? `You · ${heroName(heroKind(a.slot, a.seat, a.bot))}` : label(a.name, a.bot);
2259
+ const head = onScreen(a.x, a.y, HERO_M + 0.12 + a.h, cw, ch);
2260
+ const mid = onScreen(a.x, a.y, HERO_M * 0.45 + a.h, cw, ch);
2261
+ const side = onScreen(a.x + R_AV, a.y, HERO_M * 0.45 + a.h, cw, ch);
2262
+ if (!head.ok) continue;
2263
+ const r = Math.max(6, Math.hypot(side.x - mid.x, side.y - mid.y));
2264
+ if (mid.x + r < 0 || mid.x - r > cw || head.y > ch || mid.y + r < 0) continue; // off screen: no name at the edge
2265
+ const foot = onScreen(a.x, a.y, 0, cw, ch);
2266
+ if (a.seat !== null && !a.bot) heads.set(a.slot, { x: head.x, y: head.y - 3, seat: a.seat, mine: a.mine });
2267
+ // People before bots, nearer the view's body first; each keeps off the others' bodies when it can.
2268
+ tags.push({ key: a.slot, text, x: head.x, y: head.y - 3, w: ctx.measureText(text).width, h: fs * 1.2, below: foot.y + r * 0.6 + 4 + fs * 1.2, body: { left: mid.x - r, top: head.y, right: mid.x + r, bottom: foot.y + r * 0.4 }, self: a.mine, rank: (a.bot ? 10_000 : 0) + (viewAt ? Math.hypot(a.x - viewAt.x, a.y - viewAt.y) * 50 : 0) });
2269
+ }
2270
+ shownLabels = labels.place(tags, Math.min(0.1, (t - (lastDraw || t)) / 1000));
2271
+ lastDraw = t;
2272
+ ctx.font = `700 ${fs}px ${FONT_BODY}`;
2273
+ ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.lineJoin = 'round';
2274
+ for (const l of [...shownLabels].sort((x, y) => Number(Boolean(x.self)) - Number(Boolean(y.self)))) {
2275
+ if (l.alpha <= 0) continue;
2276
+ ctx.globalAlpha = l.alpha;
2277
+ if (l.moved) {
2278
+ // Off its own spot: a thin line to its body says whose it is.
2279
+ const under = l.top > l.y;
2280
+ ctx.strokeStyle = 'rgba(255,255,255,0.7)'; ctx.lineWidth = 1.5;
2281
+ ctx.beginPath(); ctx.moveTo(l.cx, under ? l.top : l.bottom); ctx.lineTo(l.x, under ? (l.body?.bottom ?? l.top - 6) : l.y + 2); ctx.stroke();
2282
+ }
2283
+ // Every name on the HUD's paper (yours fuller, a bot's fainter): one UI with the clock and the board.
2284
+ ctx.fillStyle = PAPER; ctx.globalAlpha = l.alpha * (l.self ? 0.94 : 0.8); ctx.beginPath(); ctx.roundRect(l.left - 6, l.top - 1, l.right - l.left + 12, l.bottom - l.top + 2, 8); ctx.fill(); ctx.globalAlpha = l.alpha;
2285
+ ctx.fillStyle = l.self ? TEXT : mixHex(TEXT, PAPER, 0.25);
2286
+ ctx.fillText(l.text, l.cx, l.cy);
2287
+ }
2288
+ ctx.globalAlpha = 1; ctx.textBaseline = 'alphabetic';
2289
+ // Speech bubbles (room chat): over each speaker's name pill, the view's own player first.
2290
+ if (bubbles.size) {
2291
+ const anchors: BubbleIn[] = [];
2292
+ for (const [slot, h] of heads) {
2293
+ const l = shownLabels.find((x) => x.key === slot && x.alpha > 0 && !x.moved);
2294
+ anchors.push({ key: h.seat, x: l ? l.cx : h.x, y: l ? l.top - 3 : h.y, self: h.mine });
2295
+ }
2296
+ shownBubbles = bubbles.place(anchors);
2297
+ paintBubbles(ctx, shownBubbles, { font: BUBBLE_TYPE, paper: PAPER, ink: TEXT, edge: mixHex(TEXT, PAPER, 0.7) });
2298
+ } else shownBubbles = [];
2299
+
2300
+ // A dodge pops a word over the jumper, rising and fading.
2301
+ for (let i = pops.length - 1; i >= 0; i -= 1) {
2302
+ const pp = pops[i] as (typeof pops)[number];
2303
+ const age = (t - pp.at) / 900;
2304
+ if (age > 1) { pops.splice(i, 1); continue; }
2305
+ const who = list.find((x) => x.slot === pp.slot);
2306
+ if (!who) continue;
2307
+ const at = onScreen(who.x, who.y, HERO_M + 0.6 + who.h + age * 0.6, cw, ch);
2308
+ if (!at.ok) continue;
2309
+ ctx.globalAlpha = Math.min(1, (1 - age) * 2);
2310
+ ctx.font = `700 ${phone ? 18 : 22}px ${FONT_DISPLAY}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.lineJoin = 'round'; ctx.lineWidth = 5;
2311
+ ctx.strokeStyle = 'rgba(255,255,255,0.9)'; ctx.strokeText(pp.text, at.x, at.y); ctx.fillStyle = PAL.accent2; ctx.fillText(pp.text, at.x, at.y);
2312
+ ctx.globalAlpha = 1;
2313
+ }
2314
+ // A big screen's HUD is drawn larger (up to 1.35 times at 840 px and taller), so it reads from the sofa as well.
2315
+ const ui = phone ? 1 : Math.max(1, Math.min(1.35, Math.min(cw, ch) / 620));
2316
+ ctx.save(); ctx.scale(ui, ui);
2317
+ hud(cw / ui, ch / ui, phone, list);
2318
+ ctx.restore();
2319
+ // The touch buttons, bottom right: Jump (the bigger, nearer the thumb) and Swing. Only on a touch screen.
2320
+ buttons.length = 0;
2321
+ if (touched && mySeat() !== null && !net.watching) {
2322
+ const r = phone ? 34 : 40; const pad = phone ? 18 : 26;
2323
+ const jx = cw - pad - r; const jy = ch - pad - r - 6;
2324
+ const sx = jx - r * 2.3; const sy = jy - r * 0.55;
2325
+ for (const b of [{ id: 'jump' as const, x: jx, y: jy, r, label: 'Jump' }, { id: 'swing' as const, x: sx, y: sy, r: r * 0.92, label: 'Swing' }]) {
2326
+ const pressed = t - (prevButtons.get(b.id) ?? -1e9) < 160;
2327
+ ctx.globalAlpha = pressed ? 0.95 : 0.78;
2328
+ ctx.fillStyle = b.id === 'jump' ? PAPER : HOT;
2329
+ ctx.beginPath(); ctx.arc(b.x, b.y, b.r * (pressed ? 0.92 : 1), 0, Math.PI * 2); ctx.fill();
2330
+ ctx.globalAlpha = 1; ctx.strokeStyle = 'rgba(0,0,0,0.18)'; ctx.lineWidth = 2; ctx.stroke();
2331
+ ctx.fillStyle = b.id === 'jump' ? TEXT : '#ffffff'; ctx.font = `700 ${phone ? 14 : 16}px ${FONT_BODY}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
2332
+ ctx.fillText(b.label, b.x, b.y + 1);
2333
+ buttons.push({ id: b.id, x: b.x, y: b.y, r: b.r, at: prevButtons.get(b.id) ?? 0 });
2334
+ }
2335
+ }
2336
+ if (stick.active) {
2337
+ ctx.strokeStyle = 'rgba(255,255,255,0.8)'; ctx.lineWidth = 3;
2338
+ ctx.beginPath(); ctx.arc(stick.ox, stick.oy, 56, 0, Math.PI * 2); ctx.stroke();
2339
+ ctx.strokeStyle = 'rgba(29,43,58,0.25)'; ctx.lineWidth = 1; ctx.beginPath(); ctx.arc(stick.ox, stick.oy, 58, 0, Math.PI * 2); ctx.stroke();
2340
+ const dx = stick.x - stick.ox; const dy = stick.y - stick.oy; const len = Math.hypot(dx, dy); const m = len > 56 ? 56 / len : 1;
2341
+ ctx.fillStyle = 'rgba(255,255,255,0.75)'; ctx.beginPath(); ctx.arc(stick.ox + dx * m, stick.oy + dy * m, 24, 0, Math.PI * 2); ctx.fill();
2342
+ }
2343
+ }
2344
+
2345
+ /** When each touch button was last pressed (for its press look). */
2346
+ const prevButtons = new Map<string, number>();
2347
+ canvas.addEventListener('pointerdown', (e) => { const b = buttonAt(e.clientX, e.clientY); if (b) prevButtons.set(b.id, performance.now()); });
2348
+ /** A rounded panel behind HUD text (style.json's "chips"): the palette's ink, a little see-through. */
2349
+ function chip(x: number, y: number, w: number, h: number, alpha = 0.88): void {
2350
+ ctx.fillStyle = PAPER; ctx.globalAlpha = Math.max(alpha, 0.82);
2351
+ ctx.beginPath(); ctx.roundRect(x, y, w, h, Math.min(12, h / 2)); ctx.fill();
2352
+ ctx.globalAlpha = 1;
2353
+ }
2354
+
2355
+ /**
2356
+ * THE ARRIVAL (NETPLAY.md section 21; createNetplay's `arrival: 'game'`). Until this game says it is playable, the play
2357
+ * page shows its arrival card: the game's title and art, and a progress line this game feeds (`net.loading`: the
2358
+ * characters first, "the heroes", then "the clearing"). It is playable once the round's state is in (a host has its
2359
+ * round; anyone else has drawn a snapshot) and the hero whose view this is stands there in its real model, drawn this
2360
+ * frame; or, when its model is still not in after about five seconds, with its stand-in. A watcher's overview waits for
2361
+ * every hero in view instead. Then `net.playable()`, once, and the hero intro starts under the lifting card.
2362
+ * The game drew its own title card at a round's start before the page had one: the arrival card is that title now, so
2363
+ * the round opens on the hero, with nothing over it. performance marks `hero:model` (your hero's real model first drawn)
2364
+ * and `hero:playable` say when, for a harness.
2365
+ */
2366
+ const BOOT_AT = performance.now();
2367
+ let playableAt = 0;
2368
+ let modelAt = 0;
2369
+ function arrival(t: number): void {
2370
+ const view = [...heroes.values()].find((h) => h.mine) ?? null;
2371
+ if (!modelAt && view?.char && !net.watching) { modelAt = t; try { performance.mark('hero:model'); } catch { /* old browser */ } }
2372
+ if (playableAt) return;
2373
+ const stateIn = Boolean(round) && (hosting || drawn.size > 0);
2374
+ const dressed = view ? Boolean(view.char) : heroes.size > 0 && [...heroes.values()].every((h) => h.char);
2375
+ if (!stateIn || (!dressed && performance.now() - BOOT_AT < 5000)) return;
2376
+ playableAt = t;
2377
+ try { performance.mark('hero:playable'); } catch { /* old browser */ }
2378
+ net.playable();
2379
+ }
2380
+
2381
+ function hud(cw: number, ch: number, phone: boolean, list: { slot: number; seat: number | null; name: string; bot: boolean; mine: boolean }[]): void {
2382
+ const pad = phone ? 12 : 18;
2383
+ const debugStrip = new URLSearchParams(location.search).get('debug') === '1' || (window as unknown as { HOMIE_NET?: { debug?: boolean } }).HOMIE_NET?.debug;
2384
+ const top = pad + (debugStrip ? (phone ? 50 : 26) : 0);
2385
+ const now = net.now();
2386
+ const r = round;
2387
+ // the clock
2388
+ ctx.textBaseline = 'middle'; ctx.textAlign = 'left';
2389
+ ctx.font = `700 ${phone ? 19 : 22}px ${FONT_DISPLAY}`;
2390
+ const left = r ? Math.max(0, Math.ceil((r.endsAt - now) / 1000)) : 0;
2391
+ const clock = `${Math.floor(left / 60)}:${String(left % 60).padStart(2, '0')}`;
2392
+ const said = r ? (r.phase === 'live' ? `Round ${r.n} · ${clock}` : `Next round in ${left}`) : 'Joining…';
2393
+ const cwid = ctx.measureText(said).width;
2394
+ const chH = phone ? 34 : 40;
2395
+ chip(pad, top, cwid + 26, chH);
2396
+ ctx.fillStyle = r?.phase === 'live' && left <= 10 ? PAL.danger : TEXT;
2397
+ ctx.fillText(said, pad + 13, top + chH / 2 + 1);
2398
+ // scores: the play page's room button (and a server's pill beside it) sit at the top right (game.json screen.share's
2399
+ // default): the scores start under that band, so the buttons never cover a score.
2400
+ const scores = new Map<number, number>();
2401
+ if (hosting) for (const b of bodies.values()) scores.set(b.slot, b.score);
2402
+ else for (const d of drawn.values()) scores.set(d.slot, d.score);
2403
+ // A phone's board is compact (the top three, a short name and a small "bot" or "AI" tag after it; a bot's dot is
2404
+ // hollow), so a game's own HUD at the top left (a basket, a timer) has room beside it. Every bot and AI says so.
2405
+ const rows = [...list].sort((a, b) => (scores.get(b.slot) ?? 0) - (scores.get(a.slot) ?? 0)).slice(0, phone ? 3 : 6);
2406
+ const TAG_FONT = `800 10px ${FONT_BODY}`;
2407
+ ctx.font = TAG_FONT;
2408
+ const marks = rows.map((a) => (!phone || (a.mine && !net.watching) ? '' : a.name.endsWith(AI_MARK) ? 'AI' : a.bot ? 'bot' : ''));
2409
+ const markW = marks.map((m) => (m ? ctx.measureText(m).width + 10 : 0));
2410
+ ctx.font = `700 ${phone ? 13 : 16}px ${FONT_BODY}`;
2411
+ const rowH = phone ? 20 : 25;
2412
+ const fit = (t: string, max: number): string => { let x = t; while (x.length > 3 && ctx.measureText(x).width > max) x = `${x.slice(0, -2)}…`; return x; };
2413
+ const texts = rows.map((a, i) => (a.mine && !net.watching ? 'You' : phone ? fit(a.name.replace(AI_MARK, '').trim(), 104 - (markW[i] ? (markW[i] as number) + 5 : 0)) : label(a.name, a.bot)));
2414
+ const nameW = Math.max(0, ...texts.map((x, i) => ctx.measureText(x).width + (markW[i] ? (markW[i] as number) + 5 : 0)));
2415
+ const boardW = nameW + (phone ? 56 : 74);
2416
+ // Together: the room's total heads the board, which moves down by a row so it stays under the room buttons.
2417
+ const board = top + 18 + 44 - rowH / 2 + (TOGETHER ? rowH + 6 : 0);
2418
+ if (TOGETHER) {
2419
+ // One total for the room, then each share (no places): a cozy room works as one.
2420
+ const total = [...scores.values()].reduce((n, v) => n + v, 0);
2421
+ const head = `Together · ${total}`;
2422
+ ctx.font = `700 ${phone ? 15 : 17}px ${FONT_DISPLAY}`;
2423
+ const hw = Math.max(boardW, ctx.measureText(head).width + 28);
2424
+ chip(cw - pad - hw, board - 6 - (rowH + 6), hw, rowH + 6 + rows.length * rowH + 12, 0.7);
2425
+ ctx.textAlign = 'left'; ctx.fillStyle = HOT;
2426
+ ctx.fillText(head, cw - pad - hw + 14, board - rowH / 2 + 1);
2427
+ ctx.font = `700 ${phone ? 13 : 16}px ${FONT_BODY}`;
2428
+ } else if (rows.length) chip(cw - pad - boardW, board - 6, boardW, rows.length * rowH + 12, 0.7);
2429
+ rows.forEach((a, i) => {
2430
+ const y = board + i * rowH + rowH / 2;
2431
+ const colour = colourOf(a.slot, a.bot ? null : a.seat);
2432
+ ctx.fillStyle = a.bot ? mixHex(colour, '#9aa3ad', 0.55) : colour;
2433
+ ctx.beginPath(); ctx.arc(cw - pad - boardW + 14, y, 5, 0, Math.PI * 2);
2434
+ if (a.bot && phone) { ctx.strokeStyle = ctx.fillStyle; ctx.lineWidth = 2; ctx.stroke(); } else ctx.fill();
2435
+ ctx.textAlign = 'left';
2436
+ ctx.fillStyle = a.mine ? TEXT : mixHex(TEXT, PAPER, a.bot ? 0.42 : 0.15);
2437
+ ctx.fillText(texts[i] as string, cw - pad - boardW + 26, y + 1);
2438
+ const mark = marks[i];
2439
+ if (mark) {
2440
+ // The tag: a small pill after the name, the HUD's ink on its paper.
2441
+ const mx = cw - pad - boardW + 26 + ctx.measureText(texts[i] as string).width + 5; const mw = markW[i] as number;
2442
+ ctx.fillStyle = mixHex(TEXT, PAPER, 0.8); ctx.beginPath(); ctx.roundRect(mx, y - 7, mw, 14, 7); ctx.fill();
2443
+ ctx.font = TAG_FONT; ctx.fillStyle = mixHex(TEXT, PAPER, 0.15); ctx.fillText(mark, mx + 5, y + 1);
2444
+ ctx.font = `700 ${phone ? 13 : 16}px ${FONT_BODY}`;
2445
+ }
2446
+ ctx.textAlign = 'right';
2447
+ ctx.fillStyle = a.mine ? HOT : TEXT;
2448
+ ctx.fillText(String(scores.get(a.slot) ?? 0), cw - pad - 12, y + 1);
2449
+ });
2450
+ // The role badge (host, replica, watching): a debugging aid, only with ?debug=1 (a player never needs it).
2451
+ if (debugStrip) {
2452
+ ctx.textAlign = 'left'; ctx.font = '600 11px ui-monospace, Menlo, monospace';
2453
+ const badge = net.offline ? 'OFFLINE HOST' : net.watching ? 'WATCHING' : net.role.toUpperCase();
2454
+ chip(pad - 4, ch - pad - 16, ctx.measureText(badge).width + 12, 20, 0.55);
2455
+ ctx.fillStyle = mixHex(TEXT, PAPER, 0.2);
2456
+ ctx.fillText(badge, pad + 2, ch - pad - 5);
2457
+ }
2458
+ if (r && r.phase === 'over' && r.results) {
2459
+ // The results card: the palette's own paper and ink, the winner in gold.
2460
+ const w = Math.min(380, cw - 32); const h = 64 + Math.min(6, r.results.length) * 30;
2461
+ const x = (cw - w) / 2; const y = (ch - h) / 2;
2462
+ ctx.fillStyle = mixHex(PAPER, '#ffffff', 0.35); ctx.globalAlpha = 0.96;
2463
+ ctx.beginPath(); ctx.roundRect(x, y, w, h, 18); ctx.fill(); ctx.globalAlpha = 1;
2464
+ ctx.strokeStyle = TEXT; ctx.globalAlpha = 0.12; ctx.lineWidth = 2; ctx.stroke(); ctx.globalAlpha = 1;
2465
+ ctx.textAlign = 'center'; ctx.fillStyle = HOT; ctx.font = `700 ${phone ? 20 : 22}px ${FONT_DISPLAY}`;
2466
+ const sum = r.results.reduce((n, row) => n + row.score, 0);
2467
+ ctx.fillText(TOGETHER ? `Together: ${sum}` : `Round ${r.n} results`, cw / 2, y + 32);
2468
+ ctx.font = `700 ${phone ? 15 : 16}px ${FONT_BODY}`;
2469
+ const view = viewSeat();
2470
+ r.results.slice(0, 6).forEach((row, i) => {
2471
+ const mine = !row.bot && row.seat !== null && row.seat === view;
2472
+ const ry = y + 66 + i * 30;
2473
+ if (mine) { ctx.fillStyle = PAL.gold; ctx.globalAlpha = 0.55; ctx.beginPath(); ctx.roundRect(x + 14, ry - 13, w - 28, 26, 10); ctx.fill(); ctx.globalAlpha = 1; }
2474
+ ctx.fillStyle = row.bot ? mixHex(TEXT, PAPER, 0.4) : TEXT;
2475
+ ctx.fillText(`${TOGETHER ? '' : `${row.place}. `}${mine && !net.watching ? 'You' : label(row.name, row.bot)}${mine && net.watching ? ' ◂' : ''} — ${row.score}`, cw / 2, ry + 1);
2476
+ });
2477
+ }
2478
+ if (!net.offline && !net.connected && net.role !== 'host') {
2479
+ ctx.textAlign = 'center'; ctx.font = `700 15px ${FONT_BODY}`;
2480
+ const text = 'Reconnecting…'; const tw = ctx.measureText(text).width;
2481
+ chip(cw / 2 - tw / 2 - 12, ch - pad - 24, tw + 24, 26);
2482
+ ctx.fillStyle = HOT; ctx.fillText(text, cw / 2, ch - pad - 10);
2483
+ }
2484
+ // The controls, for the first eight seconds of play (from the moment the arrival card lifts), above the touch
2485
+ // buttons when there are some, never under them.
2486
+ if (playableAt && performance.now() - playableAt < 8000 && mySeat() !== null && !net.watching) {
2487
+ ctx.textAlign = 'center'; ctx.font = `700 ${phone ? 14 : 16}px ${FONT_BODY}`;
2488
+ const text = phone ? 'Drag to move · Jump and Swing on the right' : 'WASD to move · Space jumps · F or click swings';
2489
+ const tw = ctx.measureText(text).width;
2490
+ const y = ch - pad - 56 - (touched ? (phone ? 96 : 110) : 0);
2491
+ chip(cw / 2 - tw / 2 - 12, y, tw + 24, 26, 0.6);
2492
+ ctx.fillStyle = TEXT; ctx.fillText(text, cw / 2, y + 14);
2493
+ }
2494
+ ctx.textBaseline = 'alphabetic';
2495
+ }
2496
+
2497
+ /* ------------------------------------------------------------------ loop */
2498
+ let lastT = -1;
2499
+ function frame(t: number): void {
2500
+ const dt = lab.time.dt(t, 0.05);
2501
+ // The look's own clock (the heroes' clips): real seconds, at most a tenth, whatever the rules' step.
2502
+ const ddt = lastT < 0 ? 0 : Math.min(0.1, Math.max(0, (t - lastT) / 1000)); lastT = t;
2503
+ stepMe(dt);
2504
+ if (hosting) stepHost(dt);
2505
+ else stepReplica(dt);
2506
+ if (lab.on) labReport(dt);
2507
+ draw(t, lab.on ? dt : ddt);
2508
+ frames += 1;
2509
+ requestAnimationFrame(frame);
2510
+ }
2511
+
2512
+ net.expose({
2513
+ // Room chat's bubbles on this screen now: whose, what, and where (an end-to-end test reads them).
2514
+ bubbles: () => shownBubbles.map((b) => ({ seat: b.key, text: b.lines.join(' '), alpha: b.alpha, left: Math.round(b.left), top: Math.round(b.top), right: Math.round(b.right), bottom: Math.round(b.bottom) })),
2515
+ self: () => (me.has ? { x: me.x, y: me.y } : null),
2516
+ peer: (seat: number) => {
2517
+ if (hosting) { const b = [...bodies.values()].find((x) => x.seat === seat); return b ? { x: b.x, y: b.y } : null; }
2518
+ const d = [...drawn.values()].find((x) => x.seat === seat);
2519
+ return d ? { x: d.x, y: d.y } : null;
2520
+ },
2521
+ frames: () => frames,
2522
+ scores: () => (hosting ? [...bodies.values()].map((b) => ({ slot: b.slot, seat: b.seat, bot: b.bot, score: b.score })) : [...drawn.values()].map((d) => ({ slot: d.slot, seat: d.seat >= 0 ? d.seat : null, bot: d.seat < 0, score: d.score }))),
2523
+ /**
2524
+ * Host: gems each slot picked up this round, the round's age, and how each bot plays: the room's dial (`dial`), the
2525
+ * level it plays at this round (`level`: a level easier in a newcomer's first round) and the rubber band (`soft`, 0
2526
+ * at its dial to 1 all the way soft). `newcomer`: somebody is in their first round here.
2527
+ */
2528
+ pickups: () => (hosting ? {
2529
+ round: round ? { n: round.n, phase: round.phase, ageMs: net.now() - round.startedAt } : null,
2530
+ newcomer: newcomerRound(people()),
2531
+ slots: [...bodies.values()].map((b) => ({ slot: b.slot, bot: b.bot, gems: pickups.get(b.slot) ?? 0, dial: b.bot ? net.skillOf(b.slot).level : null, level: b.bot ? (botPlay.get(b.slot)?.level ?? net.skillOf(b.slot).level) : null, soft: b.bot ? +(botPlay.get(b.slot)?.soft ?? 0).toFixed(2) : null })),
2532
+ } : null),
2533
+ /** Where the coins are now (rules metres): what a harness's coin-chasing player steers by. */
2534
+ gems: () => (hosting ? gems.map((g) => ({ id: g.id, x: g.x, y: g.y })) : (net.latest()?.d.g ?? []).map(([id, x, y]) => ({ id, x, y }))),
2535
+ /** Host: when each bot last looked (its reaction clock). */
2536
+ sight: () => (hosting ? [...sight.entries()].map(([slot, e]) => ({ slot, at: e.at })) : null),
2537
+ waves: () => wavesSeen,
2538
+ swings: () => wavesSeen,
2539
+ knocks: () => knocksSeen,
2540
+ zone: () => zone,
2541
+ owned: () => net.owned,
2542
+ cheatResets: () => cheatResets,
2543
+ movement: () => MOVEMENT,
2544
+ controlResets: () => controlResets,
2545
+ predictionError: () => predictionError,
2546
+ /** Where the camera looks (rules metres), how far away it is, its turn, and whose view it is. */
2547
+ camera: () => ({ x: view3.x, y: view3.y, dist: view3.dist, yaw: view3.yaw, view: viewSeat() }),
2548
+ /** The names as drawn (boxes, never the text): the e2e probe counts overlaps and checks your own. */
2549
+ labels: () => shownLabels.map((l) => ({ self: Boolean(l.self), alpha: l.alpha, moved: l.moved, left: Math.round(l.left), top: Math.round(l.top), right: Math.round(l.right), bottom: Math.round(l.bottom) })),
2550
+ /** performance.now() of the first keyed-state value and the first live snapshot this browser received. */
2551
+ arrivals: () => ({ firstStateAt, firstSnapAt }),
2552
+ /** The last frame's draw calls and triangles (renderer.info), against the phone budgets (100 and 150k). */
2553
+ drawCalls: () => renderer.info.render.calls,
2554
+ triangles: () => renderer.info.render.triangles,
2555
+ /** The models: how many loaded, their triangles, texture memory and bytes, and any refused (with why). */
2556
+ models: () => ({ ...models.stats(), standIns: [...standIns], heroes: [...heroes.values()].map((h) => ({ slot: h.slot, hero: h.kind, standIn: !h.char })) }),
2557
+ /** What every hero is doing now (IDLE, WALK, RUN, JUMP, FALL, LAND, ATTACK, CAST, HIT, HOLD), its clips and its pose rate. */
2558
+ heroes: () => [...heroes.values()].map((h) => ({ slot: h.slot, hero: h.kind, state: h.char?.state ?? 'LOADING', verbs: h.char?.verbs ?? [], lod: h.char?.lod ?? null, family: h.char?.family ?? null })),
2559
+ jumps: () => jumpsSeen,
2560
+ dodges: () => dodgesSeen,
2561
+ /** Harness hooks for this screen's own player: jump, swing. */
2562
+ debugJump: () => { jump(); return me.h > 0; },
2563
+ debugSwing: () => { swing(); return true; },
2564
+ /** Harness hook (host only): knock the body of `seat` back, toward the middle of the arena. */
2565
+ debugKnock: (seat: number) => {
2566
+ if (!hosting) return false;
2567
+ const b = [...bodies.values()].find((x) => x.seat === seat);
2568
+ if (!b) return false;
2569
+ knock(b, b.x < W / 2 ? b.x - 0.05 : b.x + 0.05, b.y, -1); // push toward the middle, away from the nearer wall (bumped by nobody)
2570
+ return true;
2571
+ },
2572
+ });
2573
+
2574
+ exposePort(net, {
2575
+ view: 'top',
2576
+ self: () => (me.has && mySeat() !== null ? { x: me.x, y: me.y } : null),
2577
+ size: R_AV,
2578
+ score: () => { const seat = mySeat(); const b = hosting ? [...bodies.values()].find((x) => x.seat === seat) : [...drawn.values()].find((x) => x.seat === seat); return b ? b.score : null; },
2579
+ });
2580
+
2581
+ void net.ready.then(() => {
2582
+ const seat = mySeat();
2583
+ if (seat !== null && hosting) {
2584
+ const b = [...bodies.values()].find((x) => x.seat === seat);
2585
+ if (b) { me.x = b.x; me.y = b.y; me.has = true; }
2586
+ }
2587
+ });
2588
+ requestAnimationFrame(frame);