@threenative/core 0.3.11 → 0.3.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1988 -204
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  5. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  6. package/dist/chunk-4SRAQFTU.js +133 -0
  7. package/dist/chunk-CFGTPFUH.js +231 -0
  8. package/dist/chunk-DIPIJICH.js +8916 -0
  9. package/dist/chunk-EEABDLUC.js +2237 -0
  10. package/dist/chunk-EFWZWLPY.js +1895 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-GYUZJQ7U.js +280 -0
  13. package/dist/chunk-H4J6IAJE.js +504 -0
  14. package/dist/chunk-KIRUKTBQ.js +187 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-SV4QVUTQ.js +31 -0
  17. package/dist/chunk-U4YHUKKL.js +615 -0
  18. package/dist/chunk-VP43GIWW.js +18 -0
  19. package/dist/chunk-XDTZ4QMO.js +160 -0
  20. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  21. package/dist/{game-DzMcitDO.d.ts → game-k8K3hZai.d.ts} +85 -9
  22. package/dist/hot.d.ts +5 -4
  23. package/dist/hot.js +5 -52
  24. package/dist/index.d.ts +633 -1351
  25. package/dist/index.js +12873 -23068
  26. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-DPTzeCcD.d.ts} +35 -3
  27. package/dist/playtest.d.ts +5 -4
  28. package/dist/playtest.js +25 -75
  29. package/dist/quality-BYqKGAwo.d.ts +868 -0
  30. package/dist/react-css.js +1 -215
  31. package/dist/react.d.ts +3 -2
  32. package/dist/render-environment.d.ts +170 -0
  33. package/dist/render-environment.js +352 -0
  34. package/dist/{renderer-rZm0hVqq.d.ts → renderer-BtOSseYf.d.ts} +42 -35
  35. package/dist/spells/index.d.ts +643 -0
  36. package/dist/spells/index.js +1558 -0
  37. package/dist/spells/ultra/index.d.ts +1600 -0
  38. package/dist/spells/ultra/index.js +6804 -0
  39. package/dist/terrain-jobs-worker.js +1 -123
  40. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  41. package/dist/ui-layer.js +6 -384
  42. package/dist/worker.js +13 -43
  43. package/dist/world.d.ts +988 -268
  44. package/dist/world.js +17464 -18290
  45. package/mcp/animation-server.mjs +1 -1
  46. package/mcp/animation.mjs +2 -3
  47. package/mcp/engine-server.mjs +245 -52
  48. package/mcp/servers.mjs +10 -3
  49. package/mcp/terrain.mjs +8 -0
  50. package/package.json +19 -7
  51. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  52. package/patches/three@0.187.0.patch +2004 -407
  53. package/src/animation-batch.ts +193 -0
  54. package/src/animation-layers.ts +7 -3
  55. package/src/animation.ts +209 -29
  56. package/src/asset-cache.ts +3 -3
  57. package/src/asset-memo.ts +202 -0
  58. package/src/assets.ts +437 -125
  59. package/src/auto-batch.ts +190 -44
  60. package/src/card-lod.ts +152 -0
  61. package/src/compressed-texture-preparation.ts +1008 -0
  62. package/src/compute-driven.ts +1 -1
  63. package/src/config.ts +8 -0
  64. package/src/debug.ts +103 -22
  65. package/src/dev-global.ts +54 -0
  66. package/src/engine-hooks.ts +37 -0
  67. package/src/frame-budget.ts +50 -23
  68. package/src/game-boot-phase.ts +269 -0
  69. package/src/game-dev-tools.ts +86 -0
  70. package/src/game-frame-loop.ts +958 -0
  71. package/src/game-renderer-metrics.ts +77 -0
  72. package/src/game-startup.ts +1076 -0
  73. package/src/game-ui.ts +84 -0
  74. package/src/game-validate.ts +70 -0
  75. package/src/game.ts +198 -2264
  76. package/src/gamepad-mappings.ts +269 -0
  77. package/src/generated/console-markers.ts +13 -0
  78. package/src/geometry-capture.ts +28 -4
  79. package/src/gpu-readings.ts +98 -0
  80. package/src/gpu-scene-bvh.ts +149 -36
  81. package/src/hot.ts +4 -7
  82. package/src/index.ts +141 -9
  83. package/src/input.ts +237 -25
  84. package/src/instanced-batch-lod.ts +3 -8
  85. package/src/interpolation.ts +171 -40
  86. package/src/launch-diagnostics.ts +22 -12
  87. package/src/look/ao-admission.ts +25 -0
  88. package/src/look/auto-exposure.ts +5 -16
  89. package/src/look/default-tone-mapping.ts +41 -5
  90. package/src/look/filmic-tone-mapping.ts +15 -13
  91. package/src/look/local-exposure.ts +2 -7
  92. package/src/look/look-diagnostics.ts +3 -3
  93. package/src/look/quad-pass.ts +21 -0
  94. package/src/look/quality.ts +14 -5
  95. package/src/look/unreal-bloom.ts +4 -13
  96. package/src/look/world-environment.ts +113 -103
  97. package/src/loop.ts +29 -0
  98. package/src/merge-parts.ts +20 -24
  99. package/src/model-lod.ts +139 -17
  100. package/src/particle-kinds.ts +515 -0
  101. package/src/particle-significance.ts +12 -0
  102. package/src/particles.ts +19 -10
  103. package/src/picking.ts +17 -3
  104. package/src/platform.ts +23 -4
  105. package/src/playtest.ts +27 -1
  106. package/src/profiling/FrameStages.ts +5 -6
  107. package/src/profiling/Spans.ts +3 -17
  108. package/src/profiling/debug-telemetry.ts +2 -6
  109. package/src/profiling/render-list-validate.ts +6 -15
  110. package/src/projection-apply.ts +4 -1
  111. package/src/projection-marker.ts +2 -1
  112. package/src/projection-plan.ts +9 -6
  113. package/src/quiet-markers.ts +3 -10
  114. package/src/render/cpu-bvh.ts +100 -0
  115. package/src/render/depth-pyramid.ts +6 -14
  116. package/src/render/environment/environmentContribution.ts +202 -0
  117. package/src/render/environment/environmentRadiance.ts +44 -0
  118. package/src/render/environment/environmentSampleCache.ts +56 -0
  119. package/src/render/environment/environmentSampling.ts +201 -0
  120. package/src/render/environment/environmentSnapshot.ts +71 -0
  121. package/src/render/environment/gate.ts +57 -0
  122. package/src/render/mesh-pool.ts +4 -20
  123. package/src/render/probe-trace.ts +872 -0
  124. package/src/render/probe-volume.ts +780 -34
  125. package/src/render/radiance-cache.ts +17 -0
  126. package/src/render/resolution-subrect.ts +2 -0
  127. package/src/render/rough-diffuse.ts +46 -12
  128. package/src/render/soft-shadow.ts +27 -12
  129. package/src/render/virtual-shadow-adaptive.ts +55 -0
  130. package/src/render/virtual-shadow-casters.ts +175 -0
  131. package/src/render/virtual-shadow-layers.ts +76 -0
  132. package/src/render/virtual-shadow-level.ts +224 -0
  133. package/src/render/virtual-shadow-markers.ts +193 -0
  134. package/src/render/virtual-shadow-options.ts +370 -0
  135. package/src/render/virtual-shadow-pages.ts +5 -0
  136. package/src/render/virtual-shadow-partial.ts +13 -0
  137. package/src/render/virtual-shadow.ts +231 -1008
  138. package/src/render/world-impostor-surface.ts +402 -40
  139. package/src/render/world-impostor.ts +5 -2
  140. package/src/render-camera-cull.ts +98 -3
  141. package/src/render-environment.ts +41 -0
  142. package/src/render-pass-budget.ts +34 -7
  143. package/src/renderProjection.ts +22 -0
  144. package/src/renderer-config.ts +36 -0
  145. package/src/renderer-facts.ts +37 -0
  146. package/src/renderer.ts +144 -65
  147. package/src/resolution-scaler.ts +3 -2
  148. package/src/scene-entry-inspectors.ts +61 -0
  149. package/src/snow-field.ts +2 -1
  150. package/src/spells/cast-pool.ts +361 -0
  151. package/src/spells/index.ts +177 -0
  152. package/src/spells/mechanisms.ts +295 -0
  153. package/src/spells/reaction-field.ts +415 -0
  154. package/src/spells/spell-lights.ts +139 -0
  155. package/src/spells/spell-world.ts +187 -0
  156. package/src/spells/spell.ts +397 -0
  157. package/src/spells/spells.ts +283 -0
  158. package/src/spells/ultra/engine/camera.ts +184 -0
  159. package/src/spells/ultra/engine/quality.ts +96 -0
  160. package/src/spells/ultra/index.ts +52 -0
  161. package/src/spells/ultra/main.ts +305 -0
  162. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  163. package/src/spells/ultra/spells/cast.ts +233 -0
  164. package/src/spells/ultra/spells/fire.ts +1267 -0
  165. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  166. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  167. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  168. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  169. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  170. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  171. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  172. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  173. package/src/spells/ultra/vfx/common.ts +1195 -0
  174. package/src/spells/ultra/vfx/noise.ts +441 -0
  175. package/src/startup-offscreen-bytes.ts +78 -0
  176. package/src/startup-readiness.ts +128 -34
  177. package/src/static-transform.ts +25 -19
  178. package/src/streamed-textures.ts +112 -0
  179. package/src/streaming.ts +68 -4
  180. package/src/texture-streaming.ts +331 -0
  181. package/src/version.ts +1 -1
  182. package/src/warmup.ts +56 -8
  183. package/src/water-surface.ts +9 -3
  184. package/src/worker.ts +12 -2
  185. package/src/world-bundle-safety.ts +446 -0
  186. package/src/world-cell-batches.ts +1178 -0
  187. package/src/world-cell-chunks.ts +1128 -0
  188. package/src/world-cell-data.ts +995 -0
  189. package/src/world-cell-impostors.ts +1461 -0
  190. package/src/world-cell-lod-bias.ts +151 -0
  191. package/src/world-cell-models.ts +1074 -0
  192. package/src/world-cell-options.ts +177 -0
  193. package/src/world-cell-placements.ts +798 -0
  194. package/src/world-cell-prewarm.ts +592 -0
  195. package/src/world-cell-readiness.ts +357 -0
  196. package/src/world-cell-records.ts +401 -0
  197. package/src/world-cell-render-bundles.ts +459 -0
  198. package/src/world-cell-render-gpu-dress.ts +710 -0
  199. package/src/world-cell-render-main-cull.ts +540 -0
  200. package/src/world-cell-render-shadow-claims.ts +198 -0
  201. package/src/world-cell-render-util.ts +259 -0
  202. package/src/world-cell-render.ts +1501 -0
  203. package/src/world-cell-residency.ts +754 -0
  204. package/src/world-cell-stale.ts +238 -0
  205. package/src/world-cells.ts +1335 -10418
  206. package/src/world-chunk-shadow.ts +308 -0
  207. package/src/world-collar.ts +315 -0
  208. package/src/world-gpu-flags.ts +131 -0
  209. package/src/world-gpu-readback.ts +881 -0
  210. package/src/world-gpu-reference.ts +524 -0
  211. package/src/world-gpu-scene.ts +256 -2286
  212. package/src/world-gpu-shadow.ts +203 -0
  213. package/src/world-gpu-types.ts +409 -0
  214. package/src/world-gpu-validation.ts +518 -0
  215. package/src/world-heightfield.ts +802 -0
  216. package/src/world-load-limiter.ts +111 -0
  217. package/src/world-model-sections.ts +80 -0
  218. package/src/world-noise.ts +241 -0
  219. package/src/world-package.ts +42 -0
  220. package/src/world-region.ts +1 -1
  221. package/src/world-river-ribbon.ts +282 -0
  222. package/src/world-root-frame.ts +39 -0
  223. package/src/world-shore-field.ts +91 -0
  224. package/src/world-static-pose.ts +163 -0
  225. package/src/world-surface-sampler.ts +48 -0
  226. package/src/world-terrain-splat.ts +361 -153
  227. package/src/world-tile-budget.ts +249 -0
  228. package/src/world-tile-geometry.ts +469 -0
  229. package/src/world-tile-lod.ts +408 -0
  230. package/src/world-tile-observation.ts +566 -0
  231. package/src/world-tile-stitch.ts +166 -0
  232. package/src/world-tiles.ts +247 -1755
  233. package/src/world-validate.ts +6 -14
  234. package/src/world-warm.ts +51 -0
  235. package/src/world-water-bodies.ts +359 -0
  236. package/src/world.ts +48 -741
