Sounds on the client

This commit is contained in:
2026-11-22 07:21:29 -03:00
parent f308ab52f1
commit 47934b272c
21 changed files with 1002 additions and 25 deletions
+1 -20
View File
@@ -3,7 +3,7 @@
import { load_texture, Texture } from "./renderer/mod.ts";
type Asset = Texture | HTMLAudioElement | string | Record<string, unknown>;
type Asset = Texture | string | Record<string, unknown>;
export class AssetManager {
static instance = new AssetManager();
@@ -29,25 +29,6 @@ export class AssetManager {
});
img.src = src;
this.loading_promises.push(promise);
} else if (src.endsWith(".ogg")) {
const audio = new Audio();
const promise = new Promise<void>((resolve, reject) => {
audio.addEventListener(
"canplaythrough",
() => resolve(),
{ once: true },
);
audio.addEventListener(
"error",
() => reject(new Error(`Failed to load audio: ${src}`)),
{ once: true },
);
});
audio.src = src;
audio.load();
this.assets[key] = audio;
this.loading_promises.push(promise);
} else if (src.endsWith(".txt") || src.endsWith(".md") || src.endsWith(".fnt")) {
const promise = async () => {
const resp = await fetch(src);
+178
View File
@@ -0,0 +1,178 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// plays what client/sounds.ts decides on with web audio: a gain per category under master, and a panner for each
// sound that comes from somewhere, fading linearly to nothing at its range
import { SOUND_CATEGORIES, type SoundCategory } from "@/common/mod_data.ts";
import type { Position } from "@/common/mod_api/shared.ts";
import type { SoundFile, SoundOutput, Voice, VoiceSettings, Volumes } from "./sounds.ts";
export class WebAudioOutput implements SoundOutput {
#context: AudioContext | undefined;
#master: GainNode | undefined;
#categories = new Map<SoundCategory, GainNode>();
// decoded once, the first time anything plays them. by the bytes, so another server's files never mix in
#buffers = new WeakMap<Uint8Array, Promise<AudioBuffer | undefined>>();
#volumes: Volumes | undefined;
constructor() {
// browsers keep audio off until the player clicks or presses a key, so it starts then
const unlock = () => {
this.#unlock();
if (this.#context?.state === "running") {
removeEventListener("pointerdown", unlock);
removeEventListener("keydown", unlock);
}
};
addEventListener("pointerdown", unlock);
addEventListener("keydown", unlock);
}
#unlock() {
if (!this.#context) {
const context = new AudioContext();
this.#master = context.createGain();
this.#master.connect(context.destination);
for (const category of SOUND_CATEGORIES) {
const gain = context.createGain();
gain.connect(this.#master);
this.#categories.set(category, gain);
}
this.#context = context;
if (this.#volumes) this.set_volumes(this.#volumes);
}
if (this.#context.state === "suspended") this.#context.resume();
}
start(file: SoundFile, settings: VoiceSettings): Voice | undefined {
const context = this.#context;
// sounds played while it's suspended would all come at once when it resumes
if (!context || context.state !== "running") return undefined;
const out = settings.category ? this.#categories.get(settings.category)! : this.#master!;
return new WebVoice(context, this.#buffer(context, file), out, settings);
}
#buffer(context: AudioContext, file: SoundFile) {
let buffer = this.#buffers.get(file.bytes);
if (!buffer) {
// decoding detaches what it's given
buffer = context.decodeAudioData(file.bytes.slice().buffer).catch((e) => {
console.error(`couldn't decode the sound file ${file.id}:`, e);
return undefined;
});
this.#buffers.set(file.bytes, buffer);
}
return buffer;
}
listen(x: number, y: number, z: number, yaw: number, pitch: number) {
const listener = this.#context?.listener;
if (!listener) return;
// the camera's forward and up, see ClientLevel's pick
const forward = [-Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), -Math.cos(yaw) * Math.cos(pitch)];
const up = [Math.sin(yaw) * Math.sin(pitch), Math.cos(pitch), Math.cos(yaw) * Math.sin(pitch)];
// firefox only has the old setters
if (listener.positionX) {
listener.positionX.value = x;
listener.positionY.value = y;
listener.positionZ.value = z;
listener.forwardX.value = forward[0];
listener.forwardY.value = forward[1];
listener.forwardZ.value = forward[2];
listener.upX.value = up[0];
listener.upY.value = up[1];
listener.upZ.value = up[2];
} else {
listener.setPosition(x, y, z);
listener.setOrientation(forward[0], forward[1], forward[2], up[0], up[1], up[2]);
}
}
set_volumes(volumes: Volumes) {
this.#volumes = volumes;
if (!this.#master) return;
this.#master.gain.value = volumes.master;
for (const [category, gain] of this.#categories) gain.gain.value = volumes[category];
}
}
class WebVoice implements Voice {
ended = false;
#source: AudioBufferSourceNode | undefined;
#gain: GainNode;
#panner: PannerNode | undefined;
#stopped = false;
// set may come before the file is decoded
#pitch: number;
constructor(
context: AudioContext,
buffer: Promise<AudioBuffer | undefined>,
out: AudioNode,
settings: VoiceSettings,
) {
this.#pitch = settings.pitch;
this.#gain = new GainNode(context, { gain: Math.min(1, settings.volume) });
if (settings.at) {
this.#panner = new PannerNode(context, {
panningModel: "HRTF",
distanceModel: "linear",
refDistance: 1,
maxDistance: settings.range,
positionX: settings.at.x,
positionY: settings.at.y,
positionZ: settings.at.z,
});
this.#gain.connect(this.#panner).connect(out);
} else {
this.#gain.connect(out);
}
// the first time a file plays it starts once it's decoded
buffer.then((buffer) => {
if (!buffer || this.#stopped) {
this.ended = true;
return;
}
const source = new AudioBufferSourceNode(context, {
buffer,
loop: settings.loop,
playbackRate: this.#pitch,
});
source.connect(this.#gain);
source.onended = () => {
this.ended = true;
this.#disconnect();
};
source.start(0, settings.loop ? settings.offset % buffer.duration : 0);
this.#source = source;
});
}
move(at: Position) {
if (!this.#panner) return;
this.#panner.positionX.value = at.x;
this.#panner.positionY.value = at.y;
this.#panner.positionZ.value = at.z;
}
set(volume: number, pitch: number, range: number) {
this.#gain.gain.value = Math.min(1, volume);
this.#pitch = pitch;
if (this.#source) this.#source.playbackRate.value = pitch;
if (this.#panner) this.#panner.maxDistance = range;
}
stop() {
this.#stopped = true;
this.ended = true;
this.#source?.stop();
this.#disconnect();
}
#disconnect() {
this.#source?.disconnect();
this.#gain.disconnect();
this.#panner?.disconnect();
}
}
+15 -2
View File
@@ -29,6 +29,7 @@ import { type BlockRegistry, EverythingRegistry } from "@/common/everything_regi
import type { EntityJson } from "@/common/mod_data.ts";
import { tick_texture_animations } from "./texture_animations.ts";
import type { RenderBenchmark } from "./benchmark/benchmark.ts";
import { sounds } from "./sounds.ts";
// holding the use button uses the held item on blocks again this often, like minecraft's 4 ticks
const USE_REPEAT_MS = 200;
@@ -136,12 +137,14 @@ export class Client {
// leaving on purpose, from the pause screen
disconnect() {
this.#stopped = true;
sounds.stop_all();
this.connection.close();
back_to_title();
}
#stop() {
this.#stopped = true;
sounds.stop_all();
this.level.dispose();
InputManager.set_mouse_grabbed(false);
}
@@ -183,8 +186,18 @@ export class Client {
this.#pending_time = Math.min(this.#pending_time, TICK_DELTA);
}
if (this.benchmark) this.benchmark.render(this.#pending_time / TICK_DELTA);
else this.game_renderer.render(this, this.#pending_time / TICK_DELTA);
const partial_tick = this.#pending_time / TICK_DELTA;
if (this.benchmark) {
this.benchmark.render(partial_tick);
} else {
this.game_renderer.render(this, partial_tick);
// from where the camera was just put
sounds.frame(
this.camera,
(id) => this.level.entities.get(id)?.render_position(partial_tick),
this.options.volume,
);
}
}
// one step of the game: what the server sent (chunks included), breaking, then every entity
+4
View File
@@ -31,6 +31,8 @@ import { in_desktop_app, type JoinServer, TitleScreen } from "./gui/title_screen
import { MainMenuScreen } from "./gui/main_menu.ts";
import { DisconnectedScreen } from "./gui/disconnected_screen.ts";
import { profiler } from "./profiler.ts";
import { sounds } from "./sounds.ts";
import { WebAudioOutput } from "./audio_output.ts";
// runs whatever is showing every frame: a menu screen before joining (and after leaving), or the game
export // while playing, the browser asks before leaving the page. sprinting is ctrl and walking is w, and ctrl+w closes the
@@ -231,6 +233,8 @@ try {
}
InputManager.initialize(game_canvas);
// waits for the first click or key, which the title screen gets
sounds.set_output(new WebAudioOutput());
self.addEventListener("resize", resize_canvas);
resize_canvas();
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
+9
View File
@@ -49,6 +49,7 @@ import { biome_season } from "@/common/worldgen/biomes.ts";
import { clock, farming_day } from "@/common/time.ts";
import type { LootTableJson } from "@/common/loot.ts";
import type { ClipJson } from "@/common/mod_data.ts";
import { sounds } from "./sounds.ts";
// each loaded mod's credits file, for the credits screen
export const mod_credits: { name: string; version: string; text: string }[] = [];
@@ -200,6 +201,7 @@ export async function load_client_mods(listings: ModListing[], mods: Mod[]) {
}
const recipes = register_mod_data(mods.map((mod) => ({ id: mod.manifest.id, data: mod.data })));
sounds.set_files(mods.map((mod) => ({ id: mod.manifest.id, sounds: mod.sounds })));
recipe_book = recipes;
inventory_overlays.length = 0;
hud_layers.length = 0;
@@ -448,6 +450,13 @@ function client_context(listing: ModListing): ClientContext {
return Object.freeze({ id, length: json.length, loop: json.loop });
},
},
sounds: {
play(sound, options) {
if (!sounds.exists(sound)) throw new Error(`[${mod}] unknown sound ${sound}`);
return sounds.play(sound, options);
},
exists: (sound) => sounds.exists(sound),
},
log: (...args) => console.log(`[${mod}]`, ...args),
};
}
+3
View File
@@ -2,10 +2,13 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import type { KeyCode } from "./input_manager.ts";
import type { Volumes } from "./sounds.ts";
// the player's settings, like minecraft's Options and its key mappings
export class Options {
render_distance = 16;
// 0 to 1, each sound category's under master's, see client/sounds.ts
volume: Volumes = { master: 1, music: 1, ambient: 1, blocks: 1, entities: 1, players: 1, ui: 1 };
key_forward: KeyCode = "KeyW";
key_back: KeyCode = "KeyS";
+242
View File
@@ -0,0 +1,242 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// what sounds play on this client, and where from: ctx.sounds.play for client phases. the sounds are the mods'
// sounds.json, see docs/modding/resources/sounds.md. this decides what plays, an output (client/audio_output.ts in the
// browser) plays it
import { EverythingRegistry } from "@/common/everything_registry.ts";
import type { SoundCategory, SoundJson } from "@/common/mod_data.ts";
import type { ClientPlayOptions, PlayingSound } from "@/common/mod_api/client.ts";
import type { Position } from "@/common/mod_api/shared.ts";
export type Volumes = Record<"master" | SoundCategory, number>;
// how far away a sound is heard at volume 1 when its definition doesn't say
const DEFAULT_RANGE = 16;
// sounds playing at once at most. past that a new one is dropped, and loops wait for room
const MAX_VOICES = 64;
// what sounds come out of: web audio in the browser, a list in tests
export interface SoundOutput {
// starts a file playing. undefined when nothing can play now, like before the player's first click
start(file: SoundFile, settings: VoiceSettings): Voice | undefined;
// where the player hears from, and which way they look, in radians like the camera
listen(x: number, y: number, z: number, yaw: number, pitch: number): void;
set_volumes(volumes: Volumes): void;
}
// a mod's file, by "<mod id>:<path in its sounds/>"
export interface SoundFile {
readonly id: string;
readonly bytes: Uint8Array;
}
export interface VoiceSettings {
// only master's volume when not given
category: SoundCategory | undefined;
// heard as it is when not given
at: Position | undefined;
// where it's faded to nothing
range: number;
// over 1 is heard further, which range has already, not louder
volume: number;
pitch: number;
loop: boolean;
// seconds into the file it starts at, for a loop coming back partway. past the file's length it goes around
offset: number;
}
// one file playing
export interface Voice {
// it played to its end
readonly ended: boolean;
move(at: Position): void;
set(volume: number, pitch: number, range: number): void;
stop(): void;
}
// where the player hears from, like the camera
export interface Listener extends Position {
yaw: number;
pitch: number;
}
class Playing implements PlayingSound {
voice: Voice | undefined;
done = false;
#volume: number;
#pitch: number;
constructor(
readonly json: SoundJson,
readonly file: SoundFile,
readonly options: ClientPlayOptions,
readonly started: number,
public at: Position | undefined,
) {
this.#volume = options.volume ?? 1;
this.#pitch = options.pitch ?? 1;
}
get playing() {
return !this.done;
}
stop() {
this.done = true;
this.voice?.stop();
this.voice = undefined;
}
get volume() {
return this.#volume;
}
set volume(volume: number) {
this.#volume = volume;
this.voice?.set(this.total_volume, this.total_pitch, this.range);
}
get pitch() {
return this.#pitch;
}
set pitch(pitch: number) {
this.#pitch = pitch;
this.voice?.set(this.total_volume, this.total_pitch, this.range);
}
get total_volume() {
return (this.json.volume ?? 1) * this.#volume;
}
get total_pitch() {
return (this.json.pitch ?? 1) * this.#pitch;
}
// a louder sound is heard further, like a sound at volume 2 twice as far
get range() {
return (this.json.range ?? DEFAULT_RANGE) * Math.max(1, this.total_volume);
}
// whether the listener is close enough to hear it, always for one heard as it is
in_range(listener: Position) {
if (!this.at) return true;
const { x, y, z } = this.at;
return Math.hypot(x - listener.x, y - listener.y, z - listener.z) < this.range;
}
}
export class Sounds {
#output: SoundOutput | undefined;
// the mods' files, by "<mod id>:<path>"
#files = new Map<string, SoundFile>();
#playing: Playing[] = [];
#listener: Position = { x: 0, y: 0, z: 0 };
#entity_position: (id: string) => Position | undefined = () => undefined;
// seconds, for how far a loop has got
constructor(readonly clock = () => performance.now() / 1000) {}
set_output(output: SoundOutput) {
this.#output = output;
}
// the loaded mods' sound files, in place of the last server's
set_files(mods: { id: string; sounds?: Map<string, Uint8Array> }[]) {
this.stop_all();
this.#files.clear();
for (const mod of mods) {
for (const [path, bytes] of mod.sounds ?? []) {
const id = `${mod.id}:${path}`;
this.#files.set(id, { id, bytes });
}
}
}
exists(sound: string) {
return EverythingRegistry.get<SoundJson>("sounds", sound) !== undefined;
}
play(sound: string, options: ClientPlayOptions = {}): PlayingSound {
const json = EverythingRegistry.get<SoundJson>("sounds", sound);
if (!json) throw new Error(`unknown sound ${sound}`);
const path = json.files[Math.floor(Math.random() * json.files.length)];
const file = this.#files.get(`${sound.split(":")[0]}:${path}`);
if (!file) throw new Error(`sound ${sound} has no file ${path}`);
const at = options.follow !== undefined ? this.#entity_position(options.follow) : options.at;
const playing = new Playing(json, file, { ...options }, this.clock(), at && { ...at });
// an entity this client doesn't have can't be followed
if (options.follow !== undefined && !at) {
playing.done = true;
return playing;
}
this.#playing.push(playing);
this.#start(playing);
if (!playing.voice && !options.loop) playing.done = true;
return playing;
}
// before each frame: the player hears from listener, sounds following an entity go where it's drawn
frame(listener: Listener, entity_position: (id: string) => Position | undefined, volumes: Volumes) {
this.#listener = { x: listener.x, y: listener.y, z: listener.z };
this.#entity_position = entity_position;
this.#output?.listen(listener.x, listener.y, listener.z, listener.yaw, listener.pitch);
this.#output?.set_volumes(volumes);
for (const playing of this.#playing) {
if (playing.done) continue;
const follow = playing.options.follow;
if (follow !== undefined) {
const at = entity_position(follow);
if (!at) {
playing.stop();
continue;
}
playing.at = { x: at.x, y: at.y, z: at.z };
playing.voice?.move(playing.at);
}
if (playing.voice?.ended) {
playing.voice = undefined;
if (!playing.options.loop) playing.done = true;
}
// loops out of range wait without a voice
if (playing.voice && playing.options.loop && !playing.in_range(this.#listener)) {
playing.voice.stop();
playing.voice = undefined;
}
}
this.#playing = this.#playing.filter((playing) => !playing.done);
for (const playing of this.#playing) {
if (!playing.voice) this.#start(playing);
}
}
// leaving the server
stop_all() {
for (const playing of this.#playing) playing.stop();
this.#playing = [];
}
// how many are playing now, for tests
get voices() {
return this.#playing.filter((playing) => playing.voice).length;
}
#start(playing: Playing) {
if (!this.#output || !playing.in_range(this.#listener) || this.voices >= MAX_VOICES) return;
playing.voice = this.#output.start(playing.file, {
category: playing.json.category,
at: playing.at,
range: playing.range,
volume: playing.total_volume,
pitch: playing.total_pitch,
loop: playing.options.loop ?? false,
offset: (this.clock() - playing.started) * playing.total_pitch,
});
}
}
// the client's, which ctx.sounds plays on
export const sounds = new Sounds();