@moku-labs/game 0.15.163 → 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
  /**
@@ -3339,7 +3339,9 @@ function beginGuide(state, signal) {
3339
3339
  * gate opened. The spread keeps a payload-less answer without a `payload` key, and `at` replaces
3340
3340
  * one a caller put on the answer. In live mode the handler is called as well: it only shows the UI,
3341
3341
  * the answer comes through the gate, so its failure is logged and does not block the node. Its
3342
- * signal ends with the answer — that is how the popup layer knows to unmount what it showed.
3342
+ * signal ends with the answer — that is how the popup layer knows to unmount what it showed. In
3343
+ * fast mode the call waits in `state.unshown` until the answer: when the mode goes back to live
3344
+ * first (a walk rests at this gate), `setMode` shows the popup then.
3343
3345
  *
3344
3346
  * @param ctx - Domain context of the flow plugin.
3345
3347
  * @param gate - Internal gate API.
@@ -3349,13 +3351,23 @@ function beginGuide(state, signal) {
3349
3351
  * @returns The answer the gate accepted, with the moment it arrived.
3350
3352
  */
3351
3353
  function openForAnswers(ctx, gate, descriptor, answers, signal) {
3354
+ const state = ctx.state.fx;
3352
3355
  const answered = gate.open({ allowed: answers }).then((answer) => ({
3353
3356
  ...answer,
3354
3357
  at: ctx.deps.clock.now()
3355
3358
  }));
3356
- if (ctx.state.fx.mode !== "live") return answered;
3357
3359
  const shown = childOf$1(signal);
3358
- invoke(ctx.state.fx, ctx.log, descriptor, shown.signal);
3360
+ /**
3361
+ * Calls the handler with the signal that ends with the answer.
3362
+ */
3363
+ const show = () => {
3364
+ invoke(state, ctx.log, descriptor, shown.signal);
3365
+ };
3366
+ if (state.mode === "live") show();
3367
+ else if (!shown.signal.aborted) state.unshown = show;
3368
+ shown.signal.addEventListener("abort", () => {
3369
+ if (state.unshown === show) state.unshown = void 0;
3370
+ });
3359
3371
  return answered.finally(() => {
3360
3372
  shown.abort();
3361
3373
  });
@@ -3438,7 +3450,11 @@ function createFxApi(ctx, deps) {
3438
3450
  for (const controller of shown) controller.abort();
3439
3451
  },
3440
3452
  setMode: (mode) => {
3453
+ const unshown = state.unshown;
3441
3454
  state.mode = mode;
3455
+ if (mode !== "live" || unshown === void 0) return;
3456
+ state.unshown = void 0;
3457
+ unshown();
3442
3458
  }
3443
3459
  };
3444
3460
  }
@@ -7167,7 +7183,8 @@ async function playRoute(ctx, modules, route, running) {
7167
7183
  * after the switch, so it never starts live and never shows its popup. The mode of the caller
7168
7184
  * is put back afterwards, also when the bookmark is refused or a step rejects, and a
7169
7185
  * substitution the route never reached is disarmed: it must not skip a sub-flow in the live play
7170
- * that follows. Back in live mode, the guide of the node the walk ends at is shown.
7186
+ * that follows. Back in live mode, the guide of the node the walk ends at is shown, and `fx`
7187
+ * shows the popup whose gate the walk rests at.
7171
7188
  *
7172
7189
  * @param ctx - Domain context of the flow plugin.
7173
7190
  * @param modules - Injected sibling APIs: features, fx, gate, inbox.
@@ -7612,6 +7629,7 @@ function createFxState() {
7612
7629
  hintListeners: [],
7613
7630
  settled: [],
7614
7631
  guides: [],
7632
+ unshown: void 0,
7615
7633
  mode: "live"
7616
7634
  };
7617
7635
  }
