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
View File
@@ -63,6 +63,7 @@ deno task build && deno task server # packs the mods and starts a se
**Resources**
- [Textures](docs/modding/resources/textures.md)
- [Sounds](docs/modding/resources/sounds.md): sound files, and playing them on a player's client
- [Block Models](docs/modding/resources/models.md)
- [Recipes](docs/modding/resources/recipes.md): crafting, smelting, smithing, stonecutting and your own recipe types
- [Tags](docs/modding/resources/tags.md): lists of blocks, items or entities that every mod can add to
+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();
+31 -1
View File
@@ -13,10 +13,13 @@ import {
type EntityJson,
type EntityModelJson,
type FluidJson,
is_ogg,
type ItemJson,
type ManifestJson,
type OreJson,
type RecipeJson,
SOUND_PATH_PATTERN,
type SoundJson,
type SpawnJson,
type TagJson,
validate_block,
@@ -30,6 +33,7 @@ import {
validate_model,
validate_ore,
validate_recipe,
validate_sound,
validate_spawn,
validate_tag,
} from "./mod_data.ts";
@@ -71,6 +75,8 @@ export interface Mod {
textures: Map<string, Uint8Array>;
// the .json of the textures that have one, like animated ones, by texture id
texture_json?: Map<string, TextureJson>;
// ogg bytes by path in its sounds/ without .ogg, like jester/stomp_1, what its sounds.json's files name
sounds?: Map<string, Uint8Array>;
credits?: string;
}
@@ -88,6 +94,7 @@ export class ModError extends Error {
// script.js
// textures/<name>.png the texture <mod id>:<name>
// textures/<name>.json its animation, if it has one
// sounds/<path>.ogg a sound file, see SoundJson
// credits.md
export function write_mod(mod: Mod): Uint8Array<ArrayBuffer> {
const text = (value: string) => new TextEncoder().encode(value);
@@ -110,6 +117,9 @@ export function write_mod(mod: Mod): Uint8Array<ArrayBuffer> {
for (const [id, json] of mod.texture_json ?? []) {
files[`textures/${id.split(":")[1]}.json`] = text(JSON.stringify(json));
}
for (const [path, ogg] of mod.sounds ?? []) {
files[`sounds/${path}.ogg`] = ogg;
}
files["manifest.json"] = text(JSON.stringify(manifest, null, "\t"));
files["data.json"] = text(JSON.stringify(mod.data));
@@ -192,6 +202,7 @@ export function read_mod(bytes: Uint8Array, file: string): Mod {
problems,
) as EntityModelJson[],
animations: checked(raw_data.animations, "animations", validate_clip, problems) as ClipJson[],
sounds: checked(raw_data.sounds, "sounds", validate_sound, problems) as SoundJson[],
effects: checked(raw_data.effects, "effects", validate_effect, problems) as EffectJson[],
fluids: checked(raw_data.fluids, "fluids", validate_fluid, problems) as FluidJson[],
tags: checked(raw_data.tags, "tags", validate_tag, problems) as TagJson[],
@@ -232,6 +243,7 @@ export function read_mod(bytes: Uint8Array, file: string): Mod {
...data.entities,
...data.entity_models,
...data.animations!,
...data.sounds!,
...data.effects,
...data.fluids,
];
@@ -302,8 +314,26 @@ export function read_mod(bytes: Uint8Array, file: string): Mod {
}
}
const sounds = new Map<string, Uint8Array>();
for (const [name, content] of Object.entries(files)) {
const match = name.match(/^sounds\/(.+)\.ogg$/);
if (!match) continue;
if (!SOUND_PATH_PATTERN.test(match[1])) {
problems.push(`${name}: sound paths must be a-z, 0-9 and _ in folders`);
} else if (!is_ogg(content)) {
problems.push(`${name}: isn't an ogg file`);
} else {
sounds.set(match[1], content);
}
}
for (const sound of data.sounds!) {
for (const path of Array.isArray(sound.files) ? sound.files : []) {
if (!sounds.has(path)) problems.push(`sound ${sound.id}: there's no sounds/${path}.ogg`);
}
}
if (problems.length > 0) throw new ModError(file, problems);
return { manifest, data, script, textures, texture_json, credits };
return { manifest, data, script, textures, texture_json, sounds, credits };
}
// the same mod without the terrain's data, its schematics and its config, what players get. the server sends them the world. its
+32
View File
@@ -9,6 +9,7 @@ import type {
ItemStack,
KeyCode,
ModInfo,
PlayOptions,
Position,
RecipeLookup,
Season,
@@ -24,6 +25,7 @@ export type {
ItemStack,
KeyCode,
ModInfo,
PlayOptions,
Position,
Season,
TagApi,
@@ -124,9 +126,39 @@ export interface ClientContext {
tags: TagApi;
// blocks drawn with code, like a shaft that turns, see docs/modding/blocks/visuals.md
render: ClientRender;
// sounds from the mods' sounds.json, played on this client only, see docs/modding/resources/sounds.md
sounds: ClientSounds;
log(...args: unknown[]): void;
}
export interface ClientSounds {
// plays a sound on this client. without at or follow it's heard as it is wherever the player is, like a click in a
// screen. throws for a sound no mod defines
play(sound: Id, options?: ClientPlayOptions): PlayingSound;
exists(sound: Id): boolean;
}
export interface ClientPlayOptions extends PlayOptions {
// where it comes from, fading out with distance until its range
at?: Position;
// an entity's id: it moves with the entity, and stops when the entity goes
follow?: string;
// plays again from the start until it's stopped. one out of the player's range waits silently, and comes back in
// as far into the file as it would have got
loop?: boolean;
}
// a sound ctx.sounds.play started
export interface PlayingSound {
// false once it finished, was stopped, or what it followed went. a sound that couldn't play at all, like one
// played out of range or before the player first clicked, is never playing, unless it loops
readonly playing: boolean;
stop(): void;
// what play was given, changed while it plays, like a machine speeding up
volume: number;
pitch: number;
}
export interface ClientRender {
// every block of this id gets a visual from create while its chunk is shown, like a block entity renderer or
// flywheel's visuals. only during setup, and one per block. replaces_model leaves the block's model out of the
+8
View File
@@ -116,6 +116,14 @@ export interface Position {
z: number;
}
// how a sound plays, on top of what its definition in sounds.json says. see docs/modding/resources/sounds.md
export interface PlayOptions {
// multiplies the sound's own. over 1 it's heard further away, not louder
volume?: number;
// multiplies the sound's own: 2 is an octave up and twice as fast
pitch?: number;
}
export type Face = "west" | "east" | "bottom" | "top" | "north" | "south";
// KeyboardEvent.code values, like "KeyE" or "Digit1"
+6
View File
@@ -16,6 +16,7 @@ import {
type OreJson,
type RecipeJson,
SHARED_TAG_NAMESPACE,
type SoundJson,
type SpawnJson,
type TagJson,
type TagRegistry,
@@ -67,6 +68,8 @@ export interface LoadedMod {
entity_models: { file: string; json: EntityModelJson }[];
// clips, see ANIMATION.md
animations: { file: string; json: ClipJson }[];
// its sounds.json, see docs/modding/resources/sounds.md
sounds: { file: string; json: SoundJson }[];
effects: { file: string; json: EffectJson }[];
fluids: { file: string; json: FluidJson }[];
tags: { file: string; json: TagJson }[];
@@ -88,6 +91,8 @@ export interface LoadedMod {
texture_files: Map<string, string>;
// textures/<name>.json by texture id, for the textures that have one (see texture_animation.ts)
texture_json: Map<string, TextureJson>;
// absolute paths of its sounds/ files by path in sounds/ without .ogg, like jester/stomp_1
sound_files: Map<string, string>;
}
// what a mod's data files hold, as packed into its .cubi
@@ -102,6 +107,7 @@ export function mod_data(mod: LoadedMod): ModData {
entities: mod.entities.map((e) => e.json),
entity_models: mod.entity_models.map((m) => m.json),
animations: mod.animations.map((a) => a.json),
sounds: mod.sounds.map((s) => s.json),
effects: mod.effects.map((e) => e.json),
fluids: mod.fluids.map((f) => f.json),
tags: mod.tags.map((t) => t.json),
+37
View File
@@ -605,6 +605,43 @@ const clip_schema = z.object({
export type ClipJson = z.infer<typeof clip_schema>;
// which volume slider a sound follows, each under the player's master volume. see docs/modding/resources/sounds.md
export const SOUND_CATEGORIES = ["music", "ambient", "blocks", "entities", "players", "ui"] as const;
export type SoundCategory = typeof SOUND_CATEGORIES[number];
// a path in a mod's sounds/ without .ogg, like jester/stomp_1, and a sound's name in sounds.json
export const SOUND_PATH_PATTERN = /^[a-z0-9_]+(\/[a-z0-9_]+)*$/;
// one of the sounds in a mod's sounds.json, with its id: the key "jester/step" in dangerous_business's is
// dangerous_business:jester/step
const sound_schema = z.object({
id: z.string('must be a sound id like "my_mod:thing/step"').regex(TAG_ID_PATTERN),
// paths in the mod's own sounds/, one picked at random each time it plays
files: z.array(
z.string('must be a path in sounds/ without .ogg, like "thing/step_1"').regex(SOUND_PATH_PATTERN),
).min(1),
// at most 1, plays multiply it. 1 when not given
volume: z.number().min(0).max(1).optional(),
// 1 when not given
pitch: z.number().gt(0).optional(),
// how far away it's heard at volume 1, in blocks. 16 when not given
range: z.number().gt(0).optional(),
// only the master volume when not given
category: z.enum(SOUND_CATEGORIES).optional(),
});
export type SoundJson = z.infer<typeof sound_schema>;
export function validate_sound(json: unknown): Problems {
return find_problems(sound_schema, json);
}
// whether a file starts the way every ogg does, so a wav or mp3 renamed to .ogg is caught when the mod is checked
// instead of failing to play
export function is_ogg(bytes: Uint8Array): boolean {
return bytes.length >= 4 && bytes[0] === 0x4f && bytes[1] === 0x67 && bytes[2] === 0x67 && bytes[3] === 0x53;
}
// something in a tag file's values or remove: an id, a "#tag", or either with whether it must exist. a plain one must
const tag_entry = z.union(
[id_or_tag, z.object({ id: id_or_tag, required: z.boolean().optional() })],
+6
View File
@@ -24,6 +24,7 @@ import {
ModRecipeJson,
OreJson,
RecipeJson,
SoundJson,
SpawnJson,
stack_problems,
TagJson,
@@ -62,6 +63,8 @@ export interface ModData {
entity_models: EntityModelJson[];
// clips, see ANIMATION.md. missing from mods packed before there were any
animations?: ClipJson[];
// its sounds.json, see docs/modding/resources/sounds.md. the files are in the .cubi's sounds/
sounds?: SoundJson[];
// status effects, see EffectJson
effects: EffectJson[];
// kinds of fluid, see FluidJson
@@ -230,6 +233,9 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
for (const clip of data.animations ?? []) {
EverythingRegistry.register<ClipJson>("animations", clip.id, clip);
}
for (const json of data.sounds ?? []) {
EverythingRegistry.register<SoundJson>("sounds", json.id, json);
}
for (const json of data.entities) {
EverythingRegistry.register<EntityJson>("entities", json.id, json);
}
+1
View File
@@ -99,6 +99,7 @@ export async function load_bundle(bundle: WorldgenBundle): Promise<LoadedBundle>
entities: [],
entity_models: [],
animations: [],
sounds: [],
effects: [],
fluids: [],
loot_tables: [],
+4 -1
View File
@@ -32,6 +32,8 @@ mods/
schematics/*.cbsm # schematics, never sent to players. see misc/schematics.md
textures/*.png
textures/*.json # animations, see resources/textures.md
sounds/**/*.ogg # sound files, see resources/sounds.md
sounds.json # the sounds they make up
scripts/
main.ts # the mod's script, its exports are its phases. sent to players, see concepts/sides.md
*.ts # whatever else it imports
@@ -116,10 +118,11 @@ deno task build # packs every mod in mods/ into server_mo
```
copper_tools.cubi
manifest.json # with main and credits pointing into the zip
data.json # every block, model, item, entity, recipe, ore, tag, loot table and schematic, and the config
data.json # every block, model, item, entity, recipe, ore, tag, loot table, sound and schematic, and the config
script.js # the script bundled into one module
textures/<name>.png
textures/<name>.json # for animated textures
sounds/<path>.ogg
credits.md
```
+114
View File
@@ -0,0 +1,114 @@
# Sounds
A mod's sounds are `.ogg` files in its `sounds/` folder, put together into sounds by its `sounds.json`. Client phases
play them with `ctx.sounds`.
## Sound Files
Any `.ogg` (Vorbis or Opus) in `sounds/`, in folders if you like. Its path without `.ogg` is what `sounds.json` names it
by, so `sounds/walker/step_1.ogg` is `walker/step_1`. Paths are a-z, 0-9 and `_`.
Mono and stereo files both work, from a point in the world or not.
## `sounds.json`
```json
{
"format_version": 1,
"sounds": {
"walker/step": {
"files": ["walker/step_1", "walker/step_2", "walker/step_3"],
"category": "entities"
},
"walker/theme": { "files": ["walker/theme"], "category": "entities", "range": 32 },
"click": { "files": ["click"], "category": "ui", "volume": 0.5 }
}
}
```
Each key is a sound, whose id is `<mod id>:<key>`, so `walker/step` in `copper_tools` is `copper_tools:walker/step`. Any
mod can play any sound by its id.
| Field | What it does |
| ---------- | ----------------------------------------------------------------------------------------------------------- |
| `files` | The files it plays, one picked at random each time. A file listed twice comes up twice as often. |
| `volume` | 0 to 1, 1 if not given. Every play multiplies it. |
| `pitch` | 1 if not given. Every play multiplies it. |
| `range` | How far away it's heard at volume 1, in blocks. 16 if not given. |
| `category` | Which volume the player's settings play it at: `music`, `ambient`, `blocks`, `entities`, `players` or `ui`. |
A sound without a category only follows the player's master volume.
`deno task check-mods` reports a file that isn't there, and warns about an `.ogg` no sound plays.
## Playing Sounds
In a client phase, `ctx.sounds.play` plays a sound on that player's client only:
```ts
export function client(ctx: ClientContext) {
ctx.ui.add_inventory_overlay({
on_render(g) {
if (g.button("Ring", 4, 4, 40, 18)) ctx.sounds.play("copper_tools:click");
},
});
}
```
With nothing but its id it's heard as it is wherever the player is, like a click in a screen. The options:
| Option | What it does |
| -------- | --------------------------------------------------------------------------------------------------- |
| `at` | A point it comes from. It fades to nothing at its range, and isn't played at all from further away. |
| `follow` | An entity's id. It comes from where the entity is drawn, and stops when the entity goes. |
| `loop` | Plays again from the start until stopped. |
| `volume` | Multiplies the sound's own. Over 1 it's heard further away, not louder: at 2, twice as far. |
| `pitch` | Multiplies the sound's own. 2 is an octave up, and twice as fast. |
`play` throws for a sound no mod defines, and `ctx.sounds.exists(id)` checks first. It returns the sound playing, which
can be stopped or changed while it plays:
```ts
const hum = ctx.sounds.play("copper_tools:machine/hum", { at: { x: 10.5, y: 64.5, z: 3.5 }, loop: true });
hum.pitch = 1.5; // the machine sped up
if (!hum.playing) ctx.log("it's done");
hum.stop();
```
A looping sound out of range waits silently, and when the player comes back in range it plays on from as far into the
file as it would have got, as if it never stopped.
### What Doesn't Play
- **Before the player's first click or key press.** Browsers keep sound off until then. A sound played earlier is
dropped, and a loop starts then.
- **More than 64 at once.** A new sound past that is dropped, and a loop waits for room.
Either way `playing` is false for a sound that never played. A file plays a moment late the first time, since it's only
decoded once something plays it.
## Lasting Sounds
A sound that lasts as long as something does, like a machine's hum while it runs or a monster's music while it's in a
state, goes with what the client already knows. Start it when that begins and stop it when it ends, like in an entity's
animator when its [client data](../entities/index.md) changes:
```ts
ctx.render.register_entity_animator("copper_tools:walker", (walker) => {
let theme: PlayingSound | undefined;
return {
on_data(field) {
if (field !== "angry") return;
if (walker.get_client_data<boolean>("angry")) {
theme ??= ctx.sounds.play("copper_tools:walker/theme", { follow: walker.id, loop: true });
} else {
theme?.stop();
theme = undefined;
}
},
pose(pose, time) {/* ... */},
};
});
```
A player who comes near after it started hears it too, since the animator gets the data when it's made.
+2
View File
@@ -223,6 +223,7 @@ function as_loaded_mod(file: string, mod: Mod): LoadedMod {
entities: entries(mod.data.entities),
entity_models: entries(mod.data.entity_models),
animations: entries(mod.data.animations ?? []),
sounds: entries(mod.data.sounds ?? []),
effects: entries(mod.data.effects),
fluids: entries(mod.data.fluids),
tags: entries(mod.data.tags),
@@ -239,5 +240,6 @@ function as_loaded_mod(file: string, mod: Mod): LoadedMod {
textures: [...mod.textures.keys()],
texture_files: new Map(),
texture_json: new Map(mod.texture_json),
sound_files: new Map(),
};
}
+258
View File
@@ -0,0 +1,258 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// sounds: sounds.json and sounds/ read, checked and packed, and what the client plays and where
import { assert, assertEquals, assertStringIncludes, assertThrows } from "@std/assert";
import { create_mod } from "@/tools/new_mod.ts";
import { load_and_check } from "@/tools/check_mods.ts";
import { pack_mod } from "@/tools/pack_mod.ts";
import { read_mod, write_mod } from "@/common/mod.ts";
import { EverythingRegistry } from "@/common/everything_registry.ts";
import type { SoundJson } from "@/common/mod_data.ts";
import type { Position } from "@/common/mod_api/shared.ts";
import {
type Listener,
type SoundFile,
type SoundOutput,
Sounds,
sounds,
type Voice,
type VoiceSettings,
type Volumes,
} from "@/client/sounds.ts";
import { copy_dir, load_as_player } from "./helpers.ts";
// what an ogg file starts with. nothing decodes them outside the browser, so the rest doesn't have to be audio
const OGG = (n: number) => new Uint8Array([0x4f, 0x67, 0x67, 0x53, n]);
// a folder of mods: the base game, which the template depends on, and one made from the template with these sound
// files and sounds.json
function sound_mod(files: Record<string, Uint8Array>, sounds_json?: Record<string, unknown>) {
const dir = Deno.makeTempDirSync({ prefix: "bworld_sounds_" });
copy_dir("mods/bworld", `${dir}/bworld`);
create_mod("noisy", "Noisy", dir);
for (const [path, bytes] of Object.entries(files)) {
const file = `${dir}/noisy/sounds/${path}`;
Deno.mkdirSync(file.slice(0, file.lastIndexOf("/")), { recursive: true });
Deno.writeFileSync(file, bytes);
}
if (sounds_json) {
Deno.writeTextFileSync(`${dir}/noisy/sounds.json`, JSON.stringify({ format_version: 1, sounds: sounds_json }));
}
return dir;
}
async function checked(dir: string) {
return (await load_and_check(dir)).find((mod) => mod.id === "noisy")!;
}
Deno.test("check-mods reads sounds.json into sounds named after their keys", async () => {
const dir = sound_mod(
{ "walker/step_1.ogg": OGG(1), "walker/step_2.ogg": OGG(2) },
{ "walker/step": { files: ["walker/step_1", "walker/step_2"], volume: 0.5, category: "entities" } },
);
const mod = await checked(dir);
assertEquals(mod.report.errors, []);
assertEquals(mod.report.warnings, []);
assertEquals(mod.sounds.map((sound) => sound.json), [
{ id: "noisy:walker/step", files: ["walker/step_1", "walker/step_2"], volume: 0.5, category: "entities" },
]);
Deno.removeSync(dir, { recursive: true });
});
Deno.test("check-mods reports missing and broken sound files, and warns about ones nothing plays", async () => {
const dir = sound_mod({ "step.ogg": OGG(1), "unused.ogg": OGG(2), "renamed.ogg": new Uint8Array([1, 2, 3]) }, {
step: { files: ["step", "nowhere"] },
loud: { files: ["step"], volume: 2 },
"Bad Name": { files: ["step"] },
odd: { files: ["step"], category: "weather" },
});
const mod = await checked(dir);
const errors = mod.report.errors.join("\n");
assertStringIncludes(errors, "step: there's no sounds/nowhere.ogg");
assertStringIncludes(errors, "loud: volume");
assertStringIncludes(errors, "Bad Name: sound names");
assertStringIncludes(errors, "odd: category");
assertStringIncludes(errors, "sounds/renamed.ogg: isn't an ogg file");
assertEquals(mod.report.warnings, ["sounds/unused.ogg: no sound in sounds.json plays it"]);
Deno.removeSync(dir, { recursive: true });
});
Deno.test("packing a mod keeps its sounds and their files", async () => {
const dir = sound_mod({ "walker/step.ogg": OGG(7) }, { "walker/step": { files: ["walker/step"], range: 24 } });
const mod = read_mod(await pack_mod(await checked(dir)), "noisy.cubi");
assertEquals(mod.data.sounds, [{ id: "noisy:walker/step", files: ["walker/step"], range: 24 }]);
assertEquals([...mod.sounds!], [["walker/step", OGG(7)]]);
// a .cubi whose sound names a file it doesn't have doesn't load
const missing = { ...mod, sounds: new Map() };
assertThrows(() => read_mod(write_mod(missing), "noisy.cubi"), Error, "there's no sounds/walker/step.ogg");
Deno.removeSync(dir, { recursive: true });
});
Deno.test("a player's client gets the sounds of the server's mods", async () => {
const dir = sound_mod({ "step.ogg": OGG(1) }, { step: { files: ["step"] } });
await load_as_player(dir);
const output = new ListOutput();
sounds.set_output(output);
assert(sounds.exists("noisy:step"));
sounds.play("noisy:step");
assertEquals(output.voices.map((voice) => voice.file), [{ id: "noisy:step", bytes: OGG(1) }]);
sounds.stop_all();
Deno.removeSync(dir, { recursive: true });
});
// the client, with an output that only keeps what it was told
class ListVoice implements Voice {
ended = false;
stopped = false;
constructor(readonly file: SoundFile, public settings: VoiceSettings) {}
move(at: Position) {
this.settings = { ...this.settings, at };
}
set(volume: number, pitch: number, range: number) {
this.settings = { ...this.settings, volume, pitch, range };
}
stop() {
this.stopped = true;
}
}
class ListOutput implements SoundOutput {
// false like a browser before the player's first click
ready = true;
voices: ListVoice[] = [];
start(file: SoundFile, settings: VoiceSettings) {
if (!this.ready) return undefined;
const voice = new ListVoice(file, settings);
this.voices.push(voice);
return voice;
}
listen() {}
set_volumes() {}
// the ones still going
get playing() {
return this.voices.filter((voice) => !voice.stopped && !voice.ended);
}
}
const VOLUMES: Volumes = { master: 1, music: 1, ambient: 1, blocks: 1, entities: 1, players: 1, ui: 1 };
const at = (x: number): Listener => ({ x, y: 0, z: 0, yaw: 0, pitch: 0 });
// a client's sounds with these definitions, each with one file of its own name, and a clock tests move
function client_sounds(definitions: Omit<SoundJson, "files">[]) {
EverythingRegistry.clear();
const files = new Map<string, Uint8Array>();
for (const json of definitions) {
const path = json.id.split(":")[1];
EverythingRegistry.register<SoundJson>("sounds", json.id, { ...json, files: [path] });
files.set(path, OGG(1));
}
const time = { now: 0 };
const client = new Sounds(() => time.now);
client.set_files([{ id: "noisy", sounds: files }]);
const output = new ListOutput();
client.set_output(output);
return { client, output, time };
}
Deno.test("a sound plays at its definition's volume and pitch times the play's", () => {
const { client, output } = client_sounds([{ id: "noisy:click", volume: 0.5, pitch: 2, category: "ui" }]);
const playing = client.play("noisy:click", { volume: 0.5, pitch: 0.75 });
assert(playing.playing);
const [voice] = output.voices;
assertEquals(voice.file.id, "noisy:click");
assertEquals([voice.settings.volume, voice.settings.pitch, voice.settings.category], [0.25, 1.5, "ui"]);
assertEquals(voice.settings.at, undefined);
playing.volume = 2;
assertEquals(voice.settings.volume, 1);
playing.stop();
assert(voice.stopped);
assert(!playing.playing);
assertThrows(() => client.play("noisy:nothing"), Error, "unknown sound noisy:nothing");
});
Deno.test("a sound at a point is only heard within its range, which a louder one reaches further", () => {
const { client, output } = client_sounds([{ id: "noisy:thud", range: 10 }]);
client.frame(at(0), () => undefined, VOLUMES);
assert(!client.play("noisy:thud", { at: { x: 15, y: 0, z: 0 } }).playing);
assertEquals(output.voices.length, 0);
assert(client.play("noisy:thud", { at: { x: 15, y: 0, z: 0 }, volume: 2 }).playing);
assertEquals(output.voices[0].settings.range, 20);
assert(client.play("noisy:thud", { at: { x: 5, y: 0, z: 0 } }).playing);
});
Deno.test("a sound finishes when its file has played", () => {
const { client, output } = client_sounds([{ id: "noisy:thud" }]);
const playing = client.play("noisy:thud");
output.voices[0].ended = true;
client.frame(at(0), () => undefined, VOLUMES);
assert(!playing.playing);
assertEquals(client.voices, 0);
});
Deno.test("a loop out of range waits, and comes back as far in as it would have got", () => {
const { client, output, time } = client_sounds([{ id: "noisy:hum", range: 10 }]);
client.frame(at(0), () => undefined, VOLUMES);
time.now = 100;
const hum = client.play("noisy:hum", { at: { x: 0, y: 0, z: 0 }, loop: true, pitch: 2 });
assertEquals(output.playing.length, 1);
time.now = 103;
client.frame(at(50), () => undefined, VOLUMES);
assertEquals(output.playing.length, 0);
assert(hum.playing);
time.now = 105;
client.frame(at(1), () => undefined, VOLUMES);
assertEquals(output.playing.length, 1);
// 5 seconds at twice the speed
assertEquals(output.playing[0].settings.offset, 10);
});
Deno.test("a loop played before anything can play starts once it can, and a one-off is dropped", () => {
const { client, output } = client_sounds([{ id: "noisy:hum" }, { id: "noisy:thud" }]);
output.ready = false;
const hum = client.play("noisy:hum", { loop: true });
const thud = client.play("noisy:thud");
assert(hum.playing);
assert(!thud.playing);
output.ready = true;
client.frame(at(0), () => undefined, VOLUMES);
assertEquals(output.voices.map((voice) => voice.file.id), ["noisy:hum"]);
});
Deno.test("a sound following an entity moves with it and stops when it goes", () => {
const { client, output } = client_sounds([{ id: "noisy:theme" }]);
const entities = new Map<string, Position>([["jester", { x: 3, y: 0, z: 0 }]]);
const where = (id: string) => entities.get(id);
client.frame(at(0), where, VOLUMES);
assert(!client.play("noisy:theme", { follow: "nobody" }).playing);
const theme = client.play("noisy:theme", { follow: "jester", loop: true });
assertEquals(output.voices[0].settings.at, { x: 3, y: 0, z: 0 });
entities.set("jester", { x: 4, y: 1, z: 0 });
client.frame(at(0), where, VOLUMES);
assertEquals(output.voices[0].settings.at, { x: 4, y: 1, z: 0 });
entities.delete("jester");
client.frame(at(0), where, VOLUMES);
assert(!theme.playing);
assert(output.voices[0].stopped);
});
Deno.test("at most 64 sounds play at once, and a loop waits for room", () => {
const { client, output } = client_sounds([{ id: "noisy:thud" }, { id: "noisy:hum" }]);
const thuds = Array.from({ length: 64 }, () => client.play("noisy:thud"));
assert(!client.play("noisy:thud").playing);
const hum = client.play("noisy:hum", { loop: true });
assert(hum.playing);
assertEquals(client.voices, 64);
thuds[0].stop();
client.frame(at(0), () => undefined, VOLUMES);
assertEquals(output.voices.at(-1)!.file.id, "noisy:hum");
assertEquals(client.voices, 64);
});
+44
View File
@@ -9,7 +9,10 @@ import {
data_file,
entity_model_from_geo,
FORMAT_VERSION,
is_ogg,
type OreJson,
SOUND_PATH_PATTERN,
type SoundJson,
type SpawnJson,
type TagJson,
validate_block,
@@ -21,6 +24,7 @@ import {
validate_model,
validate_ore,
validate_recipe,
validate_sound,
validate_spawn,
validate_tag,
} from "@/common/mod_data.ts";
@@ -133,6 +137,7 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
entities: [],
entity_models: [],
animations: [],
sounds: [],
effects: [],
fluids: [],
tags: [],
@@ -148,6 +153,7 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
textures: [],
texture_files: new Map(),
texture_json: new Map(),
sound_files: new Map(),
};
const error = (message: string) => mod.report.errors.push(message);
@@ -306,6 +312,44 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
if (problems.length === 0) mod.schematics.push({ file: path, json });
}
// sounds/<path>.ogg, the files sounds.json's sounds play
for (const file of walk(`${dir}/sounds`, ".ogg")) {
const path = file.replace(/\.ogg$/, "");
if (!SOUND_PATH_PATTERN.test(path)) {
error(`sounds/${file}: sound paths must be a-z, 0-9 and _ in folders`);
} else if (!is_ogg(Deno.readFileSync(`${dir}/sounds/${file}`))) {
error(`sounds/${file}: isn't an ogg file`);
} else {
mod.sound_files.set(path, `${dir}/sounds/${file}`);
}
}
// sounds.json: each key is the sound <mod id>:<key>
const used_sound_files = new Set<string>();
if (exists(`${dir}/sounds.json`)) {
const sounds = read_data("sounds.json", "sounds", z.record(z.string(), json_object), '{ "name": { ... } }') ??
{};
for (const [key, sound] of Object.entries(sounds)) {
const json = { ...sound, id: `${id}:${key}` };
const problems = SOUND_PATH_PATTERN.test(key)
? validate_sound(json)
: [`sound names must be a-z, 0-9 and _ in folders, like "thing/step"`];
for (const file of Array.isArray(sound.files) ? sound.files : []) {
if (typeof file !== "string") continue;
used_sound_files.add(file);
if (!mod.sound_files.has(file) && SOUND_PATH_PATTERN.test(file)) {
problems.push(`there's no sounds/${file}.ogg`);
}
}
for (const problem of problems) error(`sounds.json: ${key}: ${problem}`);
if (problems.length === 0) mod.sounds.push({ file: "sounds.json", json: json as SoundJson });
}
}
for (const path of mod.sound_files.keys()) {
if (!used_sound_files.has(path)) {
mod.report.warnings.push(`sounds/${path}.ogg: no sound in sounds.json plays it`);
}
}
if (exists(`${dir}/config.json`)) {
mod.config = read_data("config.json", "config", json_object, "{ ... }");
}
+6 -1
View File
@@ -3,7 +3,7 @@
// deno task pack-mod mods/copper_tools [copper_tools.cubi]
// builds a mod folder into a .cubi: its data merged into data.json, its script bundled into one module, and its
// textures and credits. deno task build does this for every mod in mods/, see docs/modding/gettingstarted/modfiles.md
// textures, sounds and credits. deno task build does this for every mod in mods/, see docs/modding/gettingstarted/modfiles.md
import { basename, dirname, resolve } from "@std/path";
import { MOD_EXTENSION, write_mod } from "@/common/mod.ts";
import type { ManifestJson } from "@/common/mod_data.ts";
@@ -20,6 +20,10 @@ export async function pack_mod(mod: LoadedMod): Promise<Uint8Array<ArrayBuffer>>
textures.set(id, Deno.readFileSync(path));
}
const texture_json = new Map([...mod.texture_json].sort(([a], [b]) => a.localeCompare(b)));
const sounds = new Map<string, Uint8Array>();
for (const [path, file] of [...mod.sound_files].sort(([a], [b]) => a.localeCompare(b))) {
sounds.set(path, Deno.readFileSync(file));
}
// without what the content phase registered, which the server registers again when it loads the .cubi
const data = mod_data(mod);
@@ -30,6 +34,7 @@ export async function pack_mod(mod: LoadedMod): Promise<Uint8Array<ArrayBuffer>>
script,
textures,
texture_json,
sounds,
credits: manifest.credits ? Deno.readTextFileSync(`${mod.dir}/${manifest.credits}`) : undefined,
});
}