Mod config

This commit is contained in:
2026-10-14 14:14:52 -03:00
parent d7f1b91c0a
commit cedc7725b5
20 changed files with 371 additions and 32 deletions
+2 -1
View File
@@ -2,4 +2,5 @@ build/
world/
server_mods/
dist/
ports/
ports/
/config/
+13 -4
View File
@@ -5,7 +5,7 @@ redstone, contraptions, trains, equipment, decoration and schematics. It aims to
possible, and to stay fast on both the server and the client when a world has thousands of moving parts.
Built so far: the importer and Create's imported blocks and items, R1, R2, R3 (`transformed` and `rotating`), R4, R5,
R8, S0, S7, and stonecutting from S9. Facts about Create come from reading `ports/create1.21.1` and
R8, S0, S7, S12, and stonecutting from S9. Facts about Create come from reading `ports/create1.21.1` and
`ports/create1.19.3`, and facts about bworld from its source.
## Sources
@@ -270,7 +270,12 @@ and `fluid` with tanks (P5).
**R4. Models without blocks** (P1). Any model in `models/` can be loaded by id for visuals, baked once into a GPU
buffer, and turned for whatever axis it's used on. Built: each model is baked the first time a visual uses it and
uploaded the first time it's drawn, once per level.
uploaded the first time it's drawn, once per level. Every model is packed and sent to clients whether a block uses it or
not, and the partials P1's visuals use are all imported with their textures: `shaft`, `shaft_half`, `cogwheel_shaft`,
`cogwheel_shaftless`, `large_cogwheel_shaftless`, `hand_crank/handle`, `gauge/dial`, `gauge/indicator`, both gauge heads
and `rotation_speed_controller/bracket` (as `create:block_shaft_half` and so on). 0.5.0.j's water wheel is its block's
own model. 6.0's wheels that take the wood they're made of swap the oak textures in their model, which needs their new
art and a texture override on a model reference, so it waits for that art.
**R5. The model format** (P0, built). Everything Create's static models use: `parent`, `x` turns, `uvlock` on variants
and parts, element `rotation` at any angle around one axis, and items drawn with models. An item's `model` draws it in
@@ -366,8 +371,12 @@ are mostly those. They're components with placement rules in `mods/bworld`, like
`mods/create/scripts/worldgen.ts`, or a data feature if STRUCTURES.md's data features exist by then. Zinc is a plain ore
in `ores.json`.
**S12. Mod config** (P1). A mod's `config.json`, overridable per server, read in `setup`. Create's stress values, speed
limits and processing times live there, and tests can set them.
**S12. Mod config** (P1, built). A mod's settings and their defaults in its `config.json`, which the server script reads
as `ctx.config` from `setup` on, like NeoForge's server configs. A server changes them in `config/<mod id>.json` next to
`server_mods/`, setting by setting, and a setting the mod doesn't have or a value of the wrong kind stops it from
starting. Players' copies of a mod leave the config out, so what clients need is sent like any other server data. Tests
change settings with `test_game`'s fourth argument. Create's stress values, speed limits and processing times go there
as the machines that use them are built.
**S13. NBT** (P11). Reading and writing structure NBT, shared with STRUCTURES.md's `common/nbt.ts`, for schematics and
ponder scenes.
+1
View File
@@ -72,6 +72,7 @@ deno task build && deno task server # packs the mods and starts a se
- [Screens](docs/modding/gui/index.md): plain screens, inventory overlays and drawing with `Graphics`
- [Networking](docs/modding/networking/index.md): how players get mods and the world
- [Saving Data](docs/modding/datastorage/index.md): where a mod keeps what should last
- [Config](docs/modding/misc/config.md): settings a server can change, like how fast a machine works
- [Commands](docs/modding/misc/commands.md)
- [Time](docs/modding/misc/time.md): ticks, timers, days and nights
- [Engine Access](docs/modding/misc/engine.md): reaching into the engine and hooking its methods, for what the API
+17 -5
View File
@@ -12,6 +12,7 @@ import {
type EntityJson,
type EntityModelJson,
ID_PATTERN,
is_object,
type ItemJson,
type ManifestJson,
type OreJson,
@@ -80,7 +81,7 @@ export class BmodError extends Error {
// the zip's layout:
// manifest.json the mod's manifest, with "scripts" and "credits" pointing into the zip
// data.json every block, model, item, recipe, ore, entity, entity model, effect, tag, loot table and
// biome
// biome, and the mod's config
// scripts/<side>.js
// textures/<name>.png the texture <mod id>:<name>
// textures/<name>.json its animation, if it has one
@@ -200,7 +201,11 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod {
problems,
) as BiomeSourceJson[],
features: checked(raw_data.features, "features", validate_feature, problems) as FeatureJson[],
config: raw_data.config,
};
if (raw_data.config !== undefined && !is_object(raw_data.config)) {
problems.push("data.json: config must be an object");
}
// a mod only registers ids in its own namespace
const registered = [...data.blocks, ...data.models, ...data.items, ...data.entities, ...data.entity_models];
const worldgen = [
@@ -277,14 +282,21 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod {
return { manifest, data, scripts, textures, texture_json, credits };
}
// the same mod without its server and worldgen scripts and the terrain's data, what players get. the server sends
// them the world
// the same mod without its server and worldgen scripts, the terrain's data and its config, what players get. the
// server sends them the world
export function client_copy(bmod: Bmod): Bmod {
const scripts = { ...bmod.scripts };
delete scripts.server;
delete scripts.worldgen;
const { noises: _n, density_functions: _d, noise_settings: _s, biome_sources: _b, features: _f, ...data } =
bmod.data;
const {
noises: _n,
density_functions: _d,
noise_settings: _s,
biome_sources: _b,
features: _f,
config: _c,
...data
} = bmod.data;
return { ...bmod, scripts, data };
}
+4
View File
@@ -12,6 +12,10 @@ export type { EventSignal, Face, Id, ItemStack, ModInfo, Position, Season, TagAp
export interface ServerContext {
mod: ModInfo;
// the mod's settings: its config.json's "config", with the server's changes from config/<mod id>.json. the same
// for the whole time the server runs. see docs/modding/misc/config.md
// deno-lint-ignore no-explicit-any
readonly config: any;
components: ComponentRegistry; // only during setup
commands: CommandRegistry; // only during setup
events: { before: ServerBeforeEvents; after: ServerAfterEvents };
+3
View File
@@ -67,6 +67,8 @@ export interface LoadedMod {
noise_settings: { file: string; json: NoiseSettingsJson }[];
biome_sources: { file: string; json: BiomeSourceJson }[];
features: { file: string; json: FeatureJson }[];
// config.json's settings, see docs/modding/misc/config.md
config?: Record<string, unknown>;
textures: string[];
// absolute paths by texture id
texture_files: Map<string, string>;
@@ -94,6 +96,7 @@ export function mod_data(mod: LoadedMod): ModData {
noise_settings: mod.noise_settings.map((n) => n.json),
biome_sources: mod.biome_sources.map((b) => b.json),
features: mod.features.map((f) => f.json),
config: mod.config,
};
}
+3
View File
@@ -58,6 +58,9 @@ export interface ModData {
biome_sources?: BiomeSourceJson[];
// data features, see common/worldgen/features.ts. server only too
features?: FeatureJson[];
// the mod's settings, its config.json's "config", with the server's changes once the server loads it. server only
// too, see docs/modding/misc/config.md
config?: Record<string, unknown>;
}
// a mod as the server lists it to clients, in load order: the .bmod players download, without its server script
+1
View File
@@ -56,6 +56,7 @@ function singleplayer_host(): Promise<Host> {
return await start_host({
build_dir: BUILD_DIR,
server_mods_dir: join(ROOT, "server_mods"),
config_dir: join(data_dir(), "config"),
world_dir: join(worlds, "world"),
on_fatal(message) {
console.error(message);
+1
View File
@@ -124,6 +124,7 @@ seed and chunk always give the same blocks. See [World Generation](../worldgen/i
| Item stacks and their `data` | yes | in containers the player has open or owns |
| Entities | yes | near the player |
| `ctx.storage` | yes | no |
| [Config](../misc/config.md) | yes | no |
| Server script code | yes | **never** |
| Shared script code | yes | yes, and runs it |
+2 -1
View File
@@ -31,7 +31,8 @@ const count = ctx.storage.get<number>("smelted") ?? 0;
ctx.storage.set("smelted", count + 1);
```
Each mod has its own, so keys don't clash between mods. It's for things like settings and totals. Data about one block
Each mod has its own, so keys don't clash between mods. It's for things like totals and settings changed in game.
Settings a server picks before it starts belong in the mod's [config](../misc/config.md), and data about one block
belongs in that block's tile data, which goes away with the block.
## What Isn't Saved
+3 -2
View File
@@ -11,6 +11,7 @@ mods/
manifest.json # required, everything else is optional
deno.json # makes the mod its own deno project, see below
CREDITS.md # shown on the Credits screen
config.json # settings servers can change, never sent to players. see misc/config.md
blocks/*.json # one block per file
items/*.json # items that aren't a block's item form
models/*.json # block models
@@ -120,7 +121,7 @@ deno task build # packs every mod in mods/ into server_mo
```
copper_tools.bmod
manifest.json # with scripts and credits pointing into the zip
data.json # every block, model, item, entity, recipe, ore, tag and loot table
data.json # every block, model, item, entity, recipe, ore, tag and loot table, and the config
scripts/server.js # each script bundled into one module
scripts/client.js
scripts/worldgen.js
@@ -134,5 +135,5 @@ copper_tools.bmod
- Packing the same mod twice gives the same bytes, so the file only changes when the mod does.
- `deno task build` leaves other `.bmod` files in `server_mods/` alone, so mods from elsewhere can sit next to the ones
it builds.
- Players get a copy **without** `scripts/server.js` and `scripts/worldgen.js`. See
- Players get a copy **without** `scripts/server.js`, `scripts/worldgen.js` and the config. See
[Networking](../networking/index.md).
+83
View File
@@ -0,0 +1,83 @@
# Config
A mod's config is its settings: the numbers and switches a server might want different without changing the mod, like
how fast a machine works, how far something reaches, or whether a feature is on. The mod lists them with their defaults
in `config.json`, a server changes the ones it wants in a file of its own, and the server script reads the result as
`ctx.config`. It's like NeoForge's server configs.
## `config.json`
In the mod's folder, next to `manifest.json`:
```json
{
"format_version": 1,
"config": {
"max_speed": 256,
"crank_hunger": 0.01,
"fan": { "push_distance": 20, "pull_distance": 20 },
"stress": { "copper_tools:press": 8, "copper_tools:mixer": 4 }
}
}
```
A setting can be any JSON value, and objects group settings that go together, like `fan` here. Every setting a server
can change has to be in this file with its default.
## Reading It
`ctx.config` in the server script holds the settings, with the server's changes made:
```ts
import type { ServerContext } from "bworld/server";
interface Config {
max_speed: number;
fan: { push_distance: number; pull_distance: number };
}
export function setup(ctx: ServerContext) {
const config: Config = ctx.config;
ctx.log(`fans push things up to ${config.fan.push_distance} blocks away`);
}
```
It's there from `setup` on, and stays the same for as long as the server runs. It's typed `any`, so give it a type of
your own like `Config` above.
Only the server script has it. The copy of a mod players download leaves its config out, since a server's settings
aren't always the defaults. When players need to see one, the server sends it, like any other
[server data](../concepts/sides.md#what-each-side-knows): in a block's [client data](../blocks/tiledata.md), an item's
`data`, or over a [channel](../networking/index.md#mod-channels).
## Changing It on a Server
A server reads its changes from `config/<mod id>.json`, next to `server_mods/`, or in the folder `CONFIG_DIR` says. The
desktop app's own server reads them from `config/` in the app's data folder. A file is shaped like the mod's
`config.json`, with only the settings to change:
```json
{
"format_version": 1,
"config": {
"fan": { "push_distance": 32 }
}
}
```
- Objects are changed setting by setting, so `fan.pull_distance` stays 20. Anything else, lists too, is replaced whole.
- A change has to be to a setting the mod has, and the same kind of value as its default: a number for a number, an
object for an object. Otherwise the server doesn't start, and says which setting is wrong, so a misspelled one can't
go unnoticed.
- A file for a mod the server doesn't have is left alone.
Settings are read when the server starts, so restart it after changing them.
## In Tests
[`test_game`](../gettingstarted/index.md#testing) takes changes by mod id as its fourth argument, made the same way as a
server's files are:
```ts
const { game } = await test_game("mods", undefined, undefined, { copper_tools: { fan: { push_distance: 4 } } });
```
+6 -1
View File
@@ -95,7 +95,12 @@ export async function start_game(
}
function script_of(mod: ServerModSource) {
return { mod: mod.listing.id, version: mod.listing.version, engine_access: mod.listing.engine_access ?? false };
return {
mod: mod.listing.id,
version: mod.listing.version,
engine_access: mod.listing.engine_access ?? false,
config: mod.data.config ?? {},
};
}
export function data_url(code: string) {
+12 -9
View File
@@ -110,6 +110,8 @@ interface ScriptSource {
version: string;
url: string;
engine_access: boolean;
// its settings, see ServerContext.config
config: Record<string, unknown>;
}
export function run_guarded<T>(mod: string, what: string, fn: () => T): T | undefined {
@@ -242,17 +244,17 @@ export class ModRuntime {
// shared scripts, the block rules clients run too. their world is the server's
async load_shared_scripts(game: GameServer, scripts: ScriptSource[]) {
this.game = game;
for (const { mod, version, url, engine_access } of scripts) {
await loading_mod(mod, engine_access, () => this.#load_shared_script(mod, version, url));
for (const { mod, version, url, engine_access, config } of scripts) {
await loading_mod(mod, engine_access, () => this.#load_shared_script(mod, version, url, config));
}
}
async #load_shared_script(mod: string, version: string, url: string) {
async #load_shared_script(mod: string, version: string, url: string, config: Record<string, unknown>) {
const module = await import(url);
if (typeof module.setup !== "function") {
throw new ModLoadError(mod, "the shared script doesn't export a setup function");
}
const { world } = this.#context(mod, version);
const { world } = this.#context(mod, version, config);
const ctx: SharedContext = {
mod: { id: mod, version },
side: "server",
@@ -285,19 +287,19 @@ export class ModRuntime {
async load_scripts(game: GameServer, scripts: ScriptSource[]) {
this.game = game;
for (const { mod, version, url, engine_access } of scripts) {
await loading_mod(mod, engine_access, () => this.#load_script(mod, version, url));
for (const { mod, version, url, engine_access, config } of scripts) {
await loading_mod(mod, engine_access, () => this.#load_script(mod, version, url, config));
}
}
async #load_script(mod: string, version: string, url: string) {
async #load_script(mod: string, version: string, url: string, config: Record<string, unknown>) {
const module = await import(url);
if (typeof module.setup !== "function") {
throw new ModLoadError(mod, "the server script doesn't export a setup function");
}
running_mod = mod;
try {
await module.setup(this.#context(mod, version));
await module.setup(this.#context(mod, version, config));
} finally {
running_mod = "";
}
@@ -573,7 +575,7 @@ export class ModRuntime {
};
}
#context(mod: string, version: string): ServerContext {
#context(mod: string, version: string, config: Record<string, unknown>): ServerContext {
const setup_only = (what: string) => {
if (!this.#setting_up) {
throw new Error(`[${mod}] ${what} can only be registered during setup`);
@@ -588,6 +590,7 @@ export class ModRuntime {
const ctx: ServerContext = {
mod: { id: mod, version },
config,
components: {
register_block: (id, component) => {
setup_only("components");
+4 -1
View File
@@ -24,6 +24,9 @@ export interface HostOptions {
build_dir: string;
// the .bmod files to load
server_mods_dir: string;
// <mod id>.json files that change mods' settings, see docs/modding/misc/config.md. without it every mod uses its
// own config.json
config_dir?: string;
// where DESKTOP_DOWNLOADS are, served at /dist/. without it there's nothing to download
dist_dir?: string;
// the world's folder: level.json, and the blocks in region/
@@ -44,7 +47,7 @@ export interface Host {
// throws when the mods have problems, saying what they are
export async function start_host(options: HostOptions): Promise<Host> {
const mods = await load_bmods(options.server_mods_dir, engine_texture_ids(options.build_dir));
const mods = await load_bmods(options.server_mods_dir, engine_texture_ids(options.build_dir), options.config_dir);
console.log(`Mods: ${mods.map((mod) => `${mod.listing.id} ${mod.listing.version}`).join(", ") || "none"}`);
// what players download, by path
const downloads = new Map(mods.map((mod) => [`/${mod.listing.file}`, mod.client_bytes]));
+74 -5
View File
@@ -1,12 +1,13 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the server's mods: every .bmod in server_mods/, checked, sorted so dependencies load first, and with the copy
// players download (the same mod without its server script) ready to serve
// the server's mods: every .bmod in server_mods/, checked, with the server's changes to their config, sorted so
// dependencies load first, and with the copy players download (the same mod without its server script) ready to serve
import { join } from "@std/path";
import { type Bmod, BMOD_EXTENSION, client_copy, read_bmod, write_bmod } from "$/common/bmod.ts";
import { check_references, load_order, type LoadedMod } from "$/common/mod_check.ts";
import type { ModListing } from "$/common/mod_loader.ts";
import { FORMAT_VERSION, is_object } from "$/common/mod_data.ts";
import { sha256 } from "$/common/utils.ts";
export interface ServerMod {
@@ -23,9 +24,14 @@ export class ModsError extends Error {
}
}
// engine_textures are the engine: texture ids, for checking the textures mods use. a mod with problems stops the
// whole server from starting, the game never runs with some mods missing
export async function load_bmods(dir: string, engine_textures: Iterable<string>): Promise<ServerMod[]> {
// engine_textures are the engine: texture ids, for checking the textures mods use. config_dir has the server's
// <mod id>.json files that change mods' config. a mod with problems stops the whole server from starting, the game
// never runs with some mods missing
export async function load_bmods(
dir: string,
engine_textures: Iterable<string>,
config_dir?: string,
): Promise<ServerMod[]> {
let files: string[];
try {
files = [...Deno.readDirSync(dir)]
@@ -52,6 +58,9 @@ export async function load_bmods(dir: string, engine_textures: Iterable<string>)
problems.push((e as Error).message);
}
}
if (config_dir) {
for (const { bmod } of by_id.values()) change_config(bmod, config_dir, problems);
}
// the same checks check-mods runs on mod folders
const loaded = [...by_id.values()].map(({ file, bmod }) => as_loaded_mod(file, bmod));
@@ -92,6 +101,65 @@ export async function load_bmods(dir: string, engine_textures: Iterable<string>)
}));
}
// applies config_dir/<mod id>.json to the mod's config, when the server has one
function change_config(bmod: Bmod, config_dir: string, problems: string[]) {
const file = join(config_dir, `${bmod.manifest.id}.json`);
let text: string;
try {
text = Deno.readTextFileSync(file);
} catch (e) {
if (e instanceof Deno.errors.NotFound) return;
throw e;
}
let json: unknown;
try {
json = JSON.parse(text);
} catch (e) {
problems.push(`${file}: isn't valid json: ${(e as Error).message}`);
return;
}
if (!is_object(json) || json.format_version !== FORMAT_VERSION || !is_object(json.config)) {
problems.push(`${file}: must be { "format_version": ${FORMAT_VERSION}, "config": { ... } }`);
return;
}
const changed = apply_config(bmod.data.config ?? {}, json.config);
problems.push(...changed.problems.map((problem) => `${file}: ${problem}`));
bmod.data.config = changed.config;
}
// a mod's config with changes made to it, like a server's config/<mod id>.json makes: objects are changed setting by
// setting, anything else is replaced. a change has to be to a setting the mod has, and the same kind of json value,
// so a misspelled one doesn't go unnoticed
export function apply_config(
config: Record<string, unknown>,
changes: Record<string, unknown>,
): { config: Record<string, unknown>; problems: string[] } {
const problems: string[] = [];
const apply = (settings: Record<string, unknown>, changes: Record<string, unknown>, path: string) => {
const result = { ...settings };
for (const [key, value] of Object.entries(changes)) {
const name = `${path}${key}`;
if (!Object.hasOwn(settings, key)) {
problems.push(`${name} isn't one of the mod's settings`);
} else if (json_kind(value) !== json_kind(settings[key])) {
problems.push(`${name} must be ${json_kind(settings[key])}`);
} else {
result[key] = is_object(value)
? apply(settings[key] as Record<string, unknown>, value, `${name}.`)
: value;
}
}
return result;
};
return { config: apply(config, changes, ""), problems };
}
function json_kind(value: unknown): string {
if (value === null) return "null";
if (Array.isArray(value)) return "a list";
return is_object(value) ? "an object" : `a ${typeof value}`;
}
// in the shape the checks in common/mod_check.ts take
function as_loaded_mod(file: string, bmod: Bmod): LoadedMod {
const entries = <T>(list: T[]) => list.map((json) => ({ file: `${file} data.json`, json }));
@@ -117,6 +185,7 @@ function as_loaded_mod(file: string, bmod: Bmod): LoadedMod {
noise_settings: entries(bmod.data.noise_settings ?? []),
biome_sources: entries(bmod.data.biome_sources ?? []),
features: entries(bmod.data.features ?? []),
config: bmod.data.config,
textures: [...bmod.textures.keys()],
texture_files: new Map(),
texture_json: new Map(bmod.texture_json),
+1
View File
@@ -11,6 +11,7 @@ try {
host = await start_host({
build_dir: Deno.env.get("BUILD_DIR") ?? "build",
server_mods_dir: Deno.env.get("SERVER_MODS_DIR") ?? "server_mods",
config_dir: Deno.env.get("CONFIG_DIR") ?? "config",
dist_dir: Deno.env.get("DIST_DIR") ?? "dist",
world_dir: Deno.env.get("WORLD_DIR") ?? "world",
seed: Deno.env.get("SEED"),
+17 -3
View File
@@ -8,6 +8,7 @@ import { mod_data } from "$/common/mod_check.ts";
import type { ServerModSource } from "$/server/game/load_mods.ts";
import { GameServer } from "$/server/game/game_server.ts";
import { start_game } from "$/server/game/load_mods.ts";
import { apply_config } from "$/server/load_bmods.ts";
import { PROTOCOL_VERSION } from "$/common/protocol.ts";
import { decode_level_chunk } from "$/common/chunk_streaming.ts";
import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts";
@@ -68,9 +69,22 @@ class MemoryChunks implements SavedChunks {
}
// a game with an in memory host that remembers what it sent to each connection. the seed has low, dry land around
// 0, 0, where players spawn and where tests build things
export async function test_game(mods_dir: string, save?: WorldSave, seed = "test-seed-90") {
// 0, 0, where players spawn and where tests build things. config changes mods' settings, by mod id, like a server's
// config/<mod id>.json files
export async function test_game(
mods_dir: string,
save?: WorldSave,
seed = "test-seed-90",
config: Record<string, Record<string, unknown>> = {},
) {
EverythingRegistry.clear();
const mods = mod_sources(mods_dir);
for (const mod of mods) {
if (!config[mod.listing.id]) continue;
const changed = apply_config(mod.data.config ?? {}, config[mod.listing.id]);
if (changed.problems.length) throw new Error(`${mod.listing.id}: ${changed.problems.join("; ")}`);
mod.data.config = changed.config;
}
const outbox = new Map<number, unknown[]>();
const closed = new Set<number>();
// what host.download gives back, by url. other urls fail
@@ -97,7 +111,7 @@ export async function test_game(mods_dir: string, save?: WorldSave, seed = "test
host,
{ level: save?.level, chunks },
seed,
mod_sources(mods_dir),
mods,
);
// what it saves is read back from memory, like a host's region files
const save_game = game.save.bind(game);
+115
View File
@@ -0,0 +1,115 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// mods' config.json: their settings, which servers and tests can change, see docs/modding/misc/config.md
import { assert, assertEquals, assertRejects } from "@std/assert";
import { read_bmod, write_bmod } from "$/common/bmod.ts";
import type { ModData } from "$/common/mod_loader.ts";
import { apply_config, load_bmods } from "$/server/load_bmods.ts";
import { load_and_check } from "$/tools/check_mods.ts";
import { create_mod } from "$/tools/new_mod.ts";
import { copy_dir, test_game } from "./helpers.ts";
const config_file = (config: unknown) => JSON.stringify({ format_version: 1, config });
Deno.test("changing a mod's config only changes settings it has, to the same kind of value", () => {
const config = { max_speed: 256, stress: { enabled: true, impact: { press: 8, mixer: 4 } }, fuels: ["coal"] };
const changed = apply_config(config, { max_speed: 64, stress: { impact: { press: 2 } }, fuels: [] });
assertEquals(changed.problems, []);
assertEquals(changed.config, {
max_speed: 64,
stress: { enabled: true, impact: { press: 2, mixer: 4 } },
fuels: [],
});
assertEquals(config.stress.impact.press, 8, "the mod's own settings stay as they were");
const wrong = apply_config(config, { max_sped: 64, stress: { enabled: "no", impact: 8 }, fuels: "coal" });
assertEquals(wrong.problems.map((problem) => problem.split(" ")[0]), [
"max_sped",
"stress.enabled",
"stress.impact",
"fuels",
]);
});
Deno.test("a server script reads its mod's config, with the changes a test makes", async () => {
const dir = Deno.makeTempDirSync({ prefix: "bworld_config_" });
copy_dir("mods/bworld", `${dir}/bworld`);
create_mod("copper_tools", "Copper Tools", dir);
Deno.writeTextFileSync(
`${dir}/copper_tools/scripts/server.ts`,
`import type { ServerContext } from "bworld/server";
export function setup(ctx: ServerContext) {
ctx.components.register_block("copper_tools:announce", {});
ctx.commands.register("settings", {
description: "Shows the settings",
usage: "/settings",
run: (_args, player) => player.send_message(JSON.stringify(ctx.config)),
});
}
`,
);
// what the script sees
const config_of = async (changes?: Record<string, Record<string, unknown>>) => {
const { join, send, take } = await test_game(dir, undefined, undefined, changes);
join(1, "bob");
send(1, { type: "chat", text: "/settings" });
return JSON.parse(take(1).find((m) => m.type === "chat" && m.text.startsWith("{")).text);
};
assertEquals(await config_of(), {}, "a mod without config.json has no settings");
Deno.writeTextFileSync(`${dir}/copper_tools/config.json`, config_file({ speed: 16, ore: { size: 4, depth: 30 } }));
assertEquals(await config_of(), { speed: 16, ore: { size: 4, depth: 30 } });
assertEquals(await config_of({ copper_tools: { ore: { size: 8 } } }), { speed: 16, ore: { size: 8, depth: 30 } });
await assertRejects(() => config_of({ copper_tools: { sped: 1 } }), Error, "sped");
Deno.writeTextFileSync(`${dir}/copper_tools/config.json`, config_file([16]));
const errors = load_and_check(dir).find((mod) => mod.id === "copper_tools")!.report.errors;
assert(errors.some((error) => error.startsWith("config.json")), errors.join("\n"));
Deno.removeSync(dir, { recursive: true });
});
Deno.test("a server changes a mod's settings with config/<mod id>.json, and players never get them", async () => {
const dir = Deno.makeTempDirSync({ prefix: "bworld_config_server_" });
const data: ModData = {
blocks: [],
models: [],
items: [],
recipes: [],
ores: [],
spawns: [],
entities: [],
entity_models: [],
effects: [],
tags: [],
config: { speed: 16, ore: { size: 4, depth: 30 } },
};
Deno.mkdirSync(`${dir}/server_mods`);
Deno.mkdirSync(`${dir}/config`);
Deno.writeFileSync(
`${dir}/server_mods/tiny.bmod`,
write_bmod({
manifest: { format_version: 1, id: "tiny", name: "Tiny", version: "1.0.0" },
data,
scripts: {},
textures: new Map(),
}),
);
const config_of = async () => (await load_bmods(`${dir}/server_mods`, [], `${dir}/config`))[0].bmod.data.config;
assertEquals(await config_of(), data.config, "without a file, the mod's own");
Deno.writeTextFileSync(`${dir}/config/tiny.json`, config_file({ ore: { depth: 50 } }));
assertEquals(await config_of(), { speed: 16, ore: { size: 4, depth: 50 } });
const [mod] = await load_bmods(`${dir}/server_mods`, [], `${dir}/config`);
assertEquals(read_bmod(mod.client_bytes, mod.listing.file).data.config, undefined);
Deno.writeTextFileSync(`${dir}/config/tiny.json`, config_file({ ore: { depht: 50 } }));
await assertRejects(config_of, Error, "ore.depht");
Deno.writeTextFileSync(`${dir}/config/tiny.json`, JSON.stringify({ ore: { depth: 50 } }));
await assertRejects(config_of, Error, "tiny.json");
Deno.removeSync(dir, { recursive: true });
});
+9
View File
@@ -247,6 +247,15 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
}
}
if (exists(`${dir}/config.json`)) {
const config = read_json(`${dir}/config.json`, (m) => error(`config.json: ${m}`));
if (!is_object(config) || config.format_version !== FORMAT_VERSION || !is_object(config.config)) {
error(`config.json: must be { "format_version": ${FORMAT_VERSION}, "config": { ... } }`);
} else {
mod.config = config.config;
}
}
// a mod only registers ids in its own namespace
for (const { file, json } of [...mod.blocks, ...mod.models, ...mod.items, ...mod.entities]) {
if (json.id.split(":")[0] !== id) error(`${file}: ${json.id} isn't in this mod's namespace "${id}"`);