@vibechain/os 0.4.1 → 0.5.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 (79) hide show
  1. package/AGENTS.md +76 -48
  2. package/README.md +131 -54
  3. package/SECURITY.md +45 -20
  4. package/dist/app-client.d.ts +4 -1
  5. package/dist/app-client.js +4 -1
  6. package/dist/app-host.d.ts +111 -9
  7. package/dist/app-host.js +339 -58
  8. package/dist/app-protocol.d.ts +2 -0
  9. package/dist/app-runtime.d.ts +18 -2
  10. package/dist/app-runtime.js +75 -11
  11. package/dist/app-wire.d.ts +194 -0
  12. package/dist/app-wire.js +253 -0
  13. package/dist/browser.d.ts +2 -0
  14. package/dist/browser.js +2 -0
  15. package/dist/bundle.js +6 -6
  16. package/dist/canvas.d.ts +2 -2
  17. package/dist/canvas.js +3 -1
  18. package/dist/check.d.ts +12 -0
  19. package/dist/check.js +167 -0
  20. package/dist/cli-publish.d.ts +24 -0
  21. package/dist/cli-publish.js +288 -0
  22. package/dist/cli-session.d.ts +108 -0
  23. package/dist/cli-session.js +245 -0
  24. package/dist/cli.d.ts +10 -0
  25. package/dist/cli.js +46 -10
  26. package/dist/index.d.ts +5 -0
  27. package/dist/index.js +3 -0
  28. package/dist/listing.d.ts +3 -3
  29. package/dist/listing.js +1 -1
  30. package/dist/loop.d.ts +18 -2
  31. package/dist/loop.js +13 -1
  32. package/dist/manifest.d.ts +90 -4
  33. package/dist/manifest.js +340 -5
  34. package/dist/os.d.ts +56 -0
  35. package/dist/os.js +354 -0
  36. package/dist/preview-parent.d.ts +36 -0
  37. package/dist/preview-parent.js +122 -11
  38. package/dist/preview-ui.js +1 -1
  39. package/dist/preview.js +25 -7
  40. package/dist/redact.d.ts +6 -0
  41. package/dist/redact.js +16 -0
  42. package/dist/runtime-policy.d.ts +20 -0
  43. package/dist/runtime-policy.js +45 -0
  44. package/dist/scaffold.d.ts +13 -2
  45. package/dist/scaffold.js +95 -31
  46. package/dist/submit-notice.d.ts +26 -0
  47. package/dist/submit-notice.js +34 -0
  48. package/dist/templates/plain/game.js +18 -0
  49. package/dist/testing.d.ts +63 -0
  50. package/dist/testing.js +157 -1
  51. package/dist/transport.d.ts +20 -0
  52. package/dist/transport.js +71 -19
  53. package/dist/vibemarket-os.js +1 -0
  54. package/dist/worker.d.ts +18 -0
  55. package/dist/worker.js +34 -0
  56. package/examples/paw-beat/README.md +20 -8
  57. package/examples/paw-beat/cat.ts +665 -89
  58. package/examples/paw-beat/game.ts +162 -28
  59. package/examples/paw-beat/index.html +114 -40
  60. package/examples/paw-beat/main.ts +264 -149
  61. package/examples/paw-beat/music.ts +314 -65
  62. package/examples/paw-beat/stage.ts +560 -0
  63. package/examples/paw-beat/store/icon.png +0 -0
  64. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  65. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  66. package/examples/paw-beat/vibemarket.json +2 -2
  67. package/examples/vibexp-app/README.md +7 -7
  68. package/examples/vibexp-app/index.html +3 -2
  69. package/examples/vibexp-app/plain/game.ts +20 -0
  70. package/examples/vibexp-app/plain/index.html +6 -0
  71. package/examples/vibexp-app/plain/vibemarket.json +17 -0
  72. package/examples/vibexp-app/src/main.ts +46 -31
  73. package/examples/vibexp-app/store/icon.png +0 -0
  74. package/examples/vibexp-app/three/README.md +21 -0
  75. package/examples/vibexp-app/three/index.html +4 -0
  76. package/examples/vibexp-app/three/src/main.ts +45 -0
  77. package/examples/vibexp-app/three/vibemarket.json +19 -0
  78. package/examples/vibexp-app/vibemarket.json +17 -11
  79. package/package.json +6 -2
