Update modding docs

This commit is contained in:
2026-09-29 23:29:14 -03:00
parent f0cf4e4eeb
commit 1ac7a5c943
50 changed files with 2672 additions and 1924 deletions
+71
View File
@@ -0,0 +1,71 @@
# Events
Events let a server script react to what happens in the game, and stop some of it from happening. They're the
alternative to [components](../blocks/components.md) when the behavior isn't tied to one block or item: logging chat,
protecting spawn, or reacting to every block broken anywhere.
## Before and After
Every event is a signal you subscribe to. Events come in two kinds:
- **Before events** fire before something happens. A handler can read the event, change some of its fields, and set
`cancel = true` to stop it.
- **After events** fire once it has happened. They're for reacting, and can't change anything.
```ts
import type { ServerContext } from "bworld/server";
export function setup(ctx: ServerContext) {
// nobody breaks blocks within 16 blocks of the world's center
ctx.events.before.block_break.subscribe((event) => {
const { x, z } = event.block;
if (Math.abs(x) < 16 && Math.abs(z) < 16) {
event.cancel = true;
event.player.send_message("Spawn is protected");
}
});
ctx.events.after.player_join.subscribe(({ player }) => {
player.send_message(`Welcome, ${player.name}!`);
});
}
```
`subscribe` returns a function that unsubscribes the handler.
When a before event cancels a player's break or place, the server tells that player's client to undo what it already
showed. These events fire for **every** player's actions, since they all go through the server.
> [!TIP]
> Change the world in an after event, not a before one: other handlers may still cancel the action. If a before event
> needs something to happen afterwards, schedule it with `ctx.system.run_timeout(fn, 0)`.
## The Events
| Event | Before | After | Fields |
| ---------------- | ------ | ----- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `block_break` | ✓ | ✓ | `player`, `block` (with its tile `data`), `item` held |
| `block_place` | ✓ | ✓ | `player`, `block` (`{ id, x, y, z }`), `face` clicked, `item` held |
| `block_interact` | ✓ | ✓ | `player`, `block`, `item` held. Before fires for every right click on a block, after only when a component's `on_interact` handled it |
| `chat_send` | ✓ | ✓ | `player`, `message`. Before handlers can change `message` |
| `player_damage` | ✓ | | `player`, `amount`, `cause`. Before handlers can change `amount` |
| `player_death` | | ✓ | `player`, `cause`. They've dropped what they carried and respawn right after |
| `player_join` | | ✓ | `player` |
| `player_leave` | | ✓ | `player` |
| `server_start` | | ✓ | none. Every mod's `setup` has run |
| `tick` | | ✓ | `dt`, in seconds. 20 times a second |
| `new_day` | | ✓ | `day`. At 06:00, after every block's `on_new_day` |
`cause` is `"fall"`, `"void"`, `"starve"`, or whatever a mod passed to `player.damage(amount, cause)`.
### Order
Handlers run in the order they subscribed, and mods' `setup` functions run in [load order](registries.md#loading). For
`block_interact`, the before event runs first, then the block's own components' `on_interact`. If no component handled
the click and the held item has no `on_use`, the held block is placed, which fires `block_place`.
## Errors
A handler that throws is logged under its mod's id (`[copper_tools] an event handler threw: ...`) and skipped. The other
handlers and the action itself go on as if it hadn't been there. Component handlers, commands and timers are guarded the
same way, so one broken mod doesn't stop the server.
+56
View File
@@ -0,0 +1,56 @@
# Registries
Every block, item, block model, entity, entity model and texture has an id, and is registered under it once, while mods
load. After that the game refers to things only by their id.
## Identifiers
An id looks like `namespace:name`, like `farmersdelight:cabbage`:
- `namespace` is the id of the mod that registers it, 1-32 characters of `a-z`, `0-9` and `_`.
- `name` is `a-z`, `0-9` and `_`.
- A mod only registers ids in its own namespace. It can _refer to_ any id, like using `bworld:planks` in a recipe.
- Registering an id that's already registered, by the same mod or another, is an error.
Two namespaces are reserved:
- `bworld` belongs to the base game, `mods/bworld`.
- `engine` belongs to the engine: the missing texture `engine:missing`, the breaking cracks `engine:break_0` to
`engine:break_8`, and the built-in block models `engine:cube`, `engine:cross` and `engine:crop`.
`bworld:air` is the one exception: it's the engine's empty block, but keeps that id because every save has it.
The same id can name different kinds of thing. A block registers an item with the same id unless it sets
`"item": false`, and its texture is often named the same too.
## Loading
The server and every client load mods the same way, in the same order:
1. **Order.** Dependencies come before the mods that need them, and otherwise mods load alphabetically. Mods that depend
on each other in a circle are an error. The server sends its order to clients, and they follow it.
2. **Data**, one mod at a time: its block models, blocks (and their items), items, entity models, entities, then recipes
and ores.
3. **Scripts.** Server scripts' `setup` runs on the server, and client scripts' on each client. Worldgen scripts'
`setup` runs on the server before it makes chunks.
Scripts read the registries but can't add to them. Content comes from data files.
> [!IMPORTANT]
> The server and the client must end up with exactly the same blocks, items and recipes. They do as long as content is
> only data, since both load the same files in the same order.
## Numeric Ids
Blocks get a number when they register, and chunks store those numbers. Numbers are **local to one running program**:
the server and each client can number blocks differently, so saves and the network always use string ids. When a player
joins, the server sends its list of block ids, and the client translates chunks into its own numbers as they arrive.
The practical rule: never save or send a block's number. Use its id.
## Changing What Exists
Ids never change and blocks and items can't be removed, because saves refer to them. A world saved with your mod
installed keeps your ids in its chunks, inventories and chests, so renaming a block breaks those worlds.
To retire something, stop it from being obtainable: take away its recipes and drops.
+37
View File
@@ -0,0 +1,37 @@
# Security
A server runs code from every mod it has installed, and so does every player who joins it. This page is what each of
them trusts, and what a mod should never trust.
## Players Are Untrusted
Anything a client sends can be forged by a player who edits their client. The engine already checks what it handles:
reach and the held item for every break, place and interact, and container rules (slot filters, output-only slots) on
the server. A mod's own logic has to do the same:
- Decide on the server. Client scripts show things. Server scripts decide what happens.
- Check permissions on the server, in the server script, before acting for a player, like `requires` on a
[command](../misc/commands.md).
- Never use a value from a client as an item id, a count or a position without checking it.
Server script code and tile data are never sent to clients, so a mod can keep anti-cheat logic or secrets there.
## Server Scripts
Server scripts run in the game worker with **no Deno permissions**: they can't read files, open connections or run
programs. Everything they can do goes through the mod API. Installing a server mod still means trusting it with the game
world and everything players send.
## Client Scripts
Client scripts run in the game page with the page's full access. How much that matters depends on where the page came
from:
- **The page was served by the game server** (the default). That server already chose every line of JavaScript on the
page, so running its mods doesn't trust it any more than loading the page did.
- **The page is from one site and the game server from another** (a server typed in on the title screen, or `?server=`).
Mod code from that server runs with _the page's_ origin, including its local storage. So the client lists the server's
mods and asks before loading anything, and remembers the answer per server and mod.
Every `.bmod` a client downloads is checked against the SHA-256 the server listed, and scripts are run from the checked
bytes. That guarantees the files are the ones the server listed. It doesn't protect against a malicious server.
+95
View File
@@ -0,0 +1,95 @@
# Sides
bworld is always a client connected to a server, even when you play alone. The server runs the game and the client shows
it. Knowing which of your code runs where, and what each side can see, is most of what keeps a mod correct.
## The Server Is the Authority
Clients send what the player is _trying_ to do: "break the block at x, y, z", "use the block I'm looking at", "click
slot 3". The server checks it (reach, the item being held, container rules), runs mod logic, and sends back what
happened.
For responsiveness, the client guesses the result of breaking and placing blocks and shows it right away. When the
server disagrees, like when a before event cancels a placement, it sends that player the real block and the guess is
undone. Blocks with `"interactive": true` tell the client not to guess, since right clicking them does something other
than placing.
```
server process browser
┌───────────────────────────────────────┐ ┌──────────────────────────────────┐
│ host: http, websocket, files │ │ game client (rendering, input) │
│ ┌───────────────────────────────────┐ │ ws │ + mods' client scripts │
│ │ game server worker │◄├──────────┤► │
│ │ world, inventories, tile data │ │ protocol │ chunk workers (meshing, light) │
│ │ + mods' server scripts │ │ chunks └──────────────────────────────────┘
│ │ + mods' worldgen scripts │ │
│ └───────────────────────────────────┘ │
└───────────────────────────────────────┘
```
## The Three Scripts
| Script | Runs on | Sent to players | For |
| ---------- | -------------------------------- | --------------- | ------------------------------------------------------------------- |
| `server` | the server, in the game worker | **never** | game logic: block and item components, events, commands, containers |
| `client` | every player's browser | yes | presentation: inventory overlays, and later custom screens and HUD |
| `worldgen` | the server, when it makes chunks | no | features that decorate terrain, deterministic |
Data (blocks, items, models, recipes, entities, textures) isn't a script: it's registered the same way on the server and
on every client, before any script runs. See [Registries](registries.md).
### Server Scripts
```ts
import type { ServerContext } from "bworld/server";
export function setup(ctx: ServerContext) {
// register components and commands, subscribe to events
}
```
`setup` runs once when the server starts, after every mod's data is registered. Components and commands can only be
registered during `setup`. Everything else on `ctx` works for as long as the server runs, from timers, events and
component handlers.
The game worker has **no Deno permissions**: no files, network or subprocesses. State that should last goes in the
world, through [tile data](../blocks/tiledata.md), [containers](../inventories/containers.md) and
[`ctx.storage`](../datastorage/index.md), which are saved with it.
### Client Scripts
```ts
import type { ClientContext } from "bworld/client";
export function setup(ctx: ClientContext) {
ctx.ui.add_inventory_overlay({ on_render(g, screen) {/* ... */} });
}
```
`setup` runs after the client has downloaded the server's mods and before the world appears. Client scripts are for
presentation. They can read what the client sees (`ctx.world.get_block`, `ctx.player.position`, items, recipes) but
can't change the world or inventories.
Client code is visible to players and can be changed by them. Never trust it for anything that matters. See
[Security](security.md).
### Worldgen Scripts
Worldgen scripts register features that run on every chunk the server generates. They must be deterministic: the same
seed and chunk always give the same blocks. See [World Generation](../worldgen/index.md).
## What Each Side Knows
| Data | Server | Client |
| ------------------------------------------ | ------ | ------------------------------------------- |
| Block, item, entity and recipe definitions | yes | yes, the same |
| Blocks and their states | yes | chunks near the player |
| [Tile data](../blocks/tiledata.md) | yes | **never**, show it through a screen instead |
| A block's displayed item (`item_display`) | yes | yes, near the player |
| Item stacks and their `data` | yes | in containers the player has open or owns |
| Entities | yes | near the player |
| `ctx.storage` | yes | no |
| Server script code | yes | **never** |
When a client needs to see something only the server has, the server has to send it: open a
[container screen](../inventories/menus.md), put it in an item's `data`, or set a block state the block's model shows.