@threenative/core 0.3.4 → 0.3.6
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/capabilities.json +1505 -79
- package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
- package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
- package/dist/{game-CljaDv4D.d.ts → game-Jz4Fdoeb.d.ts} +114 -11
- package/dist/hot.d.ts +4 -4
- package/dist/index.d.ts +712 -118
- package/dist/index.js +12437 -4955
- package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
- package/dist/playtest.d.ts +6 -10
- package/dist/playtest.js +57 -24
- package/dist/react-css.d.ts +62 -0
- package/dist/react-css.js +591 -0
- package/dist/react.d.ts +2 -2
- package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
- package/dist/terrain-jobs-worker.d.ts +2 -0
- package/dist/terrain-jobs-worker.js +130 -0
- package/dist/ui-layer.js +59 -8
- package/dist/world.d.ts +766 -73
- package/dist/world.js +9307 -3543
- package/gpl/recipes/export_world.py +18 -1
- package/mcp/blender-server.mjs +7 -4
- package/mcp/blender.mjs +3 -4
- package/mcp/engine-server.mjs +2 -2
- package/mcp/servers.mjs +4 -4
- package/package.json +15 -9
- package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
- package/patches/three@0.185.1.patch +6594 -700
- package/scripts/apply-three-patch.mjs +62 -4
- package/src/animation-blend.ts +264 -0
- package/src/animation-composition.ts +362 -0
- package/src/animation-layers.ts +260 -0
- package/src/animation-root-motion.ts +283 -0
- package/src/animation.ts +896 -0
- package/src/assets.ts +1303 -0
- package/src/atmosphere/index.ts +335 -0
- package/src/atmosphere/luts.ts +298 -0
- package/src/atmosphere/params.ts +323 -0
- package/src/audio.ts +912 -0
- package/src/billboard.ts +124 -0
- package/src/bone-lengths.ts +157 -0
- package/src/camera-shake.ts +116 -0
- package/src/canvas-layer.ts +47 -0
- package/src/clip-audit.ts +401 -0
- package/src/clustered-batch.ts +492 -0
- package/src/clustered-mesh.ts +638 -0
- package/src/compute-driven.ts +176 -0
- package/src/compute-timing.ts +318 -0
- package/src/config.ts +593 -0
- package/src/debug.ts +82 -0
- package/src/engine-render-hook.ts +25 -0
- package/src/entities.ts +79 -0
- package/src/entity-snapshot.ts +53 -0
- package/src/flight.ts +683 -0
- package/src/fluid-field.ts +748 -0
- package/src/fluid-particles.ts +1253 -0
- package/src/frame-budget.ts +1368 -0
- package/src/game.ts +2408 -0
- package/src/geometry-capture.ts +1098 -0
- package/src/gpu-class.ts +160 -0
- package/src/gpu-frame-observation.ts +424 -0
- package/src/gpu-readback.ts +143 -0
- package/src/gpu-scene-bvh.ts +464 -0
- package/src/grounding.ts +100 -0
- package/src/hot.ts +161 -0
- package/src/import-meta.d.ts +13 -0
- package/src/index.ts +1536 -0
- package/src/input.ts +690 -0
- package/src/instanced-batch-lod.ts +283 -0
- package/src/instanced-batch.ts +274 -0
- package/src/interpolation.ts +129 -0
- package/src/launch-diagnostics.ts +161 -0
- package/src/loop.ts +574 -0
- package/src/matrix-world.ts +245 -0
- package/src/merge-parts.ts +812 -0
- package/src/model-lod.ts +1315 -0
- package/src/net-protocol.ts +333 -0
- package/src/net-session.ts +477 -0
- package/src/net.ts +80 -0
- package/src/ocean/fft.ts +72 -0
- package/src/ocean/spectral.ts +728 -0
- package/src/particle-significance.ts +102 -0
- package/src/particles.ts +648 -0
- package/src/path-follow.ts +175 -0
- package/src/picking.ts +250 -0
- package/src/pipeline-census.ts +1566 -0
- package/src/platform.ts +210 -0
- package/src/playtest.ts +850 -0
- package/src/pointer-events.ts +411 -0
- package/src/pose-measure.ts +435 -0
- package/src/profiling/FrameCounters.ts +231 -0
- package/src/profiling/Spans.ts +548 -0
- package/src/profiling/opacity-convention.ts +21 -0
- package/src/profiling/render-list-validate.ts +175 -0
- package/src/profiling/render-trap-audit.ts +84 -0
- package/src/profiling/scene-warning.ts +190 -0
- package/src/profiling/span-probes.ts +191 -0
- package/src/profiling/unlit-foliage-warning.ts +149 -0
- package/src/projection-apply.ts +1529 -0
- package/src/projection-marker.ts +142 -0
- package/src/projection-plan.ts +1258 -0
- package/src/projection-skinned.ts +419 -0
- package/src/projection-stability.ts +409 -0
- package/src/projection-uniform.ts +328 -0
- package/src/random.ts +41 -0
- package/src/react-css.ts +604 -0
- package/src/react-glyphs.ts +114 -0
- package/src/react-host.ts +576 -0
- package/src/react-layout.ts +265 -0
- package/src/react.ts +60 -0
- package/src/render/alpha-antialiasing.ts +159 -0
- package/src/render/batched-velocity.ts +126 -0
- package/src/render/chain.ts +1021 -0
- package/src/render/daylight.ts +189 -0
- package/src/render/depth-pyramid.ts +596 -0
- package/src/render/foliage-alpha.ts +166 -0
- package/src/render/material-key.ts +60 -0
- package/src/render/mesh-pool.ts +144 -0
- package/src/render/probe-volume.ts +1668 -0
- package/src/render/resolution-subrect.ts +253 -0
- package/src/render/velocity.ts +442 -0
- package/src/render/virtual-shadow-pages.ts +827 -0
- package/src/render/virtual-shadow-partial.ts +174 -0
- package/src/render/virtual-shadow.ts +3330 -0
- package/src/render/world-impostor-surface.ts +722 -0
- package/src/render/world-impostor.ts +558 -0
- package/src/render-camera-cull.ts +441 -0
- package/src/render-pass-budget.ts +501 -0
- package/src/renderProjection.ts +758 -0
- package/src/renderer-config.ts +127 -0
- package/src/renderer.ts +1847 -0
- package/src/replay-protocol.ts +85 -0
- package/src/replay.ts +205 -0
- package/src/resolution-scaler.ts +819 -0
- package/src/rig-preparation.ts +271 -0
- package/src/ripple-field.ts +432 -0
- package/src/scale.ts +109 -0
- package/src/scene.ts +239 -0
- package/src/schedule.ts +155 -0
- package/src/skeletal-mesh.ts +61 -0
- package/src/skeleton.ts +100 -0
- package/src/snow-field.ts +744 -0
- package/src/softbody-topology.ts +269 -0
- package/src/softbody.ts +516 -0
- package/src/sprite-animator.ts +222 -0
- package/src/startup-readiness.ts +386 -0
- package/src/state.ts +66 -0
- package/src/static-transform.ts +274 -0
- package/src/storage-buffer.ts +253 -0
- package/src/streaming.ts +308 -0
- package/src/target-fps.ts +92 -0
- package/src/terrain-jobs-worker.ts +17 -0
- package/src/terrain-jobs.ts +353 -0
- package/src/textures.ts +39 -0
- package/src/tracers.ts +237 -0
- package/src/ui-bridge.ts +368 -0
- package/src/ui-hit-regions.ts +380 -0
- package/src/ui-layer.ts +83 -0
- package/src/ui-state.ts +220 -0
- package/src/version.ts +2 -0
- package/src/viewport.ts +253 -0
- package/src/warmup.ts +1357 -0
- package/src/water-surface.ts +384 -0
- package/src/wave-field.ts +524 -0
- package/src/world-capabilities.ts +131 -0
- package/src/world-cell-proxy.ts +392 -0
- package/src/world-cells.ts +10564 -0
- package/src/world-gpu-scene.ts +3354 -0
- package/src/world-heightmap.ts +82 -0
- package/src/world-package.ts +469 -0
- package/src/world-passes.ts +582 -0
- package/src/world-region.ts +17 -0
- package/src/world-terrain-splat.ts +564 -0
- package/src/world-tiles.ts +3826 -0
- package/src/world-topology.ts +370 -0
- package/src/world-validate.ts +48 -0
- package/src/world.ts +805 -0
package/src/audio.ts
ADDED
|
@@ -0,0 +1,912 @@
|
|
|
1
|
+
import { AudioListener, Object3D, PositionalAudio, Audio as ThreeAudio, type Vector3 } from "three";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Bus-level dynamics compression, every value the game's.
|
|
5
|
+
*
|
|
6
|
+
* All five are required and none has an engine default: a compressor is a mix decision, and a
|
|
7
|
+
* bus that filled in the threshold itself would be deciding how loud the game is. The ranges are
|
|
8
|
+
* Web Audio's own — threshold -100 to 0 dBFS, knee 0–40 dB, ratio 1–20, attack and release
|
|
9
|
+
* 0–1 s, where 0 is an instant response — and anything outside them throws rather than being
|
|
10
|
+
* quietly clamped into a mix the game did not ask for.
|
|
11
|
+
*/
|
|
12
|
+
export interface IAudioCompressorOptions {
|
|
13
|
+
/** Level above which the bus is compressed, in dBFS. Must be finite and between -100 and 0. */
|
|
14
|
+
readonly threshold: number;
|
|
15
|
+
/** Width of the soft transition around `threshold`, in dB. Must be finite and 0–40. */
|
|
16
|
+
readonly knee: number;
|
|
17
|
+
/** Input:output ratio above the threshold. Must be finite and 1–20. */
|
|
18
|
+
readonly ratio: number;
|
|
19
|
+
/** Seconds to reach full compression once a peak arrives. Must be finite and 0–1. */
|
|
20
|
+
readonly attack: number;
|
|
21
|
+
/** Seconds to return to unity once the mix falls back. Must be finite and 0–1. */
|
|
22
|
+
readonly release: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface IAudioBusOptions {
|
|
26
|
+
readonly camera: Object3D;
|
|
27
|
+
/**
|
|
28
|
+
* A compressor on this bus's master, holding a loud mix below clipping.
|
|
29
|
+
*
|
|
30
|
+
* Every voice sums into it before the bus's volume gain, so it sees the mix rather than each
|
|
31
|
+
* cue alone — which is the whole point: three cues that are each fine and add up to a clipped
|
|
32
|
+
* master is a defect no per-voice option can see, and a compressor that sat after the gain
|
|
33
|
+
* would be working on a level the bus volume had already moved. Opt in, and every value comes
|
|
34
|
+
* from the game. A runtime with no dynamics node reports `compressor` in `unsupported` rather
|
|
35
|
+
* than playing on uncompressed and quiet about it.
|
|
36
|
+
*/
|
|
37
|
+
readonly compressor?: IAudioCompressorOptions;
|
|
38
|
+
readonly gestureTarget?: EventTarget;
|
|
39
|
+
readonly listener?: AudioListener;
|
|
40
|
+
readonly source?: () => EventTarget | undefined;
|
|
41
|
+
/**
|
|
42
|
+
* Ceiling on simultaneously sounding one-shots. Past it the oldest voice is stopped and its
|
|
43
|
+
* slot reused: a firefight generates far more cues than a listener can resolve, and the newest
|
|
44
|
+
* event is always the one they need to hear. Looping voices from `music` are exempt.
|
|
45
|
+
* Defaults to 48.
|
|
46
|
+
*/
|
|
47
|
+
readonly maxVoices?: number;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface IAudioPlayOptions {
|
|
51
|
+
/**
|
|
52
|
+
* What this cue is, for anything reading back what the game played — a playtest above all.
|
|
53
|
+
*
|
|
54
|
+
* Nothing about the sound changes. Every other audio check answers "is the file right": that it
|
|
55
|
+
* exists, decodes, and is inside its byte budget. None of them can answer "did the game say the
|
|
56
|
+
* general-quarters line twice", which is the class of defect players actually report, so the bus
|
|
57
|
+
* keeps a ledger of the labels it was given.
|
|
58
|
+
*/
|
|
59
|
+
readonly cue?: string;
|
|
60
|
+
readonly fade?: number;
|
|
61
|
+
readonly loop?: boolean;
|
|
62
|
+
readonly volume?: number;
|
|
63
|
+
/**
|
|
64
|
+
* Metres from the source where positional attenuation begins; `playAt` only. Three's panner
|
|
65
|
+
* default of 1 m makes a shot 20 m away all but inaudible — raise this to keep mid-distance
|
|
66
|
+
* sounds loud. Must be finite and positive.
|
|
67
|
+
*/
|
|
68
|
+
readonly refDistance?: number;
|
|
69
|
+
/**
|
|
70
|
+
* How fast volume falls off past `refDistance`; `playAt` only. 0 keeps the sound at full
|
|
71
|
+
* volume at any distance. Must be finite and non-negative.
|
|
72
|
+
*/
|
|
73
|
+
readonly rolloffFactor?: number;
|
|
74
|
+
/**
|
|
75
|
+
* Pitch offset in cents; ±100 is a semitone. Applied before the first sample rather than
|
|
76
|
+
* through three's `setDetune`, which ramps over ~30 ms and turns a percussive attack into an
|
|
77
|
+
* audible sweep. A few dozen cents of per-shot spread is what stops a repeated sample
|
|
78
|
+
* comb-filtering with its own copies into a metallic buzz.
|
|
79
|
+
*/
|
|
80
|
+
readonly detune?: number;
|
|
81
|
+
/**
|
|
82
|
+
* Seconds of the buffer to pass before an exponential cut-off. A 1.4 s gunshot fired ten times
|
|
83
|
+
* a second stacks fourteen overlapping tails into mush; truncating all but the last keeps the
|
|
84
|
+
* transient and drops the wash. Must be finite and positive.
|
|
85
|
+
*/
|
|
86
|
+
readonly cutoffSeconds?: number;
|
|
87
|
+
/**
|
|
88
|
+
* Low-pass corner in Hz. Air and geometry eat the top of a sound as it crosses a space, and a
|
|
89
|
+
* sample played flat at every range is the loudest tell that a game's audio is not in a place.
|
|
90
|
+
* Must be finite and positive.
|
|
91
|
+
*/
|
|
92
|
+
readonly lowpassHz?: number;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface IAudioRuntimeSnapshot {
|
|
96
|
+
/**
|
|
97
|
+
* How many times each labelled cue has sounded, across every live bus.
|
|
98
|
+
*
|
|
99
|
+
* This is the only observation that can answer "what did the game actually say, and how often".
|
|
100
|
+
* Every other audio check in the repository is about the *file* — that it exists, decodes and is
|
|
101
|
+
* inside its budget — and all of them stay green while a one-shot line plays a second time
|
|
102
|
+
* halfway through a match, which is the defect players report. A game opts a cue in by passing
|
|
103
|
+
* `cue` to `play`/`playAt`; unlabelled sounds never appear here.
|
|
104
|
+
*/
|
|
105
|
+
readonly cues: Readonly<Record<string, number>>;
|
|
106
|
+
/** The most recent labelled cues in the order they sounded, bounded per bus. */
|
|
107
|
+
readonly recentCues: ReadonlyArray<{ readonly atMs: number; readonly cue: string }>;
|
|
108
|
+
readonly queued: number;
|
|
109
|
+
readonly voices: number;
|
|
110
|
+
/** Retired voices held for reuse. Bounded by peak concurrency, never by session length. */
|
|
111
|
+
readonly pooled: number;
|
|
112
|
+
/**
|
|
113
|
+
* Voices stopped mid-cue by `pause` and holding their position. Nonzero here while a game
|
|
114
|
+
* claims to be running is a menu that muted the world and forgot to give it back.
|
|
115
|
+
*/
|
|
116
|
+
readonly paused: number;
|
|
117
|
+
/**
|
|
118
|
+
* Cue-shaping options this runtime accepted and could not honour, sorted and de-duplicated.
|
|
119
|
+
*
|
|
120
|
+
* The native host binds a biquad filter and a compressor but no schedulable `detune`, so
|
|
121
|
+
* `detune` is silently dropped there. A mix tuned on the web and shipped to a phone is flat in
|
|
122
|
+
* a way nothing else reports, and a build can be failed on this.
|
|
123
|
+
*/
|
|
124
|
+
readonly unsupported: readonly string[];
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The live buses and the cue ledger, held on `globalThis` rather than in this module.
|
|
129
|
+
*
|
|
130
|
+
* Two reasons, and the second is why this is not over-engineering. The ledger has to outlive the
|
|
131
|
+
* bus, because a scene change disposes one and builds another and the question being asked is
|
|
132
|
+
* "did this one-shot line play again after the restart". And core ships one bundle per entry point
|
|
133
|
+
* with no shared chunks (`splitting: false`), so a game importing `@threenative/core` and
|
|
134
|
+
* `@threenative/core/playtest` loads **two copies of this module**, each with its own state: the
|
|
135
|
+
* playtest bridge runs in the second copy, so every audio observation it ever published — voices,
|
|
136
|
+
* pooled, paused, unsupported — described an empty registry no game had touched, and read as a
|
|
137
|
+
* clean zero rather than "not measured". State something else reads back has to outlive the copy
|
|
138
|
+
* it was written into.
|
|
139
|
+
*/
|
|
140
|
+
const AUDIO_STATE = Symbol.for("threenative.audio.runtime");
|
|
141
|
+
|
|
142
|
+
interface IAudioRuntimeState {
|
|
143
|
+
readonly buses: Set<AudioBus>;
|
|
144
|
+
readonly cueCounts: Map<string, number>;
|
|
145
|
+
cueLog: Array<{ atMs: number; cue: string }>;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function audioState(): IAudioRuntimeState {
|
|
149
|
+
const host = globalThis as Record<symbol, unknown>;
|
|
150
|
+
const existing = host[AUDIO_STATE] as IAudioRuntimeState | undefined;
|
|
151
|
+
if (existing !== undefined) return existing;
|
|
152
|
+
const created: IAudioRuntimeState = { buses: new Set(), cueCounts: new Map(), cueLog: [] };
|
|
153
|
+
host[AUDIO_STATE] = created;
|
|
154
|
+
return created;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Records one labelled cue. Bounded: a session that plays for hours keeps the last 200. */
|
|
158
|
+
function noteCue(cue: string | undefined): void {
|
|
159
|
+
if (cue === undefined || cue.length === 0) return;
|
|
160
|
+
const state = audioState();
|
|
161
|
+
state.cueCounts.set(cue, (state.cueCounts.get(cue) ?? 0) + 1);
|
|
162
|
+
state.cueLog.push({ atMs: Math.round(globalThis.performance?.now() ?? Date.now()), cue });
|
|
163
|
+
if (state.cueLog.length > 200) state.cueLog = state.cueLog.slice(-200);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Forgets every recorded cue.
|
|
168
|
+
*
|
|
169
|
+
* @situation clear the recorded audio cue counts between tests so one test cannot read another's plays
|
|
170
|
+
* @example resetAudioCueLedger();
|
|
171
|
+
*/
|
|
172
|
+
export function resetAudioCueLedger(): void {
|
|
173
|
+
const state = audioState();
|
|
174
|
+
state.cueCounts.clear();
|
|
175
|
+
state.cueLog = [];
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const DEFAULT_MAX_VOICES = 48;
|
|
179
|
+
/** Above 20 kHz a low-pass is inaudible, so this doubles as "no filter". */
|
|
180
|
+
const OPEN_LOWPASS_HZ = 20_000;
|
|
181
|
+
/**
|
|
182
|
+
* Ramp back in over this on `resume`, and settle a `setVolume` with no fade over it.
|
|
183
|
+
*
|
|
184
|
+
* A buffer restarted mid-waveform steps the signal, and a step is a click. 15 ms is under a
|
|
185
|
+
* frame and inaudible as a fade, which is the shortest thing that is not a click.
|
|
186
|
+
*/
|
|
187
|
+
const CLICKLESS_SECONDS = 0.015;
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Every voice this bus has ever played, one-shot or looping, positional or flat.
|
|
191
|
+
*
|
|
192
|
+
* A voice is recycled rather than rebuilt. Each one owns a `GainNode`, a `PannerNode` when it is
|
|
193
|
+
* positional, and an `Object3D` in whatever scene graph it was parented into; minting a fresh set
|
|
194
|
+
* per cue and abandoning them is unbounded growth in three places at once — scene children walked
|
|
195
|
+
* every frame, nodes left connected to the listener, and garbage produced on the hottest path a
|
|
196
|
+
* game has. A shooter emits hundreds of footsteps, shots and impacts a minute, so that growth is
|
|
197
|
+
* measured in a single round, not over a session.
|
|
198
|
+
*
|
|
199
|
+
* The pool is bounded by peak concurrency: a bus that never plays more than eight cues at once
|
|
200
|
+
* holds eight voices forever, whatever its uptime.
|
|
201
|
+
*/
|
|
202
|
+
type PooledVoice = {
|
|
203
|
+
voice: ThreeAudio<AudioNode>;
|
|
204
|
+
/** Context time playback began; the stealing policy sorts on it. */
|
|
205
|
+
startedAt: number;
|
|
206
|
+
/** Built on this voice's first filtered cue and retuned after, never rebuilt. */
|
|
207
|
+
filter: BiquadFilterNode | undefined;
|
|
208
|
+
/** Looping voices are exempt from stealing and never self-retire. */
|
|
209
|
+
looping: boolean;
|
|
210
|
+
/** Sounded seconds so far, carried across pauses so a cut-off resumes with its tail intact. */
|
|
211
|
+
elapsed: number;
|
|
212
|
+
/** Stopped by `pause` and holding its position; `resume` is the only thing that starts it. */
|
|
213
|
+
held: boolean;
|
|
214
|
+
/** The cue's target gain, restated on resume because a scheduled cut-off may have run it down. */
|
|
215
|
+
volume: number;
|
|
216
|
+
/** The cue's `cutoffSeconds`, re-armed for the remainder after a pause. */
|
|
217
|
+
cutoff: number | undefined;
|
|
218
|
+
/** The cue's `detune`. A resume builds a fresh source node, which carries none of it over. */
|
|
219
|
+
detune: number;
|
|
220
|
+
/**
|
|
221
|
+
* Which free list this voice goes back to. Recorded at construction rather than sniffed:
|
|
222
|
+
* three's `PositionalAudio` carries no `isPositionalAudio` marker, so a duck-typed check
|
|
223
|
+
* silently files every panner on the flat list and the pool never reuses one.
|
|
224
|
+
*/
|
|
225
|
+
positional: boolean;
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
export class AudioBus {
|
|
229
|
+
readonly listener: AudioListener;
|
|
230
|
+
#camera: Object3D;
|
|
231
|
+
#gestureTarget: EventTarget | undefined;
|
|
232
|
+
#gesture: (() => void) | undefined;
|
|
233
|
+
#queue: Array<{ start: () => void; voice: ThreeAudio<AudioNode> }> = [];
|
|
234
|
+
#voices = new Set<ThreeAudio<AudioNode>>();
|
|
235
|
+
/** Sounding voices, in start order, so the oldest can be stolen without a scan. */
|
|
236
|
+
#live: PooledVoice[] = [];
|
|
237
|
+
/** Retired voices ready to sound again, split by kind: a panner cannot be un-built. */
|
|
238
|
+
#freeFlat: PooledVoice[] = [];
|
|
239
|
+
#freePositional: PooledVoice[] = [];
|
|
240
|
+
#maxVoices: number;
|
|
241
|
+
/** The bus master compressor, ahead of the listener's volume gain. See `#installCompressor`. */
|
|
242
|
+
#compressor: DynamicsCompressorNode | undefined;
|
|
243
|
+
#unlocked = false;
|
|
244
|
+
#disposed = false;
|
|
245
|
+
#paused = false;
|
|
246
|
+
#volume = 1;
|
|
247
|
+
/** Names of cue options this runtime dropped. Reported once each, never per cue. */
|
|
248
|
+
#unsupported = new Set<string>();
|
|
249
|
+
|
|
250
|
+
constructor(options: IAudioBusOptions) {
|
|
251
|
+
const maxVoices = options.maxVoices ?? DEFAULT_MAX_VOICES;
|
|
252
|
+
if (!Number.isInteger(maxVoices) || maxVoices < 1)
|
|
253
|
+
throw new RangeError("maxVoices must be a positive integer.");
|
|
254
|
+
this.#maxVoices = maxVoices;
|
|
255
|
+
this.#camera = options.camera;
|
|
256
|
+
this.listener = options.listener ?? new AudioListener();
|
|
257
|
+
if (options.compressor !== undefined) this.#installCompressor(options.compressor);
|
|
258
|
+
const source = options.source ?? (() => (typeof window === "undefined" ? undefined : window));
|
|
259
|
+
this.#gestureTarget = options.gestureTarget ?? source();
|
|
260
|
+
this.setCamera(options.camera);
|
|
261
|
+
this.#gesture = () => {
|
|
262
|
+
void this.unlock().catch(() => undefined);
|
|
263
|
+
};
|
|
264
|
+
for (const event of ["keydown", "pointerdown", "touchstart"] as const) {
|
|
265
|
+
this.#gestureTarget?.addEventListener(event, this.#gesture);
|
|
266
|
+
}
|
|
267
|
+
if (this.#unsupported.size > 0) this.#flushUnsupported();
|
|
268
|
+
audioState().buses.add(this);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Warn about cue shaping this runtime dropped, once per option, before the first frame.
|
|
273
|
+
*
|
|
274
|
+
* `#dropped` is reached while a cue plays, which is too late to act on and easy to miss in a
|
|
275
|
+
* device log. A bus asked for a compressor it cannot have knows at construction, so that case
|
|
276
|
+
* is reported here instead of waiting for a mix to prove it.
|
|
277
|
+
*/
|
|
278
|
+
#flushUnsupported(): void {
|
|
279
|
+
for (const option of this.#unsupported) {
|
|
280
|
+
console.warn(`AudioBus: this runtime cannot honour "${option}"; the cue sounds without it.`);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
get queued(): number {
|
|
285
|
+
return this.#queue.length;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
get voices(): number {
|
|
289
|
+
return this.#voices.size;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Retired voices held for reuse. This is the number that used to climb without limit: it is
|
|
294
|
+
* now bounded by how many cues have ever sounded at once, so a gate can pin it.
|
|
295
|
+
*/
|
|
296
|
+
get pooled(): number {
|
|
297
|
+
return this.#freeFlat.length + this.#freePositional.length;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Voices holding their position across a `pause`. */
|
|
301
|
+
get pausedVoices(): number {
|
|
302
|
+
let held = 0;
|
|
303
|
+
for (const entry of this.#live) if (entry.held) held += 1;
|
|
304
|
+
return held;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** True between `pause` and `resume`. */
|
|
308
|
+
get paused(): boolean {
|
|
309
|
+
return this.#paused;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** The master volume last asked for — the target, not a point some ramp is passing through. */
|
|
313
|
+
get volume(): number {
|
|
314
|
+
return this.#volume;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** @see IAudioRuntimeSnapshot.unsupported */
|
|
318
|
+
get unsupported(): readonly string[] {
|
|
319
|
+
return [...this.#unsupported].sort();
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* The compressor on this bus's master, or `undefined` when the bus has none — either because
|
|
324
|
+
* the game did not ask for one or because this runtime has no dynamics node.
|
|
325
|
+
*
|
|
326
|
+
* Exposed so a game can read `reduction` off it, which is the only observation that answers
|
|
327
|
+
* "is the compressor doing anything", and so a playtest can assert on it.
|
|
328
|
+
*/
|
|
329
|
+
get compressor(): DynamicsCompressorNode | undefined {
|
|
330
|
+
return this.#compressor;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/**
|
|
334
|
+
* The whole bus's level, which is what a volume slider and a duck both move.
|
|
335
|
+
*
|
|
336
|
+
* One bus per category — ambience, effects, music — makes this the mixer: ducking the wood
|
|
337
|
+
* under a discovery cue is `ambience.setVolume(0.35, 0.4)` and `setVolume(1, 0.8)` after. It
|
|
338
|
+
* rides the listener's gain, so it costs nothing per voice and applies to cues already sounding.
|
|
339
|
+
*
|
|
340
|
+
* A bus constructed with a shared `listener` shares that listener's master with every other bus
|
|
341
|
+
* on it; give each category its own bus (the default) to mix them apart.
|
|
342
|
+
*
|
|
343
|
+
* @param volume Linear gain, 0 or greater.
|
|
344
|
+
* @param fade Seconds to reach it. Defaults to a 15 ms settle, which is a level change rather
|
|
345
|
+
* than a fade — the shortest move that does not click.
|
|
346
|
+
*/
|
|
347
|
+
setVolume(volume: number, fade = 0): void {
|
|
348
|
+
if (!Number.isFinite(volume) || volume < 0)
|
|
349
|
+
throw new RangeError("volume must be finite and non-negative.");
|
|
350
|
+
if (!Number.isFinite(fade) || fade < 0)
|
|
351
|
+
throw new RangeError("fade must be finite and non-negative.");
|
|
352
|
+
this.#volume = volume;
|
|
353
|
+
const gain = this.listener.gain.gain;
|
|
354
|
+
const now = this.listener.context.currentTime;
|
|
355
|
+
gain.cancelScheduledValues?.(now);
|
|
356
|
+
if (fade > 0) {
|
|
357
|
+
gain.setValueAtTime(gain.value, now);
|
|
358
|
+
gain.linearRampToValueAtTime(volume, now + fade);
|
|
359
|
+
} else {
|
|
360
|
+
// Not `setValueAtTime`: an instant jump on a sounding bus is the same click a hard cut is.
|
|
361
|
+
gain.setTargetAtTime(volume, now, CLICKLESS_SECONDS);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Stop every sounding voice where it stands and hold its position.
|
|
367
|
+
*
|
|
368
|
+
* The difference from `stop` is what happens next: a paused bed resumes mid-bar, a stopped one
|
|
369
|
+
* starts over. Cues asked for while paused stay queued and sound on `resume`, so a menu opened
|
|
370
|
+
* during a burst does not fire the backlog at the player when they close it.
|
|
371
|
+
*
|
|
372
|
+
* The audio context keeps running — suspending it would silence every other bus sharing it.
|
|
373
|
+
*/
|
|
374
|
+
pause(): void {
|
|
375
|
+
if (this.#disposed || this.#paused) return;
|
|
376
|
+
this.#paused = true;
|
|
377
|
+
const now = this.listener.context.currentTime;
|
|
378
|
+
for (const entry of this.#live) {
|
|
379
|
+
const voice = entry.voice;
|
|
380
|
+
if (!voice.isPlaying) continue;
|
|
381
|
+
entry.elapsed += Math.max(now - entry.startedAt, 0);
|
|
382
|
+
// three's `pause` detaches `onended` before it stops the node, so the reclaim hook this
|
|
383
|
+
// bus installed does not fire and the voice stays live and accounted for.
|
|
384
|
+
voice.pause();
|
|
385
|
+
entry.held = true;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Sound the held voices again from where they stopped, then release anything queued. */
|
|
390
|
+
resume(): void {
|
|
391
|
+
if (this.#disposed || !this.#paused) return;
|
|
392
|
+
this.#paused = false;
|
|
393
|
+
for (const entry of [...this.#live]) {
|
|
394
|
+
if (!entry.held) continue;
|
|
395
|
+
entry.held = false;
|
|
396
|
+
// A one-shot whose cut-off ran out while the game sat in a menu has nothing left to sound.
|
|
397
|
+
if (entry.cutoff !== undefined && !entry.looping && entry.cutoff - entry.elapsed <= 0) {
|
|
398
|
+
this.#reclaim(entry);
|
|
399
|
+
continue;
|
|
400
|
+
}
|
|
401
|
+
this.#sound(entry, CLICKLESS_SECONDS);
|
|
402
|
+
}
|
|
403
|
+
this.#flushQueue();
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* Put a compressor where every voice sums, ahead of this bus's volume gain.
|
|
408
|
+
*
|
|
409
|
+
* Three wires a voice's gain straight to `listener.getInput()` in its own constructor, and the
|
|
410
|
+
* listener's input is the bus's volume gain — so the only honest place for a bus compressor is
|
|
411
|
+
* the voice side of that junction, which is what `#attachToMaster` splices it into. Its
|
|
412
|
+
* alternative, `AudioListener.setFilter`, sits *after* the gain and would compress a mix the
|
|
413
|
+
* volume slider had already moved. It also shares the listener's single filter slot, so a game
|
|
414
|
+
* with two buses on one listener would have the second compressor overwrite the first.
|
|
415
|
+
*/
|
|
416
|
+
#installCompressor(options: IAudioCompressorOptions): void {
|
|
417
|
+
assertCompressor(options);
|
|
418
|
+
const context = this.listener.context as AudioContext & {
|
|
419
|
+
createDynamicsCompressor?: () => DynamicsCompressorNode;
|
|
420
|
+
};
|
|
421
|
+
if (context.createDynamicsCompressor === undefined) {
|
|
422
|
+
this.#dropped("compressor");
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
const compressor = context.createDynamicsCompressor();
|
|
426
|
+
// Every value is the game's, written before the node hears a sample.
|
|
427
|
+
for (const name of ["threshold", "knee", "ratio", "attack", "release"] as const) {
|
|
428
|
+
compressor[name].value = options[name];
|
|
429
|
+
}
|
|
430
|
+
// The compressor's own output is the bus gain, so it is the one node every voice reaches
|
|
431
|
+
// through rather than past. A bus sharing a provided listener still reaches that gain
|
|
432
|
+
// directly, so installing a compressor here never silences another bus.
|
|
433
|
+
compressor.connect(this.listener.getInput());
|
|
434
|
+
this.#compressor = compressor;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Route a freshly constructed voice into the bus master, through the compressor when there is one.
|
|
439
|
+
*
|
|
440
|
+
* The splice is the price of three not offering a way to route a voice anywhere but straight
|
|
441
|
+
* into the listener. It is paid once per pooled voice, at claim time, so a bus pays for it at
|
|
442
|
+
* peak concurrency and never again.
|
|
443
|
+
*/
|
|
444
|
+
#attachToMaster(voice: ThreeAudio<AudioNode>): ThreeAudio<AudioNode> {
|
|
445
|
+
if (this.#compressor === undefined) return voice;
|
|
446
|
+
voice.gain.disconnect();
|
|
447
|
+
voice.gain.connect(this.#compressor);
|
|
448
|
+
return voice;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
setCamera(camera: Object3D): void {
|
|
452
|
+
this.#camera = camera;
|
|
453
|
+
camera.add(this.listener);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
reparent(camera: Object3D): void {
|
|
457
|
+
this.setCamera(camera);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
async unlock(): Promise<void> {
|
|
461
|
+
if (this.#disposed || this.#unlocked) return;
|
|
462
|
+
const context = this.listener.context as AudioContext & { resume?: () => Promise<void> };
|
|
463
|
+
if (context.resume !== undefined) await context.resume();
|
|
464
|
+
this.#unlocked = true;
|
|
465
|
+
this.#flushQueue();
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* A cue with no place: the listener's own weapon, UI, narration.
|
|
470
|
+
*
|
|
471
|
+
* The returned voice is valid for as long as it is sounding. Once it ends the bus reclaims it
|
|
472
|
+
* and may hand the same object to a later cue, so a caller holding the reference past that
|
|
473
|
+
* point is addressing somebody else's sound. Read `isPlaying` before touching a voice you kept.
|
|
474
|
+
*/
|
|
475
|
+
play(buffer: AudioBuffer, options: IAudioPlayOptions = {}): ThreeAudio {
|
|
476
|
+
assertBuffer(buffer);
|
|
477
|
+
assertOptions(options);
|
|
478
|
+
noteCue(options.cue);
|
|
479
|
+
const entry = this.#claimFlat(options.loop ?? false);
|
|
480
|
+
const voice = entry.voice as ThreeAudio;
|
|
481
|
+
configureVoice(voice, options);
|
|
482
|
+
voice.setBuffer(buffer);
|
|
483
|
+
this.#queueOrStart(entry, options);
|
|
484
|
+
return voice;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* A cue somewhere in the world, at a fixed point or riding a moving object.
|
|
489
|
+
*
|
|
490
|
+
* A `Vector3` source is read in the coordinate space of the camera's parent, which is the
|
|
491
|
+
* scene in the ordinary case. Pass an `Object3D` to weld the cue to something that moves.
|
|
492
|
+
*
|
|
493
|
+
* The same reclaim rule as `play` applies to the returned voice.
|
|
494
|
+
*/
|
|
495
|
+
playAt(
|
|
496
|
+
buffer: AudioBuffer,
|
|
497
|
+
source: Object3D | Vector3,
|
|
498
|
+
options: IAudioPlayOptions = {},
|
|
499
|
+
): PositionalAudio {
|
|
500
|
+
assertBuffer(buffer);
|
|
501
|
+
assertOptions(options);
|
|
502
|
+
noteCue(options.cue);
|
|
503
|
+
if (typeof (this.listener.context as { createPanner?: unknown }).createPanner !== "function")
|
|
504
|
+
throw new Error("AudioBus.playAt needs createPanner(); this runtime has none.");
|
|
505
|
+
const entry = this.#claimPositional(options.loop ?? false);
|
|
506
|
+
const voice = entry.voice as PositionalAudio;
|
|
507
|
+
configureVoice(voice, options);
|
|
508
|
+
// A recycled voice carries the previous cue's falloff, so both are restated every time
|
|
509
|
+
// rather than only when the caller supplies them.
|
|
510
|
+
voice.setRefDistance(options.refDistance ?? 1);
|
|
511
|
+
voice.setRolloffFactor(options.rolloffFactor ?? 1);
|
|
512
|
+
voice.setBuffer(buffer);
|
|
513
|
+
if (source instanceof Object3D) source.add(voice);
|
|
514
|
+
else {
|
|
515
|
+
voice.position.copy(source);
|
|
516
|
+
(this.#camera.parent ?? this.#camera).add(voice);
|
|
517
|
+
// The panner reads its position off the world matrix, and this voice moved after the
|
|
518
|
+
// renderer's last update. Without this the cue plays where the slot last sounded.
|
|
519
|
+
voice.updateMatrixWorld(true);
|
|
520
|
+
}
|
|
521
|
+
this.#queueOrStart(entry, options);
|
|
522
|
+
return voice;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
music(buffer: AudioBuffer, options: IAudioPlayOptions = {}): ThreeAudio {
|
|
526
|
+
return this.play(buffer, { ...options, loop: options.loop ?? true });
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/**
|
|
530
|
+
* Stop one voice and give it back to the pool.
|
|
531
|
+
*
|
|
532
|
+
* The missing primitive: `stop()` silenced every voice or none, and stopping the handle
|
|
533
|
+
* directly does not work — three's `Audio.stop()` detaches `onended` before stopping the node,
|
|
534
|
+
* so the bus's reclaim hook never fires and the voice leaks out of the pool while staying in
|
|
535
|
+
* the scene. A game that wants one entity's loop to end needs exactly this, and `playAt` with
|
|
536
|
+
* `loop` is the obvious way to reach for it.
|
|
537
|
+
*
|
|
538
|
+
* Returns false for a voice this bus is not sounding — a stale handle from a voice already
|
|
539
|
+
* recycled, or one belonging to another bus. Reported rather than thrown: a caller stopping a
|
|
540
|
+
* sound that already ended has made no mistake.
|
|
541
|
+
*/
|
|
542
|
+
stopVoice(voice: ThreeAudio<AudioNode>): boolean {
|
|
543
|
+
if (this.#disposed) return false;
|
|
544
|
+
const entry = this.#live.find((candidate) => candidate.voice === voice);
|
|
545
|
+
if (entry === undefined) return false;
|
|
546
|
+
this.#queue = this.#queue.filter((pending) => pending.voice !== voice);
|
|
547
|
+
this.#reclaim(entry);
|
|
548
|
+
return true;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
stop(): void {
|
|
552
|
+
for (const { voice } of this.#queue) voice.removeFromParent();
|
|
553
|
+
this.#queue = [];
|
|
554
|
+
for (const entry of this.#live.splice(0)) this.#retire(entry);
|
|
555
|
+
this.#voices.clear();
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
dispose(): void {
|
|
559
|
+
if (this.#disposed) return;
|
|
560
|
+
this.#disposed = true;
|
|
561
|
+
// Every voice feeds the compressor, so it has to be lifted out again: leaving it connected
|
|
562
|
+
// keeps a node the game may still hold alive, still holding this bus's voices.
|
|
563
|
+
if (this.#compressor !== undefined) {
|
|
564
|
+
this.#compressor.disconnect();
|
|
565
|
+
this.#compressor = undefined;
|
|
566
|
+
}
|
|
567
|
+
this.stop();
|
|
568
|
+
// `stop` retires the live voices; `#retire` short-circuits its free-list push once disposed,
|
|
569
|
+
// so the only thing left is to unhook the ones already parked there.
|
|
570
|
+
for (const entry of [...this.#freeFlat, ...this.#freePositional]) {
|
|
571
|
+
entry.voice.removeFromParent();
|
|
572
|
+
entry.filter?.disconnect();
|
|
573
|
+
}
|
|
574
|
+
this.#freeFlat = [];
|
|
575
|
+
this.#freePositional = [];
|
|
576
|
+
this.listener.removeFromParent();
|
|
577
|
+
for (const event of ["keydown", "pointerdown", "touchstart"] as const) {
|
|
578
|
+
if (this.#gesture !== undefined)
|
|
579
|
+
this.#gestureTarget?.removeEventListener(event, this.#gesture);
|
|
580
|
+
}
|
|
581
|
+
audioState().buses.delete(this);
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
#queueOrStart(entry: PooledVoice, options: IAudioPlayOptions): void {
|
|
585
|
+
const start = () => this.#start(entry, options);
|
|
586
|
+
if (this.#unlocked && !this.#paused) start();
|
|
587
|
+
else this.#queue.push({ start, voice: entry.voice });
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
#flushQueue(): void {
|
|
591
|
+
if (!this.#unlocked || this.#paused) return;
|
|
592
|
+
const queued = this.#queue.splice(0);
|
|
593
|
+
for (const { start } of queued) start();
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
#start(entry: PooledVoice, options: IAudioPlayOptions): void {
|
|
597
|
+
if (this.#disposed) return;
|
|
598
|
+
// Everything a resume has to restate lives on the entry, because `pause` throws the source
|
|
599
|
+
// node away and `play` builds a new one carrying none of it.
|
|
600
|
+
entry.elapsed = 0;
|
|
601
|
+
entry.held = false;
|
|
602
|
+
entry.volume = options.volume ?? 1;
|
|
603
|
+
entry.cutoff = options.cutoffSeconds;
|
|
604
|
+
entry.detune = options.detune ?? 0;
|
|
605
|
+
this.#applyFilter(entry, options.lowpassHz ?? OPEN_LOWPASS_HZ);
|
|
606
|
+
this.#voices.add(entry.voice);
|
|
607
|
+
this.#live.push(entry);
|
|
608
|
+
this.#sound(entry, options.fade);
|
|
609
|
+
this.#enforceCeiling();
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* Sound this entry's voice, first time or after a pause, and reapply everything a fresh source
|
|
614
|
+
* node does not inherit: gain, detune, the remaining cut-off, and the reclaim hook.
|
|
615
|
+
*/
|
|
616
|
+
#sound(entry: PooledVoice, fade: number | undefined): void {
|
|
617
|
+
const voice = entry.voice;
|
|
618
|
+
voice.play();
|
|
619
|
+
const now = this.listener.context.currentTime;
|
|
620
|
+
entry.startedAt = now;
|
|
621
|
+
// Gain is driven by automation rather than `setVolume`, because a recycled voice can still
|
|
622
|
+
// carry a scheduled ramp from a cut-off cue, and a scheduled ramp beats a plain value write.
|
|
623
|
+
const gain = voice.gain.gain;
|
|
624
|
+
gain.cancelScheduledValues?.(now);
|
|
625
|
+
if (fade !== undefined && fade > 0) {
|
|
626
|
+
gain.setValueAtTime(0, now);
|
|
627
|
+
gain.linearRampToValueAtTime(entry.volume, now + fade);
|
|
628
|
+
} else {
|
|
629
|
+
gain.setValueAtTime(entry.volume, now);
|
|
630
|
+
}
|
|
631
|
+
const source = voice.source as
|
|
632
|
+
| (AudioNode & { onended?: (() => void) | null; detune?: AudioParam })
|
|
633
|
+
| null;
|
|
634
|
+
if (entry.detune !== 0) this.#applyDetune(source, entry.detune, now);
|
|
635
|
+
if (entry.cutoff !== undefined && entry.cutoff > 0 && !entry.looping) {
|
|
636
|
+
// Exponential, not linear: a linear cut across a decaying tail clicks, and `setTargetAtTime`
|
|
637
|
+
// follows the shape the tail already has. After a pause only the remainder is left to run.
|
|
638
|
+
gain.setTargetAtTime?.(0, now + Math.max(entry.cutoff - entry.elapsed, 0), 0.045);
|
|
639
|
+
}
|
|
640
|
+
if (source !== null && "onended" in source) {
|
|
641
|
+
const onended = source.onended;
|
|
642
|
+
source.onended = () => {
|
|
643
|
+
onended?.();
|
|
644
|
+
this.#reclaim(entry);
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
#applyDetune(
|
|
650
|
+
source: (AudioNode & { detune?: AudioParam }) | null,
|
|
651
|
+
detune: number,
|
|
652
|
+
now: number,
|
|
653
|
+
): void {
|
|
654
|
+
const param = source?.detune;
|
|
655
|
+
// The native host binds `detune` as an inert stand-in — it carries the three scheduling names
|
|
656
|
+
// and drops every write — while a real `AudioParam` also cancels. That is the whole
|
|
657
|
+
// difference visible from here, and a silently flat cue is worse than a named one.
|
|
658
|
+
if (param === undefined || typeof param.cancelScheduledValues !== "function") {
|
|
659
|
+
this.#dropped("detune");
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
// `setDetune` ramps over ~30 ms. On a percussive attack that is an audible pitch sweep,
|
|
663
|
+
// and de-phasing the attack is the entire point, so it has to land before the first sample.
|
|
664
|
+
param.cancelScheduledValues(now);
|
|
665
|
+
param.setValueAtTime(detune, now);
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/** Name a cue option this runtime cannot honour. Once per option, not once per cue. */
|
|
669
|
+
#dropped(option: string): void {
|
|
670
|
+
if (this.#unsupported.has(option)) return;
|
|
671
|
+
this.#unsupported.add(option);
|
|
672
|
+
console.warn(`AudioBus: this runtime cannot honour "${option}"; the cue sounds without it.`);
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/** Oldest one-shot first, so a burst of new cues never silences itself waiting for old ones. */
|
|
676
|
+
#enforceCeiling(): void {
|
|
677
|
+
if (this.#live.length <= this.#maxVoices) return;
|
|
678
|
+
for (let index = 0; index < this.#live.length && this.#live.length > this.#maxVoices; ) {
|
|
679
|
+
const entry = this.#live[index];
|
|
680
|
+
if (entry === undefined || entry.looping) {
|
|
681
|
+
index += 1;
|
|
682
|
+
continue;
|
|
683
|
+
}
|
|
684
|
+
this.#live.splice(index, 1);
|
|
685
|
+
this.#retire(entry);
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/** A voice that ran out on its own: out of the graph, back on the free list. */
|
|
690
|
+
#reclaim(entry: PooledVoice): void {
|
|
691
|
+
const index = this.#live.indexOf(entry);
|
|
692
|
+
if (index === -1) return;
|
|
693
|
+
this.#live.splice(index, 1);
|
|
694
|
+
this.#retire(entry);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
#retire(entry: PooledVoice): void {
|
|
698
|
+
const voice = entry.voice;
|
|
699
|
+
try {
|
|
700
|
+
if (voice.isPlaying) voice.stop();
|
|
701
|
+
} catch {}
|
|
702
|
+
this.#voices.delete(voice);
|
|
703
|
+
// Out of whatever scene graph it was parented into. Skipping this is the whole bug: the
|
|
704
|
+
// object outlives its sound and the scene grows for as long as the game runs.
|
|
705
|
+
voice.removeFromParent();
|
|
706
|
+
voice.setLoop(false);
|
|
707
|
+
entry.looping = false;
|
|
708
|
+
entry.held = false;
|
|
709
|
+
entry.elapsed = 0;
|
|
710
|
+
entry.cutoff = undefined;
|
|
711
|
+
entry.detune = 0;
|
|
712
|
+
if (this.#disposed) return;
|
|
713
|
+
const free = entry.positional ? this.#freePositional : this.#freeFlat;
|
|
714
|
+
if (!free.includes(entry)) free.push(entry);
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/**
|
|
718
|
+
* Recover voices a caller stopped behind the bus's back.
|
|
719
|
+
*
|
|
720
|
+
* The pool's reclaim hook rides on `source.onended`, and **three's `Audio.stop()` sets
|
|
721
|
+
* `onended` to null before it stops the node** — so a caller doing the natural thing with the
|
|
722
|
+
* handle `play`/`playAt` returned leaves the entry in `#live` for the life of the bus: off the
|
|
723
|
+
* pool, uncounted against `maxVoices`, and still parented into whatever scene graph `playAt`
|
|
724
|
+
* welded it to. That is precisely the leak the pool exists to prevent, reachable through the
|
|
725
|
+
* public API, and `stopVoice` is the correct route rather than the only one anybody will find.
|
|
726
|
+
*
|
|
727
|
+
* So the sweep runs where it is free — at claim time, when the bus needs a voice anyway. A
|
|
728
|
+
* voice that is not playing and is not held has nothing left to sound. `held` is the exception
|
|
729
|
+
* that matters: a paused voice is legitimately stopped at the node level and must survive.
|
|
730
|
+
*/
|
|
731
|
+
#sweepFinished(): void {
|
|
732
|
+
for (const entry of [...this.#live]) {
|
|
733
|
+
if (entry.held || entry.voice.isPlaying) continue;
|
|
734
|
+
// A queued voice has not started yet, so "not playing" is not "finished".
|
|
735
|
+
if (this.#queue.some((pending) => pending.voice === entry.voice)) continue;
|
|
736
|
+
this.#reclaim(entry);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
#claimFlat(looping: boolean): PooledVoice {
|
|
741
|
+
this.#sweepFinished();
|
|
742
|
+
const reused = this.#freeFlat.pop();
|
|
743
|
+
if (reused !== undefined) {
|
|
744
|
+
reused.looping = looping;
|
|
745
|
+
return reused;
|
|
746
|
+
}
|
|
747
|
+
return {
|
|
748
|
+
voice: this.#attachToMaster(new ThreeAudio(this.listener)),
|
|
749
|
+
startedAt: 0,
|
|
750
|
+
filter: undefined,
|
|
751
|
+
looping,
|
|
752
|
+
positional: false,
|
|
753
|
+
elapsed: 0,
|
|
754
|
+
held: false,
|
|
755
|
+
volume: 1,
|
|
756
|
+
cutoff: undefined,
|
|
757
|
+
detune: 0,
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
#claimPositional(looping: boolean): PooledVoice {
|
|
762
|
+
this.#sweepFinished();
|
|
763
|
+
const reused = this.#freePositional.pop();
|
|
764
|
+
if (reused !== undefined) {
|
|
765
|
+
reused.looping = looping;
|
|
766
|
+
return reused;
|
|
767
|
+
}
|
|
768
|
+
return {
|
|
769
|
+
voice: this.#attachToMaster(new PositionalAudio(this.listener)),
|
|
770
|
+
startedAt: 0,
|
|
771
|
+
filter: undefined,
|
|
772
|
+
looping,
|
|
773
|
+
positional: true,
|
|
774
|
+
elapsed: 0,
|
|
775
|
+
held: false,
|
|
776
|
+
volume: 1,
|
|
777
|
+
cutoff: undefined,
|
|
778
|
+
detune: 0,
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
/**
|
|
783
|
+
* Air absorption. One `BiquadFilterNode` is built on a voice's first filtered cue and retuned
|
|
784
|
+
* thereafter, so filtering costs one extra node per voice for the life of the bus rather than
|
|
785
|
+
* one per sound.
|
|
786
|
+
*/
|
|
787
|
+
#applyFilter(entry: PooledVoice, hz: number): void {
|
|
788
|
+
const voice = entry.voice;
|
|
789
|
+
if (hz >= OPEN_LOWPASS_HZ) {
|
|
790
|
+
if (voice.filters.length > 0) voice.setFilters([]);
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
793
|
+
const context = this.listener.context as AudioContext & {
|
|
794
|
+
createBiquadFilter?: () => BiquadFilterNode;
|
|
795
|
+
};
|
|
796
|
+
if (entry.filter === undefined) {
|
|
797
|
+
if (context.createBiquadFilter === undefined) {
|
|
798
|
+
this.#dropped("lowpassHz");
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
const filter = context.createBiquadFilter();
|
|
802
|
+
filter.type = "lowpass";
|
|
803
|
+
entry.filter = filter;
|
|
804
|
+
}
|
|
805
|
+
entry.filter.frequency.value = hz;
|
|
806
|
+
if (voice.filters.length === 0) voice.setFilters([entry.filter]);
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
export function audioRuntimeSnapshot(): IAudioRuntimeSnapshot {
|
|
811
|
+
let queued = 0;
|
|
812
|
+
let voices = 0;
|
|
813
|
+
let pooled = 0;
|
|
814
|
+
let paused = 0;
|
|
815
|
+
const unsupported = new Set<string>();
|
|
816
|
+
const state = audioState();
|
|
817
|
+
for (const bus of state.buses) {
|
|
818
|
+
queued += bus.queued;
|
|
819
|
+
voices += bus.voices;
|
|
820
|
+
pooled += bus.pooled;
|
|
821
|
+
paused += bus.pausedVoices;
|
|
822
|
+
for (const option of bus.unsupported) unsupported.add(option);
|
|
823
|
+
}
|
|
824
|
+
return {
|
|
825
|
+
cues: Object.fromEntries(state.cueCounts),
|
|
826
|
+
paused,
|
|
827
|
+
pooled,
|
|
828
|
+
queued,
|
|
829
|
+
recentCues: state.cueLog.map((entry) => ({ ...entry })),
|
|
830
|
+
unsupported: [...unsupported].sort(),
|
|
831
|
+
voices,
|
|
832
|
+
};
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
/**
|
|
836
|
+
* The compressor contract, checked before the node is built rather than after it is wired in.
|
|
837
|
+
*
|
|
838
|
+
* Ranges are Web Audio's own, so a value the platform would reject is refused here with its name
|
|
839
|
+
* rather than clamped into something the game did not ask for.
|
|
840
|
+
*/
|
|
841
|
+
function assertCompressor(options: IAudioCompressorOptions): void {
|
|
842
|
+
for (const name of ["threshold", "knee", "ratio", "attack", "release"] as const) {
|
|
843
|
+
if (!Number.isFinite(options[name])) {
|
|
844
|
+
throw new TypeError(`compressor.${name} must be a finite number.`);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
if (options.threshold < -100 || options.threshold > 0)
|
|
848
|
+
throw new RangeError("compressor.threshold must be between -100 and 0 dBFS.");
|
|
849
|
+
if (options.knee < 0 || options.knee > 40)
|
|
850
|
+
throw new RangeError("compressor.knee must be between 0 and 40 dB.");
|
|
851
|
+
if (options.ratio < 1 || options.ratio > 20)
|
|
852
|
+
throw new RangeError("compressor.ratio must be between 1 and 20.");
|
|
853
|
+
if (options.attack < 0 || options.attack > 1)
|
|
854
|
+
throw new RangeError("compressor.attack must be between 0 and 1 second.");
|
|
855
|
+
if (options.release < 0 || options.release > 1)
|
|
856
|
+
throw new RangeError("compressor.release must be between 0 and 1 second.");
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
/** Every numeric contract on a cue, checked before a voice is claimed rather than after. */
|
|
860
|
+
function assertOptions(options: IAudioPlayOptions): void {
|
|
861
|
+
// A cue that is not a label is a mistake the ledger would swallow: a number, an object, or an
|
|
862
|
+
// empty string all read as "unlabelled" in the counts and the miscount is silent.
|
|
863
|
+
if (options.cue !== undefined && (typeof options.cue !== "string" || options.cue.length === 0)) {
|
|
864
|
+
throw new TypeError("cue must be a non-empty string.");
|
|
865
|
+
}
|
|
866
|
+
if (
|
|
867
|
+
options.cutoffSeconds !== undefined &&
|
|
868
|
+
(!Number.isFinite(options.cutoffSeconds) || options.cutoffSeconds <= 0)
|
|
869
|
+
) {
|
|
870
|
+
throw new RangeError("cutoffSeconds must be finite and positive.");
|
|
871
|
+
}
|
|
872
|
+
if (
|
|
873
|
+
options.lowpassHz !== undefined &&
|
|
874
|
+
(!Number.isFinite(options.lowpassHz) || options.lowpassHz <= 0)
|
|
875
|
+
) {
|
|
876
|
+
throw new RangeError("lowpassHz must be finite and positive.");
|
|
877
|
+
}
|
|
878
|
+
if (options.detune !== undefined && !Number.isFinite(options.detune)) {
|
|
879
|
+
throw new RangeError("detune must be finite.");
|
|
880
|
+
}
|
|
881
|
+
// Volume/fade/refDistance/rolloffFactor used to be validated only in configureVoice —
|
|
882
|
+
// after play() had already claimed its voice, so a throwing option orphaned it for good.
|
|
883
|
+
const volume = options.volume ?? 1;
|
|
884
|
+
if (!Number.isFinite(volume) || volume < 0)
|
|
885
|
+
throw new RangeError("volume must be finite and non-negative.");
|
|
886
|
+
if (options.fade !== undefined && (!Number.isFinite(options.fade) || options.fade < 0)) {
|
|
887
|
+
throw new RangeError("fade must be finite and non-negative.");
|
|
888
|
+
}
|
|
889
|
+
if (
|
|
890
|
+
options.refDistance !== undefined &&
|
|
891
|
+
(!Number.isFinite(options.refDistance) || options.refDistance <= 0)
|
|
892
|
+
) {
|
|
893
|
+
throw new RangeError("refDistance must be finite and positive.");
|
|
894
|
+
}
|
|
895
|
+
if (
|
|
896
|
+
options.rolloffFactor !== undefined &&
|
|
897
|
+
(!Number.isFinite(options.rolloffFactor) || options.rolloffFactor < 0)
|
|
898
|
+
) {
|
|
899
|
+
throw new RangeError("rolloffFactor must be finite and non-negative.");
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
function configureVoice(voice: ThreeAudio<AudioNode>, options: IAudioPlayOptions): void {
|
|
904
|
+
const volume = options.volume ?? 1;
|
|
905
|
+
voice.setLoop(options.loop ?? false);
|
|
906
|
+
voice.setVolume(options.fade === undefined || options.fade === 0 ? volume : 0);
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
function assertBuffer(buffer: AudioBuffer): void {
|
|
910
|
+
if (buffer === null || buffer === undefined)
|
|
911
|
+
throw new TypeError("AudioBus requires a non-null AudioBuffer.");
|
|
912
|
+
}
|