@@ -3,165 +3,264 @@ import { connectVibeMarketApp, type AppValue, type VibeMarketAppSdk } from "@vib
3
3
  import { createLoop } from "@vibechain/os/loop";
4
4
  import { fitCanvas } from "@vibechain/os/canvas";
5
5
  import { createCat } from "./cat";
6
- import { BEAT_SECONDS, createGame, LANES, SONG_SECONDS, type DanceGame, type Judgement, type Lane } from "./game";
6
+ import {
7
+ BEAT_SECONDS, COMBO_MILESTONES, comboMultiplier, COUNT_IN_BEATS, createGame, gradeRound, sectionAt, SONG_SECONDS,
8
+ type DanceGame, type Judgement, type Lane, type SectionName,
9
+ } from "./game";
7
10
  import { createMusic } from "./music";
11
+ import { createStage, HIT_Z, type StageFrame } from "./stage";
8
12
 
9
13
  function element<T extends HTMLElement>(id: string): T {
10
14
  const node = document.getElementById(id);
11
15
  if (!node) throw Error(`Missing element: ${id}`);
12
16
  return node as T;
13
17
  }
14
- const canvas = element<HTMLCanvasElement>("scene"), hud = element("hud"), pads = element("pads"), call = element("call");
15
- const intro = element("intro"), done = element("done"), bestLine = element("best");
16
- const startButton = element<HTMLButtonElement>("start"), againButton = element<HTMLButtonElement>("again");
17
- const scoreText = element("score"), comboText = element("combo"), timeText = element("time");
18
-
19
- // ---- Stage layout. Two lanes run past each side of the cat toward the targets. ----
20
- const LANE_X: Readonly<Record<Lane, number>> = { left: -3.1, down: -1.75, up: 1.75, right: 3.1 };
21
- const LANE_COLOR: Readonly<Record<Lane, string>> = { left: "#ff5c8a", down: "#4cc9f0", up: "#ffd166", right: "#7bd88f" };
22
- /** Which way each arrow points when lying on the floor (rotation about the vertical axis). */
23
- const LANE_TURN: Readonly<Record<Lane, number>> = { up: 0, left: Math.PI / 2, down: Math.PI, right: -Math.PI / 2 };
24
- const HIT_Z = 1.6, SPEED = 7.5, LOOKAHEAD = 2.2;
18
+ const canvas = element<HTMLCanvasElement>("scene"), hud = element("hud"), pads = element("pads"), say = element("say");
19
+ const callout = element("callout"), call = element("call"), combo = element("combo"), comboCount = element("combo-count"), comboLabel = element("combo-label");
20
+ const intro = element("intro"), done = element("done"), bestLine = element("best"), lost = element("lost"), lostText = element("lost-text");
21
+ const startButton = element<HTMLButtonElement>("start"), againButton = element<HTMLButtonElement>("again"), resumeButton = element<HTMLButtonElement>("resume");
22
+ const soundButton = element<HTMLButtonElement>("sound"), scoreText = element("score"), multiplierText = element("multiplier");
23
+ const progress = element("progress"), played = element("played");
25
24
 
26
25
  const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: "low-power" });
27
26
  renderer.setPixelRatio(1); // fitCanvas already sizes the backing store in device pixels.
