Files
bworld/docs/modding_plan.md
T
2026-09-29 23:29:14 -03:00

347 lines
21 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Modding: Design Notes and Plan
The mod docs in [`docs/modding/`](modding/) describe what works today. This file is for people working on the engine:
the design behind the mod API, what's planned, and the questions still open.
bworld's modding takes from three places:
- **Minetest: the game is mods.** The engine is small, and everything that makes bworld _bworld_ (its blocks, items,
crafting, screens, commands and terrain) lives in `mods/bworld`, written against the same API as any other mod.
- **Minecraft Bedrock add-ons: easy to start.** Most content is JSON, blocks and items get behavior from named
components, scripts use before/after events and server-driven forms, and players get everything from the server.
- **Minecraft Java with Fabric: no ceiling.** A mod that needs to can reach into the engine itself and hook its methods,
like Fabric's mixins.
A mod is built from up to three layers. Most mods only need the first one or two:
| Layer | Like | What a mod writes | Stability |
| ----------------- | ---------------------------------------- | ---------------------------------------------------------------------- | ----------------------------------------- |
| **Data** | Bedrock behavior packs | JSON in `blocks/`, `items/`, `models/`, `recipes/`, ... | Versioned by `format_version` |
| **Game API** | Minetest's Lua API, Bedrock's Script API | TypeScript against `bworld/server`, `bworld/client`, `bworld/worldgen` | Only breaks with the game's major version |
| **Engine access** | Fabric's mixins | `import { engine, hook } from "bworld/engine"` | None, tied to one game version |
## Status
**Built:** the mod loader and `.bmod` files (packing, loading from `server_mods/`, sending players a copy without the
server and worldgen scripts), delivery to clients (hashed downloads, the confirm screen for other sites, credits), the
data layer (blocks, block models with variants, items, recipes including mods' own types, entities and entity models,
ores), server scripts (components, events, commands, timers, storage, recipes, containers, container screens, displayed
items), client scripts (item and recipe lookups, inventory overlays with `Graphics`), worldgen features and ores, the
base game's block behavior as a mod, and world time.
The code is in `common/mod_loader.ts`, `common/mod_data.ts`, `common/mod_check.ts`, `common/bmod.ts`,
`server/game/mod_runtime.ts`, `server/load_bmods.ts`, `client/mods.ts` and `common/worldgen_loader.ts`.
**In the API types but throwing:** forms, custom screens, HUD elements, keybinds, mod channels, `g.slider`, `g.slots`,
`register_terrain`.
**Not built at all:** common scripts, the registry freeze and hash, overrides, engine access.
**Known gaps:**
- Manifest `dependencies` version ranges and `game_version` aren't checked.
- Mods can't throw a `CommandError` the server recognizes: it's checked with `instanceof`, and the class isn't in the
API, so a mod's bundled copy is a different class. Export it from `bworld/server`, or recognize it by `name`.
- Tools only lose durability when their owner dies. Nothing else uses it.
## Planned API
### Common Scripts
A fourth script, `scripts.common`, run on the server and on every client while content loads, right after the mod's own
JSON is registered. Data would then be shorthand for code: loading `blocks/copper_block.json` would do exactly what
`ctx.blocks.register(...)` with the same object does, so content that's easier to generate (every color of wool) or
depends on other mods can be written as code.
```ts
import type { CommonContext } from "bworld/common";
const COLORS = ["white", "red", "green", "blue", "black"];
export function setup(ctx: CommonContext) {
for (const color of COLORS) {
ctx.blocks.register({
id: `wool:${color}_wool`,
textures: `wool:${color}_wool`,
mining: { toughness: 1 },
drops: `wool:${color}_wool`,
});
}
// every leaf block any mod registered drops sticks sometimes
for (const id of ctx.blocks.ids().filter((id) => id.endsWith("_leaves"))) {
ctx.blocks.extend(id, { components: { "wool:stick_drop": { chance: 0.05 } } });
}
}
```
```ts
interface CommonContext {
mod: { id: string; version: string };
blocks: ContentRegistry<BlockJson>;
items: ContentRegistry<ItemJson>;
models: ContentRegistry<ModelJson>;
recipes: RecipeRegistry;
log(...args: unknown[]): void;
}
// T is the same shape as the JSON file's content, checked the same way
interface ContentRegistry<T> {
register(definition: T): void;
get(id: string): Readonly<T> | undefined; // what's registered so far, by any mod
ids(): string[];
override(id: string, fields: Partial<T>): void; // like "set" in an override file
extend(id: string, change: { components?: Record<string, unknown>; remove_components?: string[] }): void;
}
interface RecipeRegistry {
register(recipe: RecipeJson): void;
remove(match: (recipe: RecipeJson) => boolean): number;
list(type: string): readonly RecipeJson[];
register_type(id: string, type: { validate(recipe: unknown): string[] }): void;
}
```
- Definitions are checked exactly like JSON files, and a problem is a load error naming the mod.
- Common scripts only run during loading and can't reach the world or players. They get the same `ctx` on both sides, so
they can't accidentally register different things.
- `register_type` would let `check-mods` and the loader validate mods' own recipe types, instead of each mod checking
its recipes in `setup`. `shaped`, `furnace`, `fuel` and `smithing` become short for `bworld:shaped` and so on.
### The Freeze and the Registry Hash
After content loads, the registries close: numeric ids, block items and recipe indexes are made then, and registering
later throws. Then each side hashes its registries (every id and its definition), and the client sends the hash with
`ready`. A mismatch turns the player away naming the first thing that differs, instead of letting them play with
mismatched blocks. This matters once common scripts exist, since code can register different things on each side.
### Overrides
A mod changes content other mods registered, like Minetest's `override_item`. `overrides/grass_weeds.json`:
```json
{
"format_version": 1,
"override": {
"block": "bworld:grass",
"set": { "mining": { "toughness": 1, "tool": "shovel" } },
"add_components": { "farming_plus:weeds": { "chance": 0.01 } }
}
}
```
| Field | Meaning |
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `block` or `item` | The id to change. |
| `set` | Fields to replace, named as in the block or item JSON. Each listed field is replaced whole. |
| `add_components` | Components to add. One it already has gets these params instead. |
| `remove_components` | Component ids to take away. |
| `remove_recipes` | Removes recipes whose fields equal the ones given (`result` matches the result's id), like `{ "type": "shaped", "result": "bworld:chest" }`. |
- A mod can only change content of mods it lists in `dependencies`, so it always loads after them. `check-mods` makes
this an error.
- Changes apply in load order, so the later mod wins. `check-mods` warns when two mods change the same field.
- Ids never change and blocks and items can't be removed. To make something unobtainable, remove its recipes and drops.
- Overrides are content: applied on every side, and part of the registry hash.
### Engine Access
For what the Game API doesn't cover yet: a new kind of rendering, different player physics, a new entity type. A mod
asks for it in its manifest:
```json
{ "engine_access": true, "game_version": "~0.4.0" }
```
```ts
// server.ts: broken blocks drop twice
import { engine, hook } from "bworld/engine";
export function setup() {
hook(engine.server.GameServer.prototype, "pop_item", {
after(game, [x, y, z, stack], entity) {
game.spawn_item(entity.x, entity.y, entity.z, stack.clone());
return entity;
},
});
}
```
```ts
function hook<T, K extends keyof T>(target: T, method: K, handlers: {
// runs first. change args in place, or return { result } to skip the method and everything after
before?(self: T, args: Parameters<T[K]>): { result: ReturnType<T[K]> } | void;
// wraps the method, calling original (or not)
replace?(self: T, args: Parameters<T[K]>, original: T[K]): ReturnType<T[K]>;
// runs last, and returns the result the caller gets
after?(self: T, args: Parameters<T[K]>, result: ReturnType<T[K]>): ReturnType<T[K]>;
// lower runs earlier, the default is 1000. ties go in load order
priority?: number;
}): () => void; // unhook
```
- `engine` holds the live modules on each side: `engine.common` everywhere, `engine.server` in server scripts,
`engine.client` in client scripts. The engine puts them on the global object at startup, and `bworld/engine` in a
mod's bundle is a shim that reads them, so a hook on a prototype changes every instance already made.
- Types are the engine's own source, so `check-mods` typechecks against exactly the engine the mod will run on.
- Several mods can hook one method: `before` hooks run in priority order, `replace` hooks nest, `after` hooks chain
results. A hook that throws is logged under its mod and skipped.
- Module exports can't be reassigned, so functions mods may want to change move onto plain objects the engine calls
through (like `engine.common.physics.move_body`). `#private` members can't be hooked, so they're kept for things with
rules that must hold, like a container's slots.
- Hooks reach one JavaScript realm. Chunk workers run their own copy of the engine, so a client hook doesn't change
meshing.
- It isn't a stable API. A mod with `engine_access` must set `game_version` within one minor version, and loading it on
another is a load error. Without `engine_access`, importing `bworld/engine` is an error.
- A server mod with engine access controls the game worker completely, but the worker still has no Deno permissions. The
confirm screen for other sites lists which mods use it.
- Prefer the Game API. Many mods hooking the same thing is a sign it should become part of the Game API.
### Forms
Simple dialogs defined by server code, like Bedrock's `@minecraft/server-ui`, drawn by the client in the game's style.
The types are in `common/mod_api/server.ts` (`message_form`, `action_form`, `modal_form`).
```ts
const result = await ctx.ui.action_form(player, {
title: "Teleporter",
body: "Where to?",
buttons: [{ text: "Spawn", icon: "bworld:compass" }, { text: "Home" }],
});
if (!result.canceled && result.selection === 0) player.teleport(0, 100, 0);
```
The promise resolves with `canceled: true` when the player closes the form, disconnects, or another screen replaces it.
The engine checks every response against the form's definition (types, ranges, option counts, text length) before mod
code sees it.
### Custom Screens
For what forms and containers can't do: maps, skill trees, minigames. The client script registers a screen, and the
server opens it with props:
```ts
// client.ts
ctx.ui.register_screen("copper_tools:stats", (props) => new StatsScreen(ctx, props));
// server.ts
const screen = ctx.ui.open_screen(player, "copper_tools:stats", { smelted: 42 });
screen.update({ smelted: 43 }); // calls on_props on the client
```
`ModScreen` has `on_open`, `on_tick`, `on_render(g)`, `on_props`, `on_close` and `on_escape`. Screens can show server
containers passed in `open_screen(..., { containers: { input } })` and drawn with `g.slots("input", layout, x, y)`,
still following the container rules. A client script can open its own screens with `ctx.ui.open(id, props)`.
### HUD, Keybinds and Mod Channels
- `ctx.hud.register(id, { on_render(g) })` draws every frame after the world, under open screens.
- `ctx.input.bind(id, default_key, on_press)` with ids like `copper_tools:open_smelter`, so a controls menu can rebind
them. They only fire while no screen is open.
- `ctx.net` on both sides: `on(channel, handler)`, `send`, and `broadcast` on the server. Channel ids are in the mod's
namespace, and a mod only sends on its own. Messages are at most 16 KB of JSON, each player can send at most 60 mod
messages a second, and the server drops anything over that. On the wire it's `{ type: "mod", channel, data }`.
Everything a client sends is untrusted.
## The Engine and the Base Game
Like a Minetest game, bworld is the engine plus one mod, `mods/bworld`, written against the same API as any other mod.
If the base game can't be written as a mod, the API is missing something, and other mods would hit the same wall.
**The engine** keeps what every game built on it needs: rendering, meshing, lighting and the sky; physics, player
movement and input; networking, saving, the game server and its loop; registries, the mod loader and the Game API;
containers, slot click rules, screens and the GUI toolkit; entities; chat; world time; `/tps`; `bworld:air`; and the
engine assets in `assets/`.
**`mods/bworld`** has everything else:
| What | Where it is now | Status |
| ---------------------------------------------------------------------- | ------------------------------------------------------------------------ | ------- |
| Blocks, items, models, entities, recipes, textures, credits | `mods/bworld` | Done |
| Hoeing, chest, furnace, smithing table, farming, watering can, fishing | `mods/bworld/scripts/server.ts` | Done |
| Recipe types `shaped`, `furnace`, `fuel`, `smithing` | engine (`common/mod_loader.ts`, `server/game/crafting.ts`) | Phase 5 |
| The player's inventory screen and crafting grid | engine (`client/gui/gui_player_inventory.ts`, `server/game/crafting.ts`) | Phase 5 |
| The hotbar and crosshair | engine (`client/gui/hud.ts`) | Phase 5 |
| `/give`, `/time` and `/summon` | engine (`server/game/game_server.ts`) | Phase 5 |
| Mining: tool speed, `requires_tool`, drops | engine (`client/game_mode.ts`, `server/game/game_server.ts`) | Phase 5 |
| Day and night lengths, sky colors | engine (`common/time.ts`, `client/rendering/game_renderer.ts`) | Phase 5 |
| Where new players spawn | engine (`server/game/world.ts`) | Phase 5 |
| Terrain, biomes, trees and ores | engine (`common/worldgen/`, `common/generation.ts`) | Phase 6 |
### Rules That Keep Existing Worlds Working
1. **Ids don't change.** Saves store blocks and items by string id, including inventories and chest contents.
2. **Terrain is identical, block for block.** A save only stores what players changed on top of generated terrain. If
the generator's output changes at all, every existing world silently changes with it.
3. **Old saves are upgraded when loading.** The save format can change, as long as older saves load into the new shape.
`tests/fixtures/` keeps a save from each version.
4. **The protocol can change, with `PROTOCOL_VERSION`.** Clients on another version are turned away before anything else
happens.
## Chunk Streaming
How the server sends the world, like Minecraft Java since 1.20.2. The code is in `common/chunk_streaming.ts`,
`server/game/player_chunks.ts` and `client/level/client_level.ts`.
- **Whole chunks.** A `level_chunk` is a binary websocket message with every block of a 16×256×16 chunk and its columns'
biomes, deflated. Blocks are in 16 sections of 16×16×16, each a paletted container like Minecraft's: one value when
the section is all one block, a palette and 1, 2, 4 or 8 bits per block up to 256 kinds, and whole values past that.
Light isn't sent.
- **Numeric ids.** Chunks use the server's numeric block ids, and `join.blocks` lists the string id for each, like
Minecraft's registry sync. Clients translate them as a chunk loads.
- **The view.** Players send their view distance with `ready` and `view_distance`. The server uses up to 10 chunks, and
sends a round area around the player plus the ring past it, which clients need to mesh and light the edge (Minecraft's
`ChunkTrackingView`). Moving into another chunk sends `set_center_chunk`, and `forget_level_chunk` for each chunk that
left the view.
- **Batches.** Chunks go out nearest first, between `chunk_batch_start` and `chunk_batch_finished { size }`. The client
answers `chunk_batch_received { chunks_per_tick }`: as many chunks as fit in 7 ms a tick. Until the first answer
there's one batch of 9 in flight, after it up to 10. The server stops building chunks for a tick after 20 ms.
- **Changes.** `set_block` only goes to players that have the chunk.
## Phases
Each phase ends with every test passing and the game playable.
**Phase 1: loading and common scripts.** `scripts.common` bundled like the client script and run on both sides between
each mod's data and the next mod. `CommonContext`, with the JSON loader going through the same functions. The freeze and
the registry hash. Recipe types as ids with `register_type`. Check: a test mod registers content from code, and the
server and a client end up with equal registries and hashes.
**Phase 2: overrides.** `override` and `extend` in common scripts, `overrides/*.json`, `recipes.remove`, and the
`check-mods` rules. Check: a test mod adds a component to `bworld:grass`, changes `bworld:glass`'s toughness and
replaces the chest recipe, on both sides and in the hash.
**Phase 3: engine access.** The global engine modules and the `bworld/engine` shim, `hook`, `engine_access` in the
manifest and its checks, and making the engine hookable where mods will want it. Check: test mods hook a server, a
client and a worldgen method, hooks on one method run in priority order, and a throwing hook is logged without breaking
the game.
**Phase 4: the rest of the Game API.** Mod channels, keybinds, forms, custom screens and HUD elements. More events:
items picked up and dropped, containers clicked, players moving between chunks, entities.
**Phase 5: gameplay out of the engine.** Everything marked phase 5 in the table above moves into `mods/bworld`. Mining
rules become something `mods/bworld` sets, with the engine asking it on both sides so clients still predict breaking.
Check: all tests pass unchanged, and old saves still load.
**Phase 6: world generation.** First a golden fixture: a SHA-256 of the final blocks of 64 chunks for 3 seeds, recorded
from the current code. Then port `common/worldgen/` to `mods/bworld/scripts/worldgen.ts` as the `bworld:overworld`
terrain generator (with `register_terrain`), and the ore table to `mods/bworld/worldgen/ores.json`. The server refuses
to start without a terrain generator. Check: the fixture matches exactly.
**Done when** searching `client/`, `common/` and `server/` for `"bworld:` finds only `bworld:air`, removing
`mods/bworld` gives an engine that starts and says it needs a terrain generator, the base game uses no engine access,
and a world saved before any of this plays exactly the same.
## Open Questions
- **Client-only mods.** Should players install their own client mods (minimaps, UI tweaks) that work on any server, like
Fabric's? They'd need a separate kind of mod that can't add content or change the registry hash, and servers might
want to forbid them.
- **Client-side prediction for mods.** Block components only run on the server, so interacting with a mod block always
waits a round trip. Components could get optional handlers that clients run to predict.
- **Engine access versions.** Tying engine access mods to one minor version is simple but strict.
- **Game API versions.** Only breaking with the game's major version needs deprecation warnings and a changelog.
- **Screen scaling.** The GUI works in raw canvas pixels. `Graphics` should probably use a UI scale players can change.
- **Entities.** Mods can define simple animals, but there's no API for entity types with their own behavior, animations,
or natural spawning.
- **Hot reload.** Restarting the server and rejoining is the answer for now.