@moku-labs/game 0.15.164 → 0.15.165

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.
@@ -1802,7 +1802,7 @@ function stopLoop(state) {
1802
1802
  *
1803
1803
  * @param ctx - Domain context of the time plugin.
1804
1804
  */
1805
- function startLoop$2(ctx) {
1805
+ function startLoop$3(ctx) {
1806
1806
  if (typeof globalThis.requestAnimationFrame !== "function") return;
1807
1807
  ctx.state.running = true;
1808
1808
  ctx.state.rafId = globalThis.requestAnimationFrame(createFrameFunction(ctx));
@@ -1815,7 +1815,7 @@ function startLoop$2(ctx) {
1815
1815
  * @param ctx - Domain context of the time plugin.
1816
1816
  */
1817
1817
  function startTime(ctx) {
1818
- startLoop$2(ctx);
1818
+ startLoop$3(ctx);
1819
1819
  startRate(ctx);
1820
1820
  }
1821
1821
  /**
@@ -11394,7 +11394,7 @@ function restingPeers(mounted) {
11394
11394
  * @param spec - The projection spec.
11395
11395
  * @param peers - The new and the old items of the projection.
11396
11396
  */
11397
- function startLoop$1(pctx, view, spec, peers) {
11397
+ function startLoop$2(pctx, view, spec, peers) {
11398
11398
  const loop = spec.motion?.loop;
11399
11399
  if (loop === void 0) return;
11400
11400
  runHook(pctx, view, "loop", () => loop(createViewHandle(pctx, view, peers)));
@@ -11902,7 +11902,7 @@ function startOwedLoops(pctx) {
11902
11902
  for (const view of mounted.live.values()) {
11903
11903
  if (!view.loopOwed) continue;
11904
11904
  view.loopOwed = false;
11905
- if (spec !== void 0) startLoop$1(pctx, view, spec, restingPeers(mounted));
11905
+ if (spec !== void 0) startLoop$2(pctx, view, spec, restingPeers(mounted));
11906
11906
  }
11907
11907
  }
11908
11908
  }
@@ -50155,12 +50155,94 @@ function applyAllGains(state) {
50155
50155
  applyGain(state, "sfx");
50156
50156
  }
50157
50157
  //#endregion
50158
+ //#region src/plugins/audio/decode.ts
50159
+ /**
50160
+ * Warns about one key exactly once per run. A missing file is a mistake in the manifest, not a
50161
+ * reason to flood the log of every frame that plays the sound.
50162
+ *
50163
+ * @param ctx - Domain context of the plugin.
50164
+ * @param key - The asset key the warning is about.
50165
+ * @param event - What happened.
50166
+ */
50167
+ function warnOnce$3(ctx, key, event) {
50168
+ if (ctx.state.warned.has(key)) return;
50169
+ ctx.state.warned.add(key);
50170
+ ctx.log.warn(event, { key });
50171
+ }
50172
+ /**
50173
+ * Decodes one key, at most once. The promise is cached before it settles, so two plays of the
50174
+ * same sound in one frame decode a single time.
50175
+ *
50176
+ * @param ctx - Domain context of the plugin.
50177
+ * @param key - Asset key of an audio file, `.mp3` or `.m4a`.
50178
+ * @returns The pending buffer, or `undefined` when the bundle carries no such file.
50179
+ */
50180
+ function decode(ctx, key) {
50181
+ const state = ctx.state;
50182
+ const cached = state.decoded.get(key);
50183
+ if (cached !== void 0) return cached;
50184
+ const context = state.context;
50185
+ if (context === void 0) return void 0;
50186
+ const asset = ctx.deps.assets.audio(key);
50187
+ if (asset === void 0) {
50188
+ warnOnce$3(ctx, key, "audio: no audio for key");
50189
+ return;
50190
+ }
50191
+ const pending = context.decodeAudioData(asset.bytes.slice(0));
50192
+ state.decoded.set(key, pending);
50193
+ return pending;
50194
+ }
50195
+ /**
50196
+ * Awaits the decoded buffer of one key. A file that does not decode warns once and plays nothing.
50197
+ *
50198
+ * @param ctx - Domain context of the plugin.
50199
+ * @param key - Asset key of an audio file, `.mp3` or `.m4a`.
50200
+ * @returns The buffer, or `undefined` when there is nothing to play.
50201
+ */
50202
+ async function bufferOf(ctx, key) {
50203
+ const pending = decode(ctx, key);
50204
+ if (pending === void 0) return void 0;
50205
+ try {
50206
+ return await pending;
50207
+ } catch {
50208
+ warnOnce$3(ctx, key, "audio: the audio file did not decode");
50209
+ return;
50210
+ }
50211
+ }
50212
+ //#endregion
50213
+ //#region src/plugins/audio/journal.ts
50214
+ /**
50215
+ * Replaces the journal with a frozen list that ends with one started sound, stamped with the
50216
+ * elapsed game time, and keeps only the newest `config.journal` entries. A size of 0, or anything
50217
+ * that is not a positive number, records nothing. The entry has an `id` only when the sound has
50218
+ * one, and `loop` only for a loop: the caller leaves the fields out otherwise, so no entry carries
50219
+ * an `undefined` key.
50220
+ *
50221
+ * @param ctx - Domain context of the plugin.
50222
+ * @param sound - What started.
50223
+ * @param sound.key - Asset key of the sound.
50224
+ * @param sound.bus - The bus it plays on.
50225
+ * @param sound.kind - `"sfx"` for a play, `"music"` for a track.
50226
+ * @param sound.id - The id of a named sound; absent for every other sound.
50227
+ * @param sound.loop - `true` for a loop; absent for every other sound.
50228
+ */
50229
+ function recordSound(ctx, sound) {
50230
+ const size = Math.floor(ctx.config.journal);
50231
+ if (!Number.isFinite(size) || size <= 0) return;
50232
+ const entry = {
50233
+ ...sound,
50234
+ at: ctx.deps.time.snapshot().elapsed
50235
+ };
50236
+ ctx.state.journal = Object.freeze([...ctx.state.journal, entry].slice(-size));
50237
+ }
50238
+ //#endregion
50158
50239
  //#region src/plugins/audio/named.ts
50159
50240
  /**
50160
50241
  * @file audio plugin — named sounds: an `sfx` with an `id` plays through a gain of its own into its
50161
50242
  * bus, so the next sound with that id, `stopSfx` and `app.audio.stop` can fade it out. One entry
50162
50243
  * per id in `state.named`; the entry object is the token a sound still decoding checks before it
50163
- * starts. A sound without an id never comes here.
50244
+ * starts. A sound without an id never comes here. A loop is a named sound that fades in and loops;
50245
+ * `state.loops` remembers it past its sound (`loops.ts`), until a stop or the leave of its scene.
50164
50246
  */
50165
50247
  /**
50166
50248
  * The key a sound with an id waits under in `pendingSfx` while the unlock resumes the context.
@@ -50211,25 +50293,31 @@ function claimNamed(state, id, seconds) {
50211
50293
  return entry;
50212
50294
  }
50213
50295
  /**
50214
- * Starts one named sound: a gain at 1 into the bus, the source into that gain. When the source
50215
- * ends, its gain is disconnected and the id is freed, unless a later sound took the id meanwhile.
50296
+ * Starts one named sound: a gain into the bus, the source into that gain. A sound that plays once
50297
+ * starts at gain 1; a loop loops and fades in from 0. When the source ends, its gain is
50298
+ * disconnected and the id is freed, unless a later sound took the id meanwhile.
50216
50299
  *
50217
50300
  * @param state - The plugin state.
50218
50301
  * @param context - The running audio context.
50219
- * @param named - The id, its entry, the decoded buffer and the gain of the bus.
50302
+ * @param named - The id, its entry, the decoded buffer, the gain of the bus and the fade-in of a loop.
50220
50303
  * @param named.id - The id the sound plays under.
50221
50304
  * @param named.entry - The entry `claimNamed` returned for it.
50222
50305
  * @param named.buffer - The decoded buffer of the sound.
50223
50306
  * @param named.bus - The gain node of the bus the sound goes to.
50307
+ * @param named.loopFadeIn - The fade-in of a loop, in seconds; `undefined` for a sound that plays once.
50224
50308
  */
50225
50309
  function startNamed(state, context, named) {
50226
- const { id, entry } = named;
50310
+ const { id, entry, loopFadeIn } = named;
50227
50311
  const gain = context.createGain();
50228
50312
  const source = context.createBufferSource();
50229
- gain.gain.value = 1;
50313
+ gain.gain.value = loopFadeIn === void 0 ? 1 : 0;
50230
50314
  gain.connect(named.bus);
50231
50315
  source.buffer = named.buffer;
50232
50316
  source.connect(gain);
50317
+ if (loopFadeIn !== void 0) {
50318
+ source.loop = true;
50319
+ ramp(gain, 1, loopFadeIn, context.currentTime);
50320
+ }
50233
50321
  source.addEventListener("ended", () => {
50234
50322
  gain.disconnect();
50235
50323
  if (state.named.get(id) === entry) state.named.delete(id);
@@ -50239,24 +50327,106 @@ function startNamed(state, context, named) {
50239
50327
  source.start();
50240
50328
  }
50241
50329
  /**
50242
- * Ends the sound under one id: the stop of `stopSfx` and of `app.audio.stop`. The entry leaves the
50243
- * map, so a sound still decoding starts nothing, and the one that plays fades out. A sound with
50244
- * that id waiting for the unlock is dropped. An id nothing plays under changes nothing.
50330
+ * Plays a sound under its id: the sound that has the id fades out over the fade of this one, and
50331
+ * this one starts through its own gain once its buffer is there, unless a later sound with the id
50332
+ * or a stop took its place while it decoded. A loop fades in over the same fade. A file that is
50333
+ * missing frees the id, and forgets a loop, so no unlock tries it again.
50334
+ *
50335
+ * @param ctx - Domain context of the plugin.
50336
+ * @param sound - The id, the key, the checked bus, the fade and the loop it is.
50337
+ */
50338
+ async function playNamed(ctx, sound) {
50339
+ const state = ctx.state;
50340
+ const { id, loop } = sound;
50341
+ const seconds = sound.fadeMs / 1e3;
50342
+ const entry = claimNamed(state, id, seconds);
50343
+ const buffer = await bufferOf(ctx, sound.key);
50344
+ if (state.named.get(id) !== entry) return;
50345
+ const context = state.context;
50346
+ const gain = state.buses[sound.bus].gain;
50347
+ if (buffer === void 0 || context === void 0 || gain === void 0) {
50348
+ state.named.delete(id);
50349
+ if (loop !== void 0) state.loops.delete(id);
50350
+ return;
50351
+ }
50352
+ try {
50353
+ startNamed(state, context, {
50354
+ id,
50355
+ entry,
50356
+ buffer,
50357
+ bus: gain,
50358
+ loopFadeIn: loop === void 0 ? void 0 : seconds
50359
+ });
50360
+ } catch (error) {
50361
+ releaseNamed(state, id, entry);
50362
+ throw error;
50363
+ }
50364
+ journalNamed(ctx, sound);
50365
+ }
50366
+ /**
50367
+ * Frees an id whose sound could not start: its gain leaves the bus, and the entry leaves the map
50368
+ * when it is still the one claimed, so a later sound under the id keeps its own. The loop stays
50369
+ * remembered in `loops`.
50370
+ *
50371
+ * @param state - The plugin state.
50372
+ * @param id - The id the sound was to play under.
50373
+ * @param entry - The entry `claimNamed` returned for it.
50374
+ */
50375
+ function releaseNamed(state, id, entry) {
50376
+ entry.gain?.disconnect();
50377
+ if (state.named.get(id) === entry) state.named.delete(id);
50378
+ }
50379
+ /**
50380
+ * Writes the journal entry of a named sound that started. A loop has one, at its first start: its
50381
+ * start again after an iOS renewal is the same sound.
50382
+ *
50383
+ * @param ctx - Domain context of the plugin.
50384
+ * @param sound - The named sound that started.
50385
+ */
50386
+ function journalNamed(ctx, sound) {
50387
+ const { key, bus, id, loop } = sound;
50388
+ if (loop === void 0) {
50389
+ recordSound(ctx, {
50390
+ key,
50391
+ bus,
50392
+ kind: "sfx",
50393
+ id
50394
+ });
50395
+ return;
50396
+ }
50397
+ if (loop.started) return;
50398
+ loop.started = true;
50399
+ recordSound(ctx, {
50400
+ key,
50401
+ bus,
50402
+ kind: "sfx",
50403
+ id,
50404
+ loop: true
50405
+ });
50406
+ }
50407
+ /**
50408
+ * Ends the sound under one id: the stop of `stopSfx`, of `app.audio.stop` and of the leave of a
50409
+ * loop's scene. The entry leaves the map, so a sound still decoding starts nothing, and the one
50410
+ * that plays fades out. A sound with that id waiting for the unlock is dropped, and so is the loop
50411
+ * remembered under it: neither the unlock nor a renewal starts it again. An id nothing plays under
50412
+ * changes nothing.
50245
50413
  *
50246
50414
  * @param state - The plugin state.
50247
50415
  * @param id - The id the sound was started with.
50248
50416
  * @param fadeMs - Length of the fade, in real milliseconds.
50249
50417
  */
50250
50418
  function stopNamed(state, id, fadeMs) {
50251
- state.pendingSfx.delete(waitingKey(id));
50419
+ if (state.pendingSfx.size > 0) state.pendingSfx.delete(waitingKey(id));
50420
+ state.loops.delete(id);
50252
50421
  const entry = state.named.get(id);
50253
50422
  if (entry === void 0) return;
50254
50423
  state.named.delete(id);
50255
50424
  fadeNamed(state, entry, fadeMs / 1e3);
50256
50425
  }
50257
50426
  /**
50258
- * Stops every named sound at once and forgets the ids. `onStop` runs it: a teardown has no time
50259
- * for a fade, and the context is closed right after.
50427
+ * Stops every named sound at once and forgets the ids. `onStop` and the iOS renewal run it: a
50428
+ * teardown has no time for a fade, and the context is closed right after. The loops stay
50429
+ * remembered, so the renewal's unlock starts them again; `onStop` forgets them itself.
50260
50430
  *
50261
50431
  * @param state - The plugin state.
50262
50432
  */
@@ -50265,96 +50435,126 @@ function stopAllNamed(state) {
50265
50435
  state.named.clear();
50266
50436
  }
50267
50437
  //#endregion
50268
- //#region src/plugins/audio/api.ts
50438
+ //#region src/plugins/audio/loops.ts
50269
50439
  /**
50270
- * @file audio plugin — API factory. Three buses, the unlock flag, the journal of started sounds and the stop of a
50271
- * named sound. Nothing here is persisted; a game keeps the player's choice in the player state and
50272
- * `config.volumes` applies it on the next commit.
50440
+ * @file audio plugin — loops: a named sound asked for with `sfx(key, { id, loop: true })`. `state.loops`
50441
+ * remembers each one by id past its sound, so the unlock and the unlock after an iOS renewal start it
50442
+ * again, and the leave of the scene it was asked in ends it. The sound itself plays through
50443
+ * `named.ts`, as every sound with an id does.
50273
50444
  */
50274
50445
  /**
50275
- * Brings a value into 0..1. `NaN`, which is what a slider divided by zero produces, becomes 0.
50446
+ * Plays a loop, or remembers it: the loop that already holds its id with its key changes nothing
50447
+ * while a sound plays or decodes under the id, and is started again on an unlocked context when an
50448
+ * earlier start failed and left no sound; any other request takes the id, and a one-shot waiting
50449
+ * for the unlock under it is dropped. A
50450
+ * locked context, or a renewal between two contexts, only keeps it in `loops`; the unlock starts
50451
+ * it. The scene it belongs to is the one mounted now.
50276
50452
  *
50277
- * @param value - The value a caller asked for.
50278
- * @returns The value, clamped.
50279
- * @example
50280
- * ```ts
50281
- * clamp(1.4); // 1
50282
- * clamp(Number.NaN); // 0
50283
- * ```
50453
+ * @param ctx - Domain context of the plugin.
50454
+ * @param request - The key, the bus and the fade of the loop.
50455
+ * @param id - The id it plays under.
50284
50456
  */
50285
- function clamp(value) {
50286
- if (Number.isNaN(value)) return 0;
50287
- return Math.min(1, Math.max(0, value));
50457
+ async function playLoop$1(ctx, request, id) {
50458
+ const state = ctx.state;
50459
+ const bus = request.bus;
50460
+ if (!isBus(state, bus)) {
50461
+ ctx.log.warn("audio: unknown bus", { bus });
50462
+ return;
50463
+ }
50464
+ if (isSameLoop(state, id, request.key)) {
50465
+ const kept = state.loops.get(id);
50466
+ if (kept !== void 0 && state.unlocked && !state.named.has(id)) await startLoop$1(ctx, id, kept);
50467
+ return;
50468
+ }
50469
+ const loop = {
50470
+ key: request.key,
50471
+ bus,
50472
+ fadeMs: request.fadeMs,
50473
+ scene: state.scene,
50474
+ started: false
50475
+ };
50476
+ state.loops.set(id, loop);
50477
+ state.pendingSfx.delete(waitingKey(id));
50478
+ if (!state.unlocked) return;
50479
+ await startLoop$1(ctx, id, loop);
50288
50480
  }
50289
50481
  /**
50290
- * Checks a bus name that came from outside the types: an untyped call, or the player state.
50482
+ * Starts one loop the plugin keeps under its id, with its own fade.
50291
50483
  *
50292
- * @param state - The plugin state.
50293
- * @param bus - The bus name to check.
50294
- * @returns The bus.
50295
- * @throws {Error} When the plugin has no such bus.
50484
+ * @param ctx - Domain context of the plugin.
50485
+ * @param id - The id the loop plays under.
50486
+ * @param loop - The loop, as `loops` keeps it.
50296
50487
  */
50297
- function busOf(state, bus) {
50298
- if (!isBus(state, bus)) throw new Error(`[game] Audio bus "${bus}" does not exist.\n Use "master", "music" or "sfx".`);
50299
- return bus;
50488
+ async function startLoop$1(ctx, id, loop) {
50489
+ await playNamed(ctx, {
50490
+ id,
50491
+ key: loop.key,
50492
+ bus: loop.bus,
50493
+ fadeMs: loop.fadeMs,
50494
+ loop
50495
+ });
50300
50496
  }
50301
50497
  /**
50302
- * Stores the volume of one bus and schedules it. `setVolume` and the `model:committed` hook both
50303
- * go through here, so the player's saved choice is clamped exactly like a call from a dev tool.
50498
+ * Starts every remembered loop whose id has no sound: what the unlock does once the context runs,
50499
+ * the first one and the one after an iOS renewal. A loop that already plays or decodes is left alone,
50500
+ * so a gesture and the start attempt that settle together start it once. Nobody awaits these
50501
+ * starts, so a failure goes to the log.
50502
+ *
50503
+ * @param ctx - Domain context of the plugin.
50504
+ */
50505
+ function startLoops(ctx) {
50506
+ const state = ctx.state;
50507
+ for (const [id, loop] of state.loops) if (!state.named.has(id)) trackLoop(ctx, startLoop$1(ctx, id, loop));
50508
+ }
50509
+ /**
50510
+ * Follows a loop start nobody awaits. A failure of the audio hardware is not the graph's problem,
50511
+ * so it goes to the log and the game plays on.
50512
+ *
50513
+ * @param ctx - Domain context of the plugin.
50514
+ * @param pending - The start that was made.
50515
+ */
50516
+ function trackLoop(ctx, pending) {
50517
+ pending.catch((error) => {
50518
+ ctx.log.error("audio: the loop did not start", void 0, error instanceof Error ? error : new Error(String(error)));
50519
+ });
50520
+ }
50521
+ /**
50522
+ * Tells whether an id already holds a loop of a key, playing, decoding or remembered for the
50523
+ * unlock: a request for it does not start a second sound, so the bed plays on from where it is.
50304
50524
  *
50305
50525
  * @param state - The plugin state.
50306
- * @param bus - The bus to change.
50307
- * @param value - The new volume; clamped to 0..1.
50526
+ * @param id - The id of the loop request.
50527
+ * @param key - The asset key it asks for.
50528
+ * @returns True when that loop is already there.
50308
50529
  */
50309
- function setBusVolume(state, bus, value) {
50310
- state.buses[bus].volume = clamp(value);
50311
- applyGain(state, bus);
50530
+ function isSameLoop(state, id, key) {
50531
+ return state.loops.get(id)?.key === key;
50312
50532
  }
50313
50533
  /**
50314
- * Creates the audio API: the three buses, the unlock flag, the journal and the stop of a named sound.
50534
+ * Stops one loop when it belongs to the scene that leaves. `this` is the plugin state, handed in
50535
+ * by the walk of `stopSceneLoops`.
50315
50536
  *
50316
- * @param ctx - Kernel context of the audio plugin.
50317
- * @returns The plugin API.
50537
+ * @param this - The plugin state, whose `leaving` names the scene and the fade.
50538
+ * @param loop - The loop.
50539
+ * @param id - The id it plays under.
50318
50540
  */
50319
- function createAudioApi(ctx) {
50320
- const state = ctx.state;
50321
- return {
50322
- setVolume: (bus, value) => setBusVolume(state, busOf(state, bus), value),
50323
- volume: (bus) => state.buses[busOf(state, bus)].volume,
50324
- mute: (bus, on) => {
50325
- const checked = busOf(state, bus);
50326
- state.buses[checked].muted = on;
50327
- applyGain(state, checked);
50328
- },
50329
- muted: (bus) => state.buses[busOf(state, bus)].muted,
50330
- unlocked: () => state.unlocked,
50331
- journal: () => state.journal,
50332
- stop: (id, options) => stopNamed(state, id, options?.fadeMs ?? ctx.config.sfxFadeMs)
50333
- };
50541
+ function stopIfLeaving(loop, id) {
50542
+ if (loop.scene === this.leaving.scene) stopNamed(this, id, this.leaving.fadeMs);
50334
50543
  }
50335
- //#endregion
50336
- //#region src/plugins/audio/journal.ts
50337
50544
  /**
50338
- * Replaces the journal with a frozen list that ends with one started sound, stamped with the
50339
- * elapsed game time, and keeps only the newest `config.journal` entries. A size of 0, or anything
50340
- * that is not a positive number, records nothing. The entry has an `id` only when the sound has
50341
- * one: the caller leaves the field out otherwise, so no entry carries an `undefined` key.
50545
+ * Ends every loop asked for while the scene that leaves was mounted, each over the fade given,
50546
+ * through `stopNamed`. A loop asked for before any scene belongs to none and stays. The walk deletes
50547
+ * from the map it walks, which a `Map` allows, and makes nothing.
50342
50548
  *
50343
- * @param ctx - Domain context of the plugin.
50344
- * @param sound - What started.
50345
- * @param sound.key - Asset key of the sound.
50346
- * @param sound.bus - The bus it plays on.
50347
- * @param sound.kind - `"sfx"` for a play, `"music"` for a track.
50348
- * @param sound.id - The id of a named sound; absent for every other sound.
50549
+ * @param state - The plugin state.
50550
+ * @param from - The scene that leaves, `undefined` at the first switch.
50551
+ * @param fadeMs - Length of the fade, in real milliseconds.
50349
50552
  */
50350
- function recordSound(ctx, sound) {
50351
- const size = Math.floor(ctx.config.journal);
50352
- if (!Number.isFinite(size) || size <= 0) return;
50353
- const entry = {
50354
- ...sound,
50355
- at: ctx.deps.time.snapshot().elapsed
50356
- };
50357
- ctx.state.journal = Object.freeze([...ctx.state.journal, entry].slice(-size));
50553
+ function stopSceneLoops(state, from, fadeMs) {
50554
+ if (from === void 0 || state.loops.size === 0) return;
50555
+ state.leaving.scene = from;
50556
+ state.leaving.fadeMs = fadeMs;
50557
+ state.loops.forEach(stopIfLeaving, state);
50358
50558
  }
50359
50559
  //#endregion
50360
50560
  //#region src/plugins/audio/stream.ts
@@ -50483,8 +50683,9 @@ function fadeOf(descriptor, fadeMs) {
50483
50683
  return validFade(fieldOf(descriptor.payload, "fadeMs"), fadeMs);
50484
50684
  }
50485
50685
  /**
50486
- * Takes a fade a descriptor named only when the clock can schedule it: a finite number, 0 or more.
50487
- * `NaN` or a negative fade would make the ramp and the stop throw inside the handler.
50686
+ * Takes a fade a descriptor or a caller named only when the clock can schedule it: a finite number,
50687
+ * 0 or more. `NaN` or a negative fade would make the ramp and the stop throw. The `stopSfx` handler
50688
+ * and `app.audio.stop` both clamp through here.
50488
50689
  *
50489
50690
  * @param fade - The `fadeMs` the payload carries.
50490
50691
  * @param fallback - The configured fade.
@@ -50498,7 +50699,8 @@ function validFade(fade, fallback) {
50498
50699
  return typeof fade === "number" && Number.isFinite(fade) && fade >= 0 ? fade : fallback;
50499
50700
  }
50500
50701
  /**
50501
- * Reads the key, the bus, the id and the fade out of the `sfx` descriptor `anim` builds.
50702
+ * Reads the key, the bus, the id, the fade and the loop flag out of the `sfx` descriptor `anim`
50703
+ * builds.
50502
50704
  *
50503
50705
  * @param descriptor - The descriptor the handler was called with.
50504
50706
  * @param fadeMs - The configured fade of a named sound, used when the descriptor names none.
@@ -50513,7 +50715,8 @@ function sfxOf(descriptor, fadeMs) {
50513
50715
  key,
50514
50716
  bus: typeof bus === "string" ? bus : DEFAULT_BUS$1,
50515
50717
  id: typeof id === "string" ? id : void 0,
50516
- fadeMs: fadeOf(descriptor, fadeMs)
50718
+ fadeMs: fadeOf(descriptor, fadeMs),
50719
+ loop: fieldOf(descriptor.payload, "loop") === true
50517
50720
  };
50518
50721
  }
50519
50722
  /**
@@ -50531,74 +50734,28 @@ function musicOf(descriptor, fadeMs) {
50531
50734
  };
50532
50735
  }
50533
50736
  /**
50534
- * Warns about one key exactly once per run. A missing file is a mistake in the manifest, not a
50535
- * reason to flood the log of every frame that plays the sound.
50536
- *
50537
- * @param ctx - Domain context of the plugin.
50538
- * @param key - The asset key the warning is about.
50539
- * @param event - What happened.
50540
- */
50541
- function warnOnce$3(ctx, key, event) {
50542
- if (ctx.state.warned.has(key)) return;
50543
- ctx.state.warned.add(key);
50544
- ctx.log.warn(event, { key });
50545
- }
50546
- /**
50547
- * Decodes one key, at most once. The promise is cached before it settles, so two plays of the
50548
- * same sound in one frame decode a single time.
50549
- *
50550
- * @param ctx - Domain context of the plugin.
50551
- * @param key - Asset key of an audio file, `.mp3` or `.m4a`.
50552
- * @returns The pending buffer, or `undefined` when the bundle carries no such file.
50553
- */
50554
- function decode(ctx, key) {
50555
- const state = ctx.state;
50556
- const cached = state.decoded.get(key);
50557
- if (cached !== void 0) return cached;
50558
- const context = state.context;
50559
- if (context === void 0) return void 0;
50560
- const asset = ctx.deps.assets.audio(key);
50561
- if (asset === void 0) {
50562
- warnOnce$3(ctx, key, "audio: no audio for key");
50563
- return;
50564
- }
50565
- const pending = context.decodeAudioData(asset.bytes.slice(0));
50566
- state.decoded.set(key, pending);
50567
- return pending;
50568
- }
50569
- /**
50570
- * Awaits the decoded buffer of one key. A file that does not decode warns once and plays nothing.
50571
- *
50572
- * @param ctx - Domain context of the plugin.
50573
- * @param key - Asset key of an audio file, `.mp3` or `.m4a`.
50574
- * @returns The buffer, or `undefined` when there is nothing to play.
50575
- */
50576
- async function bufferOf(ctx, key) {
50577
- const pending = decode(ctx, key);
50578
- if (pending === void 0) return void 0;
50579
- try {
50580
- return await pending;
50581
- } catch {
50582
- warnOnce$3(ctx, key, "audio: the audio file did not decode");
50583
- return;
50584
- }
50585
- }
50586
- /**
50587
50737
  * Plays one sound: the handler of the kind `"sfx"`. Every play is its own source, so the same key
50588
50738
  * twice in one frame is heard twice, and the promise resolves when the sound STARTED. The handler
50589
50739
  * ignores its signal: a sound that began plays to its end, unless a sound with its id or a stop
50590
50740
  * ends it. While a gesture's `resume()` is pending the sound waits in `pendingSfx`, one per id
50591
50741
  * and one per key without an id. A locked context no gesture is resuming drops it: the start
50592
- * attempt of the unlock queues nothing.
50742
+ * attempt of the unlock queues nothing. A loop goes through `playLoop`, and the latest request
50743
+ * for an id wins: a sound that plays once under it forgets the loop there.
50593
50744
  *
50594
50745
  * @param ctx - Domain context of the plugin.
50595
50746
  * @param descriptor - The `sfx` descriptor `anim` built.
50596
50747
  */
50597
50748
  async function playSfx(ctx, descriptor) {
50598
50749
  const state = ctx.state;
50599
- if (state.context === void 0) return;
50750
+ if (state.context === void 0 && state.renewing === void 0) return;
50600
50751
  const request = sfxOf(descriptor, ctx.config.sfxFadeMs);
50601
50752
  if (request === void 0) return;
50753
+ if (request.loop && request.id !== void 0) {
50754
+ await playLoop$1(ctx, request, request.id);
50755
+ return;
50756
+ }
50757
+ if (request.id !== void 0 && isBus(state, request.bus)) state.loops.delete(request.id);
50758
+ if (state.context === void 0) return;
50602
50759
  if (!state.unlocked) {
50603
50760
  queueWhileResuming(state, request);
50604
50761
  return;
@@ -50629,42 +50786,6 @@ function stopNamedSfx(ctx, descriptor) {
50629
50786
  stopNamed(ctx.state, id, fadeOf(descriptor, ctx.config.sfxFadeMs));
50630
50787
  }
50631
50788
  /**
50632
- * Plays a sound under its id: the sound that has the id fades out over the fade of this one, and
50633
- * this one starts through its own gain once its buffer is there, unless a later sound with the id
50634
- * or a stop took its place while it decoded. A file that is missing frees the id.
50635
- *
50636
- * @param ctx - Domain context of the plugin.
50637
- * @param request - The key, the fade and the id of the sound.
50638
- * @param sound - The id and the bus, both checked.
50639
- * @param sound.id - The id the sound plays under.
50640
- * @param sound.bus - The bus it goes to.
50641
- */
50642
- async function playNamed(ctx, request, sound) {
50643
- const state = ctx.state;
50644
- const { id, bus } = sound;
50645
- const entry = claimNamed(state, id, request.fadeMs / 1e3);
50646
- const buffer = await bufferOf(ctx, request.key);
50647
- if (state.named.get(id) !== entry) return;
50648
- const context = state.context;
50649
- const gain = state.buses[bus].gain;
50650
- if (buffer === void 0 || context === void 0 || gain === void 0) {
50651
- state.named.delete(id);
50652
- return;
50653
- }
50654
- startNamed(state, context, {
50655
- id,
50656
- entry,
50657
- buffer,
50658
- bus: gain
50659
- });
50660
- recordSound(ctx, {
50661
- key: request.key,
50662
- bus,
50663
- kind: "sfx",
50664
- id
50665
- });
50666
- }
50667
- /**
50668
50789
  * Starts one source of a sound on its bus. `playSfx` calls it for a live play and the unlock for
50669
50790
  * every sound that waited for the resume. A sound with an id goes through `playNamed`.
50670
50791
  *
@@ -50680,9 +50801,13 @@ async function playRequest(ctx, request) {
50680
50801
  return;
50681
50802
  }
50682
50803
  if (request.id !== void 0) {
50683
- await playNamed(ctx, request, {
50804
+ const { key, bus, fadeMs } = request;
50805
+ await playNamed(ctx, {
50684
50806
  id: request.id,
50685
- bus: request.bus
50807
+ key,
50808
+ bus,
50809
+ fadeMs,
50810
+ loop: void 0
50686
50811
  });
50687
50812
  return;
50688
50813
  }
@@ -50971,6 +51096,74 @@ function trackMusic(ctx, pending) {
50971
51096
  });
50972
51097
  }
50973
51098
  //#endregion
51099
+ //#region src/plugins/audio/api.ts
51100
+ /**
51101
+ * @file audio plugin — API factory. Three buses, the unlock flag, the journal of started sounds and the stop of a
51102
+ * named sound. Nothing here is persisted; a game keeps the player's choice in the player state and
51103
+ * `config.volumes` applies it on the next commit.
51104
+ */
51105
+ /**
51106
+ * Brings a value into 0..1. `NaN`, which is what a slider divided by zero produces, becomes 0.
51107
+ *
51108
+ * @param value - The value a caller asked for.
51109
+ * @returns The value, clamped.
51110
+ * @example
51111
+ * ```ts
51112
+ * clamp(1.4); // 1
51113
+ * clamp(Number.NaN); // 0
51114
+ * ```
51115
+ */
51116
+ function clamp(value) {
51117
+ if (Number.isNaN(value)) return 0;
51118
+ return Math.min(1, Math.max(0, value));
51119
+ }
51120
+ /**
51121
+ * Checks a bus name that came from outside the types: an untyped call, or the player state.
51122
+ *
51123
+ * @param state - The plugin state.
51124
+ * @param bus - The bus name to check.
51125
+ * @returns The bus.
51126
+ * @throws {Error} When the plugin has no such bus.
51127
+ */
51128
+ function busOf(state, bus) {
51129
+ if (!isBus(state, bus)) throw new Error(`[game] Audio bus "${bus}" does not exist.\n Use "master", "music" or "sfx".`);
51130
+ return bus;
51131
+ }
51132
+ /**
51133
+ * Stores the volume of one bus and schedules it. `setVolume` and the `model:committed` hook both
51134
+ * go through here, so the player's saved choice is clamped exactly like a call from a dev tool.
51135
+ *
51136
+ * @param state - The plugin state.
51137
+ * @param bus - The bus to change.
51138
+ * @param value - The new volume; clamped to 0..1.
51139
+ */
51140
+ function setBusVolume(state, bus, value) {
51141
+ state.buses[bus].volume = clamp(value);
51142
+ applyGain(state, bus);
51143
+ }
51144
+ /**
51145
+ * Creates the audio API: the three buses, the unlock flag, the journal and the stop of a named sound.
51146
+ *
51147
+ * @param ctx - Kernel context of the audio plugin.
51148
+ * @returns The plugin API.
51149
+ */
51150
+ function createAudioApi(ctx) {
51151
+ const state = ctx.state;
51152
+ return {
51153
+ setVolume: (bus, value) => setBusVolume(state, busOf(state, bus), value),
51154
+ volume: (bus) => state.buses[busOf(state, bus)].volume,
51155
+ mute: (bus, on) => {
51156
+ const checked = busOf(state, bus);
51157
+ state.buses[checked].muted = on;
51158
+ applyGain(state, checked);
51159
+ },
51160
+ muted: (bus) => state.buses[busOf(state, bus)].muted,
51161
+ unlocked: () => state.unlocked,
51162
+ journal: () => state.journal,
51163
+ stop: (id, options) => stopNamed(state, id, validFade(options?.fadeMs, ctx.config.sfxFadeMs))
51164
+ };
51165
+ }
51166
+ //#endregion
50974
51167
  //#region src/plugins/audio/session.ts
50975
51168
  /**
50976
51169
  * Tells whether a value is an audio session the plugin can write: an object with a string `type`.
@@ -51069,10 +51262,11 @@ const UNLOCK_EVENTS = ["pointerdown", "touchend"];
51069
51262
  /**
51070
51263
  * Reacts to a resume that went through, of a gesture or of the start attempt. The context is
51071
51264
  * unlocked only when it really runs, and only then do the listeners come off; the sounds fired
51072
- * during the resume and the track a scene declared while it was locked start here. A context that still does not run drops the sounds:
51265
+ * during the resume, the loops remembered while it was locked and the track a scene declared start
51266
+ * here. A context that still does not run drops the sounds and keeps the loops:
51073
51267
  * the next gesture is a new moment. A gesture and the start attempt that settle together both
51074
- * come here, and the music still starts once: a track that is on its way or already plays is not
51075
- * started again. A later gesture on an unlocked context tries a remembered track again.
51268
+ * come here, and the music and each loop still start once: what is on its way or already plays is
51269
+ * not started again. A later gesture on an unlocked context tries a remembered track again.
51076
51270
  *
51077
51271
  * @param ctx - Domain context of the plugin.
51078
51272
  */
@@ -51087,6 +51281,7 @@ function onResumed(ctx) {
51087
51281
  state.unlocked = true;
51088
51282
  removeUnlock(state);
51089
51283
  drainSfx(ctx);
51284
+ startLoops(ctx);
51090
51285
  const remembered = state.music;
51091
51286
  if (remembered === void 0 || isMusicPlaying(state)) return;
51092
51287
  trackMusic(ctx, playMusic(ctx, {
@@ -51292,7 +51487,8 @@ function cancelRenewal(state) {
51292
51487
  }
51293
51488
  /**
51294
51489
  * Drops every sound of the old context and keeps the music key: the track that plays, or the
51295
- * switch on its way. A decode still running on the old context may reject when it closes; such a
51490
+ * switch on its way. The loops stay in `loops`, so the unlock of the new context starts them again,
51491
+ * as the music. A decode still running on the old context may reject when it closes; such a
51296
51492
  * key is forgotten, so its next play decodes again.
51297
51493
  *
51298
51494
  * @param state - The plugin state.
@@ -51316,9 +51512,9 @@ function dropInFlight(state) {
51316
51512
  /**
51317
51513
  * Renews the context: the old one goes with every sound in it, the session is written again, and
51318
51514
  * a new context gets the graph at the same volumes and the unlock. The decoded buffers stay, an
51319
- * AudioBuffer is bound to no context. The unlock starts the remembered music once the new context
51320
- * runs. While the old context closes the plugin is headless: a sound is dropped and a music switch
51321
- * is remembered. A stop, or a newer renewal, during the close makes this one end there.
51515
+ * AudioBuffer is bound to no context. The unlock starts the remembered music and loops once the new
51516
+ * context runs. While the old context closes the plugin is headless: a sound is dropped, and a music
51517
+ * switch and a loop are remembered. A stop, or a newer renewal, during the close makes this one end there.
51322
51518
  *
51323
51519
  * @param ctx - Domain context of the plugin.
51324
51520
  */
@@ -51411,10 +51607,11 @@ function startAudio(ctx) {
51411
51607
  }
51412
51608
  /**
51413
51609
  * Frees everything `onStart` opened: the three handler registrations, the two window listeners,
51414
- * a renewal that waits or runs, the music track, every named sound, every streamed track still
51415
- * fading with its timer, the journal, the audio session and the context itself. The tracks are
51416
- * freed before the close, while their nodes can still disconnect. A browser caps how many
51417
- * contexts a page may hold, so the close is the point of this teardown.
51610
+ * a renewal that waits or runs, the music track, every named sound and every loop, the mounted
51611
+ * scene (a start again begins before any scene), every streamed track still fading with its timer,
51612
+ * the journal, the audio session and the context itself. The tracks are freed before the close,
51613
+ * while their nodes can still disconnect. A browser caps how many contexts a page may hold, so the
51614
+ * close is the point of this teardown.
51418
51615
  *
51419
51616
  * @param state - The plugin state, all a teardown context carries.
51420
51617
  * @returns A promise that resolves when the context is closed.
@@ -51426,6 +51623,8 @@ async function stopAudio(state) {
51426
51623
  removeUnlock(state);
51427
51624
  stopMusic(state);
51428
51625
  stopAllNamed(state);
51626
+ state.loops.clear();
51627
+ state.scene = void 0;
51429
51628
  for (const entry of state.retiring) disposeStream(state, entry.stream);
51430
51629
  state.decoded.clear();
51431
51630
  state.journal = Object.freeze([]);
@@ -51558,13 +51757,17 @@ function createHandlers$3(ctx) {
51558
51757
  applyVolumes(domain());
51559
51758
  },
51560
51759
  /**
51561
- * Switches the music to the track the next scene declared. A scene that declares none keeps
51562
- * the track that plays. The switch is tracked, never awaited: a hook is synchronous.
51760
+ * Notes the scene that is mounted now, fades out the loops of the scene that left over the
51761
+ * music's fade, and switches the music to the track the next scene declared. A scene that
51762
+ * declares none keeps the track that plays. The switch is tracked, never awaited: a hook is
51763
+ * synchronous.
51563
51764
  *
51564
- * @param payload - The scene that was entered and the music it declared.
51765
+ * @param payload - The scene that left, the scene that was entered and the music it declared.
51565
51766
  */
51566
51767
  "scenes:changed": (payload) => {
51567
51768
  const audioCtx = domain();
51769
+ audioCtx.state.scene = payload.to;
51770
+ stopSceneLoops(audioCtx.state, payload.from, audioCtx.config.musicFadeMs);
51568
51771
  trackMusic(audioCtx, playMusic(audioCtx, {
51569
51772
  key: payload.music ?? audioCtx.state.music?.key ?? null,
51570
51773
  fadeMs: audioCtx.config.musicFadeMs
@@ -51647,6 +51850,14 @@ function emptyNamed() {
51647
51850
  return /* @__PURE__ */ new Map();
51648
51851
  }
51649
51852
  /**
51853
+ * Creates the map of the loops the game asked for.
51854
+ *
51855
+ * @returns An empty map, keyed by id.
51856
+ */
51857
+ function emptyLoops() {
51858
+ return /* @__PURE__ */ new Map();
51859
+ }
51860
+ /**
51650
51861
  * Creates the set of streamed tracks that fade out.
51651
51862
  *
51652
51863
  * @returns An empty set of retiring tracks.
@@ -51692,6 +51903,12 @@ function createAudioState(ctx) {
51692
51903
  resuming: false,
51693
51904
  pendingSfx: emptyPending(),
51694
51905
  named: emptyNamed(),
51906
+ loops: emptyLoops(),
51907
+ scene: void 0,
51908
+ leaving: {
51909
+ scene: "",
51910
+ fadeMs: 0
51911
+ },
51695
51912
  decoded: emptyCache$1(),
51696
51913
  warned: emptyWarned$2(),
51697
51914
  warnedVolumes: false,
@@ -62411,27 +62628,6 @@ function spawn(id, components, options) {
62411
62628
  function spawned(id) {
62412
62629
  return Object.freeze({ spawned: id });
62413
62630
  }
62414
- /**
62415
- * A sound. `anim` owns the descriptor because it sits below `audio`; `audio` owns the handler,
62416
- * and a game without `audio` plays nothing and hears no error. A sound with an `id` is named:
62417
- * one sound plays per id, a new one with the same id fades the old one out over `fadeMs`, and
62418
- * `stopSfx(id)` stops it. The payload carries `id` and `fadeMs` only when they are given, so a
62419
- * sound without them stays `{ key, bus }`.
62420
- *
62421
- * @param key - Asset key of the sound.
62422
- * @param options - The bus, the name and the fade.
62423
- * @param options.bus - `"sfx"` when omitted.
62424
- * @param options.id - Name of the sound; one sound per id plays.
62425
- * @param options.fadeMs - Fade of the sound with the same id this one replaces; `audio`'s
62426
- * `sfxFadeMs` when omitted.
62427
- * @returns The descriptor, usable as a timeline step and as `fx(...)` in a node.
62428
- * @example
62429
- * ```ts
62430
- * sfx("board.merge"); // { kind: "sfx", payload: { key: "board.merge", bus: "sfx" }, cosmetic: true }
62431
- * sfx("voice.hello", { id: "voice", fadeMs: 200 });
62432
- * // { kind: "sfx", payload: { key: "voice.hello", bus: "sfx", id: "voice", fadeMs: 200 }, cosmetic: true }
62433
- * ```
62434
- */
62435
62631
  function sfx(key, options) {
62436
62632
  const payload = {
62437
62633
  key,
@@ -62439,6 +62635,7 @@ function sfx(key, options) {
62439
62635
  };
62440
62636
  if (options?.id !== void 0) payload.id = options.id;
62441
62637
  if (options?.fadeMs !== void 0) payload.fadeMs = options.fadeMs;
62638
+ if (options?.loop === true) payload.loop = true;
62442
62639
  return Object.freeze({
62443
62640
  kind: "sfx",
62444
62641
  payload: Object.freeze(payload),
@@ -79401,7 +79598,9 @@ var types_exports = /* @__PURE__ */ __exportAll({});
79401
79598
  * Binds `frames`, `sfx` and `Frames` to one game's asset keys. Type-only: the same functions and
79402
79599
  * the same component object.
79403
79600
  *
79404
- * @returns The five helpers, with the asset arguments narrowed to `Asset`.
79601
+ * @returns The `AnimKit` of this game: `defineAnimation`, `frames`, `sfx`, `play` and `Frames`, where
79602
+ * the asset keys of `frames`, `sfx` and `Frames` are narrowed to `Asset`; `defineAnimation` and
79603
+ * `play` are the unchanged functions.
79405
79604
  * @example
79406
79605
  * ```ts
79407
79606
  * const { sfx } = animFor<"board.merge">();