Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add audio addon: spatial sounds triggered from input, contacts and animation markers (#775)

Nguyen Xuan Anaac719736b26
diff --git a/README.md b/README.md
index 43a5cca3..e2687a61 100644
--- a/README.md
+++ b/README.md
@@ -140,6 +140,7 @@ Each addon is a separate import, so a page loads only what it uses.
| Physics | `67js/addons/physics` | [Rapier contacts and joints](docs/physics.md) recorded into a timeline |
| Live games | `67js/addons/runtime` | [Game loop](docs/runtime.md) with fixed or variable steps and pluggable systems |
| Live games | `67js/addons/input` | [Input](docs/input.md): keyboard, mouse, gamepad and custom sources mapped to named actions and axes |
+| Live games | `67js/addons/audio` | [Spatial audio](docs/audio.md): sounds on nodes, played from contacts, markers and input, with buses and a limiter |
| Modeling | `67js/addons/mesh`, `67js/addons/modeling`, `67js/addons/sculpt` | [Mesh editing](docs/mesh.md), [modeling](docs/modeling.md) and [sculpt brushes](https://67js.codepawl.com/sculpt.md) |
| Offline light | `67js/addons/path-tracer`, `67js/addons/light-bake` | [Path-traced stills](https://67js.codepawl.com/path-tracer.md) and [baked lightmaps](https://67js.codepawl.com/light-bake.md) |
| Post passes | `67js/addons/user-pass` | [Your own full-screen GLSL passes](docs/user-passes.md): dither, pixel downscale, quantise |
diff --git a/bench/runtime-loop/main.js b/bench/runtime-loop/main.js
index 7b3854b8..7ef2dfaf 100644
--- a/bench/runtime-loop/main.js
+++ b/bench/runtime-loop/main.js
@@ -3,6 +3,7 @@
import { Renderer67, box, sphere } from '/src/index.js';
import { createRuntime } from '/src/runtime.js';
import { createInput, gamepadSource, keyboardSource } from '/src/input.js';
+import { createAudio } from '/src/audio.js';
const GRAVITY = -9.8;
const FIXED_RATE = 20; // Low on purpose, so the difference between fixed and interpolated is visible.
@@ -11,6 +12,10 @@ const BALL_RADIUS = 0.4;
const SPIN_RADIANS_PER_SECOND = 1.5;
const CUBE_SPEED = 3; // World units per second along the moveX axis.
const JUMP_SPEED = 6;
+const CAMERA = { eye: [0, 3, 8], target: [0, 1.2, 0], up: [0, 1, 0] };
+const BALL_GROUND_POSITION = [-1.2, 0, 0];
+// The cube's animation markers: one tick at each half turn.
+const SPIN_MARKERS = [{ time: 0.5, name: 'half-turn' }, { time: 1, name: 'half-turn' }];
function translation(x, y, z, scale = 1) {
return new Float32Array([scale, 0, 0, 0, 0, scale, 0, 0, 0, 0, scale, 0, x, y, z, 1]);
@@ -22,6 +27,18 @@ function rotationAroundY(angle, x, y, z) {
return new Float32Array([cosine, 0, -sine, 0, 0, 1, 0, 0, sine, 0, cosine, 0, x, y, z, 1]);
}
+// Short synthesized tones stand in for sound files: a decaying sine at the given pitch.
+function createTone(frequency, seconds) {
+ const sampleRate = 44100;
+ const tone = new AudioBuffer({ length: Math.round(sampleRate * seconds), sampleRate, numberOfChannels: 1 });
+ const samples = tone.getChannelData(0);
+ for (let index = 0; index < samples.length; index += 1) {
+ const time = index / sampleRate;
+ samples[index] = Math.sin(2 * Math.PI * frequency * time) * Math.exp(-time * 12 / seconds);
+ }
+ return tone;
+}
+
const ballPart = {
name: 'Ball',
geometry: sphere(),
@@ -57,6 +74,9 @@ const physicsSystem = {
this.height += this.velocity * stepSeconds;
if (this.height < BALL_RADIUS) {
this.height = BALL_RADIUS;
+ audio.emitContacts([{ started: true, kind: 'contact', colliderA: 'ball', colliderB: 'ground', impulse: Math.abs(this.velocity) }], {
+ position: () => BALL_GROUND_POSITION,
+ });
this.velocity = -this.velocity * BOUNCE_ENERGY;
}
},
@@ -83,7 +103,10 @@ const spinSystem = {
this.slide(stepSeconds);
},
update(deltaSeconds, context) {
+ const previousPhase = (this.angle / (2 * Math.PI)) % 1;
this.angle += SPIN_RADIANS_PER_SECOND * deltaSeconds;
+ const phase = (this.angle / (2 * Math.PI)) % 1;
+ audio.emitMarkers(SPIN_MARKERS, previousPhase, phase, { loop: true, duration: 1, data: { position: [this.x, 0.5, 0] } });
if (context.mode === 'variable') this.slide(deltaSeconds);
},
};
@@ -101,6 +124,16 @@ const input = createInput({
},
});
+// Sounds come from a contact (the bounce, louder with the impact speed), an animation marker (the cube's half turns) and
+// an input action (Space). The listener sits on the camera, so the cube's tick pans as the cube slides.
+const audio = createAudio({ input, listener: () => CAMERA });
+audio.defineSound('thud', { buffer: createTone(110, 0.3), spatial: { referenceDistance: 4 } });
+audio.defineSound('tick', { buffer: createTone(880, 0.08), spatial: { referenceDistance: 4 }, volume: 0.4 });
+audio.defineSound('hop', { buffer: createTone(440, 0.15) });
+audio.bindEvent('contact', 'thud', { volume: data => Math.min(1, data.impulse / 10) });
+audio.bindEvent('marker:half-turn', 'tick');
+audio.bindAction('jump', 'hop');
+
const canvas = document.querySelector('canvas');
const renderer = new Renderer67(canvas, parts, { samples: 4, memoryBudgetMiB: 256 });
renderer.resize();
@@ -112,7 +145,7 @@ function buildFrame(context) {
ballPart.matrix = translation(-1.2, height, 0, BALL_RADIUS);
cubePart.matrix = rotationAroundY(spinSystem.angle, spinSystem.x, 0.5, 0);
renderer.updateParts(parts);
- return { eye: [0, 3, 8], target: [0, 1.2, 0], up: [0, 1, 0], time: context.elapsedSeconds };
+ return { ...CAMERA, time: context.elapsedSeconds };
}
let runtime = null;
@@ -123,7 +156,7 @@ function startMode(mode) {
mode,
fixedRate: FIXED_RATE,
frame: buildFrame,
- systems: [input, physicsSystem, spinSystem],
+ systems: [input, audio, physicsSystem, spinSystem],
});
runtime.start();
for (const button of document.querySelectorAll('button[data-mode]')) {
@@ -143,7 +176,7 @@ setInterval(() => {
`${stats.framesPerSecond.toFixed(0)} fps, ${stats.averageFrameMilliseconds.toFixed(1)} ms average, ${stats.maximumFrameMilliseconds.toFixed(1)} ms worst`,
`update ${stats.updateMilliseconds.toFixed(2)} ms, render ${stats.renderMilliseconds.toFixed(2)} ms`,
`fixed steps ${stats.fixedSteps}, alpha ${stats.alpha.toFixed(2)}`,
- 'A/D or arrows slide the cube, Space kicks the ball',
+ 'A/D or arrows slide the cube, Space kicks the ball (sound starts at your first key press)',
].join('\n');
}, 250);
diff --git a/changes/775.md b/changes/775.md
new file mode 100644
index 00000000..c6ff1dce
--- /dev/null
+++ b/changes/775.md
@@ -0,0 +1 @@
+- `67js/addons/audio` adds `createAudio`, spatial audio for live games on Web Audio: sounds on nodes with a listener on the camera, distance falloff and optional occlusion, triggers from input actions, physics contacts and animation markers, buses with a limiter, and a swappable backend (#775)
diff --git a/docs/audio.md b/docs/audio.md
new file mode 100644
index 00000000..7b89e5de
--- /dev/null
+++ b/docs/audio.md
@@ -0,0 +1,67 @@
+# Audio: spatial sound for a live game
+
+`67js/addons/audio` plays sounds tied to what happens in the world: a ball hits the floor, a clip reaches a footstep marker, the player presses a key, a vehicle drives past. It is a [runtime](runtime.md) system on Web Audio. It loads only when imported and adds no dependency.
+
+```js
+import { createRuntime } from '67js/addons/runtime';
+import { createInput } from '67js/addons/input';
+import { createAudio } from '67js/addons/audio';
+
+const audio = createAudio({
+ input, // from createInput; optional
+ listener: () => cameraFrame, // { eye, target, up }: the listener follows the camera
+});
+await audio.load('thud', '/sounds/thud.ogg', { spatial: { referenceDistance: 2 } });
+await audio.load('hop', '/sounds/hop.ogg');
+audio.bindEvent('contact', 'thud', { volume: data => Math.min(1, data.impulse / 20) });
+audio.bindAction('jump', 'hop');
+
+createRuntime(renderer, { systems: [input, audio, game] }).start(); // audio after input
+```
+
+Browsers keep audio silent until the page has had a user gesture. The audio starts on the first `pointerdown`, `keydown` or `touchend`; call `audio.unlock()` yourself if your own button starts the game.
+
+## Sounds
+
+`defineSound(name, { buffer, bus, volume, pitch, pitchVariance, loop, maximumInstances, spatial })` takes a decoded `AudioBuffer`. `await load(name, source, definition)` decodes a URL, an `ArrayBuffer` or an `AudioBuffer` first. `volume` is 0 to 4, `pitch` is a playback-rate multiplier from 0.1 to 4, and `pitchVariance` (0 to 1) varies the pitch of each play from a seeded generator (`createAudio({ seed })`), so a replay sounds the same. `maximumInstances` (default 8) stops the oldest copy of a sound when it plays again.
+
+A sound without `spatial` is flat, like music or a menu click. `spatial: true` or `{ referenceDistance, maximumDistance, rolloff, model, occlusion }` places it in the world with HRTF panning. `model` is `'inverse'` (default), `'linear'` or `'exponential'`, as in the Web Audio specification.
+
+## Playing
+
+- `play(name, { position, node, volume, pitch, loop })` starts a sound. A spatial sound needs `position: [x, y, z]` or a `node`. It returns a handle `{ stop(), playing, level }`, or `null` when the voice limit is full of louder sounds.
+- A node is `{ position }`, `{ matrix }` (4x4, column-major, so a part's matrix works) or a function returning either. `attach(node, name)` is `play` with `loop: true` on a node: the sound follows the node every frame until `stop()`.
+- `stopAll(name?)`, `activeVoices()` (name, bus, volume, pitch, position and `level` of every playing voice).
+- At most `maximumVoices` sounds play at once (default 32, up to 64). A new sound quieter than all of them is dropped; a louder one replaces the quietest.
+
+## Triggers
+
+`bindEvent(event, sound, { volume, pitch, position, node })` plays the sound whenever `emit(event, data)` runs. `volume`, `pitch` and `position` are a value or a function of the event data, which is how an impact sets the loudness. `bindEvent` returns a function that removes the binding. Game code calls `emit` itself; the helpers below cover the common sources.
+
+| Source | Call | Event fired |
+| --- | --- | --- |
+| Input action | `bindAction('jump', 'hop')`; the system checks `input.wasPressed` each fixed step | `input:jump`, once per press |
+| Physics contacts | `emitContacts(scene.contactEvents, { position })` | `contact` or `sensor` for each started event, plus `contact:<collider>` for both colliders |
+| Animation markers | `emitMarkers(markers, previousTime, currentTime, { loop, duration, data })` | `marker:<name>` for each `{ time, name }` crossed |
+
+`markersCrossed(markers, from, to, { loop, duration })` is the pure function behind `emitMarkers`. A marker fires once when the clip time passes it, and a loop wrap fires the markers at both ends. Pass `data: { position }` so the sound comes from the character, or bind with `position: data => ...`.
+
+## Listener, distance and occlusion
+
+The listener follows the camera: pass `listener: () => frame` to `createAudio` (the same `{ eye, target, up }` your runtime `frame` returns), or call `setListener(frame)` yourself. Distance falloff is the Web Audio distance model, and the predicted level (`handle.level`) uses the same formula (`distanceGain`), so a test can check it.
+
+Occlusion is opt in. Pass `occlusion: (listenerPosition, sourcePosition) => 0..1` to `createAudio` (for example a ray cast against your walls from [scene query](scene-query.md)) and set `spatial: { occlusion: true }` on the sounds that should use it. An occluded sound loses up to 70% of its level and is muffled by a low-pass filter that falls to 400 Hz.
+
+## Buses and the limiter
+
+Every sound plays on a bus: `music`, `effects` (the default) or `voice`; `createBus(name, volume)` adds more (16 at most). `setBusVolume(name, volume)` sets one, and `'master'` scales all of them. The graph ends in a compressor set as a limiter (ratio 20, threshold -1 dB), so a pile of loud sounds does not clip.
+
+## Another backend
+
+The system talks only to a backend object: `init`, `dispose`, `unlock`, `decode`, `createBus`, `setBusVolume`, `setListener` and `startVoice(options)` which returns `{ update(change), stop() }`. `createAudio({ backend })` takes any such object, so a native or middleware backend can replace Web Audio without touching game code. `webAudioBackend({ createContext, gestureTarget, fetch })` is the default; tests pass a fake `AudioContext` through `createContext`.
+
+## Limits
+
+256 sounds, 256 bindings, 16 buses, 64 voices, 512 markers per call (`AUDIO_LIMITS`). Errors name the field and say what to pass.
+
+A runnable sample is `bench/runtime-loop/index.html`: the ball's bounce is a contact sound (louder when it lands harder), the cube ticks at each half turn from an animation marker, and Space plays a hop through an input action.
diff --git a/package.json b/package.json
index 3a073c50..147d7358 100644
--- a/package.json
+++ b/package.json
@@ -43,6 +43,7 @@
"docs/physics.md",
"docs/runtime.md",
"docs/input.md",
+ "docs/audio.md",
"docs/scene-query.md",
"docs/user-passes.md",
"docs/skeleton-pose.md",
@@ -120,6 +121,7 @@
"./addons/cloth": "./build/cloth.js",
"./addons/runtime": "./build/runtime.js",
"./addons/input": "./build/input.js",
+ "./addons/audio": "./build/audio.js",
"./addons/update-part-vertices": "./build/update-part-vertices.js",
"./package.json": "./package.json"
},
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index c1736dd8..dc6915b5 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -53,7 +53,7 @@ const sourceDocuments = [
'vehicle.md',
'vegetation.md', 'terrain.md', 'grass.md', 'clutter.md', 'light-bake.md', 'path-tracer.md', 'gaussian-splats.md',
'camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',
- 'runtime.md', 'input.md', 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',
+ 'runtime.md', 'input.md', 'audio.md', 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',
];
for (const name of sourceDocuments) {
await copyFile(resolve(root, 'docs', name), resolve(root, 'public', name));
diff --git a/src/audio.js b/src/audio.js
new file mode 100644
index 00000000..c0a35864
--- /dev/null
+++ b/src/audio.js
@@ -0,0 +1,737 @@
+// Spatial audio for a live game, as a runtime system. Sounds are defined once, then played from events (input actions,
+// physics contacts, animation markers, game code) at a position, on a node, or flat. A listener follows the camera.
+// Everything talks to a backend object (play a buffer, move the listener, set a bus volume); the Web Audio backend is the
+// default and tests or another engine pass their own. See docs/audio.md.
+
+export const AUDIO_LIMITS = Object.freeze({
+ maximumSounds: 256,
+ maximumBindings: 256,
+ maximumBuses: 16,
+ maximumVoices: 64,
+ defaultVoices: 32,
+ defaultInstancesPerSound: 8,
+ maximumInstancesPerSound: 32,
+ maximumMarkers: 512,
+});
+
+export const DEFAULT_BUSES = Object.freeze(['music', 'effects', 'voice']);
+// An occluded source loses this share of its level and is also muffled by a low-pass filter.
+export const OCCLUDED_GAIN_LOSS = 0.7;
+const OCCLUDED_LOW_PASS_HERTZ = 400;
+const OPEN_LOW_PASS_HERTZ = 20000;
+const PARAMETER_SMOOTHING_SECONDS = 0.01;
+const DISTANCE_MODELS = ['inverse', 'linear', 'exponential'];
+const GESTURE_EVENTS = ['pointerdown', 'keydown', 'touchend'];
+
+function describe(value) {
+ return value === null ? 'null' : typeof value;
+}
+
+function requireName(value, label) {
+ if (typeof value !== 'string' || value === '') {
+ throw new TypeError(`${label} must be a non-empty string, got ${describe(value)}.`);
+ }
+ return value;
+}
+
+function requireNumberInRange(value, label, minimum, maximum) {
+ if (!Number.isFinite(value) || value < minimum || value > maximum) {
+ throw new RangeError(`${label} must be a number from ${minimum} to ${maximum}, got ${String(value)}.`);
+ }
+ return value;
+}
+
+function requireVector(value, label) {
+ if (!Array.isArray(value) && !ArrayBuffer.isView(value)) {
+ throw new TypeError(`${label} must be [x, y, z], got ${describe(value)}.`);
+ }
+ if (value.length < 3 || !Number.isFinite(value[0]) || !Number.isFinite(value[1]) || !Number.isFinite(value[2])) {
+ throw new TypeError(`${label} must be three finite numbers [x, y, z].`);
+ }
+ return [value[0], value[1], value[2]];
+}
+
+// Distance gain from the Web Audio specification, so the level measured here matches what a PannerNode applies.
+export function distanceGain(distance, { model = 'inverse', referenceDistance = 1, maximumDistance = 50, rolloff = 1 } = {}) {
+ const clamped = Math.min(Math.max(distance, referenceDistance), maximumDistance);
+ if (model === 'linear') {
+ const span = maximumDistance - referenceDistance;
+ return span <= 0 ? 1 : 1 - rolloff * (clamped - referenceDistance) / span;
+ }
+ if (model === 'exponential') return (clamped / referenceDistance) ** -rolloff;
+ return referenceDistance / (referenceDistance + rolloff * (clamped - referenceDistance));
+}
+
+function normalizeSpatial(spatial, label) {
+ if (spatial === undefined || spatial === false) return null;
+ const options = spatial === true ? {} : spatial;
+ if (options === null || typeof options !== 'object') {
+ throw new TypeError(`${label} spatial must be true or { referenceDistance, maximumDistance, rolloff, model, occlusion }, got ${describe(spatial)}.`);
+ }
+ const model = options.model ?? 'inverse';
+ if (!DISTANCE_MODELS.includes(model)) {
+ throw new RangeError(`${label} spatial model must be one of ${DISTANCE_MODELS.join(', ')}, got ${String(model)}.`);
+ }
+ const referenceDistance = requireNumberInRange(options.referenceDistance ?? 1, `${label} spatial referenceDistance`, 0.01, 1000);
+ const maximumDistance = requireNumberInRange(options.maximumDistance ?? 50, `${label} spatial maximumDistance`, referenceDistance, 100000);
+ const rolloff = requireNumberInRange(options.rolloff ?? 1, `${label} spatial rolloff`, 0, 20);
+ return Object.freeze({ model, referenceDistance, maximumDistance, rolloff, occlusion: options.occlusion === true });
+}
+
+// ---- Positions and listener ----
+
+function matrixTranslation(matrix) {
+ return [matrix[12], matrix[13], matrix[14]];
+}
+
+// A node is { position: [x, y, z] }, { matrix } (a 4x4 column-major array), or a function returning either of those.
+export function readNodePosition(node, label = 'node') {
+ const resolved = typeof node === 'function' ? node() : node;
+ if (resolved === null || typeof resolved !== 'object') {
+ throw new TypeError(`${label} must be [x, y, z], { position }, { matrix } or a function returning one of them, got ${describe(resolved)}.`);
+ }
+ if (Array.isArray(resolved) || (ArrayBuffer.isView(resolved) && resolved.length === 3)) return requireVector(resolved, label);
+ if (resolved.position !== undefined) return requireVector(resolved.position, `${label} position`);
+ if (resolved.matrix !== undefined && resolved.matrix.length === 16) return requireVector(matrixTranslation(resolved.matrix), `${label} matrix`);
+ throw new TypeError(`${label} must be [x, y, z], { position }, { matrix } or a function returning one of them.`);
+}
+
+// The listener follows the camera: pass the renderer frame ({ eye, target, up }) or { position, forward, up }.
+export function readListener(camera) {
+ if (camera === null || typeof camera !== 'object') {
+ throw new TypeError(`listener must be a camera frame { eye, target, up } or { position, forward, up }, got ${describe(camera)}.`);
+ }
+ const up = camera.up === undefined ? [0, 1, 0] : requireVector(camera.up, 'listener up');
+ if (camera.eye !== undefined) {
+ const position = requireVector(camera.eye, 'listener eye');
+ const target = requireVector(camera.target ?? [position[0], position[1], position[2] - 1], 'listener target');
+ return { position, forward: normalizeForward([target[0] - position[0], target[1] - position[1], target[2] - position[2]]), up };
+ }
+ return {
+ position: requireVector(camera.position ?? [0, 0, 0], 'listener position'),
+ forward: normalizeForward(requireVector(camera.forward ?? [0, 0, -1], 'listener forward')),
+ up,
+ };
+}
+
+function normalizeForward(vector) {
+ const length = Math.hypot(vector[0], vector[1], vector[2]);
+ if (length < 1e-9) return [0, 0, -1];
+ return [vector[0] / length, vector[1] / length, vector[2] / length];
+}
+
+function distanceBetween(first, second) {
+ return Math.hypot(first[0] - second[0], first[1] - second[1], first[2] - second[2]);
+}
+
+// ---- Animation markers ----
+
+// Markers are { time, name } on a clip. Returns the ones crossed when the clip time moves from `fromTime` (exclusive)
+// to `toTime` (inclusive). With `loop` and `duration`, a wrap from the end back to the start fires both ends.
+export function markersCrossed(markers, fromTime, toTime, { loop = false, duration = Infinity } = {}) {
+ if (!Array.isArray(markers) || markers.length > AUDIO_LIMITS.maximumMarkers) {
+ throw new RangeError(`markers must be an array of up to ${AUDIO_LIMITS.maximumMarkers} { time, name } entries.`);
+ }
+ const crossed = [];
+ const wrapped = loop && toTime < fromTime;
+ for (const marker of markers) {
+ requireName(marker?.name, 'marker name');
+ requireNumberInRange(marker.time, `marker ${marker.name} time`, 0, Number.MAX_VALUE);
+ const inRange = wrapped
+ ? (marker.time > fromTime && marker.time <= duration) || (marker.time >= 0 && marker.time <= toTime)
+ : marker.time > fromTime && marker.time <= toTime;
+ if (inRange) crossed.push(marker);
+ }
+ return crossed;
+}
+
+// ---- Web Audio backend ----
+
+function setParameter(parameter, value, now) {
+ if (typeof parameter.setTargetAtTime === 'function') parameter.setTargetAtTime(value, now, PARAMETER_SMOOTHING_SECONDS);
+ else parameter.value = value;
+}
+
+function setPannerPosition(panner, position, now) {
+ if (panner.positionX) {
+ setParameter(panner.positionX, position[0], now);
+ setParameter(panner.positionY, position[1], now);
+ setParameter(panner.positionZ, position[2], now);
+ } else {
+ panner.setPosition(position[0], position[1], position[2]);
+ }
+}
+
+function setListenerPose(listener, pose, now) {
+ if (listener.positionX) {
+ setParameter(listener.positionX, pose.position[0], now);
+ setParameter(listener.positionY, pose.position[1], now);
+ setParameter(listener.positionZ, pose.position[2], now);
+ setParameter(listener.forwardX, pose.forward[0], now);
+ setParameter(listener.forwardY, pose.forward[1], now);
+ setParameter(listener.forwardZ, pose.forward[2], now);
+ setParameter(listener.upX, pose.up[0], now);
+ setParameter(listener.upY, pose.up[1], now);
+ setParameter(listener.upZ, pose.up[2], now);
+ } else {
+ listener.setPosition(pose.position[0], pose.position[1], pose.position[2]);
+ listener.setOrientation(pose.forward[0], pose.forward[1], pose.forward[2], pose.up[0], pose.up[1], pose.up[2]);
+ }
+}
+
+function occlusionHertz(occlusion) {
+ return OPEN_LOW_PASS_HERTZ * (OCCLUDED_LOW_PASS_HERTZ / OPEN_LOW_PASS_HERTZ) ** occlusion;
+}
+
+// Graph: voice source -> [low-pass -> panner] -> voice gain -> bus gain -> master gain -> limiter -> destination.
+export function webAudioBackend(options = {}) {
+ const createContext = options.createContext ?? (() => new globalThis.AudioContext({ latencyHint: 'interactive' }));
+ const fetchBytes = options.fetch ?? (globalThis.fetch ? globalThis.fetch.bind(globalThis) : null);
+ const gestureTarget = options.gestureTarget === undefined ? globalThis.document : options.gestureTarget;
+ let context = null;
+ let master = null;
+ let limiter = null;
+ let removeGestureListeners = null;
+ const buses = new Map();
+
+ function requireContext() {
+ if (!context) throw new Error('The audio backend has not started. Call audio.init() or add the audio system to a started runtime.');
+ return context;
+ }
+
+ function unlock() {
+ if (context && context.state === 'suspended') {
+ const result = context.resume();
+ if (result && typeof result.catch === 'function') result.catch(() => {});
+ }
+ }
+
+ return {
+ name: 'web-audio',
+ get state() {
+ return context ? context.state : 'closed';
+ },
+ init() {
+ if (context) return;
+ context = createContext();
+ limiter = context.createDynamicsCompressor();
+ limiter.threshold.value = -1;
+ limiter.knee.value = 0;
+ limiter.ratio.value = 20;
+ limiter.attack.value = 0.003;
+ limiter.release.value = 0.1;
+ limiter.connect(context.destination);
+ master = context.createGain();
+ master.connect(limiter);
+ if (gestureTarget && typeof gestureTarget.addEventListener === 'function') {
+ const handler = () => {
+ unlock();
+ if (context.state !== 'suspended' && removeGestureListeners) removeGestureListeners();
+ };
+ for (const type of GESTURE_EVENTS) gestureTarget.addEventListener(type, handler);
+ removeGestureListeners = () => {
+ for (const type of GESTURE_EVENTS) gestureTarget.removeEventListener(type, handler);
+ removeGestureListeners = null;
+ };
+ }
+ },
+ dispose() {
+ if (removeGestureListeners) removeGestureListeners();
+ if (context && typeof context.close === 'function') context.close();
+ context = null;
+ buses.clear();
+ },
+ unlock,
+ createBus(name, volume) {
+ const gain = requireContext().createGain();
+ gain.gain.value = volume;
+ gain.connect(master);
+ buses.set(name, gain);
+ },
+ setBusVolume(name, volume) {
+ const bus = name === 'master' ? master : buses.get(name);
+ setParameter(bus.gain, volume, requireContext().currentTime);
+ },
+ async decode(source) {
+ const audioContext = requireContext();
+ if (typeof source === 'string') {
+ if (!fetchBytes) throw new Error('No fetch is available to load a sound from a URL. Pass an ArrayBuffer or a decoded AudioBuffer instead.');
+ const response = await fetchBytes(source);
+ if (!response.ok) throw new Error(`Loading the sound ${source} failed with status ${response.status}.`);
+ return audioContext.decodeAudioData(await response.arrayBuffer());
+ }
+ if (source instanceof ArrayBuffer) return audioContext.decodeAudioData(source);
+ if (source && typeof source.duration === 'number') return source;
+ throw new TypeError(`A sound source must be a URL string, an ArrayBuffer or a decoded AudioBuffer, got ${describe(source)}.`);
+ },
+ setListener(pose) {
+ const audioContext = requireContext();
+ setListenerPose(audioContext.listener, pose, audioContext.currentTime);
+ },
+ startVoice(voiceOptions) {
+ const audioContext = requireContext();
+ const now = audioContext.currentTime;
+ const source = audioContext.createBufferSource();
+ source.buffer = voiceOptions.buffer;
+ source.loop = voiceOptions.loop;
+ source.playbackRate.value = voiceOptions.pitch;
+ const gain = audioContext.createGain();
+ gain.gain.value = voiceOptions.volume;
+ let filter = null;
+ let panner = null;
+ let tail = source;
+ if (voiceOptions.spatial) {
+ const spatial = voiceOptions.spatial;
+ if (spatial.occlusion) {
+ filter = audioContext.createBiquadFilter();
+ filter.type = 'lowpass';
+ filter.frequency.value = occlusionHertz(voiceOptions.occlusion);
+ tail.connect(filter);
+ tail = filter;
+ }
+ panner = audioContext.createPanner();
+ panner.panningModel = 'HRTF';
+ panner.distanceModel = spatial.model;
+ panner.refDistance = spatial.referenceDistance;
+ panner.maxDistance = spatial.maximumDistance;
+ panner.rolloffFactor = spatial.rolloff;
+ setPannerPosition(panner, voiceOptions.position, now);
+ tail.connect(panner);
+ tail = panner;
+ }
+ tail.connect(gain);
+ gain.connect(buses.get(voiceOptions.bus));
+ let ended = false;
+ source.onended = () => {
+ ended = true;
+ voiceOptions.onEnded();
+ };
+ source.start(now);
+ return {
+ update(change) {
+ const time = audioContext.currentTime;
+ setParameter(gain.gain, change.volume, time);
+ setParameter(source.playbackRate, change.pitch, time);
+ if (panner) setPannerPosition(panner, change.position, time);
+ if (filter) setParameter(filter.frequency, occlusionHertz(change.occlusion), time);
+ },
+ stop() {
+ if (ended) return;
+ ended = true;
+ source.onended = null;
+ try {
+ source.stop();
+ } catch {
+ // A source that never started or already ended throws; either way it is silent.
+ }
+ source.disconnect();
+ },
+ };
+ },
+ };
+}
+
+// ---- The audio system ----
+
+function resolveNumber(value, data, label, minimum, maximum) {
+ const resolved = typeof value === 'function' ? value(data) : value;
+ return requireNumberInRange(resolved, label, minimum, maximum);
+}
+
+function createSeededRandom(seed) {
+ let state = seed >>> 0;
+ return () => {
+ state = (state + 0x6d2b79f5) >>> 0;
+ let mixed = Math.imul(state ^ (state >>> 15), 1 | state);
+ mixed = (mixed + Math.imul(mixed ^ (mixed >>> 7), 61 | mixed)) ^ mixed;
+ return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+export function createAudio(options = {}) {
+ const backend = options.backend ?? webAudioBackend(options.webAudio);
+ const maximumVoices = requireNumberInRange(options.maximumVoices ?? AUDIO_LIMITS.defaultVoices, 'createAudio maximumVoices', 1, AUDIO_LIMITS.maximumVoices);
+ const occluder = options.occlusion ?? null;
+ if (occluder !== null && typeof occluder !== 'function') {
+ throw new TypeError('createAudio occlusion must be a function (from, to) => 0 to 1, or left out.');
+ }
+ const listenerSource = options.listener ?? null;
+ if (listenerSource !== null && typeof listenerSource !== 'function') {
+ throw new TypeError('createAudio listener must be a function () => camera frame { eye, target, up }, or left out.');
+ }
+ const random = createSeededRandom(options.seed ?? 1);
+ const sounds = new Map();
+ const bindings = new Map(); // event name -> [{ sound, options }]
+ const actionEvents = new Map(); // action name -> event name
+ const busVolumes = new Map();
+ const voices = [];
+ let bindingCount = 0;
+ let nextVoiceId = 1;
+ let started = false;
+ let input = options.input ?? null;
+ let listenerPose = { position: [0, 0, 0], forward: [0, 0, -1], up: [0, 1, 0] };
+
+ function createBus(name, volume = 1) {
+ requireName(name, 'bus name');
+ requireNumberInRange(volume, `bus ${name} volume`, 0, 4);
+ if (name === 'master') throw new RangeError('The bus name master is reserved for the output level. Use setBusVolume("master", volume) to change it.');
+ if (!busVolumes.has(name) && busVolumes.size >= AUDIO_LIMITS.maximumBuses) {
+ throw new RangeError(`An audio can have at most ${AUDIO_LIMITS.maximumBuses} buses, so ${name} was not added.`);
+ }
+ busVolumes.set(name, volume);
+ if (started) backend.createBus(name, volume);
+ }
+
+ busVolumes.set('master', 1);
+ for (const name of DEFAULT_BUSES) busVolumes.set(name, 1);
+ for (const [name, volume] of Object.entries(options.buses ?? {})) createBus(name, volume);
+
+ function requireBus(name) {
+ if (!busVolumes.has(name) || name === 'master') {
+ throw new RangeError(`Unknown bus ${String(name)}. Use one of ${[...busVolumes.keys()].filter(key => key !== 'master').join(', ')} or add it with createBus(name).`);
+ }
+ return name;
+ }
+
+ function requireSound(name) {
+ const sound = sounds.get(name);
+ if (!sound) {
+ throw new RangeError(`Unknown sound ${String(name)}. Define it first with audio.defineSound(name, { buffer }) or await audio.load(name, source). Known: ${[...sounds.keys()].join(', ') || 'none'}.`);
+ }
+ return sound;
+ }
+
+ function defineSound(name, definition) {
+ requireName(name, 'sound name');
+ if (definition === null || typeof definition !== 'object') {
+ throw new TypeError(`defineSound(${name}, definition) needs { buffer, bus, volume, pitch, loop, spatial }, got ${describe(definition)}.`);
+ }
+ if (!sounds.has(name) && sounds.size >= AUDIO_LIMITS.maximumSounds) {
+ throw new RangeError(`An audio can hold at most ${AUDIO_LIMITS.maximumSounds} sounds, so ${name} was not added.`);
+ }
+ if (!definition.buffer || typeof definition.buffer.duration !== 'number') {
+ throw new TypeError(`defineSound(${name}) buffer must be a decoded AudioBuffer. To load a URL or ArrayBuffer use await audio.load(name, source).`);
+ }
+ const sound = Object.freeze({
+ name,
+ buffer: definition.buffer,
+ bus: requireBus(definition.bus ?? 'effects'),
+ volume: requireNumberInRange(definition.volume ?? 1, `sound ${name} volume`, 0, 4),
+ pitch: requireNumberInRange(definition.pitch ?? 1, `sound ${name} pitch`, 0.1, 4),
+ pitchVariance: requireNumberInRange(definition.pitchVariance ?? 0, `sound ${name} pitchVariance`, 0, 1),
+ loop: definition.loop === true,
+ maximumInstances: requireNumberInRange(definition.maximumInstances ?? AUDIO_LIMITS.defaultInstancesPerSound, `sound ${name} maximumInstances`, 1, AUDIO_LIMITS.maximumInstancesPerSound),
+ spatial: normalizeSpatial(definition.spatial, `sound ${name}`),
+ });
+ sounds.set(name, sound);
+ return sound;
+ }
+
+ async function load(name, source, definition = {}) {
+ requireName(name, 'sound name');
+ backend.init();
+ const buffer = await backend.decode(source);
+ return defineSound(name, { ...definition, buffer });
+ }
+
+ // ---- Voices ----
+
+ function voiceLevel(voice) {
+ const sound = voice.sound;
+ let level = voice.volume * busVolumes.get(sound.bus) * busVolumes.get('master');
+ if (voice.position && sound.spatial) {
+ level *= distanceGain(distanceBetween(voice.position, listenerPose.position), sound.spatial);
+ level *= 1 - OCCLUDED_GAIN_LOSS * voice.occlusion;
+ }
+ return level;
+ }
+
+ function resolveVoicePosition(voice) {
+ return readNodePosition(voice.node, `sound ${voice.sound.name} node`);
+ }
+
+ function measureOcclusion(voice) {
+ if (!occluder || !voice.sound.spatial?.occlusion || !voice.position) return 0;
+ return requireNumberInRange(occluder(listenerPose.position, voice.position), 'occlusion function result', 0, 1);
+ }
+
+ function removeVoice(voice) {
+ const index = voices.indexOf(voice);
+ if (index >= 0) voices.splice(index, 1);
+ }
+
+ function stopVoice(voice) {
+ voice.backendVoice.stop();
+ removeVoice(voice);
+ }
+
+ function makeRoom(sound, level) {
+ const sameSound = voices.filter(voice => voice.sound === sound);
+ if (sameSound.length >= sound.maximumInstances) stopVoice(sameSound[0]);
+ if (voices.length < maximumVoices) return true;
+ const quietest = voices.reduce((lowest, voice) => (voice.level < lowest.level ? voice : lowest), voices[0]);
+ if (quietest.level >= level) return false;
+ stopVoice(quietest);
+ return true;
+ }
+
+ // Plays a sound. Options: position [x, y, z] or node (follows it), volume, pitch, bus, loop. Returns a handle, or null when
+ // the voice limit is full of louder sounds.
+ function play(soundName, playOptions = {}) {
+ const sound = requireSound(soundName);
+ startBackend();
+ const volume = sound.volume * requireNumberInRange(playOptions.volume ?? 1, `play ${soundName} volume`, 0, 4);
+ const variance = sound.pitchVariance === 0 ? 0 : (random() * 2 - 1) * sound.pitchVariance;
+ const pitch = sound.pitch * requireNumberInRange(playOptions.pitch ?? 1, `play ${soundName} pitch`, 0.1, 4) * (1 + variance);
+ const voice = {
+ id: nextVoiceId,
+ sound,
+ node: playOptions.node ?? null,
+ position: null,
+ volume,
+ pitch: requireNumberInRange(pitch, `play ${soundName} resulting pitch`, 0.1, 16),
+ loop: playOptions.loop ?? sound.loop,
+ occlusion: 0,
+ level: 0,
+ backendVoice: null,
+ };
+ if (sound.spatial) {
+ if (voice.node === null && playOptions.position === undefined) {
+ throw new TypeError(`Sound ${soundName} is spatial, so play it with { position: [x, y, z] } or { node }. For a flat sound define it without spatial.`);
+ }
+ voice.position = voice.node === null
+ ? requireVector(playOptions.position, `play ${soundName} position`)
+ : resolveVoicePosition(voice);
+ }
+ voice.occlusion = measureOcclusion(voice);
+ voice.level = voiceLevel(voice);
+ if (!makeRoom(sound, voice.level)) return null;
+ nextVoiceId += 1;
+ voice.backendVoice = backend.startVoice({
+ buffer: sound.buffer,
+ bus: sound.bus,
+ volume: voice.volume,
+ pitch: voice.pitch,
+ loop: voice.loop,
+ spatial: sound.spatial,
+ position: voice.position,
+ occlusion: voice.occlusion,
+ onEnded: () => removeVoice(voice),
+ });
+ voices.push(voice);
+ return Object.freeze({
+ id: voice.id,
+ sound: soundName,
+ stop: () => stopVoice(voice),
+ get playing() {
+ return voices.includes(voice);
+ },
+ get level() {
+ return voice.level;
+ },
+ });
+ }
+
+ // A sound that follows a node: loops by default, so an engine hum stays on its vehicle until stop() is called.
+ function attach(node, soundName, playOptions = {}) {
+ return play(soundName, { loop: true, ...playOptions, node });
+ }
+
+ function stopAll(soundName) {
+ for (const voice of [...voices]) {
+ if (soundName === undefined || voice.sound.name === soundName) stopVoice(voice);
+ }
+ }
+
+ // The active voices, for tests and a debug overlay: level is the predicted output level after bus, distance and occlusion.
+ function activeVoices() {
+ return voices.map(voice => Object.freeze({
+ id: voice.id,
+ sound: voice.sound.name,
+ bus: voice.sound.bus,
+ volume: voice.volume,
+ pitch: voice.pitch,
+ loop: voice.loop,
+ position: voice.position ? [...voice.position] : null,
+ occlusion: voice.occlusion,
+ level: voice.level,
+ }));
+ }
+
+ // ---- Events ----
+
+ // Bind an event name to a sound. volume, pitch and position are numbers or functions (eventData) => value, so a contact's
+ // impulse can set the loudness: bindEvent('contact', 'thud', { volume: data => Math.min(1, data.impulse / 20) }).
+ function bindEvent(eventName, soundName, bindOptions = {}) {
+ requireName(eventName, 'event name');
+ requireSound(soundName);
+ if (bindingCount >= AUDIO_LIMITS.maximumBindings) {
+ throw new RangeError(`An audio can hold at most ${AUDIO_LIMITS.maximumBindings} event bindings, so ${eventName} was not bound.`);
+ }
+ for (const field of ['volume', 'pitch']) {
+ const value = bindOptions[field];
+ if (value !== undefined && typeof value !== 'function' && !Number.isFinite(value)) {
+ throw new TypeError(`bindEvent ${eventName} ${field} must be a number or a function (eventData) => number, got ${describe(value)}.`);
+ }
+ }
+ if (!bindings.has(eventName)) bindings.set(eventName, []);
+ const entry = { soundName, options: bindOptions };
+ bindings.get(eventName).push(entry);
+ bindingCount += 1;
+ return () => {
+ const list = bindings.get(eventName);
+ const index = list ? list.indexOf(entry) : -1;
+ if (index >= 0) {
+ list.splice(index, 1);
+ bindingCount -= 1;
+ }
+ };
+ }
+
+ function playBinding(entry, data) {
+ const settings = entry.options;
+ const playOptions = {
+ volume: settings.volume === undefined ? 1 : resolveNumber(settings.volume, data, `${entry.soundName} volume`, 0, 4),
+ pitch: settings.pitch === undefined ? 1 : resolveNumber(settings.pitch, data, `${entry.soundName} pitch`, 0.1, 4),
+ };
+ const position = typeof settings.position === 'function' ? settings.position(data) : settings.position ?? data?.position;
+ if (settings.node !== undefined) playOptions.node = settings.node;
+ else if (position !== undefined) playOptions.position = position;
+ return play(entry.soundName, playOptions);
+ }
+
+ // Fires every sound bound to the event. Returns the handles that started.
+ function emit(eventName, data = {}) {
+ requireName(eventName, 'event name');
+ const handles = [];
+ for (const entry of [...(bindings.get(eventName) ?? [])]) {
+ const handle = playBinding(entry, data);
+ if (handle) handles.push(handle);
+ }
+ return handles;
+ }
+
+ // Input: a pressed action fires the event input:<action>. The input system must run before this one.
+ function bindAction(actionName, soundName, bindOptions = {}) {
+ requireName(actionName, 'action name');
+ if (!input) throw new TypeError('bindAction needs an input: pass createAudio({ input }) or call audio.setInput(input).');
+ const eventName = `input:${actionName}`;
+ actionEvents.set(actionName, eventName);
+ return bindEvent(eventName, soundName, bindOptions);
+ }
+
+ function setInput(newInput) {
+ if (!newInput || typeof newInput.wasPressed !== 'function') {
+ throw new TypeError('setInput needs an input from createInput (it has wasPressed(action)).');
+ }
+ input = newInput;
+ }
+
+ // Physics contacts (the recorded scene's contactEvents): each started event fires contact (or sensor), plus
+ // contact:<collider> for both colliders, so a sound can bind to one body. data.position comes from options.position(event).
+ function emitContacts(contactEvents, contactOptions = {}) {
+ if (!Array.isArray(contactEvents)) {
+ throw new TypeError(`emitContacts needs an array of contact events { started, kind, colliderA, colliderB, ... }, got ${describe(contactEvents)}.`);
+ }
+ for (const event of contactEvents) {
+ if (event.started === false) continue;
+ const data = contactOptions.position ? { ...event, position: contactOptions.position(event) } : event;
+ const kind = event.kind === 'sensor' ? 'sensor' : 'contact';
+ emit(kind, data);
+ emit(`${kind}:${String(event.colliderA)}`, data);
+ emit(`${kind}:${String(event.colliderB)}`, data);
+ }
+ }
+
+ // Animation markers crossed between two clip times fire marker:<name>, with the marker and extra data in the event data.
+ function emitMarkers(markers, fromTime, toTime, markerOptions = {}) {
+ for (const marker of markersCrossed(markers, fromTime, toTime, markerOptions)) {
+ emit(`marker:${marker.name}`, { ...markerOptions.data, marker, time: marker.time });
+ }
+ }
+
+ // ---- Mixing ----
+
+ function setBusVolume(name, volume) {
+ requireNumberInRange(volume, `bus ${String(name)} volume`, 0, 4);
+ if (name !== 'master') requireBus(name);
+ busVolumes.set(name, volume);
+ if (started) backend.setBusVolume(name, volume);
+ for (const voice of voices) voice.level = voiceLevel(voice);
+ }
+
+ function getBusVolume(name) {
+ if (!busVolumes.has(name)) requireBus(name);
+ return busVolumes.get(name);
+ }
+
+ function setListener(camera) {
+ listenerPose = readListener(camera);
+ if (started) backend.setListener(listenerPose);
+ }
+
+ function synchronize() {
+ if (listenerSource) setListener(listenerSource());
+ for (const voice of [...voices]) {
+ if (voice.node !== null && voice.sound.spatial) voice.position = resolveVoicePosition(voice);
+ voice.occlusion = measureOcclusion(voice);
+ voice.level = voiceLevel(voice);
+ voice.backendVoice.update({ volume: voice.volume, pitch: voice.pitch, position: voice.position, occlusion: voice.occlusion });
+ }
+ }
+
+ // ---- Runtime system ----
+
+ function startBackend() {
+ if (started) return;
+ backend.init();
+ for (const [name, volume] of busVolumes) {
+ if (name !== 'master') backend.createBus(name, volume);
+ }
+ backend.setBusVolume('master', busVolumes.get('master'));
+ backend.setListener(listenerPose);
+ started = true;
+ }
+
+ return {
+ name: options.name ?? 'audio',
+ init() {
+ startBackend();
+ },
+ fixedUpdate(step, context) {
+ if (input) {
+ for (const [actionName, eventName] of actionEvents) {
+ if (input.wasPressed(actionName)) emit(eventName, { action: actionName });
+ }
+ }
+ if (context?.mode === 'fixed') synchronize();
+ },
+ update() {
+ synchronize();
+ },
+ dispose() {
+ stopAll();
+ backend.dispose();
+ started = false;
+ },
+ backend,
+ defineSound,
+ load,
+ createBus,
+ setBusVolume,
+ getBusVolume,
+ play,
+ attach,
+ stopAll,
+ activeVoices,
+ bindEvent,
+ bindAction,
+ setInput,
+ emit,
+ emitContacts,
+ emitMarkers,
+ setListener,
+ synchronize,
+ unlock: () => backend.unlock?.(),
+ };
+}
diff --git a/src/docs-live.js b/src/docs-live.js
index d98ebc38..6ce684bc 100644
--- a/src/docs-live.js
+++ b/src/docs-live.js
@@ -64,6 +64,7 @@ const addonLoaders = import.meta.glob([
'./cloth.js',
'./runtime.js',
'./input.js',
+ './audio.js',
'./update-part-vertices.js',
]);
const moduleCache = new Map();
diff --git a/tests/audio.test.js b/tests/audio.test.js
new file mode 100644
index 00000000..494b93e8
--- /dev/null
+++ b/tests/audio.test.js
@@ -0,0 +1,389 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import {
+ AUDIO_LIMITS,
+ createAudio,
+ distanceGain,
+ markersCrossed,
+ OCCLUDED_GAIN_LOSS,
+ readListener,
+ readNodePosition,
+ webAudioBackend,
+} from '../src/audio.js';
+import { createInput } from '../src/input.js';
+import { createRuntime } from '../src/runtime.js';
+
+function createParameter(initial = 0) {
+ return {
+ value: initial,
+ setTargetAtTime(value) {
+ this.value = value;
+ },
+ };
+}
+
+function createFakeNode(kind) {
+ const node = { kind, connections: [] };
+ node.connect = target => {
+ node.connections.push(target);
+ return target;
+ };
+ node.disconnect = () => {
+ node.connections.length = 0;
+ };
+ return node;
+}
+
+// A recording stand-in for AudioContext: no sound, but every node, connection and parameter value can be inspected.
+function createFakeAudioContext() {
+ const context = {
+ state: 'suspended',
+ currentTime: 0,
+ nodes: [],
+ closed: false,
+ listener: {
+ positionX: createParameter(), positionY: createParameter(), positionZ: createParameter(),
+ forwardX: createParameter(), forwardY: createParameter(), forwardZ: createParameter(),
+ upX: createParameter(), upY: createParameter(), upZ: createParameter(),
+ },
+ };
+ context.destination = createFakeNode('destination');
+ const track = node => {
+ context.nodes.push(node);
+ return node;
+ };
+ context.resume = async () => {
+ context.state = 'running';
+ };
+ context.close = () => {
+ context.closed = true;
+ };
+ context.createGain = () => track(Object.assign(createFakeNode('gain'), { gain: createParameter(1) }));
+ context.createDynamicsCompressor = () => track(Object.assign(createFakeNode('limiter'), {
+ threshold: createParameter(), knee: createParameter(), ratio: createParameter(), attack: createParameter(), release: createParameter(),
+ }));
+ context.createBiquadFilter = () => track(Object.assign(createFakeNode('filter'), { frequency: createParameter(), type: '' }));
+ context.createPanner = () => track(Object.assign(createFakeNode('panner'), {
+ positionX: createParameter(), positionY: createParameter(), positionZ: createParameter(),
+ }));
+ context.createBufferSource = () => track(Object.assign(createFakeNode('source'), {
+ playbackRate: createParameter(1),
+ stopped: false,
+ start() {},
+ stop() {
+ this.stopped = true;
+ },
+ finish() {
+ this.onended?.();
+ },
+ }));
+ context.decodeAudioData = async bytes => ({ duration: bytes.byteLength / 1000 });
+ return context;
+}
+
+function createFakeGestureTarget() {
+ const handlers = new Map();
+ return {
+ addEventListener(type, handler) {
+ handlers.set(type, handler);
+ },
+ removeEventListener(type) {
+ handlers.delete(type);
+ },
+ dispatch(type) {
+ handlers.get(type)?.();
+ },
+ get listenerCount() {
+ return handlers.size;
+ },
+ };
+}
+
+const buffer = { duration: 1 };
+
+function createFixture(options = {}) {
+ const context = createFakeAudioContext();
+ const gestureTarget = createFakeGestureTarget();
+ const audio = createAudio({ backend: webAudioBackend({ createContext: () => context, gestureTarget }), ...options });
+ audio.init();
+ return { audio, context, gestureTarget };
+}
+
+function sourcesOf(context) {
+ return context.nodes.filter(node => node.kind === 'source');
+}
+
+test('the output graph ends in a limiter before the destination, with music, effects and voice buses', () => {
+ const { context } = createFixture();
+ const limiter = context.nodes.find(node => node.kind === 'limiter');
+ assert.deepEqual(limiter.connections, [context.destination]);
+ assert.equal(limiter.ratio.value, 20);
+ const gains = context.nodes.filter(node => node.kind === 'gain');
+ const master = gains.find(node => node.connections.includes(limiter));
+ assert.equal(gains.filter(node => node.connections.includes(master)).length, 3);
+});
+
+test('the context resumes on the first user gesture and the listeners are then removed', () => {
+ const { context, gestureTarget } = createFixture();
+ assert.equal(context.state, 'suspended');
+ assert.equal(gestureTarget.listenerCount, 3);
+ gestureTarget.dispatch('keydown');
+ assert.equal(context.state, 'running');
+ assert.equal(gestureTarget.listenerCount, 0);
+});
+
+test('distanceGain follows the Web Audio models', () => {
+ assert.equal(distanceGain(1, { referenceDistance: 1 }), 1);
+ assert.equal(distanceGain(10, { referenceDistance: 1, rolloff: 1 }), 0.1);
+ assert.equal(distanceGain(0.2, { referenceDistance: 1 }), 1);
+ assert.ok(Math.abs(distanceGain(51, { model: 'linear', referenceDistance: 1, maximumDistance: 101, rolloff: 1 }) - 0.5) < 1e-9);
+ assert.equal(distanceGain(4, { model: 'exponential', referenceDistance: 1, rolloff: 1 }), 0.25);
+ assert.equal(
+ distanceGain(500, { referenceDistance: 1, maximumDistance: 100, rolloff: 1 }),
+ distanceGain(100, { referenceDistance: 1, maximumDistance: 100, rolloff: 1 }),
+ );
+});
+
+test('a spatial sound gets quieter with distance from the listener on the camera', () => {
+ const { audio } = createFixture();
+ audio.defineSound('thud', { buffer, spatial: { referenceDistance: 1 } });
+ audio.setListener({ eye: [0, 2, 0], target: [0, 2, -5] });
+ const near = audio.play('thud', { position: [0, 2, -1] });
+ const far = audio.play('thud', { position: [0, 2, -9] });
+ assert.equal(near.level, 1);
+ assert.ok(Math.abs(far.level - 1 / 9) < 1e-9, `far level ${far.level}`);
+ audio.setListener({ eye: [0, 2, -9], target: [0, 2, -20] });
+ audio.synchronize();
+ assert.equal(far.level, 1);
+});
+
+test('the listener is written to the context from a camera frame', () => {
+ const { audio, context } = createFixture();
+ audio.setListener({ eye: [1, 2, 3], target: [1, 2, 0] });
+ assert.equal(context.listener.positionX.value, 1);
+ assert.equal(context.listener.positionZ.value, 3);
+ assert.deepEqual([context.listener.forwardX.value, context.listener.forwardY.value, context.listener.forwardZ.value], [0, 0, -1]);
+ assert.deepEqual(readListener({ position: [0, 0, 0], forward: [0, 0, 4] }).forward, [0, 0, 1]);
+});
+
+test('a listener function follows the camera each frame', () => {
+ let eye = [0, 0, 0];
+ const { audio, context } = createFixture({ listener: () => ({ eye, target: [eye[0], eye[1], eye[2] - 1] }) });
+ audio.synchronize();
+ eye = [5, 0, 0];
+ audio.synchronize();
+ assert.equal(context.listener.positionX.value, 5);
+});
+
+test('a sound attached to a node follows it as the node moves', () => {
+ const { audio, context } = createFixture();
+ audio.defineSound('hum', { buffer, spatial: true });
+ const vehicle = { position: [10, 0, 0] };
+ const handle = audio.attach(vehicle, 'hum');
+ const panner = context.nodes.find(node => node.kind === 'panner');
+ assert.equal(panner.positionX.value, 10);
+ vehicle.position = [3, 0, 0];
+ audio.synchronize();
+ assert.equal(panner.positionX.value, 3);
+ assert.equal(audio.activeVoices()[0].loop, true);
+ handle.stop();
+ assert.equal(handle.playing, false);
+ assert.equal(sourcesOf(context)[0].stopped, true);
+ assert.deepEqual(readNodePosition({ matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 4, 5, 6, 1]) }), [4, 5, 6]);
+});
+
+test('occlusion lowers the level and the low-pass cutoff', () => {
+ let blocked = 0;
+ const { audio, context } = createFixture({ occlusion: () => blocked });
+ audio.defineSound('shot', { buffer, spatial: { referenceDistance: 1, occlusion: true } });
+ audio.defineSound('plain', { buffer, spatial: true });
+ const handle = audio.play('shot', { position: [0, 0, -1] });
+ assert.equal(handle.level, 1);
+ blocked = 1;
+ audio.synchronize();
+ assert.ok(Math.abs(handle.level - (1 - OCCLUDED_GAIN_LOSS)) < 1e-9);
+ const filter = context.nodes.find(node => node.kind === 'filter');
+ assert.ok(filter.frequency.value < 500);
+ assert.equal(audio.play('plain', { position: [0, 0, -1] }).level, 1);
+});
+
+test('contacts fire sounds with the impulse setting the volume, and ended contacts stay silent', () => {
+ const { audio } = createFixture();
+ audio.defineSound('thud', { buffer, spatial: true });
+ audio.bindEvent('contact', 'thud', { volume: data => Math.min(1, data.impulse / 10) });
+ audio.emitContacts([
+ { started: true, kind: 'contact', colliderA: 'ball', colliderB: 'floor', impulse: 5, position: [0, 0, -1] },
+ { started: false, kind: 'contact', colliderA: 'ball', colliderB: 'floor', impulse: 9, position: [0, 0, -1] },
+ { started: true, kind: 'contact', colliderA: 'ball', colliderB: 'wall', impulse: 40, position: [0, 0, -1] },
+ ]);
+ assert.deepEqual(audio.activeVoices().map(voice => voice.level), [0.5, 1]);
+});
+
+test('a contact can bind to one collider and takes its position from the options', () => {
+ const { audio } = createFixture();
+ audio.defineSound('splash', { buffer, spatial: true });
+ audio.bindEvent('sensor:pool', 'splash');
+ audio.emitContacts([{ started: true, kind: 'sensor', colliderA: 'pool', colliderB: 'ball' }], { position: () => [0, 0, -2] });
+ assert.equal(audio.activeVoices().length, 1);
+ assert.deepEqual(audio.activeVoices()[0].position, [0, 0, -2]);
+});
+
+test('animation markers fire once when the clip time crosses them, including across a loop', () => {
+ const markers = [{ time: 0.25, name: 'footstep' }, { time: 0.75, name: 'footstep' }];
+ assert.deepEqual(markersCrossed(markers, 0, 0.25).map(marker => marker.time), [0.25]);
+ assert.deepEqual(markersCrossed(markers, 0.25, 0.5), []);
+ assert.deepEqual(markersCrossed(markers, 0.5, 0.1, { loop: true, duration: 1 }).map(marker => marker.time), [0.75]);
+ assert.deepEqual(markersCrossed(markers, 0.8, 0.3, { loop: true, duration: 1 }).map(marker => marker.time), [0.25]);
+
+ const { audio } = createFixture();
+ audio.defineSound('step', { buffer, spatial: true });
+ audio.bindEvent('marker:footstep', 'step', { position: data => data.foot });
+ audio.emitMarkers(markers, 0, 0.5, { data: { foot: [0, 0, -1] } });
+ assert.equal(audio.activeVoices().length, 1);
+ audio.emitMarkers(markers, 0.5, 1, { data: { foot: [0, 0, -1] } });
+ assert.equal(audio.activeVoices().length, 2);
+});
+
+test('input actions trigger sounds from the runtime, one per press', () => {
+ const input = createInput({ actions: { jump: ['script/jump'] } });
+ const { audio } = createFixture({ input });
+ audio.defineSound('hop', { buffer });
+ audio.bindAction('jump', 'hop', { pitch: 1.5 });
+ const runtime = createRuntime({ render() {} }, {
+ mode: 'fixed',
+ fixedRate: 60,
+ systems: [input, audio],
+ scheduler: { request: () => 1, cancel() {} },
+ clock: () => 0,
+ visibility: { hidden: false, subscribe: () => () => {} },
+ });
+ runtime.start();
+ input.press('script/jump');
+ runtime.step(17);
+ assert.equal(audio.activeVoices().length, 1);
+ assert.equal(audio.activeVoices()[0].pitch, 1.5);
+ runtime.step(17);
+ assert.equal(audio.activeVoices().length, 1, 'a held key does not retrigger');
+ runtime.dispose();
+});
+
+test('buses scale the measured level and the master bus scales every bus', () => {
+ const { audio } = createFixture();
+ audio.defineSound('tune', { buffer, bus: 'music', volume: 0.8 });
+ audio.defineSound('line', { buffer, bus: 'voice' });
+ const tune = audio.play('tune');
+ const line = audio.play('line');
+ audio.setBusVolume('music', 0.5);
+ assert.ok(Math.abs(tune.level - 0.4) < 1e-9);
+ assert.equal(line.level, 1);
+ audio.setBusVolume('master', 0.5);
+ assert.ok(Math.abs(tune.level - 0.2) < 1e-9);
+ assert.equal(line.level, 0.5);
+ assert.equal(audio.getBusVolume('music'), 0.5);
+ assert.throws(() => audio.setBusVolume('nope', 1), /Unknown bus nope/);
+});
+
+test('a created bus is routed into the master bus', () => {
+ const { audio, context } = createFixture();
+ const gainsBefore = context.nodes.filter(node => node.kind === 'gain').length;
+ audio.createBus('ui', 0.25);
+ assert.equal(context.nodes.filter(node => node.kind === 'gain').length, gainsBefore + 1);
+ audio.defineSound('click', { buffer, bus: 'ui' });
+ assert.ok(audio.play('click'));
+});
+
+test('a sound that finishes leaves the active voices, and the limit keeps the loudest', () => {
+ const { audio, context } = createFixture({ maximumVoices: 2 });
+ audio.defineSound('tick', { buffer, maximumInstances: 8 });
+ audio.play('tick', { volume: 0.5 });
+ audio.play('tick', { volume: 0.7 });
+ assert.equal(audio.play('tick', { volume: 0.1 }), null, 'a quieter voice does not steal');
+ assert.ok(audio.play('tick', { volume: 1 }));
+ assert.deepEqual(audio.activeVoices().map(voice => voice.volume).sort(), [0.7, 1]);
+ sourcesOf(context).at(-1).finish();
+ assert.equal(audio.activeVoices().length, 1);
+});
+
+test('maximumInstances stops the oldest copy of a sound', () => {
+ const { audio } = createFixture();
+ audio.defineSound('clink', { buffer, maximumInstances: 2 });
+ const first = audio.play('clink');
+ audio.play('clink');
+ audio.play('clink');
+ assert.equal(first.playing, false);
+ assert.equal(audio.activeVoices().length, 2);
+});
+
+test('pitch variance is deterministic for the same seed', () => {
+ const pitches = seed => {
+ const { audio } = createFixture({ seed });
+ audio.defineSound('step', { buffer, pitchVariance: 0.2, maximumInstances: 8 });
+ for (let index = 0; index < 4; index += 1) audio.play('step');
+ return audio.activeVoices().map(voice => voice.pitch);
+ };
+ assert.deepEqual(pitches(7), pitches(7));
+ assert.notDeepEqual(pitches(7), pitches(8));
+ assert.ok(pitches(7).every(pitch => pitch >= 0.8 && pitch <= 1.2));
+});
+
+test('load decodes an ArrayBuffer into a sound', async () => {
+ const { audio } = createFixture();
+ const sound = await audio.load('boom', new ArrayBuffer(2000), { bus: 'effects' });
+ assert.equal(sound.buffer.duration, 2);
+ assert.ok(audio.play('boom'));
+ await assert.rejects(() => audio.load('bad', 42), /URL string, an ArrayBuffer or a decoded AudioBuffer/);
+});
+
+test('errors name the field and say what to pass', () => {
+ const { audio } = createFixture();
+ assert.throws(() => audio.defineSound('x', { buffer: {} }), /buffer must be a decoded AudioBuffer/);
+ assert.throws(() => audio.defineSound('x', { buffer, bus: 'sfx' }), /Unknown bus sfx/);
+ assert.throws(() => audio.defineSound('x', { buffer, spatial: { model: 'cubic' } }), /spatial model must be one of/);
+ assert.throws(() => audio.defineSound('x', { buffer, volume: 9 }), /sound x volume/);
+ assert.throws(() => audio.play('missing'), /Unknown sound missing/);
+ audio.defineSound('s', { buffer, spatial: true });
+ assert.throws(() => audio.play('s'), /play it with \{ position/);
+ assert.throws(() => audio.play('s', { position: [0, NaN, 0] }), /three finite numbers/);
+ assert.throws(() => audio.bindEvent('e', 's', { volume: 'loud' }), /volume must be a number or a function/);
+ assert.throws(() => audio.bindAction('jump', 's'), /needs an input/);
+ assert.throws(() => audio.createBus('master'), /reserved/);
+ assert.throws(() => createAudio({ occlusion: 3 }), /occlusion must be a function/);
+ assert.throws(() => readListener(null), /listener must be a camera frame/);
+ assert.throws(() => markersCrossed([{ time: 1 }], 0, 2), /marker name/);
+});
+
+test('bindings are bounded', () => {
+ const { audio } = createFixture();
+ audio.defineSound('s', { buffer });
+ for (let index = 0; index < AUDIO_LIMITS.maximumBindings; index += 1) audio.bindEvent(`e${index}`, 's');
+ assert.throws(() => audio.bindEvent('one-more', 's'), /at most 256 event bindings/);
+});
+
+test('dispose stops every voice and closes the context', () => {
+ const { audio, context } = createFixture();
+ audio.defineSound('loop', { buffer, loop: true });
+ audio.play('loop');
+ audio.dispose();
+ assert.equal(sourcesOf(context)[0].stopped, true);
+ assert.equal(context.closed, true);
+});
+
+test('a different backend plugs in behind the same calls', () => {
+ const calls = [];
+ const backend = {
+ init: () => calls.push('init'),
+ dispose: () => calls.push('dispose'),
+ createBus: name => calls.push(`bus:${name}`),
+ setBusVolume: name => calls.push(`volume:${name}`),
+ setListener: () => calls.push('listener'),
+ startVoice: voice => {
+ calls.push(`voice:${voice.bus}`);
+ return { update() {}, stop() {} };
+ },
+ };
+ const audio = createAudio({ backend });
+ audio.defineSound('beep', { buffer, bus: 'voice' });
+ audio.play('beep');
+ assert.ok(calls.includes('voice:voice'));
+ assert.ok(calls.includes('bus:music'));
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index 80d48ff3..69b1438b 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -107,6 +107,7 @@ export default defineConfig({
cloth: 'src/cloth.js',
runtime: 'src/runtime.js',
input: 'src/input.js',
+ audio: 'src/audio.js',
'update-part-vertices':'src/update-part-vertices.js',
'replace-textured-parts': 'src/replace-textured-parts.js',
// Page of the MCP preview. It imports the engine chunks above instead of bundling its own copy.