Files
bworld/docs/modding_plan.md
T
2026-11-04 21:51:26 -03:00

391 lines
26 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 NeoForge: no ceiling.** Most mods get by with registries and events on a bus, with priorities
and cancelling. A mod that needs more can reach into the engine itself and hook its methods, like NeoForge's mixins
and access transformers.
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 `cubi/server`, `cubi/client`, `cubi/worldgen` | Only breaks with the game's major version |
| **Engine access** | NeoForge's mixins | `import { engine, hook } from "cubi/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, displayed items), menus like
NeoForge's (menu types, slots, data, buttons and `still_valid` on the server, menu screens on the client, and the
player's inventory as menu 0, which mods can add slots to), client scripts (item and recipe lookups, plain screens,
inventory overlays, `Graphics` in GUI pixels), mod channels, worldgen features and ores, the base game's block behavior
and screens as a mod, world time, and worn items (an item's `worn` model, `player.set_worn`, synced to every client and
drawn on other players and on the first person arm). See [Menus](modding/inventories/menus.md),
[Screens](modding/gui/index.md) and [Worn Models](modding/items/index.md#worn-models).
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/game/menu.ts`, `server/load_bmods.ts`, `client/mods.ts`, `client/menu.ts`,
`common/worldgen_loader.ts`, and for worn items `client/rendering/worn_renderer.ts`, `player_model.ts` and
`model_math.ts`.
**In the API types but throwing:** forms, HUD elements, keybinds, `g.slider`, `register_terrain`.
**Not built at all:** common scripts, the registry freeze and hash, overrides.
**Engine access** is built (phase 3): `cubi/engine`, `hook`, `engine_access` and its checks, and `physics` as the first
plain object mods can hook. See [Engine Access](modding/misc/engine.md). The code is in `common/hooks.ts`,
`common/mod_api/engine.ts` and the `engine_modules.ts` of each side.
**Known gaps:**
- Manifest `dependencies` version ranges aren't checked, and `game_version` only is for engine access mods.
- 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 `cubi/server`, or recognize it by `name`.
- Tools only lose durability when their owner dies. Nothing else uses it.
- The GUI scale is always 3: screens work in GUI pixels like NeoForge's, but there's no option to change it yet.
- Worn models haven't been looked at in the game yet, only tested: Artifacts' power glove and feral claws and the giant
chestplate on other players, wide and slim, and on the first person arm with its equip and swing.
- Blockbench's `mirror` isn't supported in entity models, so the giant chestplate's left sleeve has the right one's
texture unflipped.
## 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` becomes short for `bworld:shaped`. Shared scripts can now register types with
`ctx.recipes.register_type`, and every one of the base game's and create's are.
### 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_block",
"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 "cubi/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. undefined keeps the result it was given
after?(self: T, args: Parameters<T[K]>, result: ReturnType<T[K]>): ReturnType<T[K]> | void;
// 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 `cubi/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.
- `hook` only works while a mod's script loads or runs `setup`, which is how it knows the mod. Each side clears every
hook before it loads mods, so tests and a client joining another server start clean.
- The wrapper is rebuilt when hooks change, with only the steps they use, and the last unhook puts the original back.
- 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 `cubi/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
NeoForge has nothing like Bedrock's server forms, but they're the quickest way to ask a player something, so they stay,
built on [menus](modding/inventories/menus.md): each kind of form is a menu whose screen the engine provides, so they
need no client code. 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 form's definition is the menu's open data. A button press is a menu button with the button's index, and a modal
form sends its values with its submit button.
- The promise resolves with `canceled: true` when the menu closes any other way: the player closes it, disconnects, or
another menu replaces it.
- The engine checks every response against the form's definition (types, ranges, option counts, text length) before mod
code sees it.
### More Worn Items
Worn items are drawn by `render_worn`, which puts an item's `worn` model on a player's parts. The same can show more:
- **Mobs' equipment.** `EntityData.equipment` is already synced but never drawn. `render_worn` can draw it on mod
entities whose bones are named like a humanoid's, and held items in their `right_arm`, like Minecraft's
`ItemInHandLayer`.
- **Other players' held items**, in their right hand the same way.
- **Hiding curio slots**, like Curios' render toggles, sent by the client and kept by the curios script.
- **A third person view.** Players would see what they wear themselves with nothing else to change, the local player has
`worn` too.
- **Glint and glowing overlays**, as `glint` and a full bright `overlay_texture` in `worn`, once the renderer has a
glint pass.
### 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`; `cubi: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 type `shaped` | 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 and ores | `mods/bworld/worldgen/` (data) | Done |
| Trees | `mods/bworld/scripts/trees.ts` (a code feature) | Done |
### 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 doesn't change by accident.** Every chunk generated is saved whole, like Minecraft, so a change to
generation only shows in chunks not generated yet, with seams where they meet saved ones.
`tests/worldgen_golden_test.ts` hashes 64 chunks for each of 3 seeds against `tests/fixtures/worldgen_golden.json`,
so it's never a surprise. A change meant to change generation records it again
(`deno test -A tests/worldgen_golden_test.ts -- --update`).
3. **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 16 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.
- **Generation.** Chunks are generated in worldgen workers (`server/game/worldgen_worker.ts`), a few by default and
`WORLDGEN_WORKERS` on the dedicated server, 0 for none. Each tick the game asks them for what the nearest chunks each
player is waiting for are built from, nearest first, and only sends a chunk once they've made it; entities and players
in a chunk they haven't made yet wait for it, like Minecraft's in chunks that aren't loaded. Each worker gets the
worldgen bundle (`common/worldgen_bundle.ts`: the mods' data generation reads and their worldgen scripts), so it makes
the same chunks as the game. The host starts them, since the game has no permissions to (see
`server/worldgen_workers.ts`), and they talk to the game through ports. Whatever needs a chunk right away, like a mod
script reading a block somewhere far, still generates it on the game thread: `/tps` shows how many chunks that was in
the last minute. `tools/chunk_loading_bench.ts` measures a player arriving somewhere new.
## 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_block`, 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 `cubi/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.** Keybinds, forms built on menus, 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.** Done, as data instead of a worldgen script with `register_terrain`: noises, density
functions, noise settings and biome sources in `mods/bworld/worldgen/` (see [Terrain](modding/worldgen/terrain.md)),
features that are code or data (bworld's trees and cacti are code, in its worldgen script), and generation in worldgen
workers (see [Chunk Streaming](#chunk-streaming)). The golden fixture checked every step made the same world block for
block, and the server refuses to start without the `bworld:overworld` generator.
**Done when** searching `client/`, `common/` and `server/` for `"bworld:` finds only `cubi: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
NeoForge's mods that only load on the client? 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.
- **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.
- **Biome rules or multi-noise?** Biome sources are ordered rules, which kept the old biomes exactly, but mods inserting
rules can step on each other in ways that are hard to see. Minecraft's multi-noise is easier to merge but would move
every biome border. A `minecraft:multi_noise` source could exist next to the rules, for mods and imported datapacks
that want it.
- **Should `register_terrain` stay?** It's still in the worldgen API, and only throws. Data covers bworld's terrain, but
a mod might want a generator that isn't density functions at all, like a flat or skyblock world. Keeping it means the
worldgen bundle also carries a terrain script, which workers can load the same way as features. Otherwise it goes.
- **Importing Minecraft's terrain.** Datapacks' noise settings assume a world from -64 to 320 and Minecraft's noises.
The formats are close enough that an importer could translate them, but the result wouldn't look like Minecraft's. Not
a goal for now.
- **Generation's loose ends.** The packaged desktop build hasn't been tried with the worldgen worker, which the desktop
task includes. In a world without land, the spawn search looks 32 chunks out on the game thread, which the server now
does at startup. Saved chunks are read on the game thread, which waits for the host (see `read_chunk` in
`server/game/worker.ts`): much faster than generating them, but Minecraft reads them ahead instead.