@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
@@ -1,10 +1,14 @@
1
- import { BEAT_SECONDS, COUNT_IN_BEATS, SONG_BEATS } from "./game";
1
+ import { BEAT_SECONDS, BEATS_PER_BAR, COUNT_IN_BEATS, createTune, sectionAt, SONG_BEATS, type TuneNote } from "./game";
2
2
 
3
3
  /**
4
- * The song, synthesized with Web Audio. Nothing is downloaded or sampled: a kick, a
5
- * clap, a hat, a bass line and a lead are built from oscillators and noise, scheduled a
6
- * little ahead of the audio clock. That same clock times the steps, so what you hear
7
- * and what you hit stay together.
4
+ * The song, synthesized with Web Audio. Nothing is downloaded or sampled: every drum, the
5
+ * bass, the pads and the lead are oscillators and noise shaped by filters and envelopes,
6
+ * scheduled a little ahead of the audio clock. That same clock times the steps, so what you
7
+ * hear and what you hit stay together.
8
+ *
9
+ * The arrangement follows the sections in game.ts: a count-in, a gentle intro that hints at
10
+ * the tune, a build with a rising arpeggio and snare roll, a drop that carries the tune, a
11
+ * breakdown on pads and bell, a fuller finale and a cadence that comes home to A minor.
8
12
  */
