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