28
- const scene = new THREE.Scene();
29
- scene.background = new THREE.Color("#150f24");
30
- scene.fog = new THREE.Fog("#150f24", 12, 24);
31
- const camera = new THREE.PerspectiveCamera(40, 1, 0.1, 60);
32
- scene.add(new THREE.HemisphereLight("#fff1dc", "#2a1d44", 1.2));
33
- const spot = new THREE.DirectionalLight("#ffe2b8", 1.5);
34
- spot.position.set(2, 6, 5);
35
- scene.add(spot);
36
-
37
- const floor = new THREE.Mesh(new THREE.PlaneGeometry(40, 60), new THREE.MeshStandardMaterial({ color: "#1d1533", roughness: 1 }));
38
- floor.rotation.x = -Math.PI / 2;
39
- floor.position.z = -12;
40
- scene.add(floor);
41
- const stageGlow = new THREE.MeshStandardMaterial({ color: "#3a2a66", emissive: "#8f6bff", emissiveIntensity: 0.2, roughness: 0.8 });
42
- const stage = new THREE.Mesh(new THREE.CylinderGeometry(1.25, 1.35, 0.18, 40), stageGlow);
43
- stage.position.y = 0.09;
44
- scene.add(stage);
45
-
46
- // One flat arrow shape, reused for every note and target.
47
- const arrowShape = new THREE.Shape();
48
- for (const [x, y] of [[0, 0.55], [0.5, 0.02], [0.2, 0.02], [0.2, -0.5], [-0.2, -0.5], [-0.2, 0.02], [-0.5, 0.02]] as const) {
49
- if (x === 0 && y === 0.55) arrowShape.moveTo(x, y);
50
- else arrowShape.lineTo(x, y);
51
- }
52
- const arrowGeometry = new THREE.ExtrudeGeometry(arrowShape, { depth: 0.1, bevelEnabled: false });
53
- arrowGeometry.rotateX(-Math.PI / 2); // lie flat, pointing away from the camera
54
-
55
- const targets = {} as Record<Lane, THREE.MeshStandardMaterial>;
56
- const noteMaterial = {} as Record<Lane, THREE.MeshStandardMaterial>;
57
- for (const lane of LANES) {
58
- const strip = new THREE.Mesh(new THREE.PlaneGeometry(1.15, 30), new THREE.MeshBasicMaterial({ color: LANE_COLOR[lane], transparent: true, opacity: 0.07 }));
59
- strip.rotation.x = -Math.PI / 2;
60
- strip.position.set(LANE_X[lane], 0.01, HIT_Z - 14);
61
- scene.add(strip);
62
- targets[lane] = new THREE.MeshStandardMaterial({ color: "#2b2147", emissive: LANE_COLOR[lane], emissiveIntensity: 0.25, roughness: 0.6, side: THREE.DoubleSide });
63
- const target = new THREE.Mesh(arrowGeometry, targets[lane]);
64
- target.position.set(LANE_X[lane], 0.02, HIT_Z);
65
- target.rotation.y = LANE_TURN[lane];
66
- target.scale.setScalar(1.12);
67
- scene.add(target);
68
- noteMaterial[lane] = new THREE.MeshStandardMaterial({ color: LANE_COLOR[lane], emissive: LANE_COLOR[lane], emissiveIntensity: 0.9, roughness: 0.4, side: THREE.DoubleSide });
69
- }
70
- // A fixed pool is enough: only a couple of seconds of notes are ever on screen.
71
- const pool = Array.from({ length: 28 }, () => {
72
- const mesh = new THREE.Mesh(arrowGeometry, noteMaterial.left);
73
- mesh.scale.setScalar(1.2);
74
- mesh.visible = false;
75
- scene.add(mesh);
76
- return mesh;
77
- });
27
+ const stage = createStage(), cat = createCat();
28
+ stage.scene.add(cat.root);
29
+ const music = createMusic();
30
+ const motion = window.matchMedia("(prefers-reduced-motion: reduce)");
78
31
 
79
- const cat = createCat();
80
- cat.root.position.y = 0.18;
81
- scene.add(cat.root);
32
+ /** How hard the cat grooves and the stage pulses in each part of the song. */
33
+ const ENERGY: Readonly<Record<SectionName, number>> = { "count-in": 0.4, intro: 0.55, build: 0.75, drop: 1, breakdown: 0.45, finale: 1, outro: 0.8 };
82
34
 
83
35
  // ---- Round state ----
84
- interface Saved { best: number; rounds: number }
36
+ interface Saved { best: number; rounds: number; muted: boolean }
85
37
  function parseSaved(value: AppValue): Saved {
86
- if (!value || typeof value !== "object" || Array.isArray(value)) return { best: 0, rounds: 0 };
38
+ if (!value || typeof value !== "object" || Array.isArray(value)) return { best: 0, rounds: 0, muted: false };
87
39
  const count = (input: AppValue | undefined) => (typeof input === "number" && Number.isFinite(input) && input >= 0 ? Math.floor(input) : 0);
88
- return { best: count(value.best), rounds: count(value.rounds) };
40
+ return { best: count(value.best), rounds: count(value.rounds), muted: value.muted === true };
89
41
  }
90
42
 
91
43
  let app: VibeMarketAppSdk | undefined;
92
44
  let game: DanceGame = createGame();
