@bendyline/molen-client 0.0.1 → 0.0.3

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.
package/dist/audio.mjs ADDED
@@ -0,0 +1,1740 @@
1
+ import { AUDIO_BUSES, audioSignalBindings, audioSignalIssues, audioSignalRefs, nearestWithDistance, resolveWeather, validate } from "@bendyline/molen-schema";
2
+ //#region src/audio/adapters.ts
3
+ /**
4
+ * Entity source over a kernel-linked client. Reads are memoized per mirrored tick, because
5
+ * `client.get` returns a detached copy and the mirror only changes when a new tick arrives.
6
+ */
7
+ function entitySourceFromClient(client, opts = {}) {
8
+ let memoTick = NaN;
9
+ const rows = /* @__PURE__ */ new Map();
10
+ const reads = /* @__PURE__ */ new Map();
11
+ const fresh = () => {
12
+ if (client.tick !== memoTick) {
13
+ memoTick = client.tick;
14
+ rows.clear();
15
+ reads.clear();
16
+ }
17
+ };
18
+ const get = (id, component) => {
19
+ fresh();
20
+ const key = `${id}\u0000${component}`;
21
+ if (!reads.has(key)) reads.set(key, client.get(id, component));
22
+ return reads.get(key);
23
+ };
24
+ return {
25
+ get tick() {
26
+ return client.tick;
27
+ },
28
+ ...opts.tickRate !== void 0 ? { tickRate: opts.tickRate } : {},
29
+ each(component) {
30
+ fresh();
31
+ let list = rows.get(component);
32
+ if (!list) {
33
+ list = [];
34
+ for (const id of client.entities()) {
35
+ const data = get(id, component);
36
+ if (data !== void 0) list.push([id, data]);
37
+ }
38
+ rows.set(component, list);
39
+ }
40
+ return list;
41
+ },
42
+ get,
43
+ onEvent: (cb) => client.onEvent("*", cb)
44
+ };
45
+ }
46
+ /** Entity source over a main-thread `World` (EarthVehicles, headless tooling). */
47
+ function entitySourceFromWorld(world) {
48
+ const handles = /* @__PURE__ */ new Map();
49
+ const handle = (name) => {
50
+ let h = handles.get(name);
51
+ if (!h) {
52
+ h = { name };
53
+ handles.set(name, h);
54
+ }
55
+ return h;
56
+ };
57
+ return {
58
+ get tick() {
59
+ return world.tick;
60
+ },
61
+ get tickRate() {
62
+ return world.tickRate;
63
+ },
64
+ *each(component) {
65
+ for (const [id, data] of world.query(handle(component))) yield [id, data];
66
+ },
67
+ get: (id, component) => world.get(id, handle(component)),
68
+ onEvent: (cb) => world.on("*", (event, ctx) => cb(event, ctx.tick))
69
+ };
70
+ }
71
+ //#endregion
72
+ //#region src/audio/bank.ts
73
+ function joinRef(base, clip) {
74
+ if (base === void 0 || base === "") return clip;
75
+ return base.endsWith("/") ? `${base}${clip}` : `${base}/${clip}`;
76
+ }
77
+ /** Merge banks; a later bank's sound replaces an earlier one with the same id (reskinning). */
78
+ function mergeSoundbanks(inputs) {
79
+ const sounds = /* @__PURE__ */ new Map();
80
+ for (const input of inputs) {
81
+ const { doc, base } = "doc" in input ? input : {
82
+ doc: input,
83
+ base: void 0
84
+ };
85
+ for (const [id, entry] of Object.entries(doc.sounds)) sounds.set(id, {
86
+ id,
87
+ entry,
88
+ refs: entry.clips.map((c) => joinRef(base, c)),
89
+ bank: doc.id
90
+ });
91
+ }
92
+ const ids = [...sounds.keys()].sort();
93
+ return {
94
+ resolve: (id) => sounds.get(id),
95
+ ids: () => ids
96
+ };
97
+ }
98
+ /** 32-bit string/number hash (FNV-1a + fmix32); deterministic across hosts. */
99
+ function hash32(...parts) {
100
+ let h = 2166136261;
101
+ for (const part of parts) {
102
+ const s = typeof part === "number" ? `#${part}` : `|${part}`;
103
+ for (let i = 0; i < s.length; i++) {
104
+ h ^= s.charCodeAt(i);
105
+ h = Math.imul(h, 16777619);
106
+ }
107
+ }
108
+ h ^= h >>> 16;
109
+ h = Math.imul(h, 2246822507);
110
+ h ^= h >>> 13;
111
+ h = Math.imul(h, 3266489909);
112
+ h ^= h >>> 16;
113
+ return h >>> 0;
114
+ }
115
+ /** Deterministic [0, 1) from any key parts. */
116
+ function unitRandom(...parts) {
117
+ return hash32(...parts) / 4294967296;
118
+ }
119
+ //#endregion
120
+ //#region src/audio/signals.ts
121
+ function walk(value, path) {
122
+ let cur = value;
123
+ for (const key of path) {
124
+ if (cur === null || typeof cur !== "object") return void 0;
125
+ cur = Array.isArray(cur) ? cur[Number(key)] : cur[key];
126
+ }
127
+ return cur;
128
+ }
129
+ function scalar(v) {
130
+ return typeof v === "number" || typeof v === "string" || typeof v === "boolean" ? v : void 0;
131
+ }
132
+ const RAD_TO_DEG = 180 / Math.PI;
133
+ /** Resolve a signal path to a scalar, or undefined when it has no value here. */
134
+ function resolveSignal(path, ctx) {
135
+ const dot = path.indexOf(".");
136
+ const head = dot < 0 ? path : path.slice(0, dot);
137
+ const rest = dot < 0 ? "" : path.slice(dot + 1);
138
+ const l = ctx.listener;
139
+ switch (head) {
140
+ case "listener": switch (rest) {
141
+ case "x": return l.position[0];
142
+ case "y":
143
+ case "altitude": return l.position[1];
144
+ case "z": return l.position[2];
145
+ case "speed": return l.speed;
146
+ case "distance": return l.distance;
147
+ case "mode": return l.mode;
148
+ case "grounded": return l.grounded ?? true;
149
+ case "surface": return l.surface;
150
+ case "heightAboveGround": return l.heightAboveGround ?? 0;
151
+ case "indoors": return l.indoors ?? false;
152
+ default: return;
153
+ }
154
+ case "weather": {
155
+ const w = resolveWeather(ctx.signals.weather ?? weatherFromSource(ctx.source));
156
+ if (rest === "windSpeed") {
157
+ const [x, y, z] = w.atmosphere.windVelocity;
158
+ return Math.hypot(x, y, z);
159
+ }
160
+ return scalar(walk(w, rest.split(".")));
161
+ }
162
+ case "sky": {
163
+ const sky = ctx.signals.sky;
164
+ if (rest === "daylight") return sky?.daylight ?? 1;
165
+ if (rest === "starVisibility") return sky?.starVisibility ?? 0;
166
+ if (rest === "sunElevation") {
167
+ const d = sky?.sunDirection;
168
+ if (!d) return 45;
169
+ const len = Math.hypot(d[0], d[1], d[2]) || 1;
170
+ return Math.asin(Math.max(-1, Math.min(1, d[1] / len))) * RAD_TO_DEG;
171
+ }
172
+ return;
173
+ }
174
+ case "time": return rest === "seconds" ? ctx.seconds : void 0;
175
+ case "host": return ctx.signals.host?.[rest];
176
+ case "self": {
177
+ if (rest === "occupied") return ctx.entity !== void 0 && ctx.occupied.has(ctx.entity);
178
+ const m = ctx.entity !== void 0 ? ctx.motion.get(ctx.entity) : void 0;
179
+ if (!m) return void 0;
180
+ if (rest === "speed") return m.speed;
181
+ if (rest === "distance") return m.distance;
182
+ if (rest === "x") return m.pos[0];
183
+ if (rest === "y") return m.pos[1];
184
+ if (rest === "z") return m.pos[2];
185
+ return;
186
+ }
187
+ default: {
188
+ if (ctx.entity === void 0 || ctx.source === void 0 || rest === "") return void 0;
189
+ const data = ctx.source.get(ctx.entity, head);
190
+ return data === void 0 ? void 0 : scalar(walk(data, rest.split(".")));
191
+ }
192
+ }
193
+ }
194
+ function weatherFromSource(source) {
195
+ if (!source) return void 0;
196
+ for (const [, data] of source.each("weather")) return data;
197
+ }
198
+ /** Margin (fraction of a range's span) that keeps an active rule active near its edges. */
199
+ const HYSTERESIS_MARGIN = .05;
200
+ function holds(cond, v, active) {
201
+ if (Array.isArray(cond)) return v !== void 0 && cond.includes(v);
202
+ if (cond !== null && typeof cond === "object") {
203
+ if ("exists" in cond) return v !== void 0 === cond.exists;
204
+ if (typeof v !== "number") return false;
205
+ const { min, max } = cond;
206
+ let m = 0;
207
+ if (active) m = (min !== void 0 && max !== void 0 ? max - min : Math.max(Math.abs(min ?? max ?? 0), 1e-6)) * HYSTERESIS_MARGIN;
208
+ return (min === void 0 || v >= min - m) && (max === void 0 || v <= max + m);
209
+ }
210
+ return v === cond;
211
+ }
212
+ /** Every condition must hold (AND). `active` widens numeric ranges (hysteresis). */
213
+ function evalWhen(when, ctx, active = false) {
214
+ if (!when) return true;
215
+ for (const [signal, cond] of Object.entries(when)) if (!holds(cond, resolveSignal(signal, ctx), active)) return false;
216
+ return true;
217
+ }
218
+ /** Piecewise-linear lookup over [input, output] points, clamped at both ends. */
219
+ function curve(points, x) {
220
+ if (points.length === 0) return 1;
221
+ const sorted = points.length > 1 ? [...points].sort((a, b) => a[0] - b[0]) : points;
222
+ const first = sorted[0];
223
+ const last = sorted[sorted.length - 1];
224
+ if (!(x > first[0])) return first[1];
225
+ if (x >= last[0]) return last[1];
226
+ for (let i = 1; i < sorted.length; i++) {
227
+ const b = sorted[i];
228
+ if (x <= b[0]) {
229
+ const a = sorted[i - 1];
230
+ const t = b[0] === a[0] ? 1 : (x - a[0]) / (b[0] - a[0]);
231
+ return a[1] + (b[1] - a[1]) * t;
232
+ }
233
+ }
234
+ return last[1];
235
+ }
236
+ /** Rising/falling edge gate: a rule turns on after `enterMs` true and off after `exitMs` false. */
237
+ var Gate = class {
238
+ enterMs;
239
+ exitMs;
240
+ active = false;
241
+ started = false;
242
+ since;
243
+ constructor(enterMs = 250, exitMs = 1e3) {
244
+ this.enterMs = enterMs;
245
+ this.exitMs = exitMs;
246
+ }
247
+ update(raw, nowMs) {
248
+ if (!this.started) {
249
+ this.started = true;
250
+ this.active = raw;
251
+ return raw;
252
+ }
253
+ if (raw === this.active) {
254
+ this.since = void 0;
255
+ return this.active;
256
+ }
257
+ this.since ??= nowMs;
258
+ if (nowMs - this.since >= (raw ? this.enterMs : this.exitMs)) {
259
+ this.active = raw;
260
+ this.since = void 0;
261
+ }
262
+ return this.active;
263
+ }
264
+ };
265
+ //#endregion
266
+ //#region src/audio/director.ts
267
+ const DEFAULT_SPATIAL = {
268
+ refDistance: 1,
269
+ maxDistance: 60,
270
+ rolloff: 1,
271
+ model: "inverse"
272
+ };
273
+ const ONE_SHOT_MIN_INTERVAL_MS = 30;
274
+ const TELEPORT_SPEED = 400;
275
+ function num(v) {
276
+ if (typeof v === "number") return v;
277
+ if (typeof v === "boolean") return v ? 1 : 0;
278
+ return 0;
279
+ }
280
+ function vec3(v) {
281
+ return Array.isArray(v) && v.length === 3 && v.every((x) => typeof x === "number") ? [
282
+ v[0],
283
+ v[1],
284
+ v[2]
285
+ ] : void 0;
286
+ }
287
+ function dist(a, b) {
288
+ return Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
289
+ }
290
+ function spatialOf(s) {
291
+ return {
292
+ refDistance: s.refDistance ?? DEFAULT_SPATIAL.refDistance,
293
+ maxDistance: s.maxDistance ?? DEFAULT_SPATIAL.maxDistance,
294
+ rolloff: s.rolloff ?? DEFAULT_SPATIAL.rolloff,
295
+ model: s.model ?? DEFAULT_SPATIAL.model
296
+ };
297
+ }
298
+ /** Approximate audible gain after distance attenuation, for budgeting only. */
299
+ function audibility(gain, spatial, d) {
300
+ if (!spatial) return gain;
301
+ const ref = spatial.refDistance;
302
+ return gain * ref / (ref + spatial.rolloff * Math.max(0, d - ref));
303
+ }
304
+ /** Vehicles someone is riding: every `mounted` component names one. */
305
+ function occupiedBy(source) {
306
+ const out = /* @__PURE__ */ new Set();
307
+ if (!source) return out;
308
+ for (const [, mounted] of source.each("mounted")) if (typeof mounted.vehicle === "string") out.add(mounted.vehicle);
309
+ return out;
310
+ }
311
+ var AudioDirector = class {
312
+ bank;
313
+ hostEnvironment;
314
+ maxOneShots;
315
+ seed;
316
+ onWarning;
317
+ live = /* @__PURE__ */ new Map();
318
+ oneShots = [];
319
+ scriptLoops = /* @__PURE__ */ new Map();
320
+ stopFades = /* @__PURE__ */ new Map();
321
+ gates = /* @__PURE__ */ new Map();
322
+ motion = /* @__PURE__ */ new Map();
323
+ firedOnce = /* @__PURE__ */ new Set();
324
+ startTickFired = /* @__PURE__ */ new Map();
325
+ triggers = /* @__PURE__ */ new Map();
326
+ lastFire = /* @__PURE__ */ new Map();
327
+ lastClip = /* @__PURE__ */ new Map();
328
+ busGains = /* @__PURE__ */ new Map();
329
+ events = [];
330
+ warned = /* @__PURE__ */ new Set();
331
+ warningList = [];
332
+ checked = /* @__PURE__ */ new WeakSet();
333
+ musicState;
334
+ musicOverride;
335
+ listenerState;
336
+ footAcc = 0;
337
+ footLast;
338
+ startMs;
339
+ lastNow;
340
+ frame = 0;
341
+ serial = 0;
342
+ hostHandles = 0;
343
+ constructor(opts) {
344
+ this.bank = opts.bank;
345
+ this.hostEnvironment = opts.environment;
346
+ this.maxOneShots = opts.maxOneShots ?? 16;
347
+ this.seed = opts.seed ?? "molen-audio";
348
+ this.onWarning = opts.onWarning;
349
+ }
350
+ setBank(bank) {
351
+ this.bank = bank;
352
+ }
353
+ setEnvironment(environment) {
354
+ this.hostEnvironment = environment;
355
+ }
356
+ /** Queue an engine event (`audio.play|stop|music` or a type mapped under `events`). */
357
+ handleEvent(event, tick = 0) {
358
+ if (this.events.length >= 256) this.events.shift();
359
+ this.events.push({
360
+ event,
361
+ tick
362
+ });
363
+ }
364
+ /** Host-side one-shot or loop (UI clicks, host-owned engines). Returns a handle for `stop`. */
365
+ play(sound, opts = {}) {
366
+ const handle = `host:${sound}#${this.hostHandles++}`;
367
+ this.handleEvent({
368
+ type: "audio.play",
369
+ payload: {
370
+ handle,
371
+ sound,
372
+ ...opts
373
+ }
374
+ });
375
+ return handle;
376
+ }
377
+ stop(target, fadeS) {
378
+ const payload = typeof target === "string" ? { handle: target } : { ...target };
379
+ if (fadeS !== void 0) payload.fadeS = fadeS;
380
+ this.handleEvent({
381
+ type: "audio.stop",
382
+ payload
383
+ });
384
+ }
385
+ music(playlist, opts = {}) {
386
+ const payload = { playlist: playlist === null ? null : Array.isArray(playlist) ? playlist : [playlist] };
387
+ if (opts.crossfadeS !== void 0) payload.crossfadeS = opts.crossfadeS;
388
+ this.handleEvent({
389
+ type: "audio.music",
390
+ payload
391
+ });
392
+ }
393
+ /** Persistent voices currently alive (loops, ambience, zones, music). */
394
+ voices() {
395
+ const out = [...this.live.values()].map((v) => ({
396
+ key: v.key,
397
+ voice: v.voice,
398
+ sound: v.sound,
399
+ bus: v.bus,
400
+ gain: v.gain,
401
+ pitch: v.pitch,
402
+ loop: v.loop,
403
+ ...v.position ? { position: v.position } : {},
404
+ ...v.entity !== void 0 ? { entity: v.entity } : {}
405
+ }));
406
+ if (this.musicState?.voice && this.musicState.sound) out.push({
407
+ key: "music",
408
+ voice: this.musicState.voice,
409
+ sound: this.musicState.sound,
410
+ bus: "music",
411
+ gain: 1,
412
+ pitch: 1,
413
+ loop: this.musicState.endsAt === void 0
414
+ });
415
+ return out;
416
+ }
417
+ warnings() {
418
+ return this.warningList;
419
+ }
420
+ /** Stop everything (fading) and forget all state except warnings. */
421
+ reset(fadeS = .2) {
422
+ const cmds = [];
423
+ for (const v of this.live.values()) cmds.push({
424
+ op: "stop",
425
+ voice: v.voice,
426
+ fadeS
427
+ });
428
+ for (const s of this.oneShots) cmds.push({
429
+ op: "stop",
430
+ voice: s.voice,
431
+ fadeS
432
+ });
433
+ if (this.musicState?.voice) cmds.push({
434
+ op: "stop",
435
+ voice: this.musicState.voice,
436
+ fadeS
437
+ });
438
+ this.live.clear();
439
+ this.oneShots.length = 0;
440
+ this.scriptLoops.clear();
441
+ this.musicState = void 0;
442
+ this.musicOverride = void 0;
443
+ this.events.length = 0;
444
+ this.gates.clear();
445
+ return cmds;
446
+ }
447
+ update(input) {
448
+ const now = input.nowMs;
449
+ this.startMs ??= now;
450
+ const dtMs = this.lastNow === void 0 ? 0 : Math.min(250, Math.max(0, now - this.lastNow));
451
+ this.lastNow = now;
452
+ const source = input.source;
453
+ const tick = source?.tick ?? this.frame;
454
+ this.frame++;
455
+ const listener = this.measureListener(input.listener, dtMs);
456
+ const env = this.environmentFor(source);
457
+ this.measureEntities(source, dtMs);
458
+ const ctx = {
459
+ listener,
460
+ signals: input.signals ?? {},
461
+ source,
462
+ entity: env?.listenerEntity,
463
+ motion: this.motion,
464
+ occupied: occupiedBy(source),
465
+ seconds: (now - this.startMs) / 1e3
466
+ };
467
+ const cmds = [{
468
+ op: "listener",
469
+ position: listener.position,
470
+ forward: listener.forward,
471
+ up: listener.up
472
+ }];
473
+ this.syncBuses(env, cmds);
474
+ const desired = [];
475
+ this.processEvents(env, ctx, now, tick, cmds);
476
+ this.collectAmbience(env, ctx, now, desired);
477
+ this.collectZones(ctx, now, desired);
478
+ this.collectSources(ctx, now, tick, desired, cmds);
479
+ this.collectScriptLoops(ctx, desired);
480
+ this.footsteps(env, ctx, now, tick, cmds);
481
+ this.updateMusic(env, ctx, now, cmds);
482
+ this.reconcile(desired, env, listener, tick, cmds);
483
+ this.pruneOneShots(now);
484
+ return cmds;
485
+ }
486
+ measureListener(partial, dtMs) {
487
+ const prev = this.listenerState;
488
+ const position = partial?.position ?? prev?.position ?? [
489
+ 0,
490
+ 0,
491
+ 0
492
+ ];
493
+ let distance = prev?.distance ?? 0;
494
+ let measured = prev?.speed ?? 0;
495
+ if (prev && dtMs > 0) {
496
+ const d = dist(position, prev.position);
497
+ if (d <= Math.max(5, TELEPORT_SPEED * dtMs / 1e3)) {
498
+ distance += d;
499
+ measured = measured + (d / (dtMs / 1e3) - measured) * .3;
500
+ }
501
+ }
502
+ const velocity = partial?.velocity;
503
+ const speed = partial?.speed ?? (velocity ? Math.hypot(...velocity) : measured);
504
+ const next = {
505
+ position,
506
+ forward: partial?.forward ?? prev?.forward ?? [
507
+ 0,
508
+ 0,
509
+ -1
510
+ ],
511
+ up: partial?.up ?? prev?.up ?? [
512
+ 0,
513
+ 1,
514
+ 0
515
+ ],
516
+ speed,
517
+ distance,
518
+ ...velocity ? { velocity } : {},
519
+ ...partial?.mode !== void 0 ? { mode: partial.mode } : {},
520
+ ...partial?.grounded !== void 0 ? { grounded: partial.grounded } : {},
521
+ ...partial?.surface !== void 0 ? { surface: partial.surface } : {},
522
+ ...partial?.indoors !== void 0 ? { indoors: partial.indoors } : {},
523
+ ...partial?.heightAboveGround !== void 0 ? { heightAboveGround: partial.heightAboveGround } : {}
524
+ };
525
+ this.listenerState = {
526
+ ...next,
527
+ speed: partial?.speed ?? measured
528
+ };
529
+ return next;
530
+ }
531
+ measureEntities(source, dtMs) {
532
+ if (!source) {
533
+ this.motion.clear();
534
+ return;
535
+ }
536
+ const seen = /* @__PURE__ */ new Set();
537
+ for (const [id] of source.each("audioSource")) {
538
+ const pos = this.entityPos(source, id);
539
+ if (!pos) continue;
540
+ seen.add(id);
541
+ const prev = this.motion.get(id);
542
+ if (!prev) {
543
+ this.motion.set(id, {
544
+ pos,
545
+ speed: 0,
546
+ distance: 0
547
+ });
548
+ continue;
549
+ }
550
+ let { speed, distance } = prev;
551
+ if (dtMs > 0) {
552
+ const d = dist(pos, prev.pos);
553
+ if (d <= Math.max(5, TELEPORT_SPEED * dtMs / 1e3)) {
554
+ distance += d;
555
+ speed += (d / (dtMs / 1e3) - speed) * .3;
556
+ }
557
+ }
558
+ this.motion.set(id, {
559
+ pos,
560
+ speed,
561
+ distance
562
+ });
563
+ }
564
+ for (const id of this.motion.keys()) if (!seen.has(id)) this.motion.delete(id);
565
+ }
566
+ environmentFor(source) {
567
+ let scene;
568
+ if (source) for (const [, data] of source.each("audioEnvironment")) {
569
+ scene = data;
570
+ break;
571
+ }
572
+ const env = scene && this.hostEnvironment ? {
573
+ ...this.hostEnvironment,
574
+ ...scene
575
+ } : scene ?? this.hostEnvironment;
576
+ if (env) this.checkSignals("audioEnvironment", env, "audioEnvironment");
577
+ return env;
578
+ }
579
+ entityPos(source, id) {
580
+ return vec3(source?.get(id, "transform")?.pos);
581
+ }
582
+ warn(key, message) {
583
+ if (this.warned.has(key)) return;
584
+ this.warned.add(key);
585
+ this.warningList.push(message);
586
+ this.onWarning?.(message);
587
+ }
588
+ sound(id, where) {
589
+ const found = this.bank.resolve(id);
590
+ if (!found) {
591
+ const near = nearestWithDistance(id, [...this.bank.ids()]);
592
+ this.warn(`sound:${id}`, `unknown sound "${id}" (${where})${near ? `; did you mean "${near.candidate}"?` : ""}`);
593
+ }
594
+ return found;
595
+ }
596
+ checkSignals(component, data, where) {
597
+ if (this.checked.has(data)) return;
598
+ this.checked.add(data);
599
+ for (const ref of audioSignalRefs(component, data)) for (const issue of audioSignalIssues(ref.signal)) this.warn(`signal:${ref.signal}`, `${where}${ref.path}: ${issue.message}${issue.hint ? ` (${issue.hint})` : ""}`);
600
+ }
601
+ gate(key) {
602
+ let g = this.gates.get(key);
603
+ if (!g) {
604
+ g = new Gate();
605
+ this.gates.set(key, g);
606
+ }
607
+ return g;
608
+ }
609
+ /** A drive's value: the product of its bindings' curves (1 when there is none). */
610
+ bound(drive, ctx) {
611
+ let value = 1;
612
+ for (const b of audioSignalBindings(drive)) value *= curve(b.curve, num(resolveSignal(b.signal, ctx)));
613
+ return value;
614
+ }
615
+ /** The smoothing time of the first binding that sets one. */
616
+ smoothing(fallback, ...drives) {
617
+ for (const drive of drives) for (const b of audioSignalBindings(drive)) if (b.smoothS !== void 0) return b.smoothS;
618
+ return fallback;
619
+ }
620
+ spatialFor(override, sound, position) {
621
+ if (!position) return void 0;
622
+ const pick = override ?? sound.entry.spatial;
623
+ if (pick === false) return void 0;
624
+ return pick ? spatialOf(pick) : DEFAULT_SPATIAL;
625
+ }
626
+ pickClip(sound, ...parts) {
627
+ const n = sound.refs.length;
628
+ if (n <= 1) return 0;
629
+ let i = Math.floor(unitRandom(this.seed, sound.id, ...parts) * n);
630
+ if (i === this.lastClip.get(sound.id)) i = (i + 1) % n;
631
+ this.lastClip.set(sound.id, i);
632
+ return i;
633
+ }
634
+ basePitch(sound, ...parts) {
635
+ const [lo, hi] = sound.entry.pitch ?? [1, 1];
636
+ return lo === hi ? lo : lo + (hi - lo) * unitRandom(this.seed, "pitch", sound.id, ...parts);
637
+ }
638
+ fireOneShot(shot, listener, now, tick, cmds) {
639
+ const { sound } = shot;
640
+ const last = this.lastFire.get(sound.id);
641
+ if (last !== void 0 && now - last < ONE_SHOT_MIN_INTERVAL_MS) return;
642
+ if (shot.spatial && shot.position) {
643
+ if (dist(shot.position, listener.position) > shot.spatial.maxDistance) return;
644
+ }
645
+ this.lastFire.set(sound.id, now);
646
+ while (this.oneShots.length >= this.maxOneShots) {
647
+ const oldest = this.oneShots.shift();
648
+ if (oldest) cmds.push({
649
+ op: "stop",
650
+ voice: oldest.voice,
651
+ fadeS: .05
652
+ });
653
+ }
654
+ const clip = this.pickClip(sound, tick, shot.key);
655
+ const pitch = this.basePitch(sound, tick, shot.key) * shot.pitchMul;
656
+ const voice = `shot:${this.serial++}`;
657
+ const { entry } = sound;
658
+ cmds.push({
659
+ op: "start",
660
+ voice,
661
+ sound: sound.id,
662
+ ref: sound.refs[clip],
663
+ loop: false,
664
+ gain: shot.gain,
665
+ pitch,
666
+ bus: shot.bus,
667
+ ...shot.spatial && shot.position ? { spatial: {
668
+ ...shot.spatial,
669
+ position: shot.position
670
+ } } : {}
671
+ });
672
+ const lengthS = (entry.durationS ?? 5) / Math.max(.05, pitch);
673
+ this.oneShots.push({
674
+ voice,
675
+ sound: sound.id,
676
+ endsAt: now + lengthS * 1e3 + 100,
677
+ ...shot.handle !== void 0 ? { handle: shot.handle } : {},
678
+ ...shot.entity !== void 0 ? { entity: shot.entity } : {}
679
+ });
680
+ }
681
+ pruneOneShots(now) {
682
+ for (let i = this.oneShots.length - 1; i >= 0; i--) if (this.oneShots[i].endsAt <= now) this.oneShots.splice(i, 1);
683
+ }
684
+ syncBuses(env, cmds) {
685
+ const wanted = env?.buses ?? {};
686
+ const names = new Set([...this.busGains.keys(), ...Object.keys(wanted)]);
687
+ for (const bus of names) {
688
+ const gain = wanted[bus] ?? 1;
689
+ if (this.busGains.get(bus) !== gain) {
690
+ this.busGains.set(bus, gain);
691
+ cmds.push({
692
+ op: "bus",
693
+ bus,
694
+ gain
695
+ });
696
+ }
697
+ }
698
+ }
699
+ collectAmbience(env, ctx, now, desired) {
700
+ (env?.ambience ?? []).forEach((layer, i) => {
701
+ const key = `amb:${i}:${layer.sound}`;
702
+ const gate = this.gate(key);
703
+ if (!gate.update(evalWhen(layer.when, ctx, gate.active), now)) return;
704
+ const sound = this.sound(layer.sound, `audioEnvironment.ambience[${i}]`);
705
+ if (!sound) return;
706
+ const gain = (sound.entry.gain ?? 1) * (layer.gain ?? 1) * this.bound(layer.gainFrom, ctx);
707
+ if (gain < (this.live.has(key) ? .002 : .01)) return;
708
+ const fade = layer.fadeS ?? 1.5;
709
+ desired.push({
710
+ key,
711
+ sound,
712
+ loop: true,
713
+ gain,
714
+ pitchMul: this.bound(layer.pitchFrom, ctx),
715
+ bus: sound.entry.bus ?? "ambience",
716
+ fadeInS: fade,
717
+ fadeOutS: fade,
718
+ rampS: this.smoothing(.3, layer.gainFrom, layer.pitchFrom),
719
+ priority: 1
720
+ });
721
+ });
722
+ }
723
+ collectZones(ctx, now, desired) {
724
+ const source = ctx.source;
725
+ if (!source) return;
726
+ const p = ctx.listener.position;
727
+ for (const [id, data] of source.each("audioZone")) {
728
+ const zone = data;
729
+ this.checkSignals("audioZone", zone, `entity "${id}" audioZone`);
730
+ const key = `zone:${id}`;
731
+ const c = this.entityPos(source, id) ?? [
732
+ 0,
733
+ 0,
734
+ 0
735
+ ];
736
+ let outside;
737
+ if (zone.shape.kind === "sphere") outside = dist(p, c) - zone.shape.radius;
738
+ else {
739
+ const h = zone.shape.halfExtents;
740
+ const dx = Math.max(0, Math.abs(p[0] - c[0]) - h[0]);
741
+ const dy = Math.max(0, Math.abs(p[1] - c[1]) - h[1]);
742
+ const dz = Math.max(0, Math.abs(p[2] - c[2]) - h[2]);
743
+ outside = Math.hypot(dx, dy, dz);
744
+ }
745
+ const fade = zone.fade ?? 5;
746
+ const factor = outside <= 0 ? 1 : fade <= 0 ? 0 : Math.max(0, 1 - outside / fade);
747
+ const gate = this.gate(key);
748
+ const entityCtx = {
749
+ ...ctx,
750
+ entity: id
751
+ };
752
+ if (!gate.update(evalWhen(zone.when, entityCtx, gate.active), now)) continue;
753
+ const sound = this.sound(zone.sound, `entity "${id}" audioZone`);
754
+ if (!sound) continue;
755
+ const gain = (sound.entry.gain ?? 1) * (zone.gain ?? 1) * factor;
756
+ if (gain < (this.live.has(key) ? .002 : .01)) continue;
757
+ desired.push({
758
+ key,
759
+ sound,
760
+ loop: true,
761
+ gain,
762
+ pitchMul: 1,
763
+ bus: zone.bus ?? sound.entry.bus ?? "ambience",
764
+ fadeInS: 1,
765
+ fadeOutS: 1,
766
+ rampS: .3,
767
+ priority: 1,
768
+ entity: id
769
+ });
770
+ }
771
+ }
772
+ collectSources(ctx, now, tick, desired, cmds) {
773
+ const source = ctx.source;
774
+ const seen = /* @__PURE__ */ new Set();
775
+ if (source) {
776
+ const lateTicks = source.tickRate ?? 30;
777
+ for (const [id, data] of source.each("audioSource")) {
778
+ const d = data;
779
+ seen.add(id);
780
+ this.checkSignals("audioSource", d, `entity "${id}" audioSource`);
781
+ const sound = this.sound(d.sound, `entity "${id}" audioSource`);
782
+ if (!sound) continue;
783
+ const key = `src:${id}`;
784
+ const entityCtx = {
785
+ ...ctx,
786
+ entity: id
787
+ };
788
+ const gate = this.gate(key);
789
+ const active = gate.update(evalWhen(d.when, entityCtx, gate.active), now);
790
+ const position = this.entityPos(source, id);
791
+ const spatial = this.spatialFor(d.spatial, sound, position);
792
+ const gain = (sound.entry.gain ?? 1) * (d.gain ?? 1) * this.bound(d.gainFrom, entityCtx);
793
+ const pitchMul = (d.pitch ?? 1) * this.bound(d.pitchFrom, entityCtx);
794
+ const bus = d.bus ?? sound.entry.bus ?? "sfx";
795
+ const loop = d.loop ?? sound.entry.loop ?? false;
796
+ const autoplay = d.autoplay ?? true;
797
+ const shotBase = {
798
+ gain,
799
+ pitchMul,
800
+ bus,
801
+ entity: id,
802
+ ...spatial ? { spatial } : {},
803
+ ...position ? { position } : {}
804
+ };
805
+ const audible = gain >= (this.live.has(key) ? .002 : .01);
806
+ if (loop && autoplay && active && audible) desired.push({
807
+ key,
808
+ sound,
809
+ loop: true,
810
+ gain,
811
+ pitchMul,
812
+ bus,
813
+ fadeInS: .3,
814
+ fadeOutS: .5,
815
+ rampS: this.smoothing(.15, d.pitchFrom, d.gainFrom),
816
+ priority: 3,
817
+ entity: id,
818
+ ...spatial ? { spatial } : {},
819
+ ...position ? { position } : {}
820
+ });
821
+ if (!loop && autoplay && active && !this.firedOnce.has(id)) {
822
+ this.firedOnce.add(id);
823
+ this.fireOneShot({
824
+ ...shotBase,
825
+ sound,
826
+ key
827
+ }, ctx.listener, now, tick, cmds);
828
+ }
829
+ if (d.startTick !== void 0 && this.startTickFired.get(id) !== d.startTick) {
830
+ if (tick >= d.startTick) {
831
+ this.startTickFired.set(id, d.startTick);
832
+ if (tick - d.startTick <= lateTicks) this.fireOneShot({
833
+ ...shotBase,
834
+ sound,
835
+ key
836
+ }, ctx.listener, now, tick, cmds);
837
+ }
838
+ }
839
+ if (d.triggerFrom) {
840
+ const t = d.triggerFrom;
841
+ const state = this.triggers.get(id) ?? { acc: 0 };
842
+ this.triggers.set(id, state);
843
+ const raw = resolveSignal(t.signal, entityCtx);
844
+ const value = num(raw);
845
+ let fire = false;
846
+ if (t.every !== void 0 && state.last !== void 0 && active) {
847
+ state.acc += Math.abs(value - state.last);
848
+ if (state.acc >= t.every) {
849
+ fire = true;
850
+ state.acc -= t.every;
851
+ if (state.acc > t.every) state.acc = 0;
852
+ }
853
+ }
854
+ if (t.onChange && active && state.lastRaw !== void 0 && raw !== state.lastRaw) fire = true;
855
+ state.last = value;
856
+ if (raw !== void 0) state.lastRaw = raw;
857
+ if (fire) {
858
+ const shotSound = t.sound ? this.sound(t.sound, `entity "${id}" triggerFrom`) : sound;
859
+ if (shotSound) this.fireOneShot({
860
+ ...shotBase,
861
+ sound: shotSound,
862
+ bus: d.bus ?? shotSound.entry.bus ?? "sfx",
863
+ key: `${key}:t`
864
+ }, ctx.listener, now, tick, cmds);
865
+ }
866
+ }
867
+ }
868
+ }
869
+ for (const id of [...this.firedOnce]) if (!seen.has(id)) this.firedOnce.delete(id);
870
+ for (const id of [...this.startTickFired.keys()]) if (!seen.has(id)) this.startTickFired.delete(id);
871
+ for (const id of [...this.triggers.keys()]) if (!seen.has(id)) this.triggers.delete(id);
872
+ for (const key of [...this.gates.keys()]) if (key.startsWith("src:") && !seen.has(key.slice(4))) this.gates.delete(key);
873
+ }
874
+ collectScriptLoops(ctx, desired) {
875
+ for (const [handle, loop] of this.scriptLoops) {
876
+ const sound = this.sound(loop.sound, "molen.audio.play");
877
+ if (!sound) {
878
+ this.scriptLoops.delete(handle);
879
+ continue;
880
+ }
881
+ const position = loop.entity !== void 0 ? this.entityPos(ctx.source, loop.entity) : loop.position;
882
+ const spatial = this.spatialFor(void 0, sound, position);
883
+ desired.push({
884
+ key: `script:${handle}`,
885
+ sound,
886
+ loop: true,
887
+ gain: (sound.entry.gain ?? 1) * loop.gain,
888
+ pitchMul: loop.pitch,
889
+ bus: loop.bus ?? sound.entry.bus ?? "sfx",
890
+ fadeInS: .1,
891
+ fadeOutS: .3,
892
+ rampS: .1,
893
+ priority: 2,
894
+ ...loop.entity !== void 0 ? { entity: loop.entity } : {},
895
+ ...spatial ? { spatial } : {},
896
+ ...position ? { position } : {}
897
+ });
898
+ }
899
+ }
900
+ resolveAt(at, payload, source) {
901
+ const obj = payload !== null && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
902
+ const from = (v) => {
903
+ if (typeof v === "string") {
904
+ const position = this.entityPos(source, v);
905
+ return position ? {
906
+ position,
907
+ entity: v
908
+ } : { entity: v };
909
+ }
910
+ const position = vec3(v);
911
+ return position ? { position } : void 0;
912
+ };
913
+ if (at === "listener") return {};
914
+ if (at?.startsWith("payload.")) return from(obj[at.slice(8)]) ?? {};
915
+ for (const field of [
916
+ "entity",
917
+ "position",
918
+ "a",
919
+ "pos"
920
+ ]) {
921
+ const hit = from(obj[field]);
922
+ if (hit?.position) return hit;
923
+ }
924
+ return {};
925
+ }
926
+ processEvents(env, ctx, now, tick, cmds) {
927
+ const events = this.events.splice(0);
928
+ for (const { event } of events) {
929
+ const p = event.payload ?? {};
930
+ switch (event.type) {
931
+ case "audio.play": {
932
+ const soundId = typeof p.sound === "string" ? p.sound : void 0;
933
+ const handle = typeof p.handle === "string" ? p.handle : `anon#${this.serial}`;
934
+ if (!soundId) break;
935
+ const sound = this.sound(soundId, "molen.audio.play");
936
+ if (!sound) break;
937
+ const entity = typeof p.entity === "string" ? p.entity : void 0;
938
+ const loop = typeof p.loop === "boolean" ? p.loop : sound.entry.loop ?? false;
939
+ const gain = typeof p.gain === "number" ? p.gain : 1;
940
+ const pitch = typeof p.pitch === "number" ? p.pitch : 1;
941
+ const bus = typeof p.bus === "string" ? p.bus : void 0;
942
+ if (loop) {
943
+ const position = vec3(p.position);
944
+ this.scriptLoops.set(handle, {
945
+ sound: soundId,
946
+ gain,
947
+ pitch,
948
+ ...entity !== void 0 ? { entity } : {},
949
+ ...position ? { position } : {},
950
+ ...bus !== void 0 ? { bus } : {}
951
+ });
952
+ } else {
953
+ const where = entity !== void 0 ? this.entityPos(ctx.source, entity) : vec3(p.position);
954
+ const spatial = this.spatialFor(void 0, sound, where);
955
+ this.fireOneShot({
956
+ sound,
957
+ gain: (sound.entry.gain ?? 1) * gain,
958
+ pitchMul: pitch,
959
+ bus: bus ?? sound.entry.bus ?? "sfx",
960
+ handle,
961
+ key: handle,
962
+ ...entity !== void 0 ? { entity } : {},
963
+ ...where ? { position: where } : {},
964
+ ...spatial ? { spatial } : {}
965
+ }, ctx.listener, now, tick, cmds);
966
+ }
967
+ break;
968
+ }
969
+ case "audio.stop": {
970
+ const fadeS = typeof p.fadeS === "number" ? p.fadeS : .15;
971
+ const matches = (m) => {
972
+ if (typeof p.handle === "string") return m.handle === p.handle;
973
+ if (p.entity === void 0 && p.sound === void 0) return false;
974
+ return (p.entity === void 0 || m.entity === p.entity) && (p.sound === void 0 || m.sound === p.sound);
975
+ };
976
+ for (const [handle, loop] of [...this.scriptLoops]) if (matches({
977
+ handle,
978
+ sound: loop.sound,
979
+ ...loop.entity ? { entity: loop.entity } : {}
980
+ })) {
981
+ this.scriptLoops.delete(handle);
982
+ this.stopFades.set(`script:${handle}`, fadeS);
983
+ }
984
+ for (let i = this.oneShots.length - 1; i >= 0; i--) {
985
+ const s = this.oneShots[i];
986
+ if (matches(s)) {
987
+ cmds.push({
988
+ op: "stop",
989
+ voice: s.voice,
990
+ fadeS
991
+ });
992
+ this.oneShots.splice(i, 1);
993
+ }
994
+ }
995
+ break;
996
+ }
997
+ case "audio.music": {
998
+ const list = Array.isArray(p.playlist) ? p.playlist.filter((x) => typeof x === "string") : [];
999
+ this.musicOverride = {
1000
+ playlist: list,
1001
+ ...typeof p.crossfadeS === "number" ? { crossfadeS: p.crossfadeS } : {}
1002
+ };
1003
+ break;
1004
+ }
1005
+ default: {
1006
+ const rule = env?.events?.[event.type];
1007
+ if (!rule) break;
1008
+ const sound = this.sound(rule.sound, `audioEnvironment.events.${event.type}`);
1009
+ if (!sound) break;
1010
+ const { position, entity } = this.resolveAt(rule.at, event.payload, ctx.source);
1011
+ const spatial = this.spatialFor(void 0, sound, position);
1012
+ this.fireOneShot({
1013
+ sound,
1014
+ gain: (sound.entry.gain ?? 1) * (rule.gain ?? 1),
1015
+ pitchMul: rule.pitch ?? 1,
1016
+ bus: rule.bus ?? sound.entry.bus ?? "sfx",
1017
+ key: `event:${event.type}`,
1018
+ ...entity !== void 0 ? { entity } : {},
1019
+ ...position ? { position } : {},
1020
+ ...spatial ? { spatial } : {}
1021
+ }, ctx.listener, now, tick, cmds);
1022
+ }
1023
+ }
1024
+ }
1025
+ }
1026
+ footsteps(env, ctx, now, tick, cmds) {
1027
+ const f = env?.footsteps;
1028
+ const travelled = ctx.listener.distance;
1029
+ const delta = this.footLast === void 0 ? 0 : travelled - this.footLast;
1030
+ this.footLast = travelled;
1031
+ if (!f || ctx.listener.grounded === false || !evalWhen(f.when, ctx)) {
1032
+ this.footAcc = 0;
1033
+ return;
1034
+ }
1035
+ const stride = f.strideM ?? .75;
1036
+ this.footAcc += delta;
1037
+ if (this.footAcc < stride) return;
1038
+ this.footAcc -= stride;
1039
+ if (this.footAcc > stride) this.footAcc = 0;
1040
+ const surface = ctx.listener.surface;
1041
+ const id = (surface !== void 0 ? f.surfaces?.[surface] : void 0) ?? f.sound;
1042
+ const sound = this.sound(id, "audioEnvironment.footsteps");
1043
+ if (!sound) return;
1044
+ this.fireOneShot({
1045
+ sound,
1046
+ gain: (sound.entry.gain ?? 1) * (f.gain ?? 1),
1047
+ pitchMul: 1,
1048
+ bus: sound.entry.bus ?? "sfx",
1049
+ key: "footstep"
1050
+ }, ctx.listener, now, tick, cmds);
1051
+ }
1052
+ updateMusic(env, ctx, now, cmds) {
1053
+ const spec = env?.music;
1054
+ const override = this.musicOverride;
1055
+ const playlist = override ? override.playlist : spec?.playlist ?? [];
1056
+ const crossfadeS = override?.crossfadeS ?? spec?.crossfadeS ?? 4;
1057
+ const shuffle = !override && spec?.mode === "shuffle";
1058
+ const gate = this.gate("music");
1059
+ const wanted = playlist.length > 0 && (override !== void 0 || gate.update(evalWhen(spec?.when, ctx, gate.active), now));
1060
+ const key = wanted ? `${shuffle ? "s" : "q"}:${playlist.join("|")}` : "";
1061
+ const state = this.musicState;
1062
+ const stopCurrent = (fadeS) => {
1063
+ if (state?.voice) cmds.push({
1064
+ op: "stop",
1065
+ voice: state.voice,
1066
+ fadeS
1067
+ });
1068
+ };
1069
+ const startTrack = (s, fadeInS) => {
1070
+ const id = s.order[s.index];
1071
+ const sound = this.sound(id, "audioEnvironment.music");
1072
+ if (!sound) {
1073
+ s.voice = void 0;
1074
+ s.sound = void 0;
1075
+ s.endsAt = void 0;
1076
+ return;
1077
+ }
1078
+ const multi = s.order.length > 1;
1079
+ const duration = sound.entry.durationS;
1080
+ if (multi && duration === void 0) this.warn(`music-duration:${id}`, `music track "${id}" has no durationS; it will loop`);
1081
+ const loop = !multi || duration === void 0;
1082
+ const voice = `music:${this.serial++}`;
1083
+ cmds.push({
1084
+ op: "start",
1085
+ voice,
1086
+ sound: id,
1087
+ ref: sound.refs[this.pickClip(sound, s.round)],
1088
+ loop,
1089
+ ...loop && sound.entry.loopStart !== void 0 ? { loopStart: sound.entry.loopStart } : {},
1090
+ ...loop && sound.entry.loopEnd !== void 0 ? { loopEnd: sound.entry.loopEnd } : {},
1091
+ gain: (sound.entry.gain ?? 1) * (override ? 1 : spec?.gain ?? 1),
1092
+ pitch: 1,
1093
+ bus: "music",
1094
+ fadeInS
1095
+ });
1096
+ s.voice = voice;
1097
+ s.sound = id;
1098
+ s.endsAt = loop ? void 0 : now + duration * 1e3;
1099
+ };
1100
+ const orderFor = (list, round) => {
1101
+ if (!shuffle) return [...list];
1102
+ return [...list].map((id, i) => ({
1103
+ id,
1104
+ r: unitRandom(this.seed, "music", round, i)
1105
+ })).sort((a, b) => a.r - b.r).map((x) => x.id);
1106
+ };
1107
+ if (!wanted) {
1108
+ if (state) {
1109
+ stopCurrent(crossfadeS);
1110
+ this.musicState = void 0;
1111
+ }
1112
+ return;
1113
+ }
1114
+ if (!state || state.key !== key) {
1115
+ stopCurrent(crossfadeS);
1116
+ const next = {
1117
+ key,
1118
+ order: orderFor(playlist, 0),
1119
+ index: 0,
1120
+ round: 0
1121
+ };
1122
+ this.musicState = next;
1123
+ startTrack(next, state ? crossfadeS : 2);
1124
+ return;
1125
+ }
1126
+ if (state.endsAt !== void 0 && now >= state.endsAt - crossfadeS * 1e3) {
1127
+ stopCurrent(crossfadeS);
1128
+ state.index++;
1129
+ if (state.index >= state.order.length) {
1130
+ state.round++;
1131
+ state.index = 0;
1132
+ state.order = orderFor(playlist, state.round);
1133
+ }
1134
+ startTrack(state, crossfadeS);
1135
+ }
1136
+ }
1137
+ reconcile(desired, env, listener, tick, cmds) {
1138
+ const scored = desired.map((d) => {
1139
+ const d2 = d.position ? dist(d.position, listener.position) : 0;
1140
+ return {
1141
+ d,
1142
+ distance: d2,
1143
+ score: audibility(d.gain, d.spatial, d2)
1144
+ };
1145
+ }).filter(({ d, distance }) => {
1146
+ if (!d.spatial) return true;
1147
+ return distance <= d.spatial.maxDistance * (this.live.has(d.key) ? 1.1 : 1);
1148
+ }).sort((a, b) => a.d.priority - b.d.priority || b.score - a.score);
1149
+ const budget = Math.max(0, (env?.maxVoices ?? 32) - (this.musicState?.voice ? 1 : 0));
1150
+ const kept = scored.slice(0, budget).map((s) => s.d);
1151
+ const keep = new Set(kept.map((d) => d.key));
1152
+ for (const [key, v] of [...this.live]) {
1153
+ if (keep.has(key)) continue;
1154
+ const fadeS = this.stopFades.get(key) ?? v.fadeOutS;
1155
+ this.stopFades.delete(key);
1156
+ cmds.push({
1157
+ op: "stop",
1158
+ voice: v.voice,
1159
+ fadeS
1160
+ });
1161
+ this.live.delete(key);
1162
+ }
1163
+ for (const d of kept) {
1164
+ const live = this.live.get(d.key);
1165
+ if (!live) {
1166
+ const basePitch = this.basePitch(d.sound, tick, d.key);
1167
+ const pitch = basePitch * d.pitchMul;
1168
+ const clip = this.pickClip(d.sound, tick, d.key);
1169
+ const voice = `${d.key}~${this.serial++}`;
1170
+ const { entry } = d.sound;
1171
+ cmds.push({
1172
+ op: "start",
1173
+ voice,
1174
+ sound: d.sound.id,
1175
+ ref: d.sound.refs[clip],
1176
+ loop: d.loop,
1177
+ ...entry.loopStart !== void 0 ? { loopStart: entry.loopStart } : {},
1178
+ ...entry.loopEnd !== void 0 ? { loopEnd: entry.loopEnd } : {},
1179
+ gain: d.gain,
1180
+ pitch,
1181
+ bus: d.bus,
1182
+ ...d.spatial && d.position ? { spatial: {
1183
+ ...d.spatial,
1184
+ position: d.position
1185
+ } } : {},
1186
+ fadeInS: d.fadeInS
1187
+ });
1188
+ this.live.set(d.key, {
1189
+ key: d.key,
1190
+ voice,
1191
+ sound: d.sound.id,
1192
+ bus: d.bus,
1193
+ loop: d.loop,
1194
+ gain: d.gain,
1195
+ pitch,
1196
+ basePitch,
1197
+ fadeOutS: d.fadeOutS,
1198
+ ...d.position ? { position: d.position } : {},
1199
+ ...d.entity !== void 0 ? { entity: d.entity } : {}
1200
+ });
1201
+ continue;
1202
+ }
1203
+ const pitch = live.basePitch * d.pitchMul;
1204
+ const set = {
1205
+ op: "set",
1206
+ voice: live.voice
1207
+ };
1208
+ let changed = false;
1209
+ if (Math.abs(d.gain - live.gain) > .005) {
1210
+ set.gain = d.gain;
1211
+ live.gain = d.gain;
1212
+ changed = true;
1213
+ }
1214
+ if (Math.abs(pitch - live.pitch) > .002) {
1215
+ set.pitch = pitch;
1216
+ live.pitch = pitch;
1217
+ changed = true;
1218
+ }
1219
+ if (d.position && (!live.position || dist(d.position, live.position) > .05)) {
1220
+ set.position = d.position;
1221
+ live.position = d.position;
1222
+ changed = true;
1223
+ }
1224
+ live.fadeOutS = d.fadeOutS;
1225
+ if (changed) {
1226
+ set.rampS = d.rampS;
1227
+ cmds.push(set);
1228
+ }
1229
+ }
1230
+ }
1231
+ };
1232
+ //#endregion
1233
+ //#region src/audio/listener.ts
1234
+ function unit(x, y, z, fallback) {
1235
+ const len = Math.hypot(x, y, z);
1236
+ return len > 1e-9 ? [
1237
+ x / len,
1238
+ y / len,
1239
+ z / len
1240
+ ] : fallback;
1241
+ }
1242
+ /**
1243
+ * Listener pose from a render camera. The renderer keeps the camera near the origin (floating
1244
+ * origin); pass `renderer.getWorldOrigin()` so the listener sits in the same world space as
1245
+ * entity transforms. Reads the matrix only, so it needs no three.js import.
1246
+ */
1247
+ function listenerFromCamera(camera, worldOrigin = [
1248
+ 0,
1249
+ 0,
1250
+ 0
1251
+ ]) {
1252
+ const e = camera.matrixWorld.elements;
1253
+ const at = (i) => e[i] ?? 0;
1254
+ return {
1255
+ position: [
1256
+ at(12) + (worldOrigin[0] ?? 0),
1257
+ at(13) + (worldOrigin[1] ?? 0),
1258
+ at(14) + (worldOrigin[2] ?? 0)
1259
+ ],
1260
+ forward: unit(-at(8), -at(9), -at(10), [
1261
+ 0,
1262
+ 0,
1263
+ -1
1264
+ ]),
1265
+ up: unit(at(4), at(5), at(6), [
1266
+ 0,
1267
+ 1,
1268
+ 0
1269
+ ])
1270
+ };
1271
+ }
1272
+ //#endregion
1273
+ //#region src/audio/recording-backend.ts
1274
+ /** A silent backend that records commands: tests, headless planning, and hosts without audio. */
1275
+ function createRecordingBackend(opts = {}) {
1276
+ const log = [];
1277
+ const active = /* @__PURE__ */ new Map();
1278
+ let unlocked = opts.unlocked ?? true;
1279
+ return {
1280
+ log,
1281
+ active,
1282
+ get unlocked() {
1283
+ return unlocked;
1284
+ },
1285
+ async unlock() {
1286
+ unlocked = true;
1287
+ },
1288
+ apply(commands) {
1289
+ for (const cmd of commands) {
1290
+ log.push(cmd);
1291
+ if (cmd.op === "start" && cmd.loop) active.set(cmd.voice, cmd);
1292
+ else if (cmd.op === "stop") active.delete(cmd.voice);
1293
+ else if (cmd.op === "set") {
1294
+ const v = active.get(cmd.voice);
1295
+ if (v) active.set(cmd.voice, {
1296
+ ...v,
1297
+ ...cmd.gain !== void 0 ? { gain: cmd.gain } : {},
1298
+ ...cmd.pitch !== void 0 ? { pitch: cmd.pitch } : {},
1299
+ ...cmd.position && v.spatial ? { spatial: {
1300
+ ...v.spatial,
1301
+ position: cmd.position
1302
+ } } : {}
1303
+ });
1304
+ }
1305
+ }
1306
+ },
1307
+ stats() {
1308
+ return {
1309
+ voices: active.size,
1310
+ decoded: 0,
1311
+ pending: 0,
1312
+ state: "headless"
1313
+ };
1314
+ },
1315
+ clear() {
1316
+ log.length = 0;
1317
+ active.clear();
1318
+ },
1319
+ dispose() {
1320
+ active.clear();
1321
+ }
1322
+ };
1323
+ }
1324
+ //#endregion
1325
+ //#region src/audio/web-audio-backend.ts
1326
+ /** Plays director commands through Web Audio: buses, panners, looped buffers, fades. */
1327
+ var WebAudioBackend = class {
1328
+ context;
1329
+ provider;
1330
+ staleS;
1331
+ onError;
1332
+ master;
1333
+ buses = /* @__PURE__ */ new Map();
1334
+ buffers = /* @__PURE__ */ new Map();
1335
+ voices = /* @__PURE__ */ new Map();
1336
+ decoded = 0;
1337
+ pending = 0;
1338
+ hostSuspended = false;
1339
+ disposed = false;
1340
+ constructor(opts) {
1341
+ this.provider = opts.provider;
1342
+ this.staleS = opts.staleOneShotS ?? .35;
1343
+ this.onError = opts.onError;
1344
+ this.context = opts.context ?? new AudioContext({ latencyHint: "interactive" });
1345
+ this.master = this.context.createGain();
1346
+ this.master.connect(this.context.destination);
1347
+ for (const bus of AUDIO_BUSES) this.bus(bus);
1348
+ }
1349
+ get unlocked() {
1350
+ return this.context.state === "running";
1351
+ }
1352
+ async unlock() {
1353
+ if (this.disposed || this.hostSuspended || this.context.state !== "suspended") return;
1354
+ await this.context.resume();
1355
+ }
1356
+ setSuspended(suspended) {
1357
+ this.hostSuspended = suspended;
1358
+ if (this.disposed) return;
1359
+ (suspended ? this.context.suspend() : this.context.resume()).catch(() => {});
1360
+ }
1361
+ async preload(refs) {
1362
+ await Promise.all(refs.map((ref) => this.load(ref)));
1363
+ }
1364
+ stats() {
1365
+ return {
1366
+ voices: this.voices.size,
1367
+ decoded: this.decoded,
1368
+ pending: this.pending,
1369
+ state: this.context.state === "interrupted" ? "suspended" : this.context.state
1370
+ };
1371
+ }
1372
+ apply(commands) {
1373
+ if (this.disposed) return;
1374
+ for (const cmd of commands) switch (cmd.op) {
1375
+ case "start":
1376
+ this.start(cmd);
1377
+ break;
1378
+ case "set":
1379
+ this.set(cmd);
1380
+ break;
1381
+ case "stop":
1382
+ this.stop(cmd.voice, cmd.fadeS);
1383
+ break;
1384
+ case "listener":
1385
+ this.setListener(cmd.position, cmd.forward, cmd.up);
1386
+ break;
1387
+ case "bus":
1388
+ this.bus(cmd.bus).gain.setTargetAtTime(cmd.gain, this.context.currentTime, .05);
1389
+ break;
1390
+ }
1391
+ }
1392
+ dispose() {
1393
+ if (this.disposed) return;
1394
+ for (const id of [...this.voices.keys()]) this.stop(id, 0);
1395
+ this.disposed = true;
1396
+ this.context.close().catch(() => {});
1397
+ }
1398
+ bus(name) {
1399
+ if (name === "master") return this.master;
1400
+ let g = this.buses.get(name);
1401
+ if (!g) {
1402
+ g = this.context.createGain();
1403
+ g.connect(this.master);
1404
+ this.buses.set(name, g);
1405
+ }
1406
+ return g;
1407
+ }
1408
+ load(ref) {
1409
+ let p = this.buffers.get(ref);
1410
+ if (!p) {
1411
+ this.pending++;
1412
+ p = this.provider.load(ref).then((bytes) => this.context.decodeAudioData(bytes.slice(0))).then((buffer) => {
1413
+ this.decoded++;
1414
+ return buffer;
1415
+ }).catch((error) => {
1416
+ this.onError?.(`audio clip "${ref}" failed to load: ${String(error)}`);
1417
+ return null;
1418
+ }).finally(() => {
1419
+ this.pending--;
1420
+ });
1421
+ this.buffers.set(ref, p);
1422
+ }
1423
+ return p;
1424
+ }
1425
+ start(cmd) {
1426
+ if (!cmd.loop && !this.unlocked) return;
1427
+ this.stop(cmd.voice, 0);
1428
+ const ctx = this.context;
1429
+ const gain = ctx.createGain();
1430
+ gain.gain.value = 0;
1431
+ let panner;
1432
+ if (cmd.spatial) {
1433
+ const s = cmd.spatial;
1434
+ panner = new PannerNode(ctx, {
1435
+ panningModel: "equalpower",
1436
+ distanceModel: s.model,
1437
+ refDistance: s.refDistance,
1438
+ maxDistance: s.maxDistance,
1439
+ rolloffFactor: s.rolloff,
1440
+ positionX: s.position[0],
1441
+ positionY: s.position[1],
1442
+ positionZ: s.position[2]
1443
+ });
1444
+ gain.connect(panner);
1445
+ panner.connect(this.bus(cmd.bus));
1446
+ } else gain.connect(this.bus(cmd.bus));
1447
+ const voice = {
1448
+ cmd,
1449
+ gain,
1450
+ panner,
1451
+ src: void 0,
1452
+ stopped: false,
1453
+ requestedAt: ctx.currentTime,
1454
+ targetGain: cmd.gain,
1455
+ pitch: cmd.pitch
1456
+ };
1457
+ this.voices.set(cmd.voice, voice);
1458
+ this.load(cmd.ref).then((buffer) => {
1459
+ if (voice.stopped || this.disposed || !buffer) {
1460
+ if (!buffer) this.cleanup(cmd.voice, voice);
1461
+ return;
1462
+ }
1463
+ if (!cmd.loop && ctx.currentTime - voice.requestedAt > this.staleS) {
1464
+ this.cleanup(cmd.voice, voice);
1465
+ return;
1466
+ }
1467
+ const src = ctx.createBufferSource();
1468
+ src.buffer = buffer;
1469
+ src.loop = cmd.loop;
1470
+ if (cmd.loop && cmd.loopStart !== void 0) src.loopStart = cmd.loopStart;
1471
+ if (cmd.loop && cmd.loopEnd !== void 0) src.loopEnd = cmd.loopEnd;
1472
+ src.playbackRate.value = voice.pitch;
1473
+ src.connect(gain);
1474
+ const now = ctx.currentTime;
1475
+ const fade = cmd.fadeInS ?? 0;
1476
+ gain.gain.setValueAtTime(fade > 0 ? 0 : voice.targetGain, now);
1477
+ if (fade > 0) gain.gain.linearRampToValueAtTime(voice.targetGain, now + fade);
1478
+ src.onended = () => this.cleanup(cmd.voice, voice);
1479
+ voice.src = src;
1480
+ src.start(now, cmd.loop && cmd.loopStart !== void 0 ? cmd.loopStart : 0);
1481
+ });
1482
+ }
1483
+ set(cmd) {
1484
+ const v = this.voices.get(cmd.voice);
1485
+ if (!v || v.stopped) return;
1486
+ const now = this.context.currentTime;
1487
+ const tau = Math.max(.01, (cmd.rampS ?? .1) / 3);
1488
+ if (cmd.gain !== void 0) {
1489
+ v.targetGain = cmd.gain;
1490
+ if (v.src) v.gain.gain.setTargetAtTime(cmd.gain, now, tau);
1491
+ }
1492
+ if (cmd.pitch !== void 0) {
1493
+ v.pitch = cmd.pitch;
1494
+ v.src?.playbackRate.setTargetAtTime(cmd.pitch, now, tau);
1495
+ }
1496
+ if (cmd.position && v.panner) {
1497
+ const [x, y, z] = cmd.position;
1498
+ v.panner.positionX.setTargetAtTime(x, now, .02);
1499
+ v.panner.positionY.setTargetAtTime(y, now, .02);
1500
+ v.panner.positionZ.setTargetAtTime(z, now, .02);
1501
+ }
1502
+ }
1503
+ stop(id, fadeS = .05) {
1504
+ const v = this.voices.get(id);
1505
+ if (!v || v.stopped) return;
1506
+ v.stopped = true;
1507
+ if (!v.src) {
1508
+ this.cleanup(id, v);
1509
+ return;
1510
+ }
1511
+ const now = this.context.currentTime;
1512
+ const g = v.gain.gain;
1513
+ g.cancelScheduledValues(now);
1514
+ g.setValueAtTime(g.value, now);
1515
+ g.linearRampToValueAtTime(0, now + Math.max(.005, fadeS));
1516
+ try {
1517
+ v.src.stop(now + Math.max(.005, fadeS) + .02);
1518
+ } catch {
1519
+ this.cleanup(id, v);
1520
+ }
1521
+ }
1522
+ cleanup(id, v) {
1523
+ if (this.voices.get(id) === v) this.voices.delete(id);
1524
+ v.stopped = true;
1525
+ try {
1526
+ v.src?.disconnect();
1527
+ v.gain.disconnect();
1528
+ v.panner?.disconnect();
1529
+ } catch {}
1530
+ }
1531
+ setListener(p, f, u) {
1532
+ const l = this.context.listener;
1533
+ const now = this.context.currentTime;
1534
+ if (l.positionX) {
1535
+ l.positionX.setTargetAtTime(p[0], now, .02);
1536
+ l.positionY.setTargetAtTime(p[1], now, .02);
1537
+ l.positionZ.setTargetAtTime(p[2], now, .02);
1538
+ l.forwardX.setTargetAtTime(f[0], now, .02);
1539
+ l.forwardY.setTargetAtTime(f[1], now, .02);
1540
+ l.forwardZ.setTargetAtTime(f[2], now, .02);
1541
+ l.upX.setTargetAtTime(u[0], now, .02);
1542
+ l.upY.setTargetAtTime(u[1], now, .02);
1543
+ l.upZ.setTargetAtTime(u[2], now, .02);
1544
+ } else {
1545
+ l.setPosition(p[0], p[1], p[2]);
1546
+ l.setOrientation(f[0], f[1], f[2], u[0], u[1], u[2]);
1547
+ }
1548
+ }
1549
+ };
1550
+ //#endregion
1551
+ //#region src/audio/layer.ts
1552
+ function defaultBackend(opts) {
1553
+ if (opts.backend) return opts.backend;
1554
+ if (opts.provider && typeof AudioContext !== "undefined") return new WebAudioBackend({
1555
+ provider: opts.provider,
1556
+ ...opts.onWarning ? { onError: opts.onWarning } : {}
1557
+ });
1558
+ return createRecordingBackend();
1559
+ }
1560
+ /**
1561
+ * The audio layer a host creates once and updates each frame. It owns the director (rules) and
1562
+ * the backend (playback). Kernel-less viewers call `update` with listener state only; kernel hosts
1563
+ * also `attachClient` or `attachWorld` so entity components and events reach the director.
1564
+ */
1565
+ function createAudioLayer(opts) {
1566
+ const director = new AudioDirector({
1567
+ bank: mergeSoundbanks(opts.banks),
1568
+ ...opts.environment ? { environment: opts.environment } : {},
1569
+ ...opts.maxOneShots !== void 0 ? { maxOneShots: opts.maxOneShots } : {},
1570
+ ...opts.seed !== void 0 ? { seed: opts.seed } : {},
1571
+ ...opts.onWarning ? { onWarning: opts.onWarning } : {}
1572
+ });
1573
+ const backend = defaultBackend(opts);
1574
+ let source;
1575
+ let detachEvents;
1576
+ let volume = opts.volume ?? 1;
1577
+ let muted = opts.muted ?? false;
1578
+ const envBus = /* @__PURE__ */ new Map();
1579
+ const hostBus = /* @__PURE__ */ new Map();
1580
+ let disposed = false;
1581
+ const applyMaster = () => {
1582
+ backend.apply([{
1583
+ op: "bus",
1584
+ bus: "master",
1585
+ gain: muted ? 0 : volume
1586
+ }]);
1587
+ };
1588
+ const busGain = (bus) => (envBus.get(bus) ?? 1) * (hostBus.get(bus) ?? 1);
1589
+ applyMaster();
1590
+ const setSource = (next) => {
1591
+ detachEvents?.();
1592
+ detachEvents = void 0;
1593
+ source = next;
1594
+ if (next?.onEvent) detachEvents = next.onEvent((event, tick) => director.handleEvent(event, tick));
1595
+ };
1596
+ let removeVisibility;
1597
+ if (opts.suspendWhenHidden !== false && typeof document !== "undefined") {
1598
+ const onVisibility = () => backend.setSuspended?.(document.hidden);
1599
+ document.addEventListener("visibilitychange", onVisibility);
1600
+ removeVisibility = () => document.removeEventListener("visibilitychange", onVisibility);
1601
+ }
1602
+ return {
1603
+ director,
1604
+ backend,
1605
+ get volume() {
1606
+ return volume;
1607
+ },
1608
+ get muted() {
1609
+ return muted;
1610
+ },
1611
+ get unlocked() {
1612
+ return backend.unlocked;
1613
+ },
1614
+ update(nowMs, listener, signals) {
1615
+ if (disposed) return;
1616
+ const r = opts.renderer;
1617
+ const fromCamera = r ? listenerFromCamera(r.camera, r.getWorldOrigin()) : void 0;
1618
+ const rendererSignals = {};
1619
+ if (r?.weather?.data) rendererSignals.weather = r.weather.data;
1620
+ if (r?.sky?.frame) rendererSignals.sky = r.sky.frame;
1621
+ const merged = {
1622
+ ...rendererSignals,
1623
+ ...opts.signals?.() ?? {},
1624
+ ...signals ?? {}
1625
+ };
1626
+ const out = director.update({
1627
+ nowMs,
1628
+ listener: {
1629
+ ...fromCamera,
1630
+ ...listener
1631
+ },
1632
+ signals: merged,
1633
+ ...source ? { source } : {}
1634
+ }).map((cmd) => {
1635
+ if (cmd.op !== "bus") return cmd;
1636
+ envBus.set(cmd.bus, cmd.gain);
1637
+ return {
1638
+ ...cmd,
1639
+ gain: busGain(cmd.bus)
1640
+ };
1641
+ });
1642
+ backend.apply(out);
1643
+ },
1644
+ attachClient(client, attachOpts) {
1645
+ setSource(entitySourceFromClient(client, attachOpts));
1646
+ return () => setSource(void 0);
1647
+ },
1648
+ attachWorld(world) {
1649
+ setSource(entitySourceFromWorld(world));
1650
+ return () => setSource(void 0);
1651
+ },
1652
+ setSource,
1653
+ play: (sound, playOpts) => director.play(sound, playOpts),
1654
+ stop: (target, fadeS) => director.stop(target, fadeS),
1655
+ music: (playlist, musicOpts) => director.music(playlist, musicOpts),
1656
+ setVolume(v) {
1657
+ volume = Math.max(0, Math.min(1, v));
1658
+ applyMaster();
1659
+ },
1660
+ setMuted(m) {
1661
+ muted = m;
1662
+ applyMaster();
1663
+ },
1664
+ setBusGain(bus, gain) {
1665
+ hostBus.set(bus, gain);
1666
+ backend.apply([{
1667
+ op: "bus",
1668
+ bus,
1669
+ gain: busGain(bus)
1670
+ }]);
1671
+ },
1672
+ setEnvironment: (environment) => director.setEnvironment(environment),
1673
+ setBanks: (banks) => director.setBank(mergeSoundbanks(banks)),
1674
+ unlock: () => backend.unlock(),
1675
+ setSuspended: (s) => backend.setSuspended?.(s),
1676
+ stats: () => ({
1677
+ voices: director.voices().length,
1678
+ warnings: director.warnings().length,
1679
+ backend: backend.stats()
1680
+ }),
1681
+ dispose() {
1682
+ if (disposed) return;
1683
+ backend.apply(director.reset(.1));
1684
+ setSource(void 0);
1685
+ removeVisibility?.();
1686
+ backend.dispose();
1687
+ disposed = true;
1688
+ }
1689
+ };
1690
+ }
1691
+ //#endregion
1692
+ //#region src/audio/packs.ts
1693
+ /**
1694
+ * Every `provides.soundbank` document in a pack set, validated, with clip refs rooted in its pack
1695
+ * (`pack:<id>/<dir>/`), ready for `createAudioLayer({ banks, provider: set.assetProvider() })`.
1696
+ * Invalid banks are reported through `onWarning` and skipped.
1697
+ */
1698
+ async function loadPackSoundbanks(set, onWarning) {
1699
+ const out = [];
1700
+ for (const { pack, path } of set.provided("soundbank")) {
1701
+ const ref = `pack:${pack.manifest.id}/${path}`;
1702
+ const result = validate("soundbank", await set.readJson(ref));
1703
+ if (!result.ok) {
1704
+ onWarning?.(`${ref} is not a valid soundbank:\n${result.formatted}`);
1705
+ continue;
1706
+ }
1707
+ const slash = path.lastIndexOf("/");
1708
+ out.push({
1709
+ doc: result.value,
1710
+ base: `pack:${pack.manifest.id}/${slash >= 0 ? path.slice(0, slash + 1) : ""}`
1711
+ });
1712
+ }
1713
+ return out;
1714
+ }
1715
+ //#endregion
1716
+ //#region src/audio/unlock.ts
1717
+ const GESTURES = [
1718
+ "pointerdown",
1719
+ "keydown",
1720
+ "touchend"
1721
+ ];
1722
+ /**
1723
+ * Browsers start audio suspended until the page gets a gesture. Resume on the first pointer,
1724
+ * key or touch on `target` (default the window); returns a detach function.
1725
+ */
1726
+ function attachAutoplayUnlock(audio, target = typeof window === "undefined" ? void 0 : window) {
1727
+ if (!target) return () => {};
1728
+ const onGesture = () => {
1729
+ audio.unlock().then(() => {
1730
+ if (audio.unlocked) detach();
1731
+ }).catch(() => {});
1732
+ };
1733
+ const detach = () => {
1734
+ for (const type of GESTURES) target.removeEventListener(type, onGesture, true);
1735
+ };
1736
+ for (const type of GESTURES) target.addEventListener(type, onGesture, true);
1737
+ return detach;
1738
+ }
1739
+ //#endregion
1740
+ export { AudioDirector, Gate, WebAudioBackend, attachAutoplayUnlock, createAudioLayer, createRecordingBackend, curve, entitySourceFromClient, entitySourceFromWorld, evalWhen, hash32, listenerFromCamera, loadPackSoundbanks, mergeSoundbanks, resolveSignal, unitRandom };