9
13
  export interface Music {
10
14
  /** Start the song from the top. Call from a user gesture. */
@@ -15,101 +19,345 @@ export interface Music {
15
19
  pump(): void;
16
20
  /** Pause or resume with the app's lifecycle. */
17
21
  setActive(active: boolean): void;
22
+ /** Silence the output without stopping the clock. */
23
+ setMuted(muted: boolean): void;
18
24
  stop(): void;
19
25
  dispose(): void;
20
26
  }
21
27
 
22
- // A minor, F, C, G: one chord per four-beat bar. Bass roots in Hz.
23
- const ROOTS = [55, 43.65, 65.41, 49];
24
- // A minor pentatonic across two octaves, for the lead.
25
- const SCALE = [220, 261.63, 293.66, 329.63, 392, 440, 523.25, 587.33, 659.25];
26
- const LOOKAHEAD = 0.4;
28
+ /** Equal temperament from A4 = 440 Hz. */
29
+ const hz = (semitonesFromA4: number) => 440 * Math.pow(2, semitonesFromA4 / 12);
30
+ /** A natural minor, as semitones above A, for the tune's scale degrees. */
31
+ const MINOR = [0, 2, 3, 5, 7, 8, 10];
32
+ const degreeHz = (degree: number) => hz(MINOR[((degree % 7) + 7) % 7]! + 12 * Math.floor(degree / 7));
27
33
 
28
- export function createMusic(): Music {
29
- let context: AudioContext | undefined, master: GainNode | undefined, noise: AudioBuffer | undefined;
30
- let startAt = 0, nextBeat = 0, playing = false, melody: number[] = [];
34
+ interface Chord { readonly bass: number; readonly pad: readonly number[]; readonly arp: readonly number[] }
35
+ // A minor, F, C, G: one chord per bar. Pad voicings stay close together around middle C.
36
+ const AM: Chord = { bass: hz(-36), pad: [hz(-12), hz(-9), hz(-5)], arp: [hz(-12), hz(-9), hz(-5), hz(0)] };
37
+ const F: Chord = { bass: hz(-40), pad: [hz(-16), hz(-12), hz(-9)], arp: [hz(-16), hz(-12), hz(-9), hz(-4)] };
38
+ const C: Chord = { bass: hz(-33), pad: [hz(-14), hz(-9), hz(-5)], arp: [hz(-9), hz(-5), hz(-2), hz(3)] };
39
+ const G: Chord = { bass: hz(-38), pad: [hz(-14), hz(-10), hz(-7)], arp: [hz(-14), hz(-10), hz(-7), hz(-2)] };
40
+ const PROGRESSION = [AM, F, C, G];
41
+
42
+ /** The chord under `beat`: the progression restarts with each section; the outro is G then home to A minor. */
43
+ function chordAt(beat: number): Chord {
44
+ const section = sectionAt(beat), bar = Math.floor((beat - section.start) / BEATS_PER_BAR);
45
+ if (section.name === "outro") return bar === 0 ? G : AM;
46
+ return PROGRESSION[bar % PROGRESSION.length]!;
47
+ }
48
+
49
+ export interface Synth {
50
+ /** The mixed, limited output. Connect it to a destination. */
51
+ readonly output: AudioNode;
52
+ /** Schedule everything that starts during song beat `index`, which begins at context time `at`. */
53
+ beat(index: number, at: number): void;
54
+ }
31
55
 
32
- const tone = (type: OscillatorType, from: number, to: number, at: number, length: number, volume: number) => {
33
- if (!context || !master) return;
34
- const voice = context.createOscillator(), envelope = context.createGain();
56
+ /**
57
+ * The instruments and the arrangement, for any audio context. The game drives it live; it
58
+ * also renders the whole song into an OfflineAudioContext for checking levels and timing.
59
+ */
60
+ export function createSynth(context: BaseAudioContext, seed: number): Synth {
61
+ // ---- Mixing: drums and music meet on one bus with conservative gains, then a soft limiter. ----
62
+ // The limiter is a wave shaper: straight through below 0.6, bending smoothly toward 0.88 above,
63
+ // and a wave shaper holds inputs past full scale at its last value, so no sample can clip.
64
+ // (A DynamicsCompressorNode would also work, but it delays everything by a fixed 6 ms look-ahead,
65
+ // which would put the music behind the clock that judges the steps.)
66
+ const bus = context.createGain(), clipper = context.createWaveShaper();
67
+ bus.gain.value = 0.52;
68
+ const curve = new Float32Array(2049);
69
+ for (let i = 0; i < curve.length; i++) {
70
+ const x = i / 1024 - 1, size = Math.abs(x);
71
+ curve[i] = Math.sign(x) * (size < 0.6 ? size : 0.6 + 0.35 * Math.tanh((size - 0.6) / 0.35));
72
+ }
73
+ clipper.curve = curve;
74
+ bus.connect(clipper);
75
+ const drums = context.createGain(), music = context.createGain();
76
+ drums.connect(bus);
77
+ // Everything but the drums ducks a little on each kick, which makes the groove pump.
78
+ music.connect(bus);
79
+
80
+ // One second of seeded white noise for the drums and risers.
81
+ const noise = context.createBuffer(1, context.sampleRate, context.sampleRate), samples = noise.getChannelData(0);
82
+ let state = 0x9e3779b9;
83
+ for (let i = 0; i < samples.length; i++) {
84
+ state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
85
+ samples[i] = state / 2147483648 - 1;
86
+ }
87
+
88
+ // ---- Building blocks ----
89
+ /** A gain envelope: quick attack to `peak`, hold, then an exponential fall to silence by `end`. */
90
+ const envelope = (at: number, peak: number, attack: number, holdUntil: number, end: number, to: AudioNode) => {
91
+ const gain = context.createGain();
92
+ gain.gain.setValueAtTime(0, at);
93
+ gain.gain.linearRampToValueAtTime(peak, at + attack);
94
+ gain.gain.setValueAtTime(peak, Math.max(at + attack, holdUntil));
95
+ gain.gain.exponentialRampToValueAtTime(0.0001, end);
96
+ gain.connect(to);
97
+ return gain;
98
+ };
99
+ const oscillator = (type: OscillatorType, frequency: number, at: number, end: number, to: AudioNode, detune = 0) => {
100
+ const voice = context.createOscillator();
35
101
  voice.type = type;
36
- voice.frequency.setValueAtTime(from, at);
37
- if (to !== from) voice.frequency.exponentialRampToValueAtTime(to, at + length);
38
- envelope.gain.setValueAtTime(volume, at);
39
- envelope.gain.exponentialRampToValueAtTime(0.0001, at + length);
40
- voice.connect(envelope).connect(master);
102
+ voice.frequency.setValueAtTime(frequency, at);
103
+ voice.detune.value = detune;
104
+ voice.connect(to);
41
105
  voice.start(at);
42
- voice.stop(at + length + 0.02);
106
+ voice.stop(end + 0.02);
107
+ return voice;
43
108
  };
44
- const hiss = (filter: BiquadFilterType, frequency: number, at: number, length: number, volume: number) => {
45
- if (!context || !master || !noise) return;
46
- const source = context.createBufferSource(), shape = context.createBiquadFilter(), envelope = context.createGain();
47
- source.buffer = noise;
48
- shape.type = filter;
109
+ const filter = (type: BiquadFilterType, frequency: number, q: number, to: AudioNode) => {
110
+ const shape = context.createBiquadFilter();
111
+ shape.type = type;
49
112
  shape.frequency.value = frequency;
50
- envelope.gain.setValueAtTime(volume, at);
51
- envelope.gain.exponentialRampToValueAtTime(0.0001, at + length);
52
- source.connect(shape).connect(envelope).connect(master);
53
- source.start(at);
113
+ shape.Q.value = q;
114
+ shape.connect(to);
115
+ return shape;
116
+ };
117
+ const hiss = (at: number, length: number, to: AudioNode) => {
118
+ const source = context.createBufferSource();
119
+ source.buffer = noise;
120
+ source.loop = true;
121
+ source.connect(to);
122
+ source.start(at, (at * 7.31) % 0.9);
54
123
  source.stop(at + length + 0.02);
55
124
  };
56
125
 
57
- const beat = (index: number) => {
58
- const at = startAt + index * BEAT_SECONDS, half = at + BEAT_SECONDS / 2;
59
- if (index < COUNT_IN_BEATS) {
60
- tone("square", 1320, 1320, at, 0.05, 0.12); // count-in tick
61
- return;
126
+ // ---- Drums ----
127
+ const kick = (at: number, level: number) => {
128
+ const body = envelope(at, level, 0.002, at + 0.02, at + 0.38, drums);
129
+ oscillator("sine", 155, at, at + 0.38, body).frequency.exponentialRampToValueAtTime(46, at + 0.13);
130
+ hiss(at, 0.012, filter("highpass", 2500, 0.7, envelope(at, level * 0.22, 0.001, at, at + 0.012, drums)));
131
+ // The duck: the music dips under the kick and swells back before the off-beat.
132
+ music.gain.setValueAtTime(0.5, at);
133
+ music.gain.linearRampToValueAtTime(1, at + 0.22);
134
+ };
135
+ const snare = (at: number, level: number) => {
136
+ hiss(at, 0.2, filter("bandpass", 1800, 0.9, envelope(at, level, 0.002, at, at + 0.2, drums)));
137
+ oscillator("triangle", 190, at, at + 0.1, envelope(at, level * 0.6, 0.002, at, at + 0.1, drums));
138
+ };
139
+ const clap = (at: number, level: number) => {
140
+ // Three quick bursts and a tail, like hands that do not quite agree.
141
+ for (const [offset, length] of [[0, 0.02], [0.012, 0.02], [0.024, 0.16]] as const) {
142
+ hiss(at + offset, length, filter("bandpass", 1300, 1.4, envelope(at + offset, level, 0.001, at + offset, at + offset + length, drums)));
143
+ }
144
+ };
145
+ const hat = (at: number, open: boolean, level: number) => {
146
+ const length = open ? 0.22 : 0.045;
147
+ hiss(at, length, filter("highpass", 7500, 0.8, envelope(at, level, 0.001, at, at + length, drums)));
148
+ };
149
+ const crash = (at: number, level: number) => hiss(at, 1.6, filter("highpass", 4200, 0.5, envelope(at, level, 0.003, at, at + 1.6, drums)));
150
+ /** Filtered noise sweeping up into the next section. */
151
+ const riser = (at: number, length: number, level: number) => {
152
+ const sweep = filter("bandpass", 300, 2, envelope(at, level, length * 0.9, at + length * 0.95, at + length, drums));
153
+ sweep.frequency.exponentialRampToValueAtTime(7000, at + length);
154
+ hiss(at, length, sweep);
155
+ };
156
+ const tick = (at: number, accent: boolean) => {
157
+ oscillator("sine", accent ? 1760 : 1320, at, at + 0.07, envelope(at, 0.5, 0.001, at, at + 0.07, drums));
158
+ oscillator("triangle", accent ? 880 : 660, at, at + 0.05, envelope(at, 0.25, 0.001, at, at + 0.05, drums));
159
+ };
160
+
161
+ // ---- Pitched instruments ----
162
+ /** A saw bass through a resonant low-pass whose cutoff snaps shut, for a round, plucky note. */
163
+ const bass = (at: number, frequency: number, length: number, level: number, bright: number) => {
164
+ const end = at + length;
165
+ const tone = filter("lowpass", 180 + bright * 1400, 5, envelope(at, level, 0.004, at + length * 0.6, end, music));
166
+ tone.frequency.setTargetAtTime(160 + bright * 200, at + 0.01, 0.06);
167
+ oscillator("sawtooth", frequency, at, end, tone);
168
+ oscillator("sine", frequency, at, end, envelope(at, level * 0.8, 0.004, at + length * 0.6, end, music));
169
+ };
170
+ /** Three chord tones, each two detuned saws, softened by a low-pass: a warm bed. */
171
+ const pad = (at: number, chord: Chord, length: number, level: number, cutoff: number) => {
172
+ const end = at + length, warm = filter("lowpass", cutoff, 0.7, envelope(at, level, 0.35, end - 0.4, end, music));
173
+ for (const frequency of chord.pad) {
174
+ oscillator("sawtooth", frequency, at, end, warm, -8);
175
+ oscillator("sawtooth", frequency, at, end, warm, 8);
62
176
  }
63
- const inBar = index % 4, root = ROOTS[Math.floor(index / 4) % ROOTS.length] ?? 55;
64
- tone("sine", 150, 45, at, 0.14, 0.7); // kick
65
- if (inBar === 1 || inBar === 3) hiss("bandpass", 1800, at, 0.12, 0.35); // clap
66
- hiss("highpass", 7000, half, 0.04, 0.16); // off-beat hat
67
- tone("triangle", root, root, at, 0.2, 0.4); // bass
68
- tone("triangle", root * 2, root * 2, half, 0.14, 0.26);
69
- // Two lead notes per beat; a zero in the pattern is a rest.
70
- for (const [slot, when] of [[index * 2, at], [index * 2 + 1, half]] as const) {
71
- const pitch = melody[slot % melody.length] ?? 0;
72
- if (pitch > 0) tone("square", pitch, pitch, when, 0.16, 0.07);
177
+ };
178
+ /** The lead: square and saw an octave apart, with a little vibrato on longer notes. */
179
+ const lead = (at: number, frequency: number, length: number, level: number) => {
180
+ const end = at + length, tone = filter("lowpass", 2600, 1.5, envelope(at, level, 0.008, end - 0.06, end + 0.08, music));
181
+ const square = oscillator("square", frequency, at, end + 0.08, tone), saw = oscillator("sawtooth", frequency / 2, at, end + 0.08, tone, 4);
182
+ if (length >= BEAT_SECONDS) {
183
+ const wobble = context.createOscillator(), depth = context.createGain();
184
+ wobble.frequency.value = 5.5;
185
+ depth.gain.setValueAtTime(0, at);
186
+ depth.gain.linearRampToValueAtTime(14, at + 0.35);
187
+ wobble.connect(depth);
188
+ depth.connect(square.detune);
189
+ depth.connect(saw.detune);
190
+ wobble.start(at);
191
+ wobble.stop(end + 0.1);
192
+ }
193
+ };
194
+ const pluck = (at: number, frequency: number, level: number, brightness: number) => {
195
+ const tone = filter("lowpass", 900 + brightness * 3000, 2, envelope(at, level, 0.003, at, at + 0.3, music));
196
+ oscillator("triangle", frequency, at, at + 0.3, tone);
197
+ oscillator("square", frequency, at, at + 0.3, envelope(at, level * 0.25, 0.003, at, at + 0.12, tone));
198
+ };
199
+ /** A soft bell: a sine and an inharmonic partial that dies sooner. */
200
+ const bell = (at: number, frequency: number, length: number, level: number) => {
201
+ oscillator("sine", frequency, at, at + length + 0.8, envelope(at, level, 0.004, at, at + length + 0.8, music));
202
+ oscillator("sine", frequency * 2.76, at, at + 0.5, envelope(at, level * 0.35, 0.002, at, at + 0.5, music));
203
+ };
204
+
205
+ // ---- The arrangement ----
206
+ const tune: TuneNote[][] = Array.from({ length: SONG_BEATS }, () => []);
207
+ for (const note of createTune(seed)) tune[Math.floor(note.beat)]?.push(note);
208
+ const playTune = (index: number, at: number, harmony: boolean) => {
209
+ for (const note of tune[index] ?? []) {
210
+ const when = at + (note.beat - index) * BEAT_SECONDS, length = note.length * BEAT_SECONDS, pitch = degreeHz(note.degree);
211
+ if (note.voice === "lead") {
212
+ lead(when, pitch, length, 0.16);
213
+ if (harmony) lead(when, degreeHz(note.degree - 2), length, 0.07); // a third below, in the finale
214
+ } else if (note.voice === "pluck") pluck(when, pitch, 0.22, 0.4);
215
+ else bell(when, pitch, length, 0.16);
73
216
  }
74
217
  };
75
218
 
219
+ return {
220
+ output: clipper,
221
+ beat(index, at) {
222
+ if (index < 0 || index >= SONG_BEATS) return;
223
+ const half = BEAT_SECONDS / 2, quarter = BEAT_SECONDS / 4;
224
+ if (index < COUNT_IN_BEATS) {
225
+ tick(at, index === COUNT_IN_BEATS - 1);
226
+ return;
227
+ }
228
+ const section = sectionAt(index), inBar = index % BEATS_PER_BAR, barStart = inBar === 0;
229
+ const inSection = index - section.start, progress = inSection / section.beats, chord = chordAt(index);
230
+ switch (section.name) {
231
+ case "intro": {
232
+ // Half-time kick for two bars, then every beat; a pad and soft hats; the tune hinted on a pluck.
233
+ if (inSection >= 8 || inBar % 2 === 0) kick(at, 0.6);
234
+ hat(at + half, false, 0.08);
235
+ if (barStart) pad(at, chord, BEATS_PER_BAR * BEAT_SECONDS, 0.06, 700 + progress * 900);
236
+ if (inBar % 2 === 0) bass(at, chord.bass, BEAT_SECONDS * 1.8, 0.22, 0.2);
237
+ playTune(index, at, false);
238
+ break;
239
+ }
240
+ case "build": {
241
+ const roll = inSection >= section.beats - 4;
242
+ kick(at, 0.8);
243
+ if (inBar === 1 || inBar === 3) clap(at, 0.4);
244
+ for (let step = 0; step < 4; step++) {
245
+ // A sixteenth-note arpeggio that climbs and brightens across the build.
246
+ pluck(at + step * quarter, chord.arp[(inSection * 4 + step) % 4]! * (progress > 0.5 ? 2 : 1), 0.1 + progress * 0.06, progress);
247
+ if (roll) snare(at + step * quarter, 0.12 + (inSection - section.beats + 4 + step / 4) * 0.07);
248
+ }
249
+ bass(at, chord.bass, half * 0.9, 0.3, 0.3 + progress * 0.4);
250
+ bass(at + half, chord.bass, half * 0.9, 0.26, 0.3 + progress * 0.4);
251
+ hat(at + half, false, 0.12);
252
+ if (inSection === section.beats - 8) riser(at, 8 * BEAT_SECONDS, 0.22);
253
+ break;
254
+ }
255
+ case "drop":
256
+ case "finale": {
257
+ const finale = section.name === "finale";
258
+ if (inSection === 0 || (inSection === 16 && !finale)) crash(at, 0.3);
259
+ kick(at, 0.95);
260
+ if (inBar === 1 || inBar === 3) { snare(at, 0.36); clap(at, 0.24); }
261
+ hat(at, false, 0.08);
262
+ hat(at + half, true, 0.11);
263
+ if (finale) { hat(at + quarter, false, 0.05); hat(at + 3 * quarter, false, 0.05); }
264
+ // Pumping bass: root on the beat, octave on the off-beat.
265
+ bass(at, chord.bass, half * 0.85, 0.36, 0.55);
266
+ bass(at + half, chord.bass * 2, half * 0.85, 0.3, 0.75);
267
+ if (barStart) pad(at, chord, BEATS_PER_BAR * BEAT_SECONDS, finale ? 0.07 : 0.05, 1600);
268
+ playTune(index, at, finale);
269
+ break;
270
+ }
271
+ case "breakdown": {
272
+ const lastBar = inSection >= section.beats - 4;
273
+ if (barStart) {
274
+ pad(at, chord, BEATS_PER_BAR * BEAT_SECONDS, 0.08, 1100);
275
+ bass(at, chord.bass, BEATS_PER_BAR * BEAT_SECONDS * 0.9, 0.2, 0.05);
276
+ }
277
+ // A soft half-time kick under the half-note steps.
278
+ if (!lastBar && inBar % 2 === 0) kick(at, 0.4);
279
+ if (lastBar) {
280
+ kick(at, 0.75);
281
+ for (let step = 0; step < 4; step++) snare(at + step * quarter, 0.1 + (inSection - section.beats + 4 + step / 4) * 0.08);
282
+ }
283
+ if (inSection === section.beats - 4) riser(at, 4 * BEAT_SECONDS, 0.2);
284
+ hat(at + half, false, 0.06);
285
+ playTune(index, at, false);
286
+ break;
287
+ }
288
+ case "outro": {
289
+ // G for a bar under the cadence, then one last A minor that rings out.
290
+ if (inSection < 4) {
291
+ kick(at, 0.85);
292
+ if (inBar === 1 || inBar === 3) snare(at, 0.32);
293
+ hat(at + half, true, 0.1);
294
+ bass(at, chord.bass, half * 0.85, 0.34, 0.5);
295
+ bass(at + half, chord.bass * 2, half * 0.85, 0.28, 0.7);
296
+ if (inSection === 0) pad(at, chord, BEATS_PER_BAR * BEAT_SECONDS, 0.07, 1600);
297
+ } else if (inSection === 4) {
298
+ kick(at, 1);
299
+ crash(at, 0.34);
300
+ pad(at, chord, 4 * BEAT_SECONDS - 0.1, 0.12, 1400);
301
+ bass(at, chord.bass, 4 * BEAT_SECONDS - 0.1, 0.36, 0.3);
302
+ }
303
+ playTune(index, at, true);
304
+ break;
305
+ }
306
+ default:
307
+ break;
308
+ }
309
+ },
310
+ };
311
+ }
312
+
313
+ const LOOKAHEAD = 0.25;
314
+
315
+ export function createMusic(): Music {
316
+ let context: AudioContext | undefined, volume: GainNode | undefined, synth: Synth | undefined;
317
+ let startAt = 0, nextBeat = 0, playing = false, muted = false;
318
+
76
319
  return {
77
320
  start(seed) {
78
321
  try {
79
- context ??= new AudioContext();
322
+ context ??= new AudioContext({ latencyHint: "interactive" });
80
323
  } catch {
81
324
  return; // No audio: the game falls back to its own clock and plays silent.
82
325
  }
83
326
  void context.resume().catch(() => {});
84
- if (!master) {
85
- master = context.createGain();
86
- master.gain.value = 0.35;
87
- master.connect(context.destination);
88
- noise = context.createBuffer(1, context.sampleRate / 2, context.sampleRate);
89
- const samples = noise.getChannelData(0);
90
- for (let i = 0; i < samples.length; i++) samples[i] = Math.random() * 2 - 1;
327
+ if (!volume) {
328
+ volume = context.createGain();
329
+ volume.gain.value = muted ? 0 : 1;
330
+ volume.connect(context.destination);
91
331
  }
92
- // A 32-step lead pattern that depends on the seed, so each round sounds a little different.
93
- let state = (seed >>> 0) || 1;
94
- melody = Array.from({ length: 32 }, () => {
95
- state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
96
- return state % 5 < 2 ? 0 : SCALE[state % SCALE.length] ?? 0;
97
- });
98
- startAt = context.currentTime + 0.12;
332
+ // A fresh mix per round: the old one's nodes finish on their own and are collected.
333
+ synth?.output.disconnect();
334
+ synth = createSynth(context, seed);
335
+ synth.output.connect(volume);
336
+ startAt = context.currentTime + 0.15;
99
337
  nextBeat = 0;
100
338
  playing = true;
101
339
  },
102
340
  time() {
103
- return context && playing && context.state === "running" ? context.currentTime - startAt : null;
341
+ if (!context || !playing || context.state !== "running") return null;
342
+ // What is heard now left the context a little earlier: subtract the output latency.
343
+ const latency = Math.min(0.2, Math.max(0, context.outputLatency || context.baseLatency || 0));
344
+ return context.currentTime - latency - startAt;
104
345
  },
105
346
  pump() {
106
- if (!context || !playing) return;
107
- while (nextBeat < SONG_BEATS && startAt + nextBeat * BEAT_SECONDS < context.currentTime + LOOKAHEAD) beat(nextBeat++);
347
+ if (!context || !synth || !playing) return;
348
+ while (nextBeat < SONG_BEATS && startAt + nextBeat * BEAT_SECONDS < context.currentTime + LOOKAHEAD) {
349
+ synth.beat(nextBeat, startAt + nextBeat * BEAT_SECONDS);
350
+ nextBeat++;
351
+ }
108
352
  },
109
353
  setActive(active) {
110
354
  if (!context) return;
111
355
  void (active ? context.resume() : context.suspend()).catch(() => {});
112
356
  },
357
+ setMuted(next) {
358
+ muted = next;
359
+ if (context && volume) volume.gain.setTargetAtTime(muted ? 0 : 1, context.currentTime, 0.02);
360
+ },
113
361
  stop() {
114
362
  playing = false;
115
363
  },
@@ -117,7 +365,8 @@ export function createMusic(): Music {
117
365
  playing = false;
118
366
  void context?.close().catch(() => {});
119
367
  context = undefined;
120
- master = undefined;
368
+ volume = undefined;
369
+ synth = undefined;
121
370
  },
122
371
  };
123
372
  }