@@ -11376,7 +11394,7 @@ function restingPeers(mounted) {
11376
11394
  * @param spec - The projection spec.
11377
11395
  * @param peers - The new and the old items of the projection.
11378
11396
  */
11379
- function startLoop$1(pctx, view, spec, peers) {
11397
+ function startLoop$2(pctx, view, spec, peers) {
11380
11398
  const loop = spec.motion?.loop;
11381
11399
  if (loop === void 0) return;
11382
11400
  runHook(pctx, view, "loop", () => loop(createViewHandle(pctx, view, peers)));
@@ -11884,7 +11902,7 @@ function startOwedLoops(pctx) {
11884
11902
  for (const view of mounted.live.values()) {
11885
11903
  if (!view.loopOwed) continue;
11886
11904
  view.loopOwed = false;
11887
- if (spec !== void 0) startLoop$1(pctx, view, spec, restingPeers(mounted));
11905
+ if (spec !== void 0) startLoop$2(pctx, view, spec, restingPeers(mounted));
11888
11906
  }
11889
11907
  }
11890
11908
  }
@@ -50137,12 +50155,94 @@ function applyAllGains(state) {
50137
50155
  applyGain(state, "sfx");
50138
50156
  }
50139
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
50140
50239
  //#region src/plugins/audio/named.ts
50141
50240
  /**
50142
50241
  * @file audio plugin — named sounds: an `sfx` with an `id` plays through a gain of its own into its
50143
50242
  * bus, so the next sound with that id, `stopSfx` and `app.audio.stop` can fade it out. One entry
50144
50243
  * per id in `state.named`; the entry object is the token a sound still decoding checks before it
50145
- * 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.
50146
50246
  */
50147
50247
  /**
50148
50248
  * The key a sound with an id waits under in `pendingSfx` while the unlock resumes the context.
@@ -50193,25 +50293,31 @@ function claimNamed(state, id, seconds) {
50193
50293
  return entry;
50194
50294
  }
50195
50295
  /**
50196
- * Starts one named sound: a gain at 1 into the bus, the source into that gain. When the source
50197
- * 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.
50198
50299
  *
50199
50300
  * @param state - The plugin state.
50200
50301
  * @param context - The running audio context.
50201
- * @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.
50202
50303
  * @param named.id - The id the sound plays under.
50203
50304
  * @param named.entry - The entry `claimNamed` returned for it.
50204
50305
  * @param named.buffer - The decoded buffer of the sound.
50205
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.
50206
50308
  */
50207
50309
  function startNamed(state, context, named) {
50208
- const { id, entry } = named;
50310
+ const { id, entry, loopFadeIn } = named;
50209
50311
  const gain = context.createGain();
50210
50312
  const source = context.createBufferSource();
50211
- gain.gain.value = 1;
50313
+ gain.gain.value = loopFadeIn === void 0 ? 1 : 0;
50212
50314
  gain.connect(named.bus);
50213
50315
  source.buffer = named.buffer;
50214
50316
  source.connect(gain);
50317
+ if (loopFadeIn !== void 0) {
50318
+ source.loop = true;
50319
+ ramp(gain, 1, loopFadeIn, context.currentTime);
50320
+ }
50215
50321
  source.addEventListener("ended", () => {
50216
50322
  gain.disconnect();
50217
50323
  if (state.named.get(id) === entry) state.named.delete(id);
@@ -50221,24 +50327,106 @@ function startNamed(state, context, named) {
50221
50327
  source.start();
50222
50328
  }
50223
50329
  /**
50224
- * Ends the sound under one id: the stop of `stopSfx` and of `app.audio.stop`. The entry leaves the
50225
- * map, so a sound still decoding starts nothing, and the one that plays fades out. A sound with
50226
- * 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.
50227
50413
  *
50228
50414
  * @param state - The plugin state.
50229
50415
  * @param id - The id the sound was started with.
50230
50416
  * @param fadeMs - Length of the fade, in real milliseconds.
50231
50417
  */
50232
50418
  function stopNamed(state, id, fadeMs) {
50233
- state.pendingSfx.delete(waitingKey(id));
50419
+ if (state.pendingSfx.size > 0) state.pendingSfx.delete(waitingKey(id));
50420
+ state.loops.delete(id);
50234
50421
  const entry = state.named.get(id);
50235
50422
  if (entry === void 0) return;
50236
50423
  state.named.delete(id);
50237
50424
  fadeNamed(state, entry, fadeMs / 1e3);
50238
50425
  }
50239
50426
  /**
50240
- * Stops every named sound at once and forgets the ids. `onStop` runs it: a teardown has no time
50241
- * 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.
50242
50430
  *
50243
50431
  * @param state - The plugin state.
50244
50432
  */
@@ -50247,96 +50435,126 @@ function stopAllNamed(state) {
50247
50435
  state.named.clear();
50248
50436
  }
50249
50437
  //#endregion
50250
- //#region src/plugins/audio/api.ts
50438
+ //#region src/plugins/audio/loops.ts
50251
50439
  /**
50252
- * @file audio plugin — API factory. Three buses, the unlock flag, the journal of started sounds and the stop of a
50253
- * named sound. Nothing here is persisted; a game keeps the player's choice in the player state and
50254
- * `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.
50255
50444
  */
50256
50445
  /**
50257
- * 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.
50258
50452
  *
50259
- * @param value - The value a caller asked for.
50260
- * @returns The value, clamped.
50261
- * @example
50262
- * ```ts
50263
- * clamp(1.4); // 1
50264
- * clamp(Number.NaN); // 0
50265
- * ```
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.
50266
50456
  */
50267
- function clamp(value) {
50268
- if (Number.isNaN(value)) return 0;
50269
- 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);
50270
50480
  }
50271
50481
  /**
50272
- * 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.
50273
50483
  *
50274
- * @param state - The plugin state.
50275
- * @param bus - The bus name to check.
50276
- * @returns The bus.
50277
- * @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.
50278
50487
  */
50279
- function busOf(state, bus) {
50280
- if (!isBus(state, bus)) throw new Error(`[game] Audio bus "${bus}" does not exist.\n Use "master", "music" or "sfx".`);
50281
- 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
+ });
50282
50496
  }
50283
50497
  /**
50284
- * Stores the volume of one bus and schedules it. `setVolume` and the `model:committed` hook both
50285
- * 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.
50286
50524
  *
50287
50525
  * @param state - The plugin state.
50288
- * @param bus - The bus to change.
50289
- * @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.
50290
50529
  */
50291
- function setBusVolume(state, bus, value) {
50292
- state.buses[bus].volume = clamp(value);
50293
- applyGain(state, bus);
50530
+ function isSameLoop(state, id, key) {
50531
+ return state.loops.get(id)?.key === key;
50294
50532
  }
50295
50533
  /**
50296
- * 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`.
50297
50536
  *
50298
- * @param ctx - Kernel context of the audio plugin.
50299
- * @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.
50300
50540
  */
50301
- function createAudioApi(ctx) {
50302
- const state = ctx.state;
50303
- return {
50304
- setVolume: (bus, value) => setBusVolume(state, busOf(state, bus), value),
50305
- volume: (bus) => state.buses[busOf(state, bus)].volume,
50306
- mute: (bus, on) => {
50307
- const checked = busOf(state, bus);
50308
- state.buses[checked].muted = on;
50309
- applyGain(state, checked);
50310
- },
50311
- muted: (bus) => state.buses[busOf(state, bus)].muted,
50312
- unlocked: () => state.unlocked,
50313
- journal: () => state.journal,
50314
- stop: (id, options) => stopNamed(state, id, options?.fadeMs ?? ctx.config.sfxFadeMs)
50315
- };
50541
+ function stopIfLeaving(loop, id) {
50542
+ if (loop.scene === this.leaving.scene) stopNamed(this, id, this.leaving.fadeMs);
50316
50543
  }
50317
- //#endregion
50318
- //#region src/plugins/audio/journal.ts
50319
50544
  /**
50320
- * Replaces the journal with a frozen list that ends with one started sound, stamped with the
50321
- * elapsed game time, and keeps only the newest `config.journal` entries. A size of 0, or anything
50322
- * that is not a positive number, records nothing. The entry has an `id` only when the sound has
50323
- * 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.
50324
50548
  *
50325
- * @param ctx - Domain context of the plugin.
50326
- * @param sound - What started.
50327
- * @param sound.key - Asset key of the sound.
50328
- * @param sound.bus - The bus it plays on.
50329
- * @param sound.kind - `"sfx"` for a play, `"music"` for a track.
50330
- * @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.
50331
50552
  */
50332
- function recordSound(ctx, sound) {
50333
- const size = Math.floor(ctx.config.journal);
50334
- if (!Number.isFinite(size) || size <= 0) return;
50335
- const entry = {
50336
- ...sound,
50337
- at: ctx.deps.time.snapshot().elapsed
50338
- };
50339
- 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);
50340
50558
  }
50341
50559
  //#endregion
50342
50560
  //#region src/plugins/audio/stream.ts
@@ -50465,8 +50683,9 @@ function fadeOf(descriptor, fadeMs) {
50465
50683
  return validFade(fieldOf(descriptor.payload, "fadeMs"), fadeMs);
50466
50684
  }
50467
50685
  /**
50468
- * Takes a fade a descriptor named only when the clock can schedule it: a finite number, 0 or more.
50469
- * `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.
50470
50689
  *
50471
50690
  * @param fade - The `fadeMs` the payload carries.
50472
50691
  * @param fallback - The configured fade.
@@ -50480,7 +50699,8 @@ function validFade(fade, fallback) {
50480
50699
  return typeof fade === "number" && Number.isFinite(fade) && fade >= 0 ? fade : fallback;
50481
50700
  }
50482
50701
  /**
50483
- * 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.
50484
50704
  *
50485
50705
  * @param descriptor - The descriptor the handler was called with.
50486
50706
  * @param fadeMs - The configured fade of a named sound, used when the descriptor names none.
@@ -50495,7 +50715,8 @@ function sfxOf(descriptor, fadeMs) {
50495
50715
  key,
50496
50716
  bus: typeof bus === "string" ? bus : DEFAULT_BUS$1,
50497
50717
  id: typeof id === "string" ? id : void 0,
50498
- fadeMs: fadeOf(descriptor, fadeMs)
50718
+ fadeMs: fadeOf(descriptor, fadeMs),
50719
+ loop: fieldOf(descriptor.payload, "loop") === true
50499
50720
  };
50500
50721
  }
50501
50722
  /**
@@ -50513,74 +50734,28 @@ function musicOf(descriptor, fadeMs) {
50513
50734
  };
50514
50735
  }
50515
50736
  /**
50516
- * Warns about one key exactly once per run. A missing file is a mistake in the manifest, not a
50517
- * reason to flood the log of every frame that plays the sound.
50518
- *
50519
- * @param ctx - Domain context of the plugin.
50520
- * @param key - The asset key the warning is about.
50521
- * @param event - What happened.
50522
- */
50523
- function warnOnce$3(ctx, key, event) {
50524
- if (ctx.state.warned.has(key)) return;
50525
- ctx.state.warned.add(key);
50526
- ctx.log.warn(event, { key });
50527
- }
50528
- /**
50529
- * Decodes one key, at most once. The promise is cached before it settles, so two plays of the
50530
- * same sound in one frame decode a single time.
50531
- *
50532
- * @param ctx - Domain context of the plugin.
50533
- * @param key - Asset key of an audio file, `.mp3` or `.m4a`.
50534
- * @returns The pending buffer, or `undefined` when the bundle carries no such file.
50535
- */
50536
- function decode(ctx, key) {
50537
- const state = ctx.state;
50538
- const cached = state.decoded.get(key);
50539
- if (cached !== void 0) return cached;
50540
- const context = state.context;
50541
- if (context === void 0) return void 0;
50542
- const asset = ctx.deps.assets.audio(key);
50543
- if (asset === void 0) {
50544
- warnOnce$3(ctx, key, "audio: no audio for key");
50545
- return;
50546
- }
50547
- const pending = context.decodeAudioData(asset.bytes.slice(0));
50548
- state.decoded.set(key, pending);
50549
- return pending;
50550
- }
50551
- /**
50552
- * Awaits the decoded buffer of one key. A file that does not decode warns once and plays nothing.
50553
- *
50554
- * @param ctx - Domain context of the plugin.
50555
- * @param key - Asset key of an audio file, `.mp3` or `.m4a`.
50556
- * @returns The buffer, or `undefined` when there is nothing to play.
50557
- */
50558
- async function bufferOf(ctx, key) {
50559
- const pending = decode(ctx, key);
50560
- if (pending === void 0) return void 0;
50561
- try {
50562
- return await pending;
50563
- } catch {
50564
- warnOnce$3(ctx, key, "audio: the audio file did not decode");
50565
- return;
50566
- }
50567
- }
50568
- /**
50569
50737
  * Plays one sound: the handler of the kind `"sfx"`. Every play is its own source, so the same key
50570
50738
  * twice in one frame is heard twice, and the promise resolves when the sound STARTED. The handler
50571
50739
  * ignores its signal: a sound that began plays to its end, unless a sound with its id or a stop
50572
50740
  * ends it. While a gesture's `resume()` is pending the sound waits in `pendingSfx`, one per id
50573
50741
  * and one per key without an id. A locked context no gesture is resuming drops it: the start
50574
- * 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.
50575
50744
  *
50576
50745
  * @param ctx - Domain context of the plugin.
50577
50746
  * @param descriptor - The `sfx` descriptor `anim` built.
50578
50747
  */
50579
50748
  async function playSfx(ctx, descriptor) {
50580
50749
  const state = ctx.state;
50581
- if (state.context === void 0) return;
50750
+ if (state.context === void 0 && state.renewing === void 0) return;
50582
50751
  const request = sfxOf(descriptor, ctx.config.sfxFadeMs);
50583
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;
50584
50759
  if (!state.unlocked) {
50585
50760
  queueWhileResuming(state, request);
50586
50761
  return;
@@ -50611,42 +50786,6 @@ function stopNamedSfx(ctx, descriptor) {
50611
50786
  stopNamed(ctx.state, id, fadeOf(descriptor, ctx.config.sfxFadeMs));
50612
50787
  }
50613
50788
  /**
50614
- * Plays a sound under its id: the sound that has the id fades out over the fade of this one, and
50615
- * this one starts through its own gain once its buffer is there, unless a later sound with the id
50616
- * or a stop took its place while it decoded. A file that is missing frees the id.
50617
- *
50618
- * @param ctx - Domain context of the plugin.
50619
- * @param request - The key, the fade and the id of the sound.
50620
- * @param sound - The id and the bus, both checked.
50621
- * @param sound.id - The id the sound plays under.
50622
- * @param sound.bus - The bus it goes to.
50623
- */
50624
- async function playNamed(ctx, request, sound) {
50625
- const state = ctx.state;
50626
- const { id, bus } = sound;
50627
- const entry = claimNamed(state, id, request.fadeMs / 1e3);
50628
- const buffer = await bufferOf(ctx, request.key);
50629
- if (state.named.get(id) !== entry) return;
50630
- const context = state.context;
50631
- const gain = state.buses[bus].gain;
50632
- if (buffer === void 0 || context === void 0 || gain === void 0) {
50633
- state.named.delete(id);
50634
- return;
50635
- }
50636
- startNamed(state, context, {
50637
- id,
50638
- entry,
50639
- buffer,
50640
- bus: gain
50641
- });
50642
- recordSound(ctx, {
50643
- key: request.key,
50644
- bus,
50645
- kind: "sfx",
50646
- id
50647
- });
50648
- }
50649
- /**
50650
50789
  * Starts one source of a sound on its bus. `playSfx` calls it for a live play and the unlock for
50651
50790
  * every sound that waited for the resume. A sound with an id goes through `playNamed`.
50652
50791
  *
@@ -50662,9 +50801,13 @@ async function playRequest(ctx, request) {
50662
50801
  return;
50663
50802
  }
50664
50803
  if (request.id !== void 0) {
50665
- await playNamed(ctx, request, {
50804
+ const { key, bus, fadeMs } = request;
50805
+ await playNamed(ctx, {
50666
50806
  id: request.id,
50667
- bus: request.bus
50807
+ key,
50808
+ bus,
50809
+ fadeMs,
50810
+ loop: void 0
50668
50811
  });
50669
50812
  return;
50670
50813
  }
@@ -50953,6 +51096,74 @@ function trackMusic(ctx, pending) {
50953
51096
  });
50954
51097
  }
50955
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
50956
51167
  //#region src/plugins/audio/session.ts
50957
51168
  /**
50958
51169
  * Tells whether a value is an audio session the plugin can write: an object with a string `type`.
@@ -51051,10 +51262,11 @@ const UNLOCK_EVENTS = ["pointerdown", "touchend"];
51051
51262
  /**
51052
51263
  * Reacts to a resume that went through, of a gesture or of the start attempt. The context is
51053
51264
  * unlocked only when it really runs, and only then do the listeners come off; the sounds fired
51054
- * 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:
51055
51267
  * the next gesture is a new moment. A gesture and the start attempt that settle together both
51056
- * come here, and the music still starts once: a track that is on its way or already plays is not
51057
- * 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.
51058
51270
  *
51059
51271
  * @param ctx - Domain context of the plugin.
51060
51272
  */
@@ -51069,6 +51281,7 @@ function onResumed(ctx) {
51069
51281
  state.unlocked = true;
51070
51282
  removeUnlock(state);
51071
51283
  drainSfx(ctx);
51284
+ startLoops(ctx);
51072
51285
  const remembered = state.music;
51073
51286
  if (remembered === void 0 || isMusicPlaying(state)) return;
51074
51287
  trackMusic(ctx, playMusic(ctx, {
@@ -51274,7 +51487,8 @@ function cancelRenewal(state) {
51274
51487
  }
51275
51488
  /**
51276
51489
  * Drops every sound of the old context and keeps the music key: the track that plays, or the
51277
- * 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
51278
51492
  * key is forgotten, so its next play decodes again.
51279
51493
  *
51280
51494
  * @param state - The plugin state.
@@ -51298,9 +51512,9 @@ function dropInFlight(state) {
51298
51512
  /**
51299
51513
  * Renews the context: the old one goes with every sound in it, the session is written again, and
51300
51514
  * a new context gets the graph at the same volumes and the unlock. The decoded buffers stay, an
51301
- * AudioBuffer is bound to no context. The unlock starts the remembered music once the new context
51302
- * runs. While the old context closes the plugin is headless: a sound is dropped and a music switch
51303
- * 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.
51304
51518
  *
51305
51519
  * @param ctx - Domain context of the plugin.
51306
51520
  */
@@ -51393,10 +51607,11 @@ function startAudio(ctx) {
51393
51607
  }
51394
51608
  /**
51395
51609
  * Frees everything `onStart` opened: the three handler registrations, the two window listeners,
51396
- * a renewal that waits or runs, the music track, every named sound, every streamed track still
51397
- * fading with its timer, the journal, the audio session and the context itself. The tracks are
51398
- * freed before the close, while their nodes can still disconnect. A browser caps how many
51399
- * 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.
51400
51615
  *
51401
51616
  * @param state - The plugin state, all a teardown context carries.
51402
51617
  * @returns A promise that resolves when the context is closed.
@@ -51408,6 +51623,8 @@ async function stopAudio(state) {
51408
51623
  removeUnlock(state);
51409
51624
  stopMusic(state);
51410
51625
  stopAllNamed(state);
51626
+ state.loops.clear();
51627
+ state.scene = void 0;
51411
51628
  for (const entry of state.retiring) disposeStream(state, entry.stream);
51412
51629
  state.decoded.clear();
51413
51630
  state.journal = Object.freeze([]);
@@ -51540,13 +51757,17 @@ function createHandlers$3(ctx) {
51540
51757
  applyVolumes(domain());
51541
51758
  },
51542
51759
  /**
51543
- * Switches the music to the track the next scene declared. A scene that declares none keeps
51544
- * 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.
51545
51764
  *
51546
- * @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.
51547
51766
  */
51548
51767
  "scenes:changed": (payload) => {
51549
51768
  const audioCtx = domain();
51769
+ audioCtx.state.scene = payload.to;
51770
+ stopSceneLoops(audioCtx.state, payload.from, audioCtx.config.musicFadeMs);
51550
51771
  trackMusic(audioCtx, playMusic(audioCtx, {
51551
51772
  key: payload.music ?? audioCtx.state.music?.key ?? null,
51552
51773
  fadeMs: audioCtx.config.musicFadeMs
@@ -51629,6 +51850,14 @@ function emptyNamed() {
51629
51850
  return /* @__PURE__ */ new Map();
51630
51851
  }
51631
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
+ /**
51632
51861
  * Creates the set of streamed tracks that fade out.
51633
51862
  *
51634
51863
  * @returns An empty set of retiring tracks.
@@ -51674,6 +51903,12 @@ function createAudioState(ctx) {
51674
51903
  resuming: false,
51675
51904
  pendingSfx: emptyPending(),
51676
51905
  named: emptyNamed(),
51906
+ loops: emptyLoops(),
51907
+ scene: void 0,
51908
+ leaving: {
51909
+ scene: "",
51910
+ fadeMs: 0
51911
+ },
51677
51912
  decoded: emptyCache$1(),
51678
51913
  warned: emptyWarned$2(),
51679
51914
  warnedVolumes: false,
@@ -62393,27 +62628,6 @@ function spawn(id, components, options) {
62393
62628
  function spawned(id) {
62394
62629
  return Object.freeze({ spawned: id });
62395
62630
  }
62396
- /**
62397
- * A sound. `anim` owns the descriptor because it sits below `audio`; `audio` owns the handler,
62398
- * and a game without `audio` plays nothing and hears no error. A sound with an `id` is named:
62399
- * one sound plays per id, a new one with the same id fades the old one out over `fadeMs`, and
62400
- * `stopSfx(id)` stops it. The payload carries `id` and `fadeMs` only when they are given, so a
62401
- * sound without them stays `{ key, bus }`.
62402
- *
62403
- * @param key - Asset key of the sound.
62404
- * @param options - The bus, the name and the fade.
62405
- * @param options.bus - `"sfx"` when omitted.
62406
- * @param options.id - Name of the sound; one sound per id plays.
62407
- * @param options.fadeMs - Fade of the sound with the same id this one replaces; `audio`'s
62408
- * `sfxFadeMs` when omitted.
62409
- * @returns The descriptor, usable as a timeline step and as `fx(...)` in a node.
62410
- * @example
62411
- * ```ts
62412
- * sfx("board.merge"); // { kind: "sfx", payload: { key: "board.merge", bus: "sfx" }, cosmetic: true }
62413
- * sfx("voice.hello", { id: "voice", fadeMs: 200 });
62414
- * // { kind: "sfx", payload: { key: "voice.hello", bus: "sfx", id: "voice", fadeMs: 200 }, cosmetic: true }
62415
- * ```
62416
- */
62417
62631
  function sfx(key, options) {
62418
62632
  const payload = {
62419
62633
  key,
@@ -62421,6 +62635,7 @@ function sfx(key, options) {
62421
62635
  };
62422
62636
  if (options?.id !== void 0) payload.id = options.id;
62423
62637
  if (options?.fadeMs !== void 0) payload.fadeMs = options.fadeMs;
62638
+ if (options?.loop === true) payload.loop = true;
62424
62639
  return Object.freeze({
62425
62640
  kind: "sfx",
62426
62641
  payload: Object.freeze(payload),
@@ -79383,7 +79598,9 @@ var types_exports = /* @__PURE__ */ __exportAll({});
79383
79598
  * Binds `frames`, `sfx` and `Frames` to one game's asset keys. Type-only: the same functions and
79384
79599
  * the same component object.
79385
79600
  *
79386
- * @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.
79387
79604
  * @example
79388
79605
  * ```ts
79389
79606
  * const { sfx } = animFor<"board.merge">();