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
+54 -1880
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,6 +1,6 @@
import type { ServerAddress, Welcome } from "./handshake.ts";
// asks before running a server's mods when the page came from somewhere else, see "Security" in MODS.md.
// asks before running a server's mods when the page came from somewhere else, see docs/modding/concepts/security.md.
// resolves with whether the player wants to join
export function confirm_mods(address: ServerAddress, welcome: Welcome): Promise<boolean> {
return new Promise((resolve) => {
+1 -1
View File
@@ -1,4 +1,4 @@
// connecting to a server and getting what it needs before joining, see "Delivery to clients" in MODS.md:
// connecting to a server and getting what it needs before joining, see docs/modding/networking/index.md:
// hello -> welcome, download and check everything, ready -> join
import { ClientMessage, PROTOCOL_VERSION, ServerMessage } from "$/common/protocol.ts";
+1 -1
View File
@@ -114,7 +114,7 @@ class ClientLoop {
// can't go back to the title screen to try again, the page has to start over
class FailedAfterLoadingMods extends Error {}
// the game only runs against a server, it owns the world and everything in it. see "Delivery to clients" in MODS.md
// the game only runs against a server, it owns the world and everything in it. see docs/modding/networking/index.md
async function join_server(address: ServerAddress, name: string, status: (text: string) => void): Promise<Connection> {
const { socket, welcome } = await connect(address, name);
console.log(`Connected to ${address.ws_url}`);
+8 -6
View File
@@ -1,5 +1,5 @@
// loads the mods the server lists: downloads their .bmod files, registers their data, then runs their client scripts.
// see "Delivery to clients" in MODS.md
// see docs/modding/networking/index.md
import { AIR } from "$/common/constants.ts";
import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
import type { ClientContext, InventoryOverlay } from "$/common/mod_api/client.ts";
@@ -75,7 +75,9 @@ function client_context(listing: ModListing): ClientContext {
const not_yet = (name: string, where: string) =>
new Proxy({}, {
get: (_, prop) => () => {
throw new Error(`[${mod}] ctx.${name}.${String(prop)} isn't implemented yet (${where} in MODS.md)`);
throw new Error(
`[${mod}] ctx.${name}.${String(prop)} isn't implemented yet (${where}, see docs/modding_plan.md)`,
);
},
});
const need_client = () => {
@@ -84,7 +86,7 @@ function client_context(listing: ModListing): ClientContext {
};
const not_yet_fn = (name: string) => () => {
throw new Error(`[${mod}] ctx.ui.${name} isn't implemented yet (Custom screens in MODS.md)`);
throw new Error(`[${mod}] ctx.ui.${name} isn't implemented yet (custom screens, see docs/modding_plan.md)`);
};
const known_item = (id: string) => {
const item = EverythingRegistry.get<ItemRegistry>("items", id);
@@ -101,9 +103,9 @@ function client_context(listing: ModListing): ClientContext {
inventory_overlays.push({ mod, overlay });
},
},
hud: not_yet("hud", "step 7") as ClientContext["hud"],
input: not_yet("input", "step 8") as ClientContext["input"],
net: not_yet("net", "step 8") as ClientContext["net"],
hud: not_yet("hud", "HUD elements") as ClientContext["hud"],
input: not_yet("input", "keybinds") as ClientContext["input"],
net: not_yet("net", "mod channels") as ClientContext["net"],
player: {
get name() {
return need_client().connection.name;
+2 -2
View File
@@ -1,5 +1,5 @@
// .bmod files: a built mod in one zip, what servers load from server_mods/ and send to players. see "Mod files" in
// MODS.md. the same code reads them on the server and in the browser, so it only works on bytes
// .bmod files: a built mod in one zip, what servers load from server_mods/ and send to players. see
// docs/modding/gettingstarted/modfiles.md. the same code reads them on the server and in the browser, so it only works on bytes
import { unzipSync, zipSync } from "fflate";
import type { ModelJson } from "./block_models.ts";
import { MAX_TEXTURE_SIZE } from "./constants.ts";
+1 -1
View File
@@ -1,5 +1,5 @@
// how the server streams the world to clients, like minecraft java since 1.20.2: whole chunks in batches around each
// player, and which chunks are in a player's view. see "Chunks" in MODS.md
// player, and which chunks are in a player's view. see "Chunk Streaming" in docs/modding_plan.md
import { deflateSync, inflateSync } from "fflate";
import { CHUNK_AREA, CHUNK_HEIGHT } from "./constants.ts";
+1 -1
View File
@@ -1,6 +1,6 @@
// commands the way minecraft's brigadier (and so fabric's command api) does them: a tree of literal words and typed
// arguments, each argument type parsing its text and suggesting what could go there. the server runs them, and players
// get its suggestions as they type. see "Commands" in MODS.md
// get its suggestions as they type. see docs/modding/misc/commands.md
import { EverythingRegistry } from "./everything_registry.ts";
export interface Suggestion {
+1 -1
View File
@@ -19,7 +19,7 @@ const BASE_ORES: OreJson[] = [
{ id: "bworld:gold_ore", replaces: "bworld:stone", min_y: 5, max_y: 36, scale: 0.04, threshold: 0.7 },
];
// what mods add to generation, see "World generation" in MODS.md
// what mods add to generation, see docs/modding/worldgen/index.md
export interface WorldgenSetup {
ores: OreJson[];
features: { id: string; generate: (chunk: FeatureChunk) => void }[];
+2 -2
View File
@@ -1,4 +1,4 @@
// what client scripts get, see "Client scripts" and "GUIs" in MODS.md
// what client scripts get, see docs/modding/gui/index.md
import type { Id, ItemStack, KeyCode, ModInfo, Position } from "./shared.ts";
export type { Id, ItemStack, KeyCode, ModInfo, Position } from "./shared.ts";
@@ -25,7 +25,7 @@ export interface ClientContext {
// the mod that registered it
mod(id: Id): string;
};
// every recipe as its json (see Recipes in MODS.md), including mods' own types, in load order. copies
// every recipe as its json (see docs/modding/resources/recipes.md), including mods' own types, in load order. copies
recipes: {
// deno-lint-ignore no-explicit-any
list(type?: Id): any[];
+2 -2
View File
@@ -1,4 +1,4 @@
// what server scripts get, see "Server scripts" in MODS.md
// what server scripts get, see docs/modding/
import type { EventSignal, Face, Id, ItemStack, ModInfo, Position } from "./shared.ts";
import type { ArgumentType, CommandNode } from "../commands.ts";
@@ -61,7 +61,7 @@ export interface ComponentRegistry {
register_item<P>(id: Id, component: ItemComponent<P>): void;
}
// commands, fabric's (brigadier's) way: see common/commands.ts and "Commands" in MODS.md
// commands, fabric's (brigadier's) way: see common/commands.ts and docs/modding/misc/commands.md
// who ran a command
export interface CommandSource {
+1 -1
View File
@@ -1,4 +1,4 @@
// what worldgen scripts get, see "World generation" in MODS.md. runs in chunk workers and must be deterministic
// what worldgen scripts get, see docs/modding/worldgen/index.md. runs on the server and must be deterministic
import type { Id } from "./shared.ts";
export type { Id } from "./shared.ts";
+1 -1
View File
@@ -1,4 +1,4 @@
// the json formats from MODS.md, and converting them to and from the engine's registry entries.
// the json formats from docs/modding/, and converting them to and from the engine's registry entries.
// the mod loader uses the from_json direction, tests use both to check nothing is lost
import { is_tint_color, type TintColor } from "./worldgen/biome_colors.ts";
import {
+1 -1
View File
@@ -102,7 +102,7 @@ export type ClientMessage =
| { type: "suggest"; id: number; text: string };
export type ServerMessage =
// what to download before joining, see "Delivery to clients" in MODS.md
// what to download before joining, see docs/modding/networking/index.md
| {
type: "welcome";
protocol: number;
+1 -1
View File
@@ -21,7 +21,7 @@ export async function load_worldgen(scripts: { mod: string; url: string }[], ore
register_terrain(id) {
throw new ModLoadError(
mod,
`can't register terrain ${id}: the base terrain is still built into the engine (phase 3 in MODS.md)`,
`can't register terrain ${id}: the base terrain is still built into the engine (see docs/modding_plan.md)`,
);
},
};
+109
View File
@@ -0,0 +1,109 @@
# Block Components
A block's JSON says what it is. Components say what it _does_. A component is a set of handlers a server script
registers under an id. Any block that lists that id in its `components` gets that behavior, with its own parameters.
This is how every block that does something works, including the base game's chests, furnaces and crops. One component
can serve many blocks: every block with `bworld:storage` is a chest, with its own number of rows.
## Using a Component
List it in the block's `components`, with its parameters:
```json
"components": {
"bworld:storage": { "rows": 3 }
}
```
A block can list several. Their handlers run in the listed order.
## Registering a Component
In the server script:
```ts
import type { ServerContext } from "bworld/server";
interface OxidizesParams {
seconds: number;
into: string;
}
export function setup(ctx: ServerContext) {
ctx.components.register_block<OxidizesParams>("copper_tools:oxidizes", {
on_create(block) {
block.data = { age: 0 };
},
on_second(block, params) {
block.data.age += 1;
if (block.data.age >= params.seconds) {
ctx.world.set_block(block.x, block.y, block.z, params.into);
}
},
});
}
```
```json
"components": {
"copper_tools:oxidizes": { "seconds": 600, "into": "copper_tools:oxidized_copper_block" }
}
```
Components can only be registered during `setup`, and only in the mod's own namespace. Once every mod's `setup` has run,
a block or item that lists a component nobody registered stops the server from starting, naming the block and the
component.
## Handlers
| Handler | Called when | Returns |
| ------------------------------------ | ----------------------------------------------------------------- | -------------------------- |
| `on_create(block, params)` | The block is placed or set, by a player or a script. | |
| `on_break(block, params, player?)` | The block is broken or replaced. `player` when a player broke it. | |
| `on_click(block, params, player)` | A player starts hitting it. | |
| `on_interact(block, params, player)` | A player right clicks it. | `true` if it did something |
| `on_tick(block, params, dt)` | Every tick, 20 times a second, near a player. | |
| `on_second(block, params, dt)` | Every second, near a player. | |
| `on_new_day(block, params, day)` | Every morning at 06:00, anywhere in the world. | |
`block` is `{ id, x, y, z, data }`, where `data` is the block's [tile data](tiledata.md). `params` is what the block's
JSON lists for this component, and `dt` is in seconds.
### Interacting
When a player right clicks a block, every component's `on_interact` runs. If any of them returns `true`, the click was
handled and nothing else happens. Otherwise the held item is used or placed, as if the block had no components.
Give a block `"interactive": true` when right clicking it always does something, like opening a screen. Otherwise
clients guess that the click places the held block and show it for a moment before the server corrects them.
### Ticking
`on_tick` and `on_second` only run for blocks that **have tile data**, within 6 chunks of a player. So a component that
ticks from the start sets `block.data` in `on_create`, like `copper_tools:oxidizes` above.
`on_new_day` runs for every block with tile data in the whole world, near a player or not, so crops keep growing while
nobody's around. When time jumps forward past several mornings, like with `/time add`, each of them runs, up to the
last 64.
The server runs a fixed 20 ticks a second. When a tick takes too long, up to ten of the next ones run back to back to
catch up. If it's further behind than that, it skips the rest and logs a warning. `/tps` shows how it's keeping up.
## The Base Game's Components
`mods/bworld/scripts/server.ts` registers these, and any mod that depends on `bworld` can use them:
| Component | Params | What it does |
| ----------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `bworld:storage` | `rows` | A chest: `rows` × 9 slots, dropped when it's broken. |
| `bworld:furnace` | none | Smelts with `furnace` and `fuel` [recipes](../resources/recipes.md). Needs `lit` and `facing` states, see `blocks/furnace.json`. |
| `bworld:smithing_table` | none | Upgrades tools with `smithing` recipes. |
| `bworld:hoeable` | `tool`, `into` | Right clicking with a tool of type `tool` turns it into `into`, like a hoe on grass. |
| `bworld:farmland` | none | Watered with the watering can, dries out every morning. |
| `bworld:crop` | see [Crops](crops.md) | Grows a stage every morning its farmland was watered. |
| `bworld:crop_top` | see [Crops](crops.md) | The top half of a two block crop, like rice. |
| `bworld:water_source` | none | Refills the watering can. |
| `bworld:fishable` | none | Can be fished in with the fishing rod. |
Item components work the same way, see [Items](../items/index.md#item-components).
+120
View File
@@ -0,0 +1,120 @@
# Crops
A crop is a block with an `age` state, the base game's `bworld:crop` [component](components.md), and a seeds item that
places it. Adding one takes no code.
Crops grow on Stardew Valley's clock with Minecraft's rules: every morning at 06:00, a crop whose farmland was watered
the day before grows a day, then all farmland dries out. The crop shows the stage for how far along it is.
`mods/farmersdelight` adds its cabbages, onions, tomatoes and rice this way.
## A Basic Crop
`blocks/cabbages.json`, with one texture per stage through [variants](states.md#variants):
```json
{
"format_version": 1,
"block": {
"id": "farmersdelight:cabbages",
"model": "engine:cross",
"textures": { "cross": "farmersdelight:cabbages_stage0" },
"variants": {
"age=1": { "textures": { "cross": "farmersdelight:cabbages_stage1" } },
"age=2": { "textures": { "cross": "farmersdelight:cabbages_stage2" } }
},
"render_layer": "cutout",
"collision": false,
"mining": { "toughness": 0 },
"item": false,
"place_on": ["bworld:hoed_dirt"],
"states": [{ "name": "age", "bits": 3, "default": 0 }],
"components": {
"bworld:crop": {
"days": 12,
"stages": 8,
"fertilizer": "bworld:bone_meal",
"drops": {
"young": "farmersdelight:cabbage_seeds",
"mature": "farmersdelight:cabbage",
"bonus": "farmersdelight:cabbage_seeds"
}
}
}
}
}
```
`"item": false` because players plant the seeds, not the crop. `items/cabbage_seeds.json`:
```json
{
"format_version": 1,
"item": {
"id": "farmersdelight:cabbage_seeds",
"texture": "farmersdelight:cabbage_seeds",
"places": "farmersdelight:cabbages"
}
}
```
`place_on` keeps it on farmland, and it pops off when the farmland is dug up.
## Parameters
| Param | Meaning |
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `days` | Watered mornings from planting to fully grown. |
| `stages` | How many ages it shows, 0 to `stages - 1`, spread evenly over `days`. The `age` state must fit them. |
| `drops` | What it drops when broken: `young` before it's grown, `mature` once it is, and `bonus`, 1 to 4 of an item when grown (Minecraft's 1 plus 3 tries at 57%, like wheat's seeds). `young` and `mature` can be one id or a list. |
| `fertilizer` | An item that grows it a day right away when used on it, like bone meal. |
| `water` | `"farmland"` (the default) needs watered farmland under it. `"always"` grows every morning. |
| `regrow_days`, `harvest` | Right clicking it once grown picks it, dropping `harvest.item` (`count` is `[min, max]`), and it grows back after `regrow_days`. |
| `upper` | `{ block, stages, supporting_age }`: its last stages grow a second block on top, see below. |
| `leaves` | What the spot becomes when it's broken, like the water rice was planted in. |
## Harvesting By Hand
Tomatoes are picked instead of broken:
```json
"bworld:crop": {
"days": 11,
"stages": 8,
"regrow_days": 4,
"harvest": { "item": "farmersdelight:tomato", "count": [1, 2] },
"drops": {
"young": "farmersdelight:tomato_seeds",
"mature": ["farmersdelight:tomato", "farmersdelight:tomato_seeds"]
}
}
```
## Two Block Crops
Rice grows in water and, once it's tall enough, grows panicles on top. The crop stays at `supporting_age` while the top
block goes through its own `stages`:
```json
"place_in": ["bworld:water"],
"place_on": ["bworld:dirt", "bworld:grass", "bworld:hoed_dirt"],
"components": {
"bworld:crop": {
"days": 6,
"stages": 4,
"water": "always",
"upper": { "block": "farmersdelight:rice_panicles", "stages": 4, "supporting_age": 4 },
"leaves": "bworld:water",
"drops": { "young": "farmersdelight:rice", "mature": "farmersdelight:rice" }
}
}
```
The top block uses `bworld:crop_top` with its own `stages` and `drops`. Breaking either half harvests the whole plant:
```json
"components": {
"bworld:crop_top": { "stages": 4, "drops": { "mature": "farmersdelight:rice_panicle" } }
}
```
Since water is `replaceable` and rice has `place_in`, players plant rice by clicking the water itself.
+106
View File
@@ -0,0 +1,106 @@
# Blocks
Blocks make up the world. Each kind of block is defined once, in a JSON file in the mod's `blocks/` folder, and the
world is made of references to those definitions at different positions.
A block's definition says how it looks, how it's mined and what it drops. What it _does_ comes from
[components](components.md), which server scripts register.
## A Basic Block
`blocks/copper_block.json`:
```json
{
"format_version": 1,
"block": {
"id": "copper_tools:copper_block",
"textures": "copper_tools:copper_block",
"mining": { "toughness": 5, "tool": "pickaxe", "requires_tool": true, "tier": 1 },
"drops": "copper_tools:copper_block"
}
}
```
This registers the block and an item with the same id that places it. It's a full cube with the same texture on every
side, takes 5 seconds to break by hand, breaks faster with a pickaxe, and only drops itself when broken with a pickaxe
of tier 1 (stone or copper) or better.
## Properties
### Looks
| Field | Default | Meaning |
| ---------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | required | The block's id. |
| `name` | from the id | What players see. `copper_tools:copper_block` is "Copper Block" when not set. Its item uses it too. |
| `textures` | required | One texture id for every side, `{ "top", "bottom", "side" }`, or `{ "front", "side" }` (optionally with `top` and `bottom`) for a block that faces a way. With another `model`, the model's texture variables. |
| `model` | `engine:cube` | The [block model](../resources/models.md). |
| `variants` | none | Other models, textures or rotations for some [states](states.md). |
| `render_layer` | `solid` | `solid`; `cutout` for texels that are fully opaque or fully clear, like leaves; `translucent` for blended ones, like water and glass. |
| `cull_same` | see meaning | Hide the faces between two of this block. `true` for translucent blocks, `false` otherwise. |
| `alpha` | `1` | Opacity, for translucent blocks. |
| `tint` | none | Draws its textures in a color, see [below](#tinting). |
| `light_emission` | `0` | Light it gives off, 0-15. A torch is 14. |
| `light_opacity` | see meaning | How much light passing through it loses, 0-15. `15` for solid blocks, `0` otherwise. Leaves and water use `1`. |
Only `solid` blocks hide their neighbors' faces. Blocks that aren't full cubes, like plants, should use `cutout`, or
there will be holes in the world behind them.
### Behavior
| Field | Default | Meaning |
| ---------------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `collision` | `true` | Whether entities bump into it. Plants and water set `false`. |
| `mining.toughness` | unbreakable | Seconds to break by hand. Without `mining`, a block can't be broken. |
| `mining.tool` | none | The [tool type](../items/tools.md) that breaks it faster, like `pickaxe`, `axe` or `shovel`. |
| `mining.requires_tool` | `false` | Only drops when broken with `mining.tool`. |
| `mining.tier` | `0` | With `requires_tool`, the lowest tool tier it drops for. Iron ore is `1`, so a wood pickaxe gets nothing. |
| `drops` | nothing | The item id it drops when broken. |
| `item` | `true` | Also register an item that places it, with the same id. |
| `interactive` | `false` | Right clicking it does something, like opening a screen, so clients don't guess that it places a block. |
| `replaceable` | `false` | Placing a block into it replaces it, like water. |
| `place_in` | see meaning | Block ids it can be placed into, replacing them, like `["bworld:water"]` for rice. Air and `replaceable` blocks when not set. |
| `place_on` | anywhere | Block ids it can stand on, like `["bworld:hoed_dirt"]` for crops. See [below](#placement). |
| `states` | none | Named [state](states.md) bits, like a crop's age. |
| `components` | none | [Components](components.md) and their parameters. |
| `item_display` | none | Shows an item on top of it, see [Tile Data](tiledata.md#showing-an-item). |
A block's definition goes to every player, since clients need it to draw the block, time breaking and collide with it.
It can't hold functions.
## Mining
Breaking takes `mining.toughness` seconds by hand. A tool whose type matches `mining.tool` breaks it `tool.speed` times
faster. The client times breaking itself, and the server checks the result.
When it breaks, the block's components' `on_break` runs and it drops `drops`, unless it has `requires_tool` and the
player's tool is the wrong type or a tier below `mining.tier`.
## Placement
Players place a block by right clicking a face of another block with its item. It goes next to the face they clicked, or
into the clicked block itself when that one is `replaceable`, like water.
It's only placed when:
- the spot is one it can go into: air or a `replaceable` block, or one of `place_in`,
- the block under the spot is one of `place_on`, when the block has `place_on`,
- and, for blocks with collision, no player or mob is in the way.
A block with `place_on` also pops off (dropping what it drops) when the block under it becomes something else, like a
crop when its farmland is dug up.
Food that places a block, like potatoes, is planted when clicked somewhere it can go and eaten otherwise.
## Tinting
`tint` draws a block's textures in a color, for textures painted in greys:
```json
"tint": { "color": "grass", "textures": ["top"] }
```
`color` is `"grass"` or `"foliage"` for the biome's color, blended across biome borders like Minecraft's grass and
leaves, or a fixed color like `"#80a755"`. `textures` lists the texture variables to tint, like only the grass block's
top. Without it every texture is tinted. In inventories, where there's no biome, the block uses plains' color.
+88
View File
@@ -0,0 +1,88 @@
# Block States
A block's states are a few named numbers stored with each copy of it in the world, like a crop's growth stage or which
way a furnace faces. They're saved with the world, synced to players, and can change how the block looks through
`variants`.
States are for small values the client needs, like what to draw. For anything else a block keeps, use
[tile data](tiledata.md).
## Declaring States
```json
"states": [
{ "name": "age", "bits": 3, "default": 0 },
{ "name": "facing", "bits": 2, "default": 0 }
]
```
Each state is `bits` wide, so `age` above holds 0 to 7. A block has at most 16 bits of state in total. It starts with
the defaults when it's placed or generated.
## Reading and Changing States
Server scripts use `ctx.world`:
```ts
const age = ctx.world.get_state(x, y, z, "age") ?? 0;
ctx.world.set_state(x, y, z, "age", age + 1);
```
`get_state` is `undefined` where there's no block, and `set_state` does nothing there and returns `false`. Both throw
for a state the block doesn't have, and `set_state` for a value that doesn't fit its bits. Changes are synced to
everyone who can see the block. Unlike `set_block`, it doesn't run `on_break` or `on_create`, and the block keeps its
tile data.
## Variants
`variants` gives a block a different `model`, `textures` or rotation depending on its states. `blocks/wheat.json` shows
a texture per growth stage:
```json
{
"format_version": 1,
"block": {
"id": "bworld:wheat",
"model": "engine:crop",
"textures": { "crop": "bworld:wheat_stage_0" },
"variants": {
"age=1": { "textures": { "crop": "bworld:wheat_stage_1" } },
"age=2": { "textures": { "crop": "bworld:wheat_stage_2" } }
},
"render_layer": "cutout",
"collision": false,
"states": [{ "name": "age", "bits": 3, "default": 0 }]
}
}
```
- A key is a condition on the block's states: `"age=3"`, or `"age=3,facing=1"` when all of them have to match. `""`
matches always.
- A variant sets any of `model`, `textures` and `y`, a turn around the vertical axis of 0, 90, 180 or 270 degrees,
clockwise seen from above.
- **Each of the three comes from the first matching variant that sets it.** So one variant can turn the block and a
later one change its textures, and both apply.
- What no matching variant sets comes from the block itself.
## Facing
A block with a `facing` state of at least 2 bits faces the player who places it: `facing` is set from which way they
look, 0 to 3. Pair it with turning variants, like the furnace:
```json
"textures": { "front": "bworld:furnace_front", "side": "bworld:furnace_side", "top": "bworld:furnace_top", "bottom": "bworld:cobblestone" },
"variants": {
"facing=1": { "y": 90 },
"facing=2": { "y": 180 },
"facing=3": { "y": 270 },
"lit=1": { "textures": { "front": "bworld:furnace_front_lit", "side": "bworld:furnace_side", "top": "bworld:furnace_top", "bottom": "bworld:cobblestone" } }
},
"states": [
{ "name": "lit", "bits": 1, "default": 0 },
{ "name": "facing", "bits": 2, "default": 0 }
]
```
A lit furnace facing east matches both `facing=1` (its turn) and `lit=1` (its textures).
Turning also turns a [displayed item](tiledata.md#showing-an-item), like the knife on Farmer's Delight's cutting board.
+73
View File
@@ -0,0 +1,73 @@
# Tile Data
Tile data is extra data kept for one block in the world, like what a chest holds or how far along a furnace is. It's
bworld's version of Minecraft's block entities: a [block state](states.md) is a few bits every client knows, while tile
data is any JSON value that only the server knows.
## Reading and Writing
A [component](components.md)'s handlers get the block's data as `block.data`. It's `undefined` until a handler sets it,
and it can be any JSON value:
```ts
ctx.components.register_block("copper_tools:counter", {
on_create(block) {
block.data = { clicks: 0 };
},
on_interact(block, _params, player) {
block.data.clicks += 1;
player.send_message(`Clicked ${block.data.clicks} times`);
return true;
},
});
```
Outside a handler, `ctx.world.get_block_data<T>(x, y, z)` reads it.
- Tile data is saved with the world, and goes away when the block is broken or replaced.
- It's **never sent to clients**. To show it to a player, open a [container screen](../inventories/menus.md), or change
a block state that the block's `variants` show.
- Only blocks with tile data run `on_tick`, `on_second` and `on_new_day`.
## Blocks With Containers
A block that holds items keeps a [container](../inventories/containers.md) and stores its id in tile data. Containers
are saved until they're deleted, so the block deletes it when it's broken, after dropping what's inside:
```ts
ctx.components.register_block("copper_tools:crate", {
on_create(block) {
block.data = { container: ctx.containers.create(9).id };
},
on_break(block) {
const container = ctx.containers.get(block.data.container);
if (!container) return;
for (let slot = 0; slot < container.size; slot++) {
const item = container.get(slot);
if (item) ctx.world.drop_item(block.x, block.y, block.z, item);
}
ctx.containers.delete(container.id);
},
});
```
The base game's `bworld:storage` does exactly this, see `mods/bworld/scripts/server.ts`.
## Showing an Item
A block with `item_display` draws one item lying on top of it, like the food on Farmer's Delight's cutting board:
```json
"item_display": { "surface": 1 }
```
`surface` is the height in pixels the item lies at, 0 to 16. The server script sets the item:
```ts
ctx.world.set_block_item(x, y, z, { id: "farmersdelight:cabbage", count: 1 });
const shown = ctx.world.get_block_item(x, y, z); // a copy, or undefined
ctx.world.set_block_item(x, y, z, undefined); // shows nothing
```
Unlike the rest of tile data, the displayed item is synced to players. It's saved with the block, turns with the block's
`y` variant, and disappears with the block without dropping, so drop it in `on_break` if it should.
+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.
+43
View File
@@ -0,0 +1,43 @@
# Saving Data
Server scripts have no file access, so everything a mod keeps goes through the world, and is saved with it. Pick the
place by what the data belongs to:
| Data belongs to | Keep it in | Sent to players |
| ---------------------------- | ---------------------------------------------------- | ----------------------- |
| one block | its [tile data](../blocks/tiledata.md), `block.data` | never |
| one block, small and visible | a [block state](../blocks/states.md) | yes |
| a set of items | a [container](../inventories/containers.md) | while a screen shows it |
| one item stack | the stack's `data` | with the stack |
| the whole mod | `ctx.storage` | never |
Everything here must be plain JSON: objects, arrays, strings, numbers, booleans and `null`. No classes, `Map`s or
functions.
## Mod Storage
`ctx.storage` is a small key value store for each mod, saved with the world:
```ts
interface ModStorage {
get<T>(key: string): T | undefined;
set(key: string, value: unknown): void; // JSON values only
delete(key: string): void;
}
```
```ts
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
belongs in that block's tile data, which goes away with the block.
## What Isn't Saved
- Variables in a script. Everything in memory is gone when the server restarts, so rebuild it in `setup` from what was
saved.
- [Timers](../misc/time.md#timers).
- Scripted [entities](../entities/index.md#behaviors), like the fishing hook.
- `get_lore` text, which is worked out each time a stack is sent.
+97
View File
@@ -0,0 +1,97 @@
# Entities
Entities are the things in the world that aren't blocks and move on their own: animals, dropped items, the fishing hook,
and players. Mods define new kinds in their `entities/` folder, and draw them with a model from `models/`.
## Defining an Entity
`entities/chicken.json`:
```json
{
"format_version": 1,
"entity": {
"id": "bworld:chicken",
"model": "bworld:chicken",
"texture": "bworld:chicken",
"width": 0.3,
"height": 0.4,
"max_health": 4,
"movement_speed": 0.25
}
}
```
| Field | Default | Meaning |
| ----------------- | ---------- | ------------------------------------------------------------------------------------------------------ |
| `id` | required | The entity's id. |
| `texture` | required | Any texture, stretched over the model's `texture_width` and `texture_height`. |
| `model` | none | An [entity model](#entity-models). Without one it's drawn as its texture, facing the camera. |
| `behavior` | `"animal"` | `"animal"` or `"scripted"`, see below. |
| `width`, `height` | required | Its collision box in blocks, up to 16. `width` is for both x and z. Its eyes are at 85% of the height. |
| `max_health` | `10` | In half hearts. |
| `movement_speed` | `0.25` | Minecraft's per tick speed, 0.25 for most animals. |
`/summon <entity>` spawns one where you stand.
## Behaviors
**Animals** (the default) are mobs: they wander around, panic when hurt, look at players now and then, swim up in water,
and never despawn. They're saved with the world, and players can't place solid blocks where one is standing.
**Scripted** entities stay exactly where a script puts them. They don't fall, think or get hurt, and aren't saved with
the world, so a script never finds one it doesn't know about after a restart. The fishing hook is one:
```json
{
"format_version": 1,
"entity": {
"id": "bworld:fishing_hook",
"texture": "bworld:fishing_hook",
"behavior": "scripted",
"width": 0.25,
"height": 0.25
}
}
```
## Spawning From Scripts
```ts
const hook = ctx.world.spawn_entity("bworld:fishing_hook", x, y, z); // feet at x, y, z
hook.teleport(x, y + 0.1, z);
if (!hook.removed) hook.remove();
```
`spawn_entity` throws for a kind that doesn't exist, and returns an `EntityRef`:
```ts
interface EntityRef {
readonly id: string; // this entity's own id
readonly type: string; // its kind, like "bworld:fishing_hook"
readonly position: { x: number; y: number; z: number };
readonly removed: boolean;
teleport(x: number, y: number, z: number): void;
remove(): void;
}
```
Once an entity is removed, by a script or anything else, it stays removed, and teleporting it does nothing. Check
`removed` before relying on one you kept from earlier.
## Entity Models
Entity models are `models/<name>.geo.json`, as Blockbench exports them for Bedrock (the "Bedrock Entity" format), and
get the id `<mod id>:<name>`. From the file's first geometry, bworld uses:
- the description's `texture_width` and `texture_height`,
- each bone's `name`, `parent`, `pivot` and `rotation`,
- each cube's `origin`, `size`, `uv` and `inflate`.
Cubes need box UV: per face UV isn't supported. A bone's parent has to come before it. The model faces -z, 16 pixels to
a block with its feet at 0, and shows the way Blockbench shows it.
Models don't animate yet. The whole model turns with the entity, and a bone named `head` turns to where it looks.
Without a model, the whole texture is drawn facing the camera, 16 pixels to a block, centered on the middle of the
entity's box.
+64
View File
@@ -0,0 +1,64 @@
# Players
Server scripts see players as `Player` objects: in events, in component handlers, from `ctx.players`, and as the source
of a command.
## Finding Players
```ts
ctx.players.all(); // everyone online
ctx.players.get(id); // by id, undefined when they're offline
ctx.players.by_name("alice");
```
A `Player` is only valid while they're online. Keep their `id` or `name`, not the object, and look them up again later.
## The Player API
```ts
interface Player {
readonly id: string;
readonly name: string;
readonly position: { x: number; y: number; z: number }; // their feet
readonly inventory: Container; // 36 slots, the hotbar is 0-8
readonly selected_slot: number;
readonly held_item: ItemStack | undefined;
give_item(id: string, count?: number, data?: unknown): void; // what doesn't fit drops at their feet
send_message(text: string): void;
teleport(x: number, y: number, z: number): void;
readonly health: number; // out of max_health
readonly max_health: number; // 20
readonly food: number; // hunger, out of 20
readonly saturation: number; // never above food
damage(amount: number, cause?: string): void;
heal(amount: number): void;
feed(nutrition: number, saturation_modifier: number): void;
add_exhaustion(amount: number): void;
}
```
`inventory` is a live [container](../inventories/containers.md), and `held_item` a live stack: changing them changes
what the player has.
## Health and Hunger
Players follow Minecraft's rules, with 20 health (10 hearts) and 20 hunger:
- **Exhaustion** comes from sprinting, swimming, jumping, breaking blocks, taking damage and healing. Every 4 costs a
point of saturation, or of hunger once saturation is gone.
- **Healing** happens on a full stomach: quickly while there's saturation, slowly with at least 18 hunger.
- **Starving**: at 0 hunger they lose health every 4 seconds, down to half a heart.
- **Falling** hurts 1 per block after the first 3, unless they land in water.
- **The void**: below the world, they keep taking damage until they die.
`damage(amount, cause)` hurts them like anything else would. `cause` shows in the `player_damage` and `player_death`
[events](../concepts/events.md) and in the death message. Before events can change the amount or cancel it.
## Death
When a player dies, everything they carried falls out where they died, and their tools lose durability (see
[Tools](../items/tools.md#durability)). They respawn at spawn right away with full health and hunger, and `player_death`
fires.
+106
View File
@@ -0,0 +1,106 @@
# Getting Started
This section covers making a new mod, checking it, and running it on a local server.
## Prerequisites
- Familiarity with TypeScript (or JavaScript). Scripts can be `.ts` or `.js`, and the mod API is typed.
- [Deno](https://deno.com). Every tool in this repository runs through `deno task`.
- A clone of the bworld repository. Mods live in its `mods/` folder while you work on them.
bworld is always played on a server, with no single player mode. A mod is installed **on the server** only. Players who
join download its client code, data and textures from that server automatically, so they never install anything
themselves.
## Creating a Mod
```sh
deno task new-mod copper_tools "Copper Tools"
```
This copies `templates/mod` to `mods/copper_tools` and fills in the id and name. The template has one of everything: a
block with a custom component, an item, a shaped recipe, two textures, and a server, client and worldgen script. Delete
what you don't need, along with its entry in `manifest.json`.
The first argument is the mod's id, its [namespace](../concepts/registries.md#identifiers). It has to match the folder
name.
> [!TIP]
> The mods already in the repository are the best reference. `mods/bworld` is the base game itself, written against the
> same API as any other mod. `mods/farmersdelight` adds crops, a stove, a cooking pot and a cutting board, and
> `mods/recipe_viewer` is a client-only mod that draws over inventory screens.
## Checking Your Mod
```sh
deno task check-mods
```
This checks every mod in `mods/`:
- the manifest and every data file, against the formats in these docs,
- that every block, item, model and entity model a mod refers to exists,
- that textures exist (a missing one is a warning, since it shows as the missing texture instead of failing),
- that a mod lists the mods whose ids it uses in its `dependencies` (a warning),
- that ids are in the mod's own namespace, and that no two mods register the same id,
- that the scripts typecheck against the API types.
Folders in `mods/` starting with `_` or `.` are skipped, which is handy for parking a mod you aren't working on.
## Building and Running
```sh
deno task build # packs every mod in mods/ into server_mods/<id>.bmod, and builds the client
deno task server # starts a server with every .bmod in server_mods/
```
`build` refuses to pack a mod that has errors. The server checks every `.bmod` again when it starts, and a problem in
any mod stops it from starting, naming the mod and what's wrong. The game never runs with some mods missing.
Open the server's address in a browser to play. To try a change, rebuild and restart the server, then rejoin. Leaving a
server reloads the page, so no old mod code stays loaded.
### Useful Commands In Game
| Command | What it does |
| ---------------------- | ------------------------------------------------------- |
| `/give <item> [count]` | Gives you an item |
| `/summon <entity>` | Spawns an entity where you stand |
| `/time set <when>` | Jumps to `day`, `noon`, `sunset`, `night` or `midnight` |
| `/time add <ticks>` | Moves time forward, running every morning it passes |
| `/help` | Lists every command |
See [Commands](../misc/commands.md) for the rest, and for adding your own.
## Testing
`deno task test` runs the repository's tests. `tests/helpers.ts` has `test_game`, which starts a real game server with
the mods in a folder and lets a test join as a player and send what a client would:
```ts
import { assertEquals } from "@std/assert";
import { test_game } from "./helpers.ts";
Deno.test("a hoe turns grass into farmland", async () => {
const { game, join, send, take } = await test_game("mods");
join(1, "alice");
game.set_block(1, 100, 1, "bworld:grass");
send(1, { type: "move", x: 2.5, y: 101, z: 2.5, yaw: 0, pitch: 0 });
send(1, { type: "chat", text: "/give bworld:wood_hoe" });
const inventory = take(1).filter((m) => m.type === "container" && m.container === "inventory").at(-1).items;
send(1, {
type: "select_slot",
slot: inventory.findIndex((i: { id: string } | null) => i?.id === "bworld:wood_hoe"),
});
send(1, { type: "use_block", x: 1, y: 100, z: 1, face: "top" });
assertEquals(game.world.get_block_id(1, 100, 1), "bworld:hoed_dirt");
});
```
`tests/farming_test.ts`, `tests/cooking_test.ts` and `tests/cutting_board_test.ts` test mods this way.
## Next Steps
- [Mod Files](modfiles.md): the manifest, the folder layout, and `.bmod` files.
- [Sides](../concepts/sides.md): which script runs where, and why it matters.
- [Blocks](../blocks/index.md) and [Items](../items/index.md): most mods start here.
+123
View File
@@ -0,0 +1,123 @@
# Mod Files
A mod is a folder with a `manifest.json`, some data files, textures, and up to three scripts. The build packs it into a
single `.bmod` file, which is what servers load.
## Layout
```
mods/
copper_tools/
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
blocks/*.json # one block per file
items/*.json # items that aren't a block's item form
models/*.json # block models
models/*.geo.json # entity models
entities/*.json
recipes/*.json
worldgen/ores.json
textures/*.png
scripts/
server.ts # game logic, never sent to players
client.ts # sent to players
worldgen.ts # terrain features, never sent to players
```
Data folders can have subfolders. Every data file holds one definition, wrapped with the format version:
```json
{
"format_version": 1,
"block": { "id": "copper_tools:copper_block", "textures": "copper_tools:copper_block" }
}
```
The key is `block`, `item`, `model`, `entity` or `recipe`, depending on the folder. File names don't matter, the `id`
inside does.
## `manifest.json`
```json
{
"format_version": 1,
"id": "copper_tools",
"name": "Copper Tools",
"description": "Copper blocks and a copper pickaxe.",
"version": "1.0.0",
"authors": ["paula"],
"game_version": ">=0.1.0",
"dependencies": [{ "id": "bworld", "version": "*" }],
"scripts": {
"server": "scripts/server.ts",
"client": "scripts/client.ts",
"worldgen": "scripts/worldgen.ts"
},
"credits": "CREDITS.md"
}
```
| Field | Required | Meaning |
| ---------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `format_version` | yes | Always `1`. Loaders reject versions they don't know. |
| `id` | yes | The mod's [namespace](../concepts/registries.md#identifiers). 1-32 characters of `a-z`, `0-9` and `_`, matching the folder name. |
| `name` | yes | Display name, shown to players when they join from another site and on the Credits screen. |
| `description` | no | A sentence or two. |
| `version` | yes | The mod's own version, semver like `1.0.0`. |
| `authors` | no | A list of names. |
| `game_version` | no | The bworld versions the mod works with, as a semver range. Not checked yet. |
| `dependencies` | no | Other mods, `{ "id", "version" }`. A missing dependency is an error, and dependencies load first. The version range isn't checked yet. |
| `scripts` | no | Paths to the `server`, `client` and `worldgen` scripts. See [Sides](../concepts/sides.md). |
| `credits` | no | A markdown file for licenses and thanks, shown on the Credits screen. Raw HTML in it is shown as text. |
List every mod whose ids you use in `dependencies`, including `bworld` for the base game's blocks and items. It
guarantees they're loaded before yours, and `check-mods` warns when one is missing.
## Scripts
Each script is an ES module that exports a `setup` function. The build bundles every script on its own into one module,
so they can import other files and packages, but code imported by several scripts is copied into each bundle.
> [!WARNING]
> Anything the client script imports is sent to every player who joins. Don't import secrets or anti-cheat logic into
> code the client script shares with the server script.
### Mods as Deno Projects
When a mod's folder has a `deno.json`, its scripts are bundled and typechecked with it, so the mod can have its own
imports and npm or JSR packages. Mods without one use the `deno.json` of the folder the build runs in, like the mods in
this repository. That config maps the API types, which scripts import as `bworld/server`, `bworld/client` and
`bworld/worldgen`:
```ts
import type { ServerContext } from "bworld/server";
```
## `.bmod` Files
A `.bmod` is a built mod in one zip file. Servers load every `.bmod` in their `server_mods/` folder, so installing a mod
on a server is dropping its file there and restarting.
```sh
deno task pack-mod mods/copper_tools # writes copper_tools.bmod, to share
deno task build # packs every mod in mods/ into server_mods/
```
```
copper_tools.bmod
manifest.json # with scripts and credits pointing into the zip
data.json # every block, model, item, entity, recipe and ore
scripts/server.js # each script bundled into one module
scripts/client.js
scripts/worldgen.js
textures/<name>.png
credits.md
```
- Packing checks the mod first, like `check-mods`, and refuses one with errors.
- 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
[Networking](../networking/index.md).
+117
View File
@@ -0,0 +1,117 @@
# Screens
There are a few ways for a mod to show players a GUI. Pick the first one that's enough:
| Way | Code | For |
| -------------------------------------------- | ------------- | ---------------------------------------------------------- |
| [Container screens](../inventories/menus.md) | server only | Inventories and machines: slots, filters, progress bars |
| [Inventory overlays](#inventory-overlays) | client only | Drawing next to every inventory screen, like a recipe list |
| Forms, custom screens and HUD elements | not built yet | See [below](#not-built-yet) |
## Inventory Overlays
An inventory overlay draws on every inventory screen (the player's inventory, chests, furnaces and every other container
screen), over the screen, like Just Enough Items' item list. `mods/recipe_viewer` is one.
```ts
import type { ClientContext } from "bworld/client";
export function setup(ctx: ClientContext) {
ctx.ui.add_inventory_overlay({
on_render(g, screen) {
// screen is the inventory's box, and what's in the slot under the mouse
const x = screen.x + screen.width + 16;
if (screen.hovered_item) g.text(ctx.items.name(screen.hovered_item.id), x, 16);
},
});
}
```
`on_render` runs every frame the screen is open, with a [`Graphics`](#graphics) to draw with and the screen's box:
```ts
interface InventoryScreenView {
readonly x: number;
readonly y: number;
readonly width: number;
readonly height: number;
readonly hovered_item: ItemStack | undefined; // what's in the slot under the mouse
}
```
Overlays get the mouse before the slots:
- A click an overlay uses, with `g.button` or `g.consume_click()`, doesn't reach the slots.
- `g.block_mouse(x, y, w, h)` keeps the slots from reacting to the mouse under something drawn over them.
- While a `g.text_input` has the keyboard, keybinds like the inventory key don't fire. Text inputs edit like chat:
selecting with shift or the mouse, ctrl+a, and copy, cut and paste.
An overlay that throws is removed, with the error in the console.
## Graphics
`Graphics` is an immediate mode drawing API: every frame, draw everything again, and ask widgets like `button` what
happened. It's styled with the game's GUI sprites.
```ts
interface Graphics {
readonly width: number; // the screen, in pixels
readonly height: number;
readonly mouse: { x: number; y: number; down: boolean; pressed: boolean; right_pressed: boolean };
rect(x: number, y: number, w: number, h: number, color?: [r, g, b, a]): void;
panel(x: number, y: number, w: number, h: number): void; // the game's panel background
text(text: string, x: number, y: number, options?: { scale?: number; color?: [r, g, b, a] }): void;
measure_text(text: string, scale?: number): number;
texture(id: string, x: number, y: number, w: number, h: number): void; // any texture
item(id: string, x: number, y: number, count?: number): void; // an item as a slot shows it
clip(x: number, y: number, w: number, h: number, draw: () => void): void; // only draws inside the box
button(label: string, x: number, y: number, w: number, h: number): boolean; // true the frame it's clicked
text_input(id: string, x: number, y: number, w: number): string; // what's typed in it so far
key_pressed(key: string): boolean; // KeyboardEvent.code, like "KeyE". false while a text input has the keyboard
tooltip(lines: (string | { text: string; color?: Color })[], x: number, y: number): void; // over everything
item_tooltip(id: string, x: number, y: number, extra?: (string | { text: string; color?: Color })[]): void;
consume_click(): void; // nothing under it gets this click
block_mouse(x: number, y: number, w: number, h: number): void; // the screen underneath ignores the mouse there
}
```
Colors are `[r, g, b, a]` from 0 to 1. The last `tooltip` drawn in a frame is the one shown, and `item_tooltip` shows
the game's own tooltip for an item (its name, food, durability and lore) with extra lines under it.
`slider` and `slots` are in the type but not built yet.
## Reading Game State
Client scripts can read what the client knows, to show it:
```ts
ctx.player.name;
ctx.player.position; // { x, y, z }
ctx.world.get_block(x, y, z); // a block id, what this client sees
ctx.world.time; // see Time
ctx.items.ids(); // every item, in load order
ctx.items.exists(id);
ctx.items.name(id); // "Cooked Rice"
ctx.items.mod(id); // the name of the mod that added it
ctx.recipes.list(type?); // every recipe as its JSON, including mods' own types
```
`ctx.player` and `ctx.world` only work once the player is in the world, not during `setup`.
## Not Built Yet
The client and server APIs have types for these, but calling them throws for now:
- **Forms** (`ctx.ui.message_form`, `action_form` and `modal_form` on the server): simple dialogs defined entirely by
the server script, like Bedrock's server forms.
- **Custom screens** (`ctx.ui.register_screen` and `open` on the client, `open_screen` on the server): whole screens
drawn with `Graphics`, opened by the server with some props.
- **HUD elements** (`ctx.hud.register`): drawing over the world every frame.
- **Keybinds** (`ctx.input.bind`).
- **Mod channels** (`ctx.net`), for a mod's client and server scripts to talk. Without them, a client script can't send
anything to the server.
See [the modding plan](../../modding_plan.md) for how they're meant to work.
+45
View File
@@ -0,0 +1,45 @@
# Containers
A container is a list of item slots that the server owns and saves: a chest's contents, a furnace's input, fuel and
result, a player's inventory. Server scripts make and use them through `ctx.containers`.
## Making Containers
```ts
const container = ctx.containers.create(27); // 1 to 256 slots, saved with the world
const id = container.id; // keep this, like in a block's tile data
ctx.containers.get(id); // the container, or undefined once it's deleted
ctx.containers.delete(id); // closes any screen showing it
```
Containers are saved with the world until they're deleted. A block that owns one keeps its id in
[tile data](../blocks/tiledata.md#blocks-with-containers), and deletes it when it's broken.
## Using Containers
```ts
interface Container {
readonly id: string;
readonly size: number;
get(slot: number): ItemStack | undefined; // live, see below
set(slot: number, item: ItemStack | undefined): void;
add(item: ItemStack): ItemStack | undefined; // fills matching stacks, then empty slots. returns what didn't fit
on_change(fn: (slot: number) => void): () => void; // returns a function that stops watching
}
```
```ts
container.set(0, { id: "bworld:coal", count: 8 });
const left = container.add({ id: "bworld:coal", count: 100 });
if (left) ctx.world.drop_item(x, y, z, left);
```
Stacks from `get` are live: setting `count` or `data` changes the stack in the container, and a stack counted down to 0
is gone. `set` and `add` copy what they're given.
Changes are synced to every player viewing the container, whether a script or a player made them.
A player's inventory is a container too, `player.inventory`, with the hotbar in slots 0-8.
To let players see and use a container, open a [container screen](menus.md) for it.
+93
View File
@@ -0,0 +1,93 @@
# Container Screens
A container screen shows a [container](containers.md)'s slots to a player, above their own inventory and hotbar, so they
can move items in and out. Chests, furnaces, the smithing table and Farmer's Delight's cooking pot are all container
screens. They're defined entirely by the server script, so they need no client code.
Every click goes to the server, which applies it following the screen's rules, and everyone viewing the container sees
the result.
## Opening a Screen
Usually from a block's `on_interact`:
```ts
ctx.components.register_block("copper_tools:smelter", {
on_create(block) {
block.data = { container: ctx.containers.create(3).id, progress: 0 };
},
on_interact(block, _params, player) {
const screen = ctx.ui.open_container(player, {
container: ctx.containers.get(block.data.container)!,
layout: [
{ slot: 0, x: 3, y: 0, filter: "smeltable" },
{ slot: 1, x: 3, y: 2, filter: "fuel" },
{ slot: 2, x: 5, y: 1, output_only: true },
],
bars: [{
x: 4,
y: 1,
value: "progress",
max: "progress_max",
direction: "right",
empty_texture: "bworld:arrow_empty",
full_texture: "bworld:arrow_full",
}],
});
screen.set_property("progress", block.data.progress);
screen.set_property("progress_max", 200);
return true;
},
});
```
Give the block `"interactive": true` so clients don't guess that the click places a block.
## Layout
`layout` lists which of the container's slots to show, and where:
| Field | Meaning |
| ------------- | ----------------------------------------------------------------------------------------------------------------- |
| `slot` | The container's slot. |
| `x`, `y` | Where, in slot units from the top left of the screen's area. Can be fractional. |
| `filter` | What can be put in: `"smeltable"` (has a furnace recipe), `"fuel"`, or a function `(item) => boolean`. |
| `output_only` | Can only be taken from, all at once, like the furnace result. |
| `on_take` | For `output_only` slots: runs when a player takes from it, before they get the item. Return `false` to stop them. |
`rows` sets the height of the screen's area in slots. By default it fits the slots and bars.
`filter`, `output_only` and `on_take` run **on the server**, so players can't put the wrong items in by editing their
client. `on_take` is the place to use up a recipe's inputs, so taking the result and spending the inputs happen in the
same step, like the smithing table does.
## Progress Bars
`bars` draws progress bars, filled with one property divided by another:
| Field | Meaning |
| ------------------------------- | ----------------------------------------------------------------- |
| `x`, `y` | Where, in slot units. |
| `value`, `max` | Names of properties set with `screen.set_property(name, number)`. |
| `direction` | `"up"`, like the furnace's fire, or `"right"`, like its arrow. |
| `empty_texture`, `full_texture` | The textures for the empty and full bar. |
Properties are synced when they change, so a component can update them every tick.
## The Screen Handle
`open_container` returns a handle:
```ts
interface ScreenHandle {
readonly player: Player;
readonly open: boolean;
set_property(id: string, value: number): void;
close(): void;
on_close(fn: () => void): void; // when it closes for any reason
}
```
A screen closes when the player closes it, leaves, or opens another screen, when a script calls `close()`, and when its
container is deleted. To keep a furnace's bars moving for everyone looking at it, keep the handles of open screens and
drop them in `on_close`, like the base game's furnace in `mods/bworld/scripts/server.ts`.
+40
View File
@@ -0,0 +1,40 @@
# Food
An item with a `food` property can be eaten. Players eat by right clicking while holding it, when they're hungry.
```json
{
"format_version": 1,
"item": {
"id": "farmersdelight:cooked_rice",
"texture": "farmersdelight:cooked_rice",
"max_stack": 16,
"food": { "nutrition": 6, "saturation_modifier": 0.4, "returns": "bworld:bowl" }
}
}
```
| Field | Default | Meaning |
| --------------------- | -------- | ------------------------------------------------------------------------------------------ |
| `nutrition` | required | Hunger points it restores, out of 20. A whole number. |
| `saturation_modifier` | required | Like Minecraft's: the saturation it gives is `nutrition × modifier × 2`. Bread's is `0.6`. |
| `always_edible` | `false` | Can be eaten even when not hungry. |
| `returns` | none | An item left in the hand after eating, like a bowl after soup. |
Food that places a block, like potatoes with `places`, is planted when clicked somewhere it can go and eaten otherwise.
## Hunger and Health
Hunger and health work like Minecraft's:
- Sprinting, swimming, jumping, breaking blocks, taking damage and healing add **exhaustion**. Every 4 exhaustion costs
a point of saturation, or of hunger once saturation is gone.
- A full stomach heals: quickly while there's saturation, slowly with at least 18 hunger.
- At 0 hunger, players lose health every 4 seconds, down to half a heart.
Server scripts can feed players directly, and read and change their hunger. See [Players](../entities/players.md).
```ts
player.feed(4, 0.3); // like eating 4 nutrition with a 0.3 modifier
player.add_exhaustion(8); // two points of saturation or hunger
```
+110
View File
@@ -0,0 +1,110 @@
# Items
Items are what players carry: in their inventory, in chests, and dropped on the ground. Every block registers an item
that places it, unless it sets `"item": false`. Everything else is defined in the mod's `items/` folder.
## Items and Item Stacks
Like blocks, each kind of item is defined once. What players hold are **item stacks**: an item id, a count, and optional
`data`.
```ts
interface ItemStack {
readonly id: string;
count: number;
data?: unknown; // any JSON value, set by server scripts
}
```
`data` is how one stack differs from another of the same item, like the water left in a watering can or the damage on a
tool. It's saved, and synced to clients as part of the container the stack is in, so client code can read it.
Stacks handed to server scripts are live: setting `count` or `data` on one changes the real stack, and a stack counted
down to 0 is gone.
## A Basic Item
`items/copper_ingot.json`:
```json
{
"format_version": 1,
"item": {
"id": "copper_tools:copper_ingot",
"texture": "copper_tools:copper_ingot",
"lore": "Smelted from copper ore."
}
}
```
## Properties
| Field | Default | Meaning |
| --------------- | ------------------- | ----------------------------------------------------------------------------- |
| `id` | required | The item's id. |
| `texture` | required | The texture it's drawn with. |
| `name` | from the id | What players see. `copper_tools:copper_ingot` is "Copper Ingot" when not set. |
| `lore` | none | Tooltip text under the name. `\n` starts a new line. |
| `max_stack` | `64`, `1` for tools | How many fit in one slot. |
| `places` | none | A block it places when used on a block, like seeds. |
| `tool` | none | Makes it a [tool](tools.md). |
| `food` | none | Makes it [edible](food.md). |
| `data_textures` | none | Other textures, picked by the stack's `data`, see below. |
| `components` | none | [Item components](#item-components) and their parameters. |
### Textures From Data
`data_textures` draws a stack with another texture when a key in its `data` is set, like the fishing rod while its line
is out:
```json
"data_textures": { "cast": "bworld:fishing_rod_cast" }
```
A stack whose `data.cast` is truthy uses `bworld:fishing_rod_cast`. When several keys are, the first listed wins.
## Item Components
Like [block components](../blocks/components.md), item components give items behavior. The server script registers them:
```ts
ctx.components.register_item<{ max_water: number }>("bworld:watering_can", {
on_create(item, params) {
item.data = { water: params.max_water };
},
get_lore(item, params) {
return `Water: ${(item.data as { water: number }).water}/${params.max_water}`;
},
on_use(item, params, player) {
// right clicked while holding it
},
});
```
and items list them with their parameters:
```json
"components": { "bworld:watering_can": { "max_water": 32 } }
```
| Handler | Called when |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| `on_create(item, params)` | A stack of it is made: crafted, given, dropped by a block, and so on. |
| `get_lore(item, params)` | The server sends the stack to a player. Returns extra tooltip text for that stack, shown under the item's own `lore`. It isn't saved. |
| `on_use(item, params, player)` | A player right clicks while holding it, at nothing or at a block. |
At a block, the block's own [interaction](../blocks/components.md#interacting) comes first. An item with `on_use` is
used instead of being placed.
`on_use` doesn't say which block was clicked. For that, pair it with a block component's `on_interact`, the way the
watering can uses `bworld:water_source`, or subscribe to the `block_interact` [event](../concepts/events.md).
## Server Script Helpers
```ts
ctx.items.exists("bworld:carrot"); // true
ctx.items.max_stack("bworld:wood_pickaxe"); // 1
ctx.items.tool("bworld:wood_pickaxe"); // "pickaxe", or undefined for items that aren't tools
player.give_item("bworld:carrot", 3); // what doesn't fit drops at their feet
```
+51
View File
@@ -0,0 +1,51 @@
# Tools
A tool is an item with a `tool` property. It breaks blocks of its type faster, lets players get drops from blocks that
require it, and wears out over time.
```json
{
"format_version": 1,
"item": {
"id": "copper_tools:copper_pickaxe",
"texture": "copper_tools:copper_pickaxe",
"tool": { "type": "pickaxe", "tier": 1, "speed": 4, "durability": 5 }
}
}
```
| Field | Default | Meaning |
| ------------ | -------- | ------------------------------------------------------------------------------------------------------------------- |
| `type` | required | Matched against blocks' `mining.tool`, like `"pickaxe"`, `"axe"`, `"shovel"`, `"hoe"` or `"knife"`. Any word works. |
| `durability` | required | How many uses it has before it breaks, see below. |
| `tier` | `0` | Compared with blocks' `mining.tier`. |
| `speed` | `2` | How many times faster than a hand it breaks blocks of its type. |
Tools stack to 1 unless they set `max_stack`.
## Mining
A block breaks `speed` times faster when the held tool's `type` is the block's `mining.tool`. A block with
`"requires_tool": true` only drops when broken with a tool of its type whose `tier` is at least the block's
`mining.tier`. See [Mining](../blocks/index.md#mining).
The base game's tiers:
| Tier | Tools | Durability | Gets drops from |
| ---- | ------------- | --------------------- | ----------------------------------- |
| `0` | wood, gold | 2 (wood), 9 (gold) | stone, coal ore |
| `1` | stone, copper | 3 (stone), 5 (copper) | also copper, tin, iron and gold ore |
| `2` | iron | 7 | everything so far |
Tool types don't have to be the base game's. A mod can add a `"sickle"` type and blocks with `"tool": "sickle"`, and a
server script can check a held item's type with `ctx.items.tool(id)`, like the base game's `bworld:hoeable` does for
hoes.
## Durability
Like Sunlit Valley, tools don't wear out from use. They lose durability when their owner dies: everything a player
carries falls out where they died, and each tool loses 1 durability first. A tool that runs out breaks instead of
dropping.
The damage a tool has taken is kept in its stack's `data.damage`, and its tooltip shows what's left, like
`Durability: 4 / 5`. Upgrading a tool at the smithing table keeps its data, damage included.
+117
View File
@@ -0,0 +1,117 @@
# Commands
Players run commands by typing `/name` in chat. Commands run on the server, and players see suggestions above the chat
box as they type: Tab puts one in, Up and Down pick one.
bworld's commands work like Fabric's, which are Minecraft's Brigadier: a tree of literal words and typed arguments. Each
argument type reads its part of the text and suggests what could go there.
## Registering a Command
In the server script's `setup`:
```ts
import type { Player, ServerContext } from "bworld/server";
export function setup(ctx: ServerContext) {
const { literal, argument, types } = ctx.commands;
const heal = (player: Player, amount: number) => player.heal(amount);
ctx.commands.register(
literal("heal")
.describe("Heals a player")
.requires((source) => source.player.name === ctx.storage.get("owner"))
.executes((context) => heal(context.source.player, 20))
.then(
argument("amount", types.integer(1, 20))
.executes((context) => heal(context.source.player, context.get<number>("amount")))
.then(
argument("target", types.player())
.executes((context) => heal(context.get<Player>("target"), context.get<number>("amount"))),
),
),
);
}
```
That's `/heal`, `/heal 5` and `/heal 5 alice`.
| Builder | What it does |
| ---------------------- | --------------------------------------------------------------------------------------------- |
| `literal(name)` | A word that has to be typed as is. Words are tried before arguments. |
| `argument(name, type)` | A value read by `type`, which `executes` gets with `context.get(name)`. |
| `.then(node)` | What can come next. |
| `.executes(fn)` | Runs when the command ends here. Without it, ending here tells the player what's missing. |
| `.requires(fn)` | Only for sources it returns `true` for. Others can't run it and don't see it suggested. |
| `.suggests(fn)` | `(partial, source) => [{ text, tooltip? }]`, in place of the argument type's own suggestions. |
| `.describe(text)` | Shown by `/help`. |
`context.source` has the `player` who typed the command and `send_message(text)` to answer them.
## Argument Types
| `types.` | Reads | Suggests |
| --------------------- | --------------------------------------------------------------- | -------------- |
| `integer(min?, max?)` | a whole number | |
| `number(min?, max?)` | any number | |
| `boolean()` | `true` or `false` | both |
| `word()` | one word | |
| `greedy_string()` | the rest of the line, spaces and all. Nothing can come after it | |
| `choice([...])` | one of the given words | them |
| `item()`, `block()` | an id. `carrot` works too, while only one mod has a `carrot` | ids |
| `player()` | an online player's name, as a `Player` | online players |
## Errors
To tell the player what's wrong, answer them and return:
```ts
.executes((context) => {
const player = context.source.player;
if (ctx.items.tool(player.held_item?.id ?? "") !== "pickaxe") {
context.source.send_message("You need to be holding a pickaxe");
return;
}
// ...
})
```
An error thrown from a mod's command is logged with the mod's id, and the player is told something went wrong.
> [!NOTE]
> The engine's own commands throw a `CommandError` to show the player a message, but mods can't yet: the API doesn't
> export the class, and a copy bundled into a mod isn't recognized.
## The Simple Form
A command can also take the rest of the line, split on spaces:
```ts
ctx.commands.register("hello", {
description: "Says hello",
usage: "/hello [name]",
run(args, player) {
player.send_message(`Hello ${args[0] ?? player.name}!`);
},
});
```
## Names
Command names are `a-z`, `0-9` and `_`. Two mods registering the same name, or a mod registering one of the engine's,
stops the server from starting. Every mod command can also be run as `/<mod id>:<name>`, like `/copper_tools:heal`.
Commands can only be registered during `setup`.
## The Engine's Commands
| Command | What it does |
| ------------------------------------------------------- | -------------------------------------------------------- |
| `/give <item> [count]` | Gives you an item |
| `/summon <entity>` | Spawns an entity where you are |
| `/time` | Shows the time |
| `/time set <day\|noon\|sunset\|night\|midnight\|ticks>` | Jumps to the next time of day. Time never goes back |
| `/time add <ticks>` | Moves time forward |
| `/tps` | Shows how the game loop keeps up |
| `/skin [url] [slim\|normal]` | Changes your skin to a 64×64 PNG, or back to the default |
| `/help [command]` | Every command's usage, or one's |
+41
View File
@@ -0,0 +1,41 @@
# Time
The server runs at a fixed 20 ticks a second, and everything in the game is measured in ticks: cooking times, burn
times, timers and the time of day.
## Timers
`ctx.system` runs code later, counted in ticks:
```ts
const handle = ctx.system.run_timeout(() => player.send_message("Five seconds later"), 5 * 20);
const every_minute = ctx.system.run_interval(() => save_stats(), 60 * 20);
ctx.system.clear_run(every_minute);
ctx.system.current_tick; // ticks since the server started
```
`run_timeout(fn, 0)` runs on the next tick, which is how a [before event](../concepts/events.md) gets something done
after it. Timers aren't saved: they're gone after a restart, so set them up again in `setup`.
For work every tick, subscribe to the `tick` event. For work on a block, use a
[component](../blocks/components.md#ticking)'s `on_tick` or `on_second`.
## World Time
`ctx.world.time` counts ticks since 06:00 of the world's first day, and never wraps around:
- A **day**, 06:00 to 18:00, is 36000 ticks: 30 minutes.
- A **night**, 18:00 to 06:00, is 12000 ticks: 10 minutes. So in game hours go by faster at night.
- Dusk is the first minute of the night and dawn the last, so it's bright all day.
`ctx.world.day` is the number of days since the world started, 0 on the first day, going up at 06:00. Every morning at
06:00, blocks' `on_new_day` runs, then the `new_day` event fires. That's the clock crops grow on.
`ctx.world.set_time(ticks)` changes the time for everyone. Moving it forward past mornings runs each of them, up to the
last 64. Moving it back doesn't repeat mornings.
`common/time.ts` has `clock`, `format_clock`, `is_day` and `daylight` for turning ticks into something readable. Client
scripts can read the time as `ctx.world.time`.
Players can change it with `/time set <day|noon|sunset|night|midnight|ticks>` and `/time add <ticks>`.
+79
View File
@@ -0,0 +1,79 @@
# Networking
Players never install mods. When they join a server, their client downloads that server's mods and loads them, then the
server streams them the world. This page is what happens along the way, and what a mod can rely on.
## Joining
```
client server
│ hello { name, protocol } │
├────────────────────────────────────────►│ a different protocol is turned away
│ welcome { protocol, mods[] } │ mods[i] = { id, name, version, sha256, file, size }
│◄────────────────────────────────────────┤
│ │
│ [another site: confirm screen] │
│ download every .bmod, check each one's │
│ sha256, build the texture atlas, load │
│ data in the listed order, run client │
│ scripts' setup, start chunk workers │
│ │
│ ready { view_distance } │
├────────────────────────────────────────►│
│ join { id, name, players, entities, │ the player is created here and player_join
│ blocks, spawn, selected_slot } │ fires. their inventory follows
│◄────────────────────────────────────────┤
│ chunks, nearest first │
│◄────────────────────────────────────────┤
```
- The client loads mods **in the order the server lists them**, so both sides register the same content the same way.
- Every `.bmod` is checked against its SHA-256 before it's opened, and scripts run from the checked bytes, so what runs
is exactly what the server listed.
- Players get each mod's `.bmod` **without its server and worldgen scripts**. The server makes that copy when it starts,
named by its hash so it can be cached forever.
- If any download, hash check or client `setup` fails, the client disconnects and says which mod failed. It never joins
with some mods missing.
- Until `ready`, the connection isn't a player: nobody sees it, and anything else it sends is ignored. A client that
doesn't send `ready` within 60 seconds is turned away.
- Leaving a server reloads the page, so one server's mod code never stays loaded while playing on another.
When the game's protocol changes (`PROTOCOL_VERSION` in `common/protocol.ts`), clients on another version are turned
away before anything is downloaded.
## The World
The server sends the world the way Minecraft Java does since 1.20.2. Clients never generate terrain, so worldgen scripts
stay on the server.
- Chunks are 16×256×16 and sent whole, compressed, in batches, nearest first. The server paces batches by how fast each
client says it loads them.
- Players see chunks up to their view distance, at most 10 on the server's side. Light isn't sent: clients light chunks
themselves.
- Block changes go only to players who have the chunk. Everyone else gets the change with the chunk when they come
close.
- Entities near a player are sent to them, and their movement follows.
For a mod, this means: what a client knows about the world is what's near its player. Tile data, `ctx.storage` and
server code are never sent at all. See [Sides](../concepts/sides.md#what-each-side-knows).
## Mod Channels
> [!NOTE]
> Not built yet. `ctx.net` exists on both sides but throws.
Mod channels will let a mod's client and server scripts send each other JSON messages:
```ts
// server.ts
ctx.net.on("copper_tools:reset_stats", (player, data) => {/* check everything, the client is untrusted */});
ctx.net.send(player, "copper_tools:heat", { value: 12 });
ctx.net.broadcast("copper_tools:announcement", { text: "the smelter exploded" });
// client.ts
ctx.net.on("copper_tools:heat", (data) => {/* ... */});
ctx.net.send("copper_tools:reset_stats", {});
```
Until then, the server reaches the client through what's already synced: [container screens](../inventories/menus.md)
and their properties, item stack `data`, block states, and displayed items.
+83
View File
@@ -0,0 +1,83 @@
# Block Models
A block's model is its shape: the boxes it's made of and which texture goes on each face. Blocks use `engine:cube`
unless they set `model`. For entity models, see [Entities](../entities/index.md#entity-models).
## Built-In Models
| Model | Texture variables | Shape |
| -------------- | --------------------------------------------------------- | ---------------------------------------------- |
| `engine:cube` | one texture, `{ top, bottom, side }` or `{ front, side }` | A full block. |
| `engine:cross` | `cross` | Two crossed planes, like flowers and saplings. |
| `engine:crop` | `crop` | Four planes in a # shape, like wheat. |
Blocks that aren't full cubes should use the `cutout` or `translucent` [render layer](../blocks/index.md#looks), since
`solid` blocks hide their neighbors' faces. They usually want `"collision": false` too.
In inventories, a block with a full cube model is drawn as a cube. Any other block is drawn flat, as its first texture,
like Minecraft's plants.
## Texture Variables
Models name their textures with variables, like `#side`, and blocks fill them in with `textures`:
```json
{
"id": "bworld:sapling",
"model": "engine:cross",
"textures": { "cross": "bworld:sapling" }
}
```
For `engine:cube`, one texture id fills every face. `{ "front", "side" }` puts `front` on the north face and `side` on
the rest. It's for blocks that [face a way](../blocks/states.md#facing), and can also set `top` and `bottom`.
## Custom Models
Mods add models in `models/`, in Minecraft's block model format: boxes measured in pixels, where 0 to 16 is the block,
with a texture per face. `models/slab.json`:
```json
{
"format_version": 1,
"model": {
"id": "copper_tools:slab",
"textures": { "top": "#side", "bottom": "#side" },
"elements": [{
"from": [0, 0, 0],
"to": [16, 8, 16],
"faces": {
"top": { "texture": "#top" },
"bottom": { "texture": "#bottom", "cullface": "bottom" },
"north": { "texture": "#side", "cullface": "north" },
"south": { "texture": "#side", "cullface": "south" },
"west": { "texture": "#side", "cullface": "west" },
"east": { "texture": "#side", "cullface": "east" }
}
}]
}
}
```
A block using it sets `"model": "copper_tools:slab"` and `"textures": { "side": "bworld:planks" }`, and gets planks on
every face, since `top` and `bottom` default to `#side`.
| Field | Meaning |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | The model's id, in the mod's namespace. |
| `textures` | Defaults for texture variables. Values are texture ids or other variables, like `"#side"`. |
| `elements[].from`, `to` | Opposite corners of the box, `[x, y, z]` in pixels. |
| `elements[].rotation` | `{ origin, axis, angle, rescale }`: turns the box around `origin` on `x`, `y` or `z` by -45, -22.5, 0, 22.5 or 45 degrees. `rescale` stretches it back to the block's width. |
| `elements[].shade` | Darker faces on the sides and bottom. `true` by default, plants turn it off. |
| `elements[].faces` | Any of `top`, `bottom`, `north`, `south`, `west` and `east`. |
| `faces.*.texture` | A variable like `"#side"`, filled in by the block's `textures`, or a texture id. |
| `faces.*.uv` | `[u1, v1, u2, v2]`, the part of the texture in pixels. Defaults to the part the face covers. |
| `faces.*.rotation` | Turns the texture on the face clockwise by 0, 90, 180 or 270 degrees. |
| `faces.*.cullface` | Hides the face when the neighbor on that side is a solid block. Only for faces on the block's edge. |
Faces are only drawn from the front, so a flat plane that should be seen from both sides needs a face each way.
## Lighting
Faces flat against the block's edge get smooth lighting and ambient occlusion like a full block's. Anything inside the
block is lit evenly with the light of the block's own space.
+126
View File
@@ -0,0 +1,126 @@
# Recipes
Recipes are data in a mod's `recipes/` folder, one per file. The base game has four types, for its crafting grid,
furnace and smithing table. Mods can make up types of their own for their machines.
## Crafting: `shaped`
For the crafting grid in the player's inventory screen:
```json
{
"format_version": 1,
"recipe": {
"type": "shaped",
"pattern": ["PPP", "P P", "PPP"],
"key": { "P": "bworld:planks" },
"result": { "id": "bworld:chest", "count": 1 }
}
}
```
`pattern` is 1 to 3 rows of 1 to 3 characters, where a space is an empty slot. `key` maps each letter to an item. The
pattern fits anywhere in the grid.
## Smelting: `furnace` and `fuel`
```json
{
"format_version": 1,
"recipe": {
"type": "furnace",
"input": "bworld:iron_ore",
"output": { "id": "bworld:iron_ingot", "count": 1 },
"cook_time": 200
}
}
```
```json
{
"format_version": 1,
"recipe": { "type": "fuel", "item": "bworld:coal", "burn_time": 1000 }
}
```
`cook_time` and `burn_time` are in ticks, 20 to a second. Two furnace recipes for the same input are an error. For fuel,
a later recipe for the same item replaces an earlier one.
## Smithing: `smithing`
For the smithing table, which upgrades a tool:
```json
{
"format_version": 1,
"recipe": {
"type": "smithing",
"tool": "bworld:wood_pickaxe",
"material": { "id": "bworld:stone", "count": 5 },
"result": "bworld:stone_pickaxe"
}
}
```
An optional `addition` is a third item it also takes. Upgrading uses up the tool, `count` of the material and the
addition, and the result keeps the tool's `data`, like its [durability](../items/tools.md#durability). Two smithing
recipes with the same tool, material and addition are an error.
## Choices
Anywhere a recipe takes an item (`key` values, `input`, `item`), a list of ids means any of them fits:
```json
"key": { "P": ["bworld:planks", "bworld:birch_planks", "bworld:spruce_planks"] }
```
In the crafting grid, each slot can hold a different one of them, so a stick can be made from oak and birch planks
together. The recipe viewer takes turns showing them.
## Custom Recipe Types
Any `type` with a namespace is a mod's own, like `farmersdelight:cooking` for the cooking pot. The engine only stores
these recipes. Everything else about them is up to the mod:
```json
{
"format_version": 1,
"recipe": {
"type": "farmersdelight:cooking",
"ingredients": ["farmersdelight:cabbage", ["bworld:carrot", "bworld:potato", "farmersdelight:onion"]],
"result": { "id": "farmersdelight:cabbage_rolls", "count": 1 },
"cook_time": 100
}
}
```
The mod's server script reads them in `setup` and checks their fields itself:
```ts
const recipes = ctx.recipes.list("farmersdelight:cooking").map((json, i) => {
if (!Array.isArray(json.ingredients) || json.ingredients.length > 6) {
throw new Error(`cooking recipe ${i + 1}: ingredients must be 1 to 6 items`);
}
// ...check the rest, and turn it into whatever the machine needs
return json;
});
```
Throwing in `setup` stops the server from starting with the error, so a broken recipe is caught when the server starts
rather than when someone uses the machine. Other mods can add recipes of your type too, as long as they depend on your
mod.
`list` returns copies, in load order. Client scripts can read every recipe with `ctx.recipes.list(type?)`, which is how
the recipe viewer shows mods' own types.
## Looking Up Recipes
Server scripts can ask about the base game's types:
```ts
ctx.recipes.furnace_result("bworld:iron_ore"); // { output, cook_time }, or undefined
ctx.recipes.is_smeltable("bworld:iron_ore");
ctx.recipes.is_fuel("bworld:coal");
ctx.recipes.fuel_value("bworld:coal"); // burn time in ticks, 0 when it isn't fuel
ctx.recipes.smithing("bworld:wood_pickaxe", "bworld:stone"); // { result, material_count }, or undefined
```
+36
View File
@@ -0,0 +1,36 @@
# Textures
Every `.png` in a mod's `textures/` folder becomes a texture that blocks, items, entities and screens can use.
## Texture Ids
A texture's id is `<mod id>:<file name without .png>`. Subfolders are joined with `_`, so in the mod `copper_tools`:
| File | Texture id |
| --------------------------- | --------------------------- |
| `textures/copper_block.png` | `copper_tools:copper_block` |
| `textures/ores/tin.png` | `copper_tools:ores_tin` |
Any mod can use any texture by its id, including the base game's, like `bworld:stone`.
## Sizes
Textures can be any size up to 256×256. Blocks and items are made for 16×16 and stretch a texture of another size over
the same face, so a 32×32 block texture is just a sharper one. Larger ones are for things like entity skins.
## Missing Textures
A texture id that doesn't exist shows the magenta and black checker, `engine:missing`, and `check-mods` warns about it.
It isn't an error, so a mod still loads while its art is unfinished.
## Engine Textures
The engine's own textures use the `engine` namespace and come from `assets/`, not from a mod:
- `engine:missing`, the missing texture,
- `engine:break_0` to `engine:break_8`, the cracks drawn on a block being broken.
## How Players Get Them
Textures go in the mod's `.bmod`. When a player joins, their client puts every mod's textures into one atlas. The server
never decodes images.
+107
View File
@@ -0,0 +1,107 @@
# World Generation
The server generates chunks from the world's seed, and players get the finished chunks. Mods add to what it generates
with ores (data) and features (a worldgen script).
## Determinism
A save only keeps what players changed on top of the generated terrain. Everything else is generated again whenever a
chunk loads, so a chunk has to come out **exactly the same every time**. If it doesn't, blocks players broke reappear
and their builds end up half buried.
- **Never use `Math.random`, `Date`, `performance.now` or anything else that changes between runs.** Use the chunk's
`rng` and noise helpers, which are seeded from the world's seed.
- Don't keep state between chunks. Chunks generate in any order.
- Adding or removing a mod's features is safe for chunks that haven't been generated yet, but changes existing worlds'
untouched terrain the next time it loads.
## The Passes
Each chunk goes through three passes:
1. **Terrain.** The ground, water, caves and trees. This is built into the engine for now, see below.
2. **Ores.** Every mod's `worldgen/ores.json`, in load order.
3. **Features.** Every mod's registered features, in load order.
The world is 256 blocks tall and the sea is at y 64.
## Ores
`worldgen/ores.json`:
```json
{
"format_version": 1,
"ores": [
{
"id": "copper_tools:rich_copper_ore",
"replaces": "bworld:stone",
"min_y": 5,
"max_y": 40,
"scale": 0.05,
"threshold": 0.72
}
]
}
```
Every block in the chunk that is `replaces` and between `min_y` and `max_y` becomes the first ore whose 3D noise,
sampled at `(x, y, z) × scale`, is above `threshold`. A smaller `scale` makes bigger veins, and a higher `threshold`
makes rarer ones. Each ore's noise is seeded with its id, so ores don't line up with each other.
## Features
Features are functions that run on every chunk after terrain and ores. The worldgen script registers them:
```ts
import type { WorldgenContext } from "bworld/worldgen";
export function setup(gen: WorldgenContext) {
gen.register_feature("copper_tools:boulders", (chunk) => {
if (chunk.rng.next() > 0.1) return;
const x = chunk.x * 16 + Math.floor(chunk.rng.next() * 16);
const z = chunk.z * 16 + Math.floor(chunk.rng.next() * 16);
chunk.set_block(x, chunk.height_at(x, z) + 1, z, "bworld:stone");
});
}
```
Feature ids are in the mod's namespace. Each feature's `rng` is seeded with the world's seed, the chunk and the
feature's id, so adding another mod's feature doesn't change what this one generates.
```ts
interface FeatureChunk {
readonly x: number; // chunk coordinates. blocks are chunk.x * 16 to chunk.x * 16 + 15
readonly z: number;
readonly seed: string;
readonly rng: { next(): number }; // 0 to 1
noise_2d(name: string): (x: number, z: number) => number;
noise_3d(name: string): (x: number, y: number, z: number) => number;
height_at(x: number, z: number): number; // surface height, inside this chunk only
biome_at(x: number, z: number): string; // like "bworld:plains", inside this chunk only
get_block(x: number, y: number, z: number): string | undefined; // inside this chunk only
set_block(x: number, y: number, z: number, id: string): void; // up to one chunk away
}
```
All coordinates are world coordinates. `noise_2d` and `noise_3d` return seeded noise functions, the same for the same
`name` in every chunk, so features can make patterns that continue across chunk borders.
`set_block` can write up to one chunk away, so a tree near the border can grow into the next chunk. Writes into another
chunk only fill air, so the result doesn't depend on which chunk generates first.
Generated blocks don't run `on_create`, and worldgen scripts can't use the server or client API.
## Terrain
The terrain itself is built into the engine (`common/worldgen/`). It works like Minecraft 1.18+ with the Terralith
datapack: continentalness, erosion and weirdness noises set every column's height and roughness, a 3D density is carved
into caves, and on top of that come terraced plateaus, shattered hills, river valleys and gorges, jagged peaks and rare
sky islands. Biome ids are the keys of `BIOMES` in `common/worldgen/overworld.ts`, like `bworld:yosemite_cliffs` or
`bworld:skylands`.
`deno run -A tools/worldgen_preview.ts [seed]` renders it to PNG files.
> [!NOTE]
> `register_terrain` exists in the API for mods that replace the terrain generator, but it throws for now: the terrain
> hasn't moved out of the engine yet.
+346
View File
@@ -0,0 +1,346 @@
# 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.
+4 -10
View File
@@ -1,13 +1,7 @@
# bworld
The base game as a mod, following "The base game as a mod" in `MODS.md`. The game loads its blocks, items, recipes and
textures from here, the same way it loads any other mod.
The base game as a mod. The game loads its blocks, items, entities, recipes and textures from here, and its block and
item behavior from `scripts/server.ts`, the same way it loads any other mod.
Still built into the engine, by phase:
| Phase | What |
| ----- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 2 | Block behavior in `server/game/blocks.ts` (hoeing, chest, furnace) and the watering can's starting water. They become the `bworld:hoeable`, `bworld:storage`, `bworld:furnace` and `bworld:watering_can` components. |
| 3 | Terrain, biomes, trees and ores in `common/generation.ts`. |
`bworld:stick` has no texture yet, so sticks show as missing.
Some of the base game is still built into the engine: recipe types, the inventory screen and crafting grid, the HUD,
`/give` and `/time`, mining rules, and terrain generation. See "The Engine and the Base Game" in `docs/modding_plan.md`.
+1 -1
View File
@@ -305,7 +305,7 @@ interface CropDrops {
}
// a crop, like a fabric CropBlock: its "age" state is its stage, and it grows one day every morning its farmland was
// watered the day before. see "Crops" in MODS.md
// watered the day before. see docs/modding/blocks/crops.md
interface CropParams {
// watered mornings from planting to fully grown
days: number;
+1 -1
View File
@@ -615,7 +615,7 @@ export class GameServer {
// containers.main. the components keep those fields and put the items in a ctx.containers container
// messages
// hello -> welcome, then ready -> join. see "Delivery to clients" in MODS.md
// hello -> welcome, then ready -> join. see docs/modding/networking/index.md
#handshake(conn: number, message: ClientMessage) {
if (message.type === "hello") {
if (this.#pending.has(conn)) {
+7 -7
View File
@@ -1,5 +1,5 @@
// runs mods' server scripts: builds each one's ServerContext and keeps what they register.
// see "Server scripts" in MODS.md. parts not built yet throw when used, saying so
// see docs/modding/. parts not built yet throw when used, saying so
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
import { Container as EngineContainer, ItemStack as EngineItemStack } from "$/common/inventory.ts";
import { get_state_value, set_state_value } from "$/common/utils.ts";
@@ -530,12 +530,12 @@ export class ModRuntime {
},
ui: {
open_container: (player, options) => this.#open_container(mod, player, options),
message_form: not_yet(mod, "ui.message_form", "step 7 in MODS.md"),
action_form: not_yet(mod, "ui.action_form", "step 7 in MODS.md"),
modal_form: not_yet(mod, "ui.modal_form", "step 7 in MODS.md"),
open_screen: not_yet(mod, "ui.open_screen", "step 7 in MODS.md"),
message_form: not_yet(mod, "ui.message_form", "see docs/modding_plan.md"),
action_form: not_yet(mod, "ui.action_form", "see docs/modding_plan.md"),
modal_form: not_yet(mod, "ui.modal_form", "see docs/modding_plan.md"),
open_screen: not_yet(mod, "ui.open_screen", "see docs/modding_plan.md"),
},
net: not_yet_object(mod, "net", "step 8 in MODS.md"),
net: not_yet_object(mod, "net", "see docs/modding_plan.md"),
storage: {
get: (key) => structuredClone(this.storage[mod]?.[key]) as never,
set: (key, value) => {
@@ -621,7 +621,7 @@ export class ModRuntime {
}
screen.properties[id] = value;
},
update: not_yet(mod, "update", "custom screens are step 7 in MODS.md"),
update: not_yet(mod, "update", "custom screens, see docs/modding_plan.md"),
close() {
if (server_player.screen === screen) game.close_screen(server_player);
},
+1 -1
View File
@@ -1,6 +1,6 @@
# Example Mod
A bworld mod. The format is described in `MODS.md` at the root of the bworld repo.
A bworld mod. `MODS.md` at the root of the bworld repo links to the modding docs.
## Files
-1
View File
@@ -50,7 +50,6 @@ if (import.meta.main) {
try {
const path = create_mod(id, display_name);
console.log(`Created ${path}. Edit its manifest.json, then run deno task check-mods.`);
console.log("Note: the game can't load mods yet, see the implementation plan in MODS.md.");
} catch (e) {
console.error((e as Error).message);
Deno.exit(1);
+1 -1
View File
@@ -1,6 +1,6 @@
// deno task pack-mod mods/copper_tools [copper_tools.bmod]
// builds a mod folder into a .bmod: its data merged into data.json, each script bundled into one module, and its
// textures and credits. deno task build does this for every mod in mods/, see "Mod files" in MODS.md
// textures 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 { type Bmod, BMOD_EXTENSION, SCRIPT_SIDES, type ScriptSide, write_bmod } from "$/common/bmod.ts";
import type { ManifestJson } from "$/common/mod_data.ts";