93
- let saved: Saved = { best: 0, rounds: 0 };
94
- let running = false, silentClock = 0, shownScore = -1, shownCombo = -1, shownTime = -1;
95
- const flash: Record<Lane, number> = { left: 0, down: 0, up: 0, right: 0 };
96
- const music = createMusic();
45
+ let saved: Saved = { best: 0, rounds: 0, muted: false };
46
+ type Phase = "title" | "playing" | "results";
47
+ let phase: Phase = "title", paused = false, contextLost = false;
48
+ let songTime = 0, idleClock = 0, lastMilestone = 0, reported = false, reportTimer: number | undefined;
49
+ let shownScore = -1, shownCombo = -1, shownMultiplier = -1, shownProgress = -1, shownCount = -1, shownX = -1, shownY = -1;
50
+ const catHead = new THREE.Vector3(), anchor = new THREE.Vector3(0, 0.05, HIT_Z + 0.35), screen = new THREE.Vector2();
51
+ /** What the stage reads each frame; one object, rewritten in place. */
52
+ const frame: StageFrame = { beat: 0, section: "intro", energy: 0.35, reducedMotion: false, catHead, catLift: 0 };
53
+ let pendingScore = 0, viewWidth = 0, viewHeight = 0;
97
54
 
98
- function announce(kind: Judgement) {
55
+ function save() {
56
+ // A failed write only loses the personal best and the sound setting; the game goes on.
57
+ void app?.checkpoint.write({ best: saved.best, rounds: saved.rounds, muted: saved.muted }).catch(() => {});
58
+ }
59
+
60
+ // ---- Feedback ----
61
+ const WORDS: Readonly<Record<Judgement, string>> = { perfect: "Perfect!", great: "Great", good: "Good", miss: "Miss" };
62
+ function pop(target: HTMLElement, big: boolean) {
63
+ // The Web Animations API restarts cleanly without forcing a layout.
64
+ const scale = motion.matches ? 1 : big ? 1.35 : 1.15;
65
+ target.animate([{ opacity: 1, transform: `scale(${scale})` }, { opacity: 1, transform: "scale(1)", offset: 0.25 }, { opacity: 0, transform: "scale(1)" }], { duration: 650, easing: "ease-out" });
66
+ }
67
+ function judge(kind: Judgement, streak: number) {
99
68
  call.dataset.kind = kind;
100
- call.textContent = kind === "miss" ? "Miss" : kind === "perfect" ? "Perfect!" : kind === "great" ? "Great" : "Good";
101
- call.classList.remove("show");
102
- void call.offsetWidth; // restart the CSS animation
103
- call.classList.add("show");
69
+ call.textContent = WORDS[kind];
70
+ pop(call, kind === "perfect");
71
+ // Assistive tech hears the same thing, politely: the word, then the run of steps.
72
+ say.textContent = streak >= 2 ? `${WORDS[kind]} ${streak} combo` : WORDS[kind];
73
+ }
74
+ function showCombo(count: number) {
75
+ if (count === shownCombo) return;
76
+ shownCombo = count;
77
+ combo.hidden = count < 3;
78
+ comboCount.textContent = String(count);
79
+ const milestone = COMBO_MILESTONES.includes(count);
80
+ combo.classList.toggle("milestone", count >= COMBO_MILESTONES[0]!);
81
+ comboLabel.textContent = milestone ? `${count} IN A ROW!` : "COMBO";
82
+ if (milestone && count > lastMilestone) {
83
+ lastMilestone = count;
84
+ combo.animate([{ transform: motion.matches ? "none" : "scale(1.6)" }, { transform: "scale(1)" }], { duration: 500, easing: "ease-out" });
85
+ cat.celebrate();
86
+ stage.confetti();
87
+ say.textContent = `${count} in a row!`;
88
+ }
89
+ }
90
+
91
+ /**
92
+ * The song position. While the audio clock runs it is the truth; without audio (or if the device
93
+ * stalls) the loop's own steps carry on. It never goes backwards, so the two cannot fight.
94
+ */
95
+ function tickClock(seconds: number) {
96
+ const audio = music.time();
97
+ songTime = audio !== null ? Math.max(songTime, audio) : songTime + seconds;
98
+ }
99
+ /** Notes that scrolled past unhit become misses: a stumble, a greyed note and the word. */
100
+ function catchUp() {
101
+ const missed = game.advance(songTime);
102
+ if (missed.length === 0) return;
103
+ for (const note of missed) stage.miss(note.lane);
104
+ cat.stumble();
105
+ judge("miss", 0);
106
+ drawScore();
104
107
  }
105
108
 
106
109
  function press(lane: Lane) {
107
- if (!running) return;
108
- flash[lane] = 1;
110
+ pads.querySelector(`[data-lane="${lane}"]`)?.classList.add("down");
111
+ if (phase !== "playing" || paused) return;
112
+ // Judge against the clock at the moment of the press, not the last frame, which on a slow
113
+ // machine can be tens of milliseconds stale.
114
+ tickClock(0);
115
+ catchUp();
116
+ stage.press(lane);
109
117
  const hit = game.press(lane);
110
118
  if (!hit?.judged) return; // a stray press costs nothing
111
- cat.dance(lane);
112
- announce(hit.judged);
119
+ cat.dance(lane, hit.judged);
120
+ stage.hit(lane, hit.judged);
121
+ drawScore();
122
+ judge(hit.judged, shownCombo);
123
+ }
124
+ function release(lane: Lane) {
125
+ pads.querySelector(`[data-lane="${lane}"]`)?.classList.remove("down");
126
+ }
127
+
128
+ function setSound(on: boolean) {
129
+ saved.muted = !on;
130
+ music.setMuted(!on);
131
+ soundButton.setAttribute("aria-pressed", String(on));
132
+ soundButton.textContent = on ? "♪ Sound on" : "♪ Sound off";
113
133
  }
114
134
 
135
+ // ---- Flow: title, count-in and song, results ----
115
136
  function begin() {
137
+ report(); // a previous round's score goes to the host before the next starts
116
138
  const seed = saved.rounds + 1;
117
139
  game = createGame(seed);
118
- silentClock = 0;
140
+ songTime = 0;
141
+ lastMilestone = 0;
142
+ shownCount = -1;
119
143
  music.start(seed);
120
- running = true;
144
+ music.setMuted(saved.muted);
145
+ phase = "playing";
121
146
  intro.hidden = done.hidden = true;
122
147
  hud.hidden = pads.hidden = false;
148
+ layout();
149
+ cat.setMood("neutral");
150
+ stage.frame("play", motion.matches);
151
+ drawScore();
152
+ say.textContent = "Get ready.";
123
153
  canvas.focus();
124
154
  }
125
155
 
126
156
  function end() {
127
- running = false;
157
+ phase = "results";
128
158
  music.stop();
129
- const { score, bestCombo, counts } = game.state;
130
- saved = { best: Math.max(saved.best, score), rounds: saved.rounds + 1 };
131
- // A failed write only loses the personal best; the result still goes to the host.
132
- void app?.checkpoint.write({ best: saved.best, rounds: saved.rounds }).catch(() => {});
133
- hud.hidden = pads.hidden = true;
134
- element("done-score").textContent = String(score);
135
- element("done-note").textContent = `${counts.perfect} perfect · ${counts.great} great · ${counts.good} good · ${counts.miss} missed. Best run of steps: ${bestCombo}.`;
159
+ stage.hideNotes();
160
+ const { score, bestCombo, counts } = game.state, result = gradeRound(counts);
161
+ const newBest = score > saved.best && score > 0;
162
+ saved = { ...saved, best: Math.max(saved.best, score), rounds: saved.rounds + 1 };
163
+ save();
164
+ hud.hidden = pads.hidden = combo.hidden = true;
165
+ call.textContent = "";
166
+ element("grade").textContent = result.grade;
167
+ element("done-score").textContent = score.toLocaleString("en-US");
168
+ element("new-best").hidden = !newBest;
169
+ element("accuracy").textContent = `${result.accuracy.toFixed(1)}%`;
170
+ element("done-combo").textContent = String(bestCombo);
171
+ element("full-combo").hidden = !result.fullCombo;
172
+ for (const kind of ["perfect", "great", "good", "miss"] as const) element(`done-${kind}`).textContent = String(counts[kind]);
173
+ element("sent").textContent = "Your score goes to VibeMarket OS in a moment.";
136
174
  done.hidden = false;
137
- // The host owns the results screen and normally replaces this frame. If it declines
138
- // (it accepts one score per open window), the card above stays as the result.
139
- void app?.game.finish({ score }).catch(() => {});
175
+ stage.frame("title", motion.matches);
176
+ cat.setMood(result.grade === "S" || result.grade === "A" || result.grade === "B" ? "happy" : result.grade === "D" ? "sad" : "neutral");
177
+ if (result.grade === "S" || result.grade === "A") { cat.celebrate(); stage.confetti(); }
178
+ say.textContent = `Song over. Grade ${result.grade}, ${score} points, ${result.accuracy.toFixed(1)} percent accuracy.${newBest ? " New best!" : ""}`;
179
+ againButton.focus();
180
+ // The host owns the final results screen and may replace this frame once it has the score, so
181
+ // the card above gets a few seconds first. If the host declines (it accepts one score per open
182
+ // window), the card simply stays as the result.
183
+ reported = false;
184
+ reportTimer = window.setTimeout(report, 4000);
185
+ pendingScore = score;
186
+ }
187
+ function report() {
188
+ window.clearTimeout(reportTimer);
189
+ if (reported || phase !== "results") return;
190
+ reported = true;
191
+ app?.game.finish({ score: pendingScore }).then(
192
+ () => { element("sent").textContent = "Score sent to VibeMarket OS."; },
193
+ () => { element("sent").textContent = "VibeMarket OS keeps one score per open window, so this one stays here."; },
194
+ );
140
195
  }
141
196
 
142
- // ---- Input: arrow keys, WASD, or the on-screen pads. ----
197
+ // ---- Input: arrow keys, WASD, or the on-screen pads. M toggles sound. ----
143
198
  const KEY_LANE: Readonly<Record<string, Lane>> = {
144
199
  ArrowLeft: "left", ArrowDown: "down", ArrowUp: "up", ArrowRight: "right", KeyA: "left", KeyS: "down", KeyW: "up", KeyD: "right",
145
200
  };
146
201
  window.addEventListener("keydown", event => {
202
+ if (event.code === "KeyM" && !event.repeat) { setSound(saved.muted); save(); return; }
147
203
  const lane = KEY_LANE[event.code];
148
204
  if (!lane) return;
149
205
  event.preventDefault(); // arrow keys must not scroll the frame
150
206
  if (!event.repeat) press(lane);
151
207
  });
208
+ window.addEventListener("keyup", event => {
209
+ const lane = KEY_LANE[event.code];
210
+ if (lane) release(lane);
211
+ });
152
212
  for (const pad of Array.from(pads.querySelectorAll<HTMLButtonElement>("button[data-lane]"))) {
153
213
  const lane = pad.dataset.lane as Lane;
154
- pad.addEventListener("pointerdown", event => {
155
- event.preventDefault();
156
- press(lane);
157
- });
214
+ pad.addEventListener("pointerdown", event => { event.preventDefault(); press(lane); });
215
+ for (const type of ["pointerup", "pointercancel", "pointerleave"]) pad.addEventListener(type, () => release(lane));
216
+ // Enter or Space on a focused pad arrives as a click with no pointer (detail 0).
217
+ pad.addEventListener("click", event => { if (event.detail === 0) { press(lane); release(lane); } });
218
+ }
219
+ soundButton.addEventListener("click", () => { setSound(saved.muted); save(); });
220
+
221
+ // ---- HUD: touch the DOM only when a value actually changed ----
222
+ /** Score, multiplier and combo change only on a hit or a miss, so this runs on those events, not every frame. */
223
+ function drawScore() {
224
+ const state = game.state;
225
+ if (state.score !== shownScore) scoreText.textContent = (shownScore = state.score).toLocaleString("en-US");
226
+ const multiplier = comboMultiplier(state.combo);
227
+ if (multiplier !== shownMultiplier) {
228
+ shownMultiplier = multiplier;
229
+ multiplierText.hidden = multiplier <= 1;
230
+ multiplierText.textContent = `×${multiplier.toFixed(1)}`;
231
+ }
232
+ showCombo(state.combo);
233
+ }
234
+ function drawHud(now: number) {
235
+ const percent = Math.max(0, Math.min(100, Math.floor((now / SONG_SECONDS) * 100)));
236
+ if (percent !== shownProgress) {
237
+ shownProgress = percent;
238
+ played.style.width = `${percent}%`;
239
+ progress.setAttribute("aria-valuenow", String(percent));
240
+ }
241
+ // Count-in: 3, 2, 1, Go! on the four clicks.
242
+ const count = now < COUNT_IN_BEATS * BEAT_SECONDS ? Math.max(0, Math.floor(now / BEAT_SECONDS)) : 4;
243
+ if (count !== shownCount && count < 4) {
244
+ call.dataset.kind = "count";
245
+ call.textContent = ["3", "2", "1", "Go!"][count]!;
246
+ pop(call, true);
247
+ }
248
+ shownCount = count;
249
+ }
250
+
251
+ /** The stage needs to know how much of the bottom the pads cover, so the targets stay above them. */
252
+ function layout() {
253
+ if (viewWidth > 0) stage.resize(viewWidth, viewHeight, pads.hidden ? 0 : pads.offsetHeight);
158
254
  }
159
255
 
160
- function drawHud(score: number, combo: number, secondsLeft: number) {
161
- // Touch the DOM only when a number actually changed.
162
- if (score !== shownScore) scoreText.textContent = String((shownScore = score));
163
- if (combo !== shownCombo) comboText.textContent = String((shownCombo = combo));
164
- if (secondsLeft !== shownTime) timeText.textContent = String((shownTime = secondsLeft));
256
+ /** Keep the judgement and combo in the gap in front of the cat, between the inner targets: never over its face. */
257
+ function placeCallout() {
258
+ stage.project(anchor, screen);
259
+ const x = Math.round(screen.x), y = Math.round(Math.min(screen.y, window.innerHeight - 4));
260
+ if (x === shownX && y === shownY) return;
261
+ shownX = x;
262
+ shownY = y;
263
+ callout.style.transform = `translate(${x}px, ${y}px) translate(-50%, -100%)`;
165
264
  }
166
265
 
167
266
  // ---- Boot: connect, restore, then let the host know the first frame is up. ----
@@ -174,70 +273,86 @@ async function boot() {
174
273
  }
175
274
  const host = app;
176
275
  fitCanvas(host, canvas, {
177
- onResize({ width, height }) {
276
+ // 1.5 device pixels per CSS pixel is still sharp with antialiasing, and on a high-density screen it
277
+ // shades about half the pixels of 2, which keeps modest integrated graphics at 60 fps in big windows.
278
+ maxPixelRatio: 1.5,
279
+ onResize({ width, height, pixelRatio }) {
178
280
  renderer.setSize(width, height, false);
179
- camera.aspect = width / height;
180
- // Pull back on tall, narrow windows so all four lanes stay in frame.
181
- const pull = Math.max(1, 1.25 / camera.aspect);
182
- camera.position.set(0, 5.4 * pull, 10.5 * pull);
183
- camera.lookAt(0, 0.9, -1.5);
184
- camera.updateProjectionMatrix();
281
+ viewWidth = width / pixelRatio;
282
+ viewHeight = height / pixelRatio;
283
+ layout();
284
+ },
285
+ onContextLost() {
286
+ // GPU resources are gone. Pause the song with the game so nothing is judged blind.
287
+ contextLost = paused = true;
288
+ music.setActive(false);
289
+ lostText.textContent = "The graphics stopped. Waiting for them to come back…";
290
+ resumeButton.hidden = true;
291
+ lost.hidden = false;
185
292
  },
186
- onContextLost: () => { running = false; },
293
+ onContextRestored() {
294
+ // Three.js re-uploads geometry and shaders on its own; the player picks up when ready.
295
+ contextLost = false;
296
+ lostText.textContent = "The graphics are back.";
297
+ resumeButton.hidden = false;
298
+ resumeButton.focus();
299
+ },
300
+ });
301
+ resumeButton.addEventListener("click", () => {
302
+ lost.hidden = true;
303
+ paused = false;
304
+ if (host.lifecycle.current().active) music.setActive(true);
305
+ canvas.focus();
187
306
  });
188
307
  createLoop(host, {
189
308
  update(stepMs) {
190
309
  const seconds = stepMs / 1000;
191
- silentClock += running ? seconds : 0;
192
- // The audio clock is the truth while there is sound; otherwise the loop keeps time.
193
- const now = running ? music.time() ?? silentClock : 0;
194
- if (running) {
310
+ if (paused) return;
311
+ idleClock += seconds;
312
+ let beat = idleClock * 0.9, section: SectionName = "intro", energy = 0.35;
313
+ if (phase === "playing") {
314
+ tickClock(seconds);
315
+ const now = songTime;
195
316
  music.pump();
196
- if (game.advance(now).length > 0) {
197
- cat.stumble();
198
- announce("miss");
199
- }
200
- const state = game.state;
201
- drawHud(state.score, state.combo, Math.max(0, Math.ceil(SONG_SECONDS - state.time)));
202
- if (state.finished) end();
203
- }
204
- const beatPhase = ((now / BEAT_SECONDS) % 1 + 1) % 1, pulse = Math.pow(1 - beatPhase, 3);
205
- cat.animate(seconds, beatPhase);
206
- stageGlow.emissiveIntensity = 0.2 + pulse * 0.7;
207
- for (const lane of LANES) {
208
- flash[lane] = Math.max(0, flash[lane] - seconds * 5);
209
- targets[lane].emissiveIntensity = 0.25 + pulse * 0.2 + flash[lane] * 1.4;
210
- }
211
- // Lay out the notes that are on screen right now.
212
- let used = 0;
213
- if (running) {
214
- game.each(now - 0.35, now + LOOKAHEAD, (note, judged) => {
215
- // A step that was hit disappears; a missed one slides on past the target.
216
- const mesh = judged && judged !== "miss" ? undefined : pool[used];
217
- if (!mesh) return;
218
- used += 1;
219
- mesh.material = noteMaterial[note.lane];
220
- mesh.position.set(LANE_X[note.lane], 0.06, HIT_Z - (note.time - now) * SPEED);
221
- mesh.rotation.y = LANE_TURN[note.lane];
222
- mesh.visible = true;
223
- });
317
+ catchUp();
318
+ drawHud(now);
319
+ beat = now / BEAT_SECONDS;
320
+ section = sectionAt(Math.max(0, beat)).name;
321
+ energy = ENERGY[section];
322
+ stage.notes(now, game.each);
323
+ if (now >= SONG_SECONDS) end();
324
+ } else if (phase === "results") {
325
+ energy = 0.5;
326
+ section = "outro";
224
327
  }
225
- for (let index = used; index < pool.length; index++) pool[index]!.visible = false;
328
+ cat.animate(seconds, beat, energy);
329
+ cat.head.getWorldPosition(catHead);
330
+ frame.beat = beat;
331
+ frame.section = section;
332
+ frame.energy = energy;
333
+ frame.reducedMotion = motion.matches;
334
+ frame.catLift = cat.lift();
335
+ stage.update(seconds, frame);
336
+ cat.setRim(stage.accent);
337
+ placeCallout();
226
338
  },
227
339
  render() {
228
- renderer.render(scene, camera);
340
+ if (!contextLost) renderer.render(stage.scene, stage.camera);
229
341
  },
230
342
  });
231
- host.lifecycle.onChanged(state => music.setActive(state.active));
343
+ host.lifecycle.onChanged(state => { if (!paused) music.setActive(state.active); });
232
344
 
233
345
  saved = parseSaved(await host.checkpoint.read().catch(() => null));
234
- bestLine.textContent = saved.rounds > 0 ? `Best: ${saved.best} over ${saved.rounds} song${saved.rounds === 1 ? "" : "s"}.` : "One song is about a minute.";
346
+ setSound(!saved.muted);
347
+ bestLine.textContent = saved.rounds > 0 ? `Best: ${saved.best.toLocaleString("en-US")} over ${saved.rounds} song${saved.rounds === 1 ? "" : "s"}.` : "One song, about a minute.";
348
+ stage.frame("title", true);
235
349
  startButton.textContent = "Start dancing";
236
350
  startButton.disabled = false;
237
351
  startButton.addEventListener("click", begin);
238
352
  againButton.addEventListener("click", begin);
239
353
  await host.ready();
240
- window.addEventListener("pagehide", () => { music.dispose(); cat.dispose(); host.destroy(); }, { once: true });
354
+ startButton.focus();
355
+ window.addEventListener("pagehide", () => { report(); music.dispose(); cat.dispose(); stage.dispose(); renderer.dispose(); host.destroy(); }, { once: true });
241
356
  }
242
357
  canvas.tabIndex = 0;
243
358
  void boot();