@@ -0,0 +1,615 @@
1
+ import { hostGestureTarget, hostWindow } from './chunk-XDTZ4QMO.js';
2
+ import { AudioListener, Object3D, Audio, PositionalAudio, AudioContext } from 'three';
3
+
4
+ var AUDIO_STATE = /* @__PURE__ */ Symbol.for("threenative.audio.runtime");
5
+ function audioState() {
6
+ const host = globalThis;
7
+ const existing = host[AUDIO_STATE];
8
+ if (existing !== void 0) return existing;
9
+ const created = { buses: /* @__PURE__ */ new Set(), cueCounts: /* @__PURE__ */ new Map(), cueLog: [] };
10
+ host[AUDIO_STATE] = created;
11
+ return created;
12
+ }
13
+ function noteCue(cue) {
14
+ if (cue === void 0 || cue.length === 0) return;
15
+ const state = audioState();
16
+ state.cueCounts.set(cue, (state.cueCounts.get(cue) ?? 0) + 1);
17
+ state.cueLog.push({ atMs: Math.round(globalThis.performance?.now() ?? Date.now()), cue });
18
+ if (state.cueLog.length > 200) state.cueLog = state.cueLog.slice(-200);
19
+ }
20
+ function resetAudioCueLedger() {
21
+ const state = audioState();
22
+ state.cueCounts.clear();
23
+ state.cueLog = [];
24
+ }
25
+ var DEFAULT_MAX_VOICES = 48;
26
+ var OPEN_LOWPASS_HZ = 2e4;
27
+ var CLICKLESS_SECONDS = 0.015;
28
+ function adoptWorkerAudioContext() {
29
+ if (hostWindow() !== void 0 || typeof globalThis.AudioContext !== "function") return;
30
+ try {
31
+ AudioContext.getContext();
32
+ } catch {
33
+ AudioContext.setContext(new globalThis.AudioContext());
34
+ }
35
+ }
36
+ var AudioBus = class {
37
+ listener;
38
+ #camera;
39
+ #gestureTarget;
40
+ #gesture;
41
+ #queue = [];
42
+ #voices = /* @__PURE__ */ new Set();
43
+ /** Sounding voices, in start order, so the oldest can be stolen without a scan. */
44
+ #live = [];
45
+ /** Retired voices ready to sound again, split by kind: a panner cannot be un-built. */
46
+ #freeFlat = [];
47
+ #freePositional = [];
48
+ #maxVoices;
49
+ /** The bus master compressor, ahead of the listener's volume gain. See `#installCompressor`. */
50
+ #compressor;
51
+ #unlocked = false;
52
+ #disposed = false;
53
+ #paused = false;
54
+ #volume = 1;
55
+ /** Names of cue options this runtime dropped. Reported once each, never per cue. */
56
+ #unsupported = /* @__PURE__ */ new Set();
57
+ constructor(options) {
58
+ const maxVoices = options.maxVoices ?? DEFAULT_MAX_VOICES;
59
+ if (!Number.isInteger(maxVoices) || maxVoices < 1)
60
+ throw new RangeError("maxVoices must be a positive integer.");
61
+ this.#maxVoices = maxVoices;
62
+ this.#camera = options.camera;
63
+ if (options.listener === void 0) adoptWorkerAudioContext();
64
+ this.listener = options.listener ?? new AudioListener();
65
+ if (options.compressor !== void 0) this.#installCompressor(options.compressor);
66
+ const source = options.source ?? hostGestureTarget;
67
+ this.#gestureTarget = options.gestureTarget ?? source();
68
+ this.setCamera(options.camera);
69
+ this.#gesture = () => {
70
+ void this.unlock().catch(() => void 0);
71
+ };
72
+ for (const event of ["keydown", "pointerdown", "touchstart"]) {
73
+ this.#gestureTarget?.addEventListener(event, this.#gesture);
74
+ }
75
+ if (this.#unsupported.size > 0) this.#flushUnsupported();
76
+ audioState().buses.add(this);
77
+ }
78
+ /**
79
+ * Warn about cue shaping this runtime dropped, once per option, before the first frame.
80
+ *
81
+ * `#dropped` is reached while a cue plays, which is too late to act on and easy to miss in a
82
+ * device log. A bus asked for a compressor it cannot have knows at construction, so that case
83
+ * is reported here instead of waiting for a mix to prove it.
84
+ */
85
+ #flushUnsupported() {
86
+ for (const option of this.#unsupported) {
87
+ console.warn(`AudioBus: this runtime cannot honour "${option}"; the cue sounds without it.`);
88
+ }
89
+ }
90
+ get queued() {
91
+ return this.#queue.length;
92
+ }
93
+ get voices() {
94
+ return this.#voices.size;
95
+ }
96
+ /**
97
+ * Retired voices held for reuse. This is the number that used to climb without limit: it is
98
+ * now bounded by how many cues have ever sounded at once, so a gate can pin it.
99
+ */
100
+ get pooled() {
101
+ return this.#freeFlat.length + this.#freePositional.length;
102
+ }
103
+ /** Voices holding their position across a `pause`. */
104
+ get pausedVoices() {
105
+ let held = 0;
106
+ for (const entry of this.#live) if (entry.held) held += 1;
107
+ return held;
108
+ }
109
+ /** True between `pause` and `resume`. */
110
+ get paused() {
111
+ return this.#paused;
112
+ }
113
+ /** The master volume last asked for — the target, not a point some ramp is passing through. */
114
+ get volume() {
115
+ return this.#volume;
116
+ }
117
+ /** @see IAudioRuntimeSnapshot.unsupported */
118
+ get unsupported() {
119
+ return [...this.#unsupported].sort();
120
+ }
121
+ /**
122
+ * The compressor on this bus's master, or `undefined` when the bus has none — either because
123
+ * the game did not ask for one or because this runtime has no dynamics node.
124
+ *
125
+ * Exposed so a game can read `reduction` off it, which is the only observation that answers
126
+ * "is the compressor doing anything", and so a playtest can assert on it.
127
+ */
128
+ get compressor() {
129
+ return this.#compressor;
130
+ }
131
+ /**
132
+ * The whole bus's level, which is what a volume slider and a duck both move.
133
+ *
134
+ * One bus per category — ambience, effects, music — makes this the mixer: ducking the wood
135
+ * under a discovery cue is `ambience.setVolume(0.35, 0.4)` and `setVolume(1, 0.8)` after. It
136
+ * rides the listener's gain, so it costs nothing per voice and applies to cues already sounding.
137
+ *
138
+ * A bus constructed with a shared `listener` shares that listener's master with every other bus
139
+ * on it; give each category its own bus (the default) to mix them apart.
140
+ *
141
+ * @param volume Linear gain, 0 or greater.
142
+ * @param fade Seconds to reach it. Defaults to a 15 ms settle, which is a level change rather
143
+ * than a fade — the shortest move that does not click.
144
+ */
145
+ setVolume(volume, fade = 0) {
146
+ if (!Number.isFinite(volume) || volume < 0)
147
+ throw new RangeError("volume must be finite and non-negative.");
148
+ if (!Number.isFinite(fade) || fade < 0)
149
+ throw new RangeError("fade must be finite and non-negative.");
150
+ this.#volume = volume;
151
+ const gain = this.listener.gain.gain;
152
+ const now = this.listener.context.currentTime;
153
+ gain.cancelScheduledValues?.(now);
154
+ if (fade > 0) {
155
+ gain.setValueAtTime(gain.value, now);
156
+ gain.linearRampToValueAtTime(volume, now + fade);
157
+ } else {
158
+ gain.setTargetAtTime(volume, now, CLICKLESS_SECONDS);
159
+ }
160
+ }
161
+ /**
162
+ * Stop every sounding voice where it stands and hold its position.
163
+ *
164
+ * The difference from `stop` is what happens next: a paused bed resumes mid-bar, a stopped one
165
+ * starts over. Cues asked for while paused stay queued and sound on `resume`, so a menu opened
166
+ * during a burst does not fire the backlog at the player when they close it.
167
+ *
168
+ * The audio context keeps running — suspending it would silence every other bus sharing it.
169
+ */
170
+ pause() {
171
+ if (this.#disposed || this.#paused) return;
172
+ this.#paused = true;
173
+ const now = this.listener.context.currentTime;
174
+ for (const entry of this.#live) {
175
+ const voice = entry.voice;
176
+ if (!voice.isPlaying) continue;
177
+ entry.elapsed += Math.max(now - entry.startedAt, 0);
178
+ voice.pause();
179
+ entry.held = true;
180
+ }
181
+ }
182
+ /** Sound the held voices again from where they stopped, then release anything queued. */
183
+ resume() {
184
+ if (this.#disposed || !this.#paused) return;
185
+ this.#paused = false;
186
+ for (const entry of [...this.#live]) {
187
+ if (!entry.held) continue;
188
+ entry.held = false;
189
+ if (entry.cutoff !== void 0 && !entry.looping && entry.cutoff - entry.elapsed <= 0) {
190
+ this.#reclaim(entry);
191
+ continue;
192
+ }
193
+ this.#sound(entry, CLICKLESS_SECONDS);
194
+ }
195
+ this.#flushQueue();
196
+ }
197
+ /**
198
+ * Put a compressor where every voice sums, ahead of this bus's volume gain.
199
+ *
200
+ * Three wires a voice's gain straight to `listener.getInput()` in its own constructor, and the
201
+ * listener's input is the bus's volume gain — so the only honest place for a bus compressor is
202
+ * the voice side of that junction, which is what `#attachToMaster` splices it into. Its
203
+ * alternative, `AudioListener.setFilter`, sits *after* the gain and would compress a mix the
204
+ * volume slider had already moved. It also shares the listener's single filter slot, so a game
205
+ * with two buses on one listener would have the second compressor overwrite the first.
206
+ */
207
+ #installCompressor(options) {
208
+ assertCompressor(options);
209
+ const context = this.listener.context;
210
+ if (context.createDynamicsCompressor === void 0) {
211
+ this.#dropped("compressor");
212
+ return;
213
+ }
214
+ const compressor = context.createDynamicsCompressor();
215
+ for (const name of ["threshold", "knee", "ratio", "attack", "release"]) {
216
+ compressor[name].value = options[name];
217
+ }
218
+ compressor.connect(this.listener.getInput());
219
+ this.#compressor = compressor;
220
+ }
221
+ /**
222
+ * Route a freshly constructed voice into the bus master, through the compressor when there is one.
223
+ *
224
+ * The splice is the price of three not offering a way to route a voice anywhere but straight
225
+ * into the listener. It is paid once per pooled voice, at claim time, so a bus pays for it at
226
+ * peak concurrency and never again.
227
+ */
228
+ #attachToMaster(voice) {
229
+ if (this.#compressor === void 0) return voice;
230
+ voice.gain.disconnect();
231
+ voice.gain.connect(this.#compressor);
232
+ return voice;
233
+ }
234
+ setCamera(camera) {
235
+ this.#camera = camera;
236
+ camera.add(this.listener);
237
+ }
238
+ reparent(camera) {
239
+ this.setCamera(camera);
240
+ }
241
+ async unlock() {
242
+ if (this.#disposed || this.#unlocked) return;
243
+ const context = this.listener.context;
244
+ if (context.resume !== void 0) await context.resume();
245
+ this.#unlocked = true;
246
+ this.#flushQueue();
247
+ }
248
+ /**
249
+ * A cue with no place: the listener's own weapon, UI, narration.
250
+ *
251
+ * The returned voice is valid for as long as it is sounding. Once it ends the bus reclaims it
252
+ * and may hand the same object to a later cue, so a caller holding the reference past that
253
+ * point is addressing somebody else's sound. Read `isPlaying` before touching a voice you kept.
254
+ */
255
+ play(buffer, options = {}) {
256
+ assertBuffer(buffer);
257
+ assertOptions(options);
258
+ noteCue(options.cue);
259
+ const entry = this.#claimFlat(options.loop ?? false);
260
+ const voice = entry.voice;
261
+ configureVoice(voice, options);
262
+ voice.setBuffer(buffer);
263
+ this.#queueOrStart(entry, options);
264
+ return voice;
265
+ }
266
+ /**
267
+ * A cue somewhere in the world, at a fixed point or riding a moving object.
268
+ *
269
+ * A `Vector3` source is read in the coordinate space of the camera's parent, which is the
270
+ * scene in the ordinary case. Pass an `Object3D` to weld the cue to something that moves.
271
+ *
272
+ * The same reclaim rule as `play` applies to the returned voice.
273
+ */
274
+ playAt(buffer, source, options = {}) {
275
+ assertBuffer(buffer);
276
+ assertOptions(options);
277
+ noteCue(options.cue);
278
+ if (typeof this.listener.context.createPanner !== "function")
279
+ throw new Error("AudioBus.playAt needs createPanner(); this runtime has none.");
280
+ const entry = this.#claimPositional(options.loop ?? false);
281
+ const voice = entry.voice;
282
+ configureVoice(voice, options);
283
+ voice.setRefDistance(options.refDistance ?? 1);
284
+ voice.setRolloffFactor(options.rolloffFactor ?? 1);
285
+ voice.setBuffer(buffer);
286
+ if (source instanceof Object3D) source.add(voice);
287
+ else {
288
+ voice.position.copy(source);
289
+ (this.#camera.parent ?? this.#camera).add(voice);
290
+ voice.updateMatrixWorld(true);
291
+ }
292
+ this.#queueOrStart(entry, options);
293
+ return voice;
294
+ }
295
+ music(buffer, options = {}) {
296
+ return this.play(buffer, { ...options, loop: options.loop ?? true });
297
+ }
298
+ /**
299
+ * Stop one voice and give it back to the pool.
300
+ *
301
+ * The missing primitive: `stop()` silenced every voice or none, and stopping the handle
302
+ * directly does not work — three's `Audio.stop()` detaches `onended` before stopping the node,
303
+ * so the bus's reclaim hook never fires and the voice leaks out of the pool while staying in
304
+ * the scene. A game that wants one entity's loop to end needs exactly this, and `playAt` with
305
+ * `loop` is the obvious way to reach for it.
306
+ *
307
+ * Returns false for a voice this bus is not sounding — a stale handle from a voice already
308
+ * recycled, or one belonging to another bus. Reported rather than thrown: a caller stopping a
309
+ * sound that already ended has made no mistake.
310
+ */
311
+ stopVoice(voice) {
312
+ if (this.#disposed) return false;
313
+ const entry = this.#live.find((candidate) => candidate.voice === voice);
314
+ if (entry === void 0) return false;
315
+ this.#queue = this.#queue.filter((pending) => pending.voice !== voice);
316
+ this.#reclaim(entry);
317
+ return true;
318
+ }
319
+ stop() {
320
+ for (const { voice } of this.#queue) voice.removeFromParent();
321
+ this.#queue = [];
322
+ for (const entry of this.#live.splice(0)) this.#retire(entry);
323
+ this.#voices.clear();
324
+ }
325
+ dispose() {
326
+ if (this.#disposed) return;
327
+ this.#disposed = true;
328
+ if (this.#compressor !== void 0) {
329
+ this.#compressor.disconnect();
330
+ this.#compressor = void 0;
331
+ }
332
+ this.stop();
333
+ for (const entry of [...this.#freeFlat, ...this.#freePositional]) {
334
+ entry.voice.removeFromParent();
335
+ entry.filter?.disconnect();
336
+ }
337
+ this.#freeFlat = [];
338
+ this.#freePositional = [];
339
+ this.listener.removeFromParent();
340
+ for (const event of ["keydown", "pointerdown", "touchstart"]) {
341
+ if (this.#gesture !== void 0)
342
+ this.#gestureTarget?.removeEventListener(event, this.#gesture);
343
+ }
344
+ audioState().buses.delete(this);
345
+ }
346
+ #queueOrStart(entry, options) {
347
+ const start = () => this.#start(entry, options);
348
+ if (this.#unlocked && !this.#paused) start();
349
+ else this.#queue.push({ start, voice: entry.voice });
350
+ }
351
+ #flushQueue() {
352
+ if (!this.#unlocked || this.#paused) return;
353
+ const queued = this.#queue.splice(0);
354
+ for (const { start } of queued) start();
355
+ }
356
+ #start(entry, options) {
357
+ if (this.#disposed) return;
358
+ entry.elapsed = 0;
359
+ entry.held = false;
360
+ entry.volume = options.volume ?? 1;
361
+ entry.cutoff = options.cutoffSeconds;
362
+ entry.detune = options.detune ?? 0;
363
+ this.#applyFilter(entry, options.lowpassHz ?? OPEN_LOWPASS_HZ);
364
+ this.#voices.add(entry.voice);
365
+ this.#live.push(entry);
366
+ this.#sound(entry, options.fade);
367
+ this.#enforceCeiling();
368
+ }
369
+ /**
370
+ * Sound this entry's voice, first time or after a pause, and reapply everything a fresh source
371
+ * node does not inherit: gain, detune, the remaining cut-off, and the reclaim hook.
372
+ */
373
+ #sound(entry, fade) {
374
+ const voice = entry.voice;
375
+ voice.play();
376
+ const now = this.listener.context.currentTime;
377
+ entry.startedAt = now;
378
+ const gain = voice.gain.gain;
379
+ gain.cancelScheduledValues?.(now);
380
+ if (fade !== void 0 && fade > 0) {
381
+ gain.setValueAtTime(0, now);
382
+ gain.linearRampToValueAtTime(entry.volume, now + fade);
383
+ } else {
384
+ gain.setValueAtTime(entry.volume, now);
385
+ }
386
+ const source = voice.source;
387
+ if (entry.detune !== 0) this.#applyDetune(source, entry.detune, now);
388
+ if (entry.cutoff !== void 0 && entry.cutoff > 0 && !entry.looping) {
389
+ gain.setTargetAtTime?.(0, now + Math.max(entry.cutoff - entry.elapsed, 0), 0.045);
390
+ }
391
+ if (source !== null && "onended" in source) {
392
+ const onended = source.onended;
393
+ source.onended = () => {
394
+ onended?.();
395
+ this.#reclaim(entry);
396
+ };
397
+ }
398
+ }
399
+ #applyDetune(source, detune, now) {
400
+ const param = source?.detune;
401
+ if (param === void 0 || typeof param.cancelScheduledValues !== "function") {
402
+ this.#dropped("detune");
403
+ return;
404
+ }
405
+ param.cancelScheduledValues(now);
406
+ param.setValueAtTime(detune, now);
407
+ }
408
+ /** Name a cue option this runtime cannot honour. Once per option, not once per cue. */
409
+ #dropped(option) {
410
+ if (this.#unsupported.has(option)) return;
411
+ this.#unsupported.add(option);
412
+ console.warn(`AudioBus: this runtime cannot honour "${option}"; the cue sounds without it.`);
413
+ }
414
+ /** Oldest one-shot first, so a burst of new cues never silences itself waiting for old ones. */
415
+ #enforceCeiling() {
416
+ if (this.#live.length <= this.#maxVoices) return;
417
+ for (let index = 0; index < this.#live.length && this.#live.length > this.#maxVoices; ) {
418
+ const entry = this.#live[index];
419
+ if (entry === void 0 || entry.looping) {
420
+ index += 1;
421
+ continue;
422
+ }
423
+ this.#live.splice(index, 1);
424
+ this.#retire(entry);
425
+ }
426
+ }
427
+ /** A voice that ran out on its own: out of the graph, back on the free list. */
428
+ #reclaim(entry) {
429
+ const index = this.#live.indexOf(entry);
430
+ if (index === -1) return;
431
+ this.#live.splice(index, 1);
432
+ this.#retire(entry);
433
+ }
434
+ #retire(entry) {
435
+ const voice = entry.voice;
436
+ try {
437
+ voice.stop();
438
+ } catch {
439
+ }
440
+ this.#voices.delete(voice);
441
+ voice.removeFromParent();
442
+ voice.setLoop(false);
443
+ entry.looping = false;
444
+ entry.held = false;
445
+ entry.elapsed = 0;
446
+ entry.cutoff = void 0;
447
+ entry.detune = 0;
448
+ if (this.#disposed) return;
449
+ const free = entry.positional ? this.#freePositional : this.#freeFlat;
450
+ if (!free.includes(entry)) free.push(entry);
451
+ }
452
+ /**
453
+ * Recover voices a caller stopped behind the bus's back.
454
+ *
455
+ * The pool's reclaim hook rides on `source.onended`, and **three's `Audio.stop()` sets
456
+ * `onended` to null before it stops the node** — so a caller doing the natural thing with the
457
+ * handle `play`/`playAt` returned leaves the entry in `#live` for the life of the bus: off the
458
+ * pool, uncounted against `maxVoices`, and still parented into whatever scene graph `playAt`
459
+ * welded it to. That is precisely the leak the pool exists to prevent, reachable through the
460
+ * public API, and `stopVoice` is the correct route rather than the only one anybody will find.
461
+ *
462
+ * So the sweep runs where it is free — at claim time, when the bus needs a voice anyway. A
463
+ * voice that is not playing and is not held has nothing left to sound. `held` is the exception
464
+ * that matters: a paused voice is legitimately stopped at the node level and must survive.
465
+ */
466
+ #sweepFinished() {
467
+ for (const entry of [...this.#live]) {
468
+ if (entry.held || entry.voice.isPlaying) continue;
469
+ if (this.#queue.some((pending) => pending.voice === entry.voice)) continue;
470
+ this.#reclaim(entry);
471
+ }
472
+ }
473
+ #claimFlat(looping) {
474
+ this.#sweepFinished();
475
+ const reused = this.#freeFlat.pop();
476
+ if (reused !== void 0) {
477
+ reused.looping = looping;
478
+ return reused;
479
+ }
480
+ return {
481
+ voice: this.#attachToMaster(new Audio(this.listener)),
482
+ startedAt: 0,
483
+ filter: void 0,
484
+ looping,
485
+ positional: false,
486
+ elapsed: 0,
487
+ held: false,
488
+ volume: 1,
489
+ cutoff: void 0,
490
+ detune: 0
491
+ };
492
+ }
493
+ #claimPositional(looping) {
494
+ this.#sweepFinished();
495
+ const reused = this.#freePositional.pop();
496
+ if (reused !== void 0) {
497
+ reused.looping = looping;
498
+ return reused;
499
+ }
500
+ return {
501
+ voice: this.#attachToMaster(new PositionalAudio(this.listener)),
502
+ startedAt: 0,
503
+ filter: void 0,
504
+ looping,
505
+ positional: true,
506
+ elapsed: 0,
507
+ held: false,
508
+ volume: 1,
509
+ cutoff: void 0,
510
+ detune: 0
511
+ };
512
+ }
513
+ /**
514
+ * Air absorption. One `BiquadFilterNode` is built on a voice's first filtered cue and retuned
515
+ * thereafter, so filtering costs one extra node per voice for the life of the bus rather than
516
+ * one per sound.
517
+ */
518
+ #applyFilter(entry, hz) {
519
+ const voice = entry.voice;
520
+ if (hz >= OPEN_LOWPASS_HZ) {
521
+ if (voice.filters.length > 0) voice.setFilters([]);
522
+ return;
523
+ }
524
+ const context = this.listener.context;
525
+ if (entry.filter === void 0) {
526
+ if (context.createBiquadFilter === void 0) {
527
+ this.#dropped("lowpassHz");
528
+ return;
529
+ }
530
+ const filter = context.createBiquadFilter();
531
+ filter.type = "lowpass";
532
+ entry.filter = filter;
533
+ }
534
+ entry.filter.frequency.value = hz;
535
+ if (voice.filters.length === 0) voice.setFilters([entry.filter]);
536
+ }
537
+ };
538
+ function audioRuntimeSnapshot() {
539
+ let queued = 0;
540
+ let voices = 0;
541
+ let pooled = 0;
542
+ let paused = 0;
543
+ const unsupported = /* @__PURE__ */ new Set();
544
+ const state = audioState();
545
+ for (const bus of state.buses) {
546
+ queued += bus.queued;
547
+ voices += bus.voices;
548
+ pooled += bus.pooled;
549
+ paused += bus.pausedVoices;
550
+ for (const option of bus.unsupported) unsupported.add(option);
551
+ }
552
+ return {
553
+ cues: Object.fromEntries(state.cueCounts),
554
+ paused,
555
+ pooled,
556
+ queued,
557
+ recentCues: state.cueLog.map((entry) => ({ ...entry })),
558
+ unsupported: [...unsupported].sort(),
559
+ voices
560
+ };
561
+ }
562
+ function assertCompressor(options) {
563
+ for (const name of ["threshold", "knee", "ratio", "attack", "release"]) {
564
+ if (!Number.isFinite(options[name])) {
565
+ throw new TypeError(`compressor.${name} must be a finite number.`);
566
+ }
567
+ }
568
+ if (options.threshold < -100 || options.threshold > 0)
569
+ throw new RangeError("compressor.threshold must be between -100 and 0 dBFS.");
570
+ if (options.knee < 0 || options.knee > 40)
571
+ throw new RangeError("compressor.knee must be between 0 and 40 dB.");
572
+ if (options.ratio < 1 || options.ratio > 20)
573
+ throw new RangeError("compressor.ratio must be between 1 and 20.");
574
+ if (options.attack < 0 || options.attack > 1)
575
+ throw new RangeError("compressor.attack must be between 0 and 1 second.");
576
+ if (options.release < 0 || options.release > 1)
577
+ throw new RangeError("compressor.release must be between 0 and 1 second.");
578
+ }
579
+ function assertOptions(options) {
580
+ if (options.cue !== void 0 && (typeof options.cue !== "string" || options.cue.length === 0)) {
581
+ throw new TypeError("cue must be a non-empty string.");
582
+ }
583
+ if (options.cutoffSeconds !== void 0 && (!Number.isFinite(options.cutoffSeconds) || options.cutoffSeconds <= 0)) {
584
+ throw new RangeError("cutoffSeconds must be finite and positive.");
585
+ }
586
+ if (options.lowpassHz !== void 0 && (!Number.isFinite(options.lowpassHz) || options.lowpassHz <= 0)) {
587
+ throw new RangeError("lowpassHz must be finite and positive.");
588
+ }
589
+ if (options.detune !== void 0 && !Number.isFinite(options.detune)) {
590
+ throw new RangeError("detune must be finite.");
591
+ }
592
+ const volume = options.volume ?? 1;
593
+ if (!Number.isFinite(volume) || volume < 0)
594
+ throw new RangeError("volume must be finite and non-negative.");
595
+ if (options.fade !== void 0 && (!Number.isFinite(options.fade) || options.fade < 0)) {
596
+ throw new RangeError("fade must be finite and non-negative.");
597
+ }
598
+ if (options.refDistance !== void 0 && (!Number.isFinite(options.refDistance) || options.refDistance <= 0)) {
599
+ throw new RangeError("refDistance must be finite and positive.");
600
+ }
601
+ if (options.rolloffFactor !== void 0 && (!Number.isFinite(options.rolloffFactor) || options.rolloffFactor < 0)) {
602
+ throw new RangeError("rolloffFactor must be finite and non-negative.");
603
+ }
604
+ }
605
+ function configureVoice(voice, options) {
606
+ const volume = options.volume ?? 1;
607
+ voice.setLoop(options.loop ?? false);
608
+ voice.setVolume(options.fade === void 0 || options.fade === 0 ? volume : 0);
609
+ }
610
+ function assertBuffer(buffer) {
611
+ if (buffer === null || buffer === void 0)
612
+ throw new TypeError("AudioBus requires a non-null AudioBuffer.");
613
+ }
614
+
615
+ export { AudioBus, audioRuntimeSnapshot, resetAudioCueLedger };
@@ -0,0 +1,18 @@
1
+ // src/dev-global.ts
2
+ var DEV_GLOBAL_KEY = "__THREENATIVE__";
3
+ function devGlobal(scope) {
4
+ const value = scope?.[DEV_GLOBAL_KEY];
5
+ return typeof value === "object" && value !== null ? value : void 0;
6
+ }
7
+ function publishDevGlobal(name, value, scope) {
8
+ const host = scope;
9
+ if (host === void 0) return;
10
+ const current = devGlobal(scope);
11
+ if (current !== void 0) {
12
+ current[name] = value;
13
+ return;
14
+ }
15
+ host[DEV_GLOBAL_KEY] = { [name]: value };
16
+ }
17
+
18
+ export { DEV_GLOBAL_KEY, devGlobal, publishDevGlobal };