diff --git a/MODS.md b/MODS.md index 1dfefce..a766e50 100644 --- a/MODS.md +++ b/MODS.md @@ -1,1906 +1,80 @@ -# bworld mods specification +# Making bworld Mods -Status: **draft, format_version 1**, partly built. The [Implementation plan](#implementation-plan) lists what works -today and what's planned, and sections about planned features say so. +Mods add blocks, items, entities, recipes, world generation, game logic and screens to bworld. A mod is installed **on +the server**. Players who join download its client code, data and textures from that server automatically, so they never +install anything themselves. -Mods add blocks, items, textures, recipes, world generation, game logic and GUIs to bworld, and can change how the game -itself works. A mod is installed **on the server**. Players who join download its client code, data and textures from -the server automatically, so they don't install anything themselves. bworld is always played on a server; there is no -single player mode. +The base game is a mod too: `mods/bworld` is written against the same API as any other mod, so anything it does, your +mod can do, and it's the best place to look for examples. -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, inventory screen, HUD, commands and terrain) lives in `mods/bworld`, written against the same API as any - other mod. Mods can change each other's content, including the base game's. -- **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 any of its - methods, on the server and on the client, like Fabric's mixins. - -## Contents - -- [Overview](#overview) -- [Loading](#loading) -- [Creating a mod](#creating-a-mod) -- [Mod layout](#mod-layout) -- [manifest.json](#manifestjson) -- [Identifiers](#identifiers) -- Data: [Textures](#textures), [Blocks](#blocks), [Block models](#block-models), [Crops](#crops), [Items](#items), - [Recipes](#recipes), [Entities](#entities), [Overrides](#overrides) -- Game API: [Common scripts](#common-scripts), [Server scripts](#server-scripts), [Client scripts](#client-scripts), - [GUIs](#guis), [Mod channels](#mod-channels), [World generation](#world-generation) -- [Engine access](#engine-access) -- [Delivery to clients](#delivery-to-clients) -- [Security](#security) -- [Example mod](#example-mod) -- [The engine and the base game](#the-engine-and-the-base-game) -- [Implementation plan](#implementation-plan) -- [Open questions](#open-questions) - -## Overview - -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/`, `overrides/`, `worldgen/`, and textures | Versioned by `format_version` | -| **Game API** | Minetest's Lua API, Bedrock's Script API | TypeScript against `bworld/common`, `bworld/server`, `bworld/client` and `bworld/worldgen` | Stable, only breaks with the game's major version | -| **[Engine access](#engine-access)** | Fabric's mixins | `import { engine, hook } from "bworld/engine"`, opted into in the manifest | None, tied to one game version | - -Data is shorthand for the Game API: loading `blocks/copper_block.json` does exactly what `ctx.blocks.register(...)` with -the same object does in a common script. So anything a JSON file can do, code can do too, for content that's easier to -generate (every color of wool) or that depends on other mods. - -A mod can have up to four scripts, each running in a different place: - -| Script | Runs on | Sent to clients | Owns | -| ---------- | ---------------------------------------------- | --------------- | ------------------------------------------------------------------------------------ | -| `common` | the server and every client, before the others | yes | content: registering blocks, items, models and recipes, and changing other mods' content | -| `server` | the server, in a worker | **never** | game logic: block components, ticking, tile data, containers, commands, events | -| `client` | every client, main thread | yes | presentation: custom screens, HUD, keybinds | -| `worldgen` | the server | no | terrain and features, must be deterministic | - -**The server is the authority.** Clients send what the player is trying to do ("break the block at x, y, z", "click slot -3"). The server checks it, runs mod logic and sends back what happened. For responsiveness, clients show the expected -result of breaking and placing immediately, and the server sends a correction if it disagrees. - -``` - server process browser -┌───────────────────────────────────────┐ ┌──────────────────────────────────┐ -│ host: http, websocket, files │ │ game client (rendering, input) │ -│ ┌───────────────────────────────────┐ │ ws │ + mod common and client │ -│ │ game server worker │◄├──────────┤► scripts │ -│ │ world, inventories, tile data │ │ protocol │ │ -│ │ + mod common and server scripts │ │ chunks │ chunk workers (meshing, light) │ -│ │ + mod worldgen scripts │ │ └──────────────────────────────────┘ -│ └───────────────────────────────────┘ │ -└───────────────────────────────────────┘ -``` - -## Loading - -The server and every client load mods the same way, in the same order: dependencies first, otherwise alphabetical. The -server sends its order to clients, and they follow it. - -1. **Content**, one mod at a time: the mod's JSON data is registered, then its `common` script's `setup` runs. So a - common script sees its own data and everything from the mods before it, and can change it. -2. **Freeze.** The registries close: blocks get their numeric ids, block items are created and recipes are indexed. - Registering or changing content after this throws. -3. **Scripts.** `server` scripts' `setup` runs on the server, `client` scripts' on each client, and `worldgen` scripts - where the server generates chunks. These can read every registry but not change them. -4. The server starts ticking, or the client sends `ready` and joins. - -**Content has to come out the same on every side.** Common scripts run on the server and on every client, and all of -them must end up with exactly the same blocks, items and recipes: no `Math.random`, dates, or anything that differs -between the server and a client. After the freeze each side hashes its registries (every id and its definition), and -the client sends the hash with `ready`. When it doesn't match the server's, the player is turned away with a message -naming the first thing that differs, instead of playing with mismatched blocks. _Planned, phase 1._ - -## Creating a mod +A mod is mostly data: JSON files for blocks, items, recipes and entities, and PNG textures. Behavior comes from +TypeScript scripts: a server script for game logic, a client script for what players see, and a worldgen script for +terrain features. ```sh -deno task new-mod copper_tools "Copper Tools" # copies templates/mod to mods/copper_tools -deno task check-mods # validates every mod in mods/ +deno task new-mod copper_tools "Copper Tools" # a new mod in mods/copper_tools, from templates/mod +deno task check-mods # checks every mod in mods/ +deno task build && deno task server # packs the mods and starts a server with them ``` -The template has one of everything: a block with a custom component, an item, a shaped recipe, textures, and a script -for each side. `check-mods` checks manifests and data files against this spec, checks that every id, item and texture a -mod refers to exists (and that it depends on the mods those come from), and typechecks scripts against the API types in -`common/mod_api/`, which scripts import as `bworld/common`, `bworld/server`, `bworld/client`, `bworld/worldgen` and, -with engine access, `bworld/engine`. Folders in `mods/` starting with `_` or `.` are ignored. +## Documentation -`deno task build` packs every mod in `mods/` into a `.bmod` in `server_mods/` and fails if any has errors; -`deno task server` then loads every `.bmod` there. `deno task pack-mod mods/copper_tools` packs one mod into a file to -share, see [Mod files](#mod-files). +**Getting started** -## Mod layout +- [Getting Started](docs/modding/gettingstarted/index.md): making, checking, running and testing a mod +- [Mod Files](docs/modding/gettingstarted/modfiles.md): the folder layout, `manifest.json`, scripts and `.bmod` files -``` -mods/ - copper_tools/ - manifest.json - deno.json # optional: the mod is its own deno project, see Mod files - blocks/*.json - models/*.json - models/*.geo.json # entity models - items/*.json - entities/*.json - recipes/*.json - overrides/*.json # changes to other mods' content - worldgen/ores.json - textures/*.png - scripts/ - common.ts # content, runs on both sides - server.ts # game logic, stays on the server - client.ts # sent to players - worldgen.ts # stays on the server, players get the chunks it makes - shared/ # anything several scripts import, bundled into each -``` +**Concepts** -Only `manifest.json` is required. Data folders can have subfolders, with one definition per file. +- [Sides](docs/modding/concepts/sides.md): what runs on the server and what runs on players' clients +- [Registries](docs/modding/concepts/registries.md): ids, namespaces and how mods load +- [Events](docs/modding/concepts/events.md): reacting to and cancelling what players do +- [Security](docs/modding/concepts/security.md): what servers and players trust -## manifest.json +**Blocks** -```json -{ - "format_version": 1, - "id": "copper_tools", - "name": "Copper Tools", - "description": "Copper blocks, a copper pickaxe and a smelter with its own screen.", - "version": "1.0.0", - "authors": ["paula"], - "game_version": ">=0.1.0", - "dependencies": [ - { "id": "bworld", "version": "*" }, - { "id": "more_ores", "version": "^2.0.0" } - ], - "scripts": { - "common": "scripts/common.ts", - "server": "scripts/server.ts", - "client": "scripts/client.ts", - "worldgen": "scripts/worldgen.ts" - } -} -``` +- [Blocks](docs/modding/blocks/index.md): looks, mining, drops and placement +- [Block States](docs/modding/blocks/states.md): state bits, variants and facing +- [Block Components](docs/modding/blocks/components.md): giving blocks behavior from a server script +- [Tile Data](docs/modding/blocks/tiledata.md): data kept for one block, and blocks that hold or show items +- [Crops](docs/modding/blocks/crops.md): farming without writing code -| Field | Required | Meaning | -| ------------------ | -------- | ----------------------------------------------------------------------------------------- | -| `format_version` | yes | Version of this spec the mod targets. Loaders reject versions they don't know. | -| `id` | yes | The mod's namespace, see [Identifiers](#identifiers). Must match the folder name. | -| `name` | yes | Display name, shown to players when joining. | -| `description` | no | One or two sentences. | -| `version` | yes | Semver of the mod itself. | -| `authors` | no | List of names. | -| `game_version` | no | Semver range of bworld versions the mod works with. Mods with `engine_access` need one. | -| `dependencies` | no | Other mods by `id`, with a semver range. Missing or mismatched dependencies fail loading. A mod can only change content of mods it depends on. | -| `scripts.common` | no | Content entry, run on the server and sent to every player. _Planned, phase 1._ | -| `scripts.server` | no | Server entry. Never sent to clients. | -| `scripts.client` | no | Client entry, sent to every player. | -| `scripts.worldgen` | no | Worldgen entry, run on the server. Never sent to clients, they get chunks. | -| `engine_access` | no | `true` lets the mod's scripts import `bworld/engine`, see [Engine access](#engine-access). _Planned, phase 3._ | -| `credits` | no | A markdown file in the mod, shown on the Credits screen. For asset licenses and thanks. | +**Items** -Scripts can be `.js` or `.ts`. The build bundles each entry separately into one ES module. Code imported by several -entries is copied into each bundle, so **don't import secrets into shared code**. Anything the common or client bundles -import is visible to players. +- [Items](docs/modding/items/index.md): items, item stacks and item components +- [Tools](docs/modding/items/tools.md): tool types, tiers and durability +- [Food](docs/modding/items/food.md): hunger and saturation -## Identifiers +**Entities** -Everything a mod registers has an id of the form `namespace:name`: +- [Entities](docs/modding/entities/index.md): animals, scripted entities and entity models +- [Players](docs/modding/entities/players.md): the player API, health and hunger -- `namespace` is the mod's `id`. It must match `^[a-z0-9_]+$` and be at most 32 characters. -- Two namespaces are reserved. `bworld` belongs to the base game mod shipped in `mods/bworld` (see - [The engine and the base game](#the-engine-and-the-base-game)). `engine` belongs to the engine itself, for things - every game needs, like the block-breaking cracks and the built-in block models. The one exception is `bworld:air`: - it's the engine's empty block, but it keeps that id because every save already contains it. -- `name` must match `^[a-z0-9_]+$`. -- A mod only registers ids in its own namespace: blocks, items, models, components, recipe types, screens, channels and - HUD elements. It can _refer to_ any id, and [change](#overrides) other mods' content. -- Registering an id that already exists is a load error. Changing an existing one is what overrides are for. +**Inventories** -Blocks get a numeric id when they register, and chunk data stores those numbers. Numeric ids are **local to one running -program**, so the server and each client can number blocks differently. Saves and the network always use string ids. +- [Containers](docs/modding/inventories/containers.md): slots the server owns and saves +- [Container Screens](docs/modding/inventories/menus.md): showing containers to players -## Textures +**Resources** -- Every `.png` in `textures/` becomes a texture with id `:`. Subfolders are joined with - `_`, so `textures/ores/tin.png` becomes `:ores_tin`. -- 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. Bigger ones are for things like entity sprites. -- They go in the mod's `.bmod`, and clients put every mod's textures into one atlas when they join. -- A missing texture shows the magenta and black checker (`engine:missing`) and logs a warning. It isn't a load error. -- The engine's own textures use the `engine` namespace: `engine:missing` and the breaking cracks `engine:break_0` to - `engine:break_8`. They come from `assets/`, not from a mod. +- [Textures](docs/modding/resources/textures.md) +- [Block Models](docs/modding/resources/models.md) +- [Recipes](docs/modding/resources/recipes.md): crafting, smelting, smithing and your own recipe types -## Blocks +**Everything else** -`blocks/copper_block.json`: +- [World Generation](docs/modding/worldgen/index.md): ores and features +- [Screens](docs/modding/gui/index.md): inventory overlays and drawing with `Graphics` +- [Networking](docs/modding/networking/index.md): how players get mods and the world +- [Saving Data](docs/modding/datastorage/index.md): where a mod keeps what should last +- [Commands](docs/modding/misc/commands.md) +- [Time](docs/modding/misc/time.md): ticks, timers, days and nights -```json -{ - "format_version": 1, - "block": { - "id": "copper_tools:copper_block", - "textures": "copper_tools:copper_block", - "collision": true, - "mining": { "toughness": 5, "tool": "pickaxe", "requires_tool": true }, - "drops": "copper_tools:copper_block", - "item": true, - "components": { - "copper_tools:oxidizes": { "seconds": 600, "into": "copper_tools:oxidized_copper_block" } - } - } -} -``` +## API Types -| Field | Default | Maps to `BlockRegistry` | Meaning | -| ---------------------- | ----------- | ----------------------- | -------------------------------------------------------------------------------------------- | -| `id` | required | `id` | The block's id. | -| `name` | from the id | `name` | What players see, like `"Copper Block"`. Its item gets it too. Without it the name is made from the id: `copper_tools:copper_block` is "Copper Block". | -| `textures` | required | `textures` | One texture id, `{ top, bottom, side }` or `{ front, side }`. With another `model`, the model's texture variables, like `{ "crop": "..." }`. | -| `model` | `engine:cube` | `model` | The [block model](#block-models). | -| `variants` | none | `variants` | A different `model`, `textures` or `y` rotation for some states, see [block models](#block-models). | -| `render_layer` | `solid` | `render_layer` | `solid`, `cutout` (texels fully opaque or fully clear, like leaves) or `translucent` (blended, like water and glass). Non-solid blocks don't hide their neighbors' faces. | -| `cull_same` | see meaning | `cull_same` | Hide faces between two of this block. Defaults to `true` for translucent blocks, `false` otherwise. | -| `tint` | none | `tint` | Draws its textures in a color: `{ "color": "grass" }` or `"foliage"` for the biome's (blended across biome edges, like minecraft's grass and leaves), or a fixed one like `"#80a755"`. `"textures": ["top"]` tints only those texture variables, like the grass block's top. Paint the textures grey. Its item uses plains' color. | -| `light_emission` | `0` | `light_emission` | Light level 0-15 it gives off, like a torch (14). | -| `light_opacity` | see meaning | `light_opacity` | How much light passing through it loses, 0-15. Defaults to `15` (blocks all light) for solid blocks and `0` otherwise. Leaves and water use `1`. | -| `alpha` | `1` | `alpha` | Opacity for translucent blocks. | -| `collision` | `true` | `has_collision` | Whether entities collide with it. | -| `mining.toughness` | unbreakable | `toughness` | Seconds to break by hand. A matching tool is its `tool.speed` times faster. | -| `mining.tool` | none | `tool_to_break` | Tool type that speeds it up, like `pickaxe`, `axe` or `shovel`. | -| `mining.requires_tool` | `false` | `requires_tool` | Only drops when broken with `mining.tool`. | -| `mining.tier` | `0` | `tool_tier` | With `requires_tool`, the lowest `tool.tier` it drops for, like Minecraft's `incorrect_for_*_tool` tags. Iron ore is `1`, so a wood pickaxe gets nothing. | -| `drops` | nothing | `drop_table` | Item id dropped on the ground when broken, for players to pick up. | -| `item` | `true` | `register_block_item` | Also register an item that places this block, with the same id. | -| `interactive` | `false` | `interactive` | Right clicking it does something (opens a screen), so clients don't guess it places a block. | -| `replaceable` | `false` | new | Placing a block into it replaces it, like water. | -| `place_in` | see meaning | `place_in` | Block ids it can be placed into, replacing them, like `["bworld:water"]` for rice. Air and `replaceable` blocks when not set. | -| `place_on` | anywhere | `place_on` | Block ids it can stand on, like `["bworld:hoed_dirt"]` for crops. Players can't place it anywhere else, and it breaks (with its drops) when the block under it becomes something else, like Minecraft's `canSurvive`. | -| `states` | none | `states` | Up to 16 bits of named state, like `hoed_dirt` has now. | -| `components` | none | `components` | Custom components with parameters, handled by server scripts. | +The API types are the reference for everything scripts can call. Scripts import them as `bworld/server`, `bworld/client` +and `bworld/worldgen`, and they live in [`common/mod_api/`](common/mod_api/). -The client needs this data too (for meshing, mining time and collision), so it's sent to every player. It can't contain -functions. - -Block states are declared like `[{ "name": "facing", "bits": 2, "default": 0 }]`, at most 16 bits in total. A block -starts with its defaults when it's placed or generated, and server scripts read and change them with -`ctx.world.get_state` / `set_state`. States are saved with the world and synced to players. `variants` changes how the -block looks with them. - -## Block models - -A block's shape comes from its model, `engine:cube` unless it sets `model`. The engine has three: - -| 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, because `solid` blocks hide their -neighbors' faces. This is what minecraft's `"render_type": "minecraft:cutout"` does. They usually want -`"collision": false` too, and show as a flat sprite of their first texture in inventories. - -`blocks/wheat.json` picks a texture per growth stage with `variants`. The keys are conditions on the block's states, -`"age=3"` or `"age=3,facing=1"` (all have to match), and the first variant that matches replaces the block's `model`, -`textures` or turns it by `y` (0, 90, 180 or 270 degrees, clockwise seen from above): - -```json -{ - "format_version": 1, - "block": { - "id": "bworld:wheat", - "model": "engine:crop", - "textures": { "crop": "bworld:wheat_stage_0" }, - "variants": { - "age=0": { "textures": { "crop": "bworld:wheat_stage_0" } }, - "age=1": { "textures": { "crop": "bworld:wheat_stage_1" } } - }, - "render_layer": "cutout", - "collision": false, - "states": [{ "name": "age", "bits": 3, "default": 0 }] - } -} -``` - -Mods add their own models in `models/`, in minecraft's block model format: boxes in pixels (0-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" } - } - }] - } -} -``` - -| Field | Meaning | -| ---------------------------- | ---------------------------------------------------------------------------------------------- | -| `id` | The model's id, in the mod's namespace. | -| `textures` | Defaults for texture variables. Values are texture ids or other variables (`"#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` | `top`, `bottom`, `north`, `south`, `west` and `east`. Faces are only drawn from the front, so a flat plane needs one face each way. | -| `faces.*.texture` | A variable (`"#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` | Hidden when the neighbor on that side is a solid block. Only for faces on the block's edge. | - -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 block's own light. - -## Crops - -Like a Fabric `CropBlock`, a crop is a block with an `age` state and a seeds item that places it, so adding one is only -data. The base game's `bworld:crop` component (in `mods/bworld/scripts/server.ts`) does the growing, with Stardew -Valley's clock: every morning at 06:00 a crop whose farmland was watered the day before grows a day, and it shows the -stage for how far along it is. `mods/farmersdelight` adds its cabbages, onions, tomatoes and rice this way. - -`blocks/cabbages.json`, with its `variants` giving one texture per age (see [Block models](#block-models)): - -```json -{ - "format_version": 1, - "block": { - "id": "farmersdelight:cabbages", - "model": "engine:cross", - "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" - } - } - } - } -} -``` - -and `items/cabbage_seeds.json` with `"places": "farmersdelight:cabbages"`. - -| 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` | Like a crop's loot table: `young` (not grown yet), `mature` (grown), and `bonus`, 1 to 4 of an item when grown, like wheat's seeds (Minecraft's 1 plus 3 tries at 57%). `young` and `mature` can be one id or a list. | -| `fertilizer` | An item that grows it a day right away, like bone meal. | -| `regrow_days`, `harvest` | Picked by right clicking once grown, dropping `harvest.item` (`count` is `[min, max]`), then grown again after `regrow_days`, like tomatoes. | -| `water` | `"farmland"` (the default): needs watered farmland under it. `"always"`: grows every morning, like rice in water. | -| `upper` | `{ block, stages, supporting_age }`: its last stages grow a second block on top, like rice's panicles. The top block uses the `bworld:crop_top` component with `{ stages, drops }`; breaking it harvests the whole plant. | -| `leaves` | What the spot becomes after it's broken, like water where rice was. | - -Players place blocks into the block they click when it's `replaceable`, like Minecraft, so rice (with -`"place_in": ["bworld:water"]`) is planted by clicking water. Food that places a block, like potatoes, is planted when -clicked on somewhere it can go and eaten otherwise. - -## Items - -`items/copper_pickaxe.json`: - -```json -{ - "format_version": 1, - "item": { - "id": "copper_tools:copper_pickaxe", - "texture": "copper_tools:copper_pickaxe", - "tool": { "type": "pickaxe", "tier": 1, "speed": 3.5, "durability": 190 }, - "lore": "Better than wood, worse than iron." - } -} -``` - -| Field | Default | Maps to `ItemRegistry` | Meaning | -| ------------ | -------- | ------------------------ | -------------------------------------------------- | -| `id` | required | registry key | The item's id. | -| `name` | from the id | `name` | What players see, like `"Copper Pickaxe"`. Made from the id when not set. | -| `texture` | required | `texture_id` | Texture id. | -| `data_textures` | none | `data_textures` | `{ "cast": "bworld:fishing_rod_cast" }`: a stack whose `data` has that key set is drawn with that texture instead, like a cast fishing rod. The first key that's set wins. | -| `tool` | none | `tool` | Makes it a tool, like Fabric's `ToolMaterial`: `type` (matched against blocks' `mining.tool`, like `"pickaxe"`), `tier` (default `0`, see blocks' `mining.tier`), `speed` (default `2`, how many times faster than a hand) and `durability` (shown in its tooltip, nothing uses it up yet). The base game's tiers are wood and gold `0`, stone and copper `1`, iron `2`. | -| `places` | none | `block_id` | Block placed when used on a block face. | -| `max_stack` | `64`, `1` for tools | new | Largest stack size. | -| `food` | none | `food` | Makes it edible: `{ "nutrition": 3, "saturation_modifier": 0.6 }`, with Minecraft's meanings (hunger points out of 20, and saturation of nutrition × modifier × 2). Optional `always_edible` (eaten even when full) and `returns` (an item left in the hand, like a bowl). Players eat it by right clicking while hungry. | -| `lore` | none | `lore` | Tooltip text under the name. `\n` starts a new line. | -| `components` | none | `on_create` / `get_lore` | Custom item components, handled by server scripts. | - -Item stacks can carry `data`, a JSON value set by the server (like the watering can's water level). It's synced to -clients as part of the container it's in, so client screens can show it. - -## Recipes - -`recipes/smelt_copper_block.json`: - -```json -{ - "format_version": 1, - "recipe": { - "type": "furnace", - "input": "copper_tools:copper_block", - "output": { "id": "bworld:copper_ingot", "count": 9 }, - "cook_time": 400 - } -} -``` - -| `type` | Fields | Notes | -| --------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | -| `shaped` | `pattern` rows (space is empty), `key` letter to item id (or a list of ids), `result` `{ id, count }` | Used by the crafting grid, fits anywhere in it | -| `furnace` | `input` item id (or a list of ids), `output` `{ id, count }`, `cook_time` in ticks | Used by the furnace | -| `fuel` | `item` id (or a list of ids), `burn_time` in ticks | Used by the furnace | -| `smithing` | `tool` item id, `material` `{ id, count }`, optional `addition` item id, `result` item id | Used by the smithing table: upgrades the tool, keeping its data. Uses up the tool, `count` of the material and the addition | - -A smithing recipe, `recipes/smithing_stone_pickaxe.json`: - -```json -{ - "format_version": 1, - "recipe": { - "type": "smithing", - "tool": "bworld:wood_pickaxe", - "material": { "id": "bworld:stone", "count": 5 }, - "result": "bworld:stone_pickaxe" - } -} -``` - -A shaped recipe, 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 } - } -} -``` - -Where a recipe takes an item, a list of ids means any of them fits, like every kind of planks in the stick recipe: -`"key": { "P": ["bworld:planks", "bworld:birch_planks"] }`. In a 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. - -Two furnace recipes with the same `input`, two smithing recipes with the same tool, material and addition, or two -shaped recipes with the same pattern and key, are a load error. - -Mods can use recipe types of their own for their machines: any `type` with a namespace, like Farmer's Delight's -`farmersdelight:cooking` for its cooking pot. The engine only stores them, the mod's server script reads them with -`ctx.recipes.list("farmersdelight:cooking")` and checks the rest of the fields itself (throwing in `setup` makes a bad -recipe a load error). Other mods can add recipes of that type too. `recipes/cooking_cabbage_rolls.json`: - -```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 cooking pot takes up to 6 `ingredients` in any slots, each an item id or a list of ids any of which will do. The -optional `container` (like `"bworld:bowl"`) is what the meal is served in, and `cook_time` is in ticks, 200 when not -set. It cooks while the block under it is hot: a lit stove (placed lit, relit with coal, put out with a shovel), or a -burning furnace, whose `lit` state is 1 while it has fuel. - -## Entities - -Mobs are an entity in `entities/` and a bedrock entity model in `models/`. `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 | What it does | -| ---------------- | ---------- | ------------------------------------------------------------------------------------- | -| `model` | | An entity model, see below. Without one it's drawn as its texture, facing the camera. | -| `texture` | | Any texture, stretched to the model's `texture_width` and `texture_height`. | -| `behavior` | `"animal"` | `"animal"` or `"scripted"`, see below. | -| `width`/`height` | | Its collision box in blocks. Its eyes are at 85% of the height. | -| `max_health` | `10` | Half hearts. | -| `movement_speed` | `0.25` | Minecraft's per tick speed, 0.25 for most animals. | - -An animal wanders around, panics when hurt, looks at players now and then, swims up in water and never despawns. A -scripted entity stays where a script puts it (see `spawn_entity` in [Server scripts](#server-scripts)): it doesn't fall, -think or get hurt, and isn't saved with the world, so a script never finds one it doesn't know about after a restart. -The fishing hook is one, drawn as its texture since it has no model: - -```json -{ - "format_version": 1, - "entity": { - "id": "bworld:fishing_hook", - "texture": "bworld:fishing_hook", - "behavior": "scripted", - "width": 0.25, - "height": 0.25 - } -} -``` - -Without a model, the whole texture is drawn 16 pixels to a block, centered on the middle of its box. -`/summon ` spawns one where you stand. - -Entity models are `models/.geo.json`, as Blockbench exports them for Bedrock (the "Bedrock Entity" format), with -id `:`. Only the first geometry is used, and from it the bones' `name`, `parent`, `pivot` and `rotation` -and the cubes' `origin`, `size`, `uv` and `inflate`. Cubes need box uv, per face uv isn't supported. The model faces --z, 16 pixels to a block, and shows the way Blockbench shows it. It doesn't animate yet: the whole model turns with the -entity, and a bone named `head` turns to where it looks. - -## Overrides - -A mod can change content other mods registered, like Minetest's `override_item`. The JSON form covers the common cases, -and a [common script](#common-scripts) can do the same with `override` and `extend`. _Planned, phase 2._ - -`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, with the same names as in the block or item JSON. Each listed field is replaced whole, so `mining` above replaces all of the old `mining`. | -| `add_components` | Components to add. One the block or item already has gets these params instead. | -| `remove_components` | Component ids to take away. | - -A recipe override removes recipes, so a mod can replace them with its own: - -```json -{ - "format_version": 1, - "override": { "remove_recipes": { "type": "shaped", "result": "bworld:chest" } } -} -``` - -`remove_recipes` matches recipes whose fields equal the ones given (`result` matches the result's id). - -Rules: - -- 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 when two mods change the same field the later one wins. `check-mods` warns about it. -- Ids never change, and blocks and items can't be removed, because saves refer to them. To make something unobtainable, - remove its recipes and drops. -- Overrides are content like everything else: they're applied on the server and every client, and are part of the - registry hash. - -## Common scripts - -`scripts.common` exports `setup`, called on the server and on every client while content loads, right after the mod's -own JSON is registered (see [Loading](#loading)). _Planned, phase 1._ - -```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`, - }); - ctx.recipes.register({ - type: "shaped", - pattern: ["D", "W"], - key: { D: `wool:${color}_dye`, W: "wool:white_wool" }, - result: { id: `wool:${color}_wool`, count: 1 }, - }); - } - - // wool burns in the base game's furnace - for (const color of COLORS) { - ctx.recipes.register({ type: "fuel", item: `wool:${color}_wool`, burn_time: 100 }); - } - - // 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; - items: ContentRegistry; - models: ContentRegistry; - recipes: RecipeRegistry; - log(...args: unknown[]): void; -} - -// T is the same shape as the JSON file's content, checked the same way -interface ContentRegistry { - register(definition: T): void; - get(id: string): Readonly | undefined; // what's registered so far, by any mod - ids(): string[]; - override(id: string, fields: Partial): void; // like "set" in an override file - extend(id: string, change: { components?: Record; remove_components?: string[] }): void; -} - -interface RecipeRegistry { - register(recipe: RecipeJson): void; - remove(match: (recipe: RecipeJson) => boolean): number; // how many it removed - list(type: string): readonly RecipeJson[]; - // a new recipe type: its recipes are checked with validate, and scripts read them with list - 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. They can't keep state for later, and can't reach the world, players or - anything else: that's what server and client scripts are for. They get the same `ctx` shape on both sides on - purpose, so they can't accidentally register different things. -- Recipe types are ids like everything else. `shaped`, `furnace`, `fuel` and `smithing` are short for `bworld:shaped` - and so on, since the base game's crafting grid, furnace and smithing table use them. A mod's machine registers its own - type (`copper_tools:alloy`) and its server script reads the recipes with `ctx.recipes.list("copper_tools:alloy")`. - -## Server scripts - -`scripts.server` exports `setup`, called once when the server starts: - -```ts -import type { ServerContext } from "bworld/server"; - -export function setup(ctx: ServerContext) { - // register components, commands, containers, event handlers -} -``` - -Server scripts run in the game server worker with **no Deno permissions** (see [Security](#security)). They get the mod -API and standard JavaScript, but no file, network or subprocess access; persistent state goes through `ctx.storage`. - -`ctx` is the Game API for the server. Content is already registered and frozen by now (see [Loading](#loading)), so -server scripts read registries but don't change them. - -```ts -interface ServerContext { - mod: { id: string; version: string }; - components: ComponentRegistry; // only during setup - commands: CommandRegistry; // only during setup - events: { before: ServerBeforeEvents; after: ServerAfterEvents }; - system: System; - world: ServerWorld; - players: PlayerList; - containers: ContainerApi; - items: ItemApi; - recipes: RecipeApi; - ui: ServerUi; // see GUIs - net: ServerNet; // see Mod channels - storage: ModStorage; - log(...args: unknown[]): void; -} -``` - -### Block and item components - -Blocks and items get behavior from components registered here: - -```ts -ctx.components.register_block("copper_tools:oxidizes", { - on_create(block) { - block.data = { age: 0 }; - }, - on_second(block, params, dt) { - block.data.age += dt; - if (block.data.age >= params.seconds) { - ctx.world.set_block(block.x, block.y, block.z, params.into); - } - }, -}); -``` - -| Handler | Called when | Return value | -| ------------------------------------ | ----------------------------------------- | ------------------------------------------ | -| `on_create(block, params)` | The block is placed or set. | ignored | -| `on_break(block, params, player?)` | The block is broken or replaced. | ignored | -| `on_click(block, params, player)` | A player starts hitting it. | ignored | -| `on_interact(block, params, player)` | A player right clicks it. | `true` if handled, so no block gets placed | -| `on_tick(block, params, dt)` | Every tick (20 per second) near a player. | ignored | -| `on_second(block, params, dt)` | Every second near a player. | ignored | -| `on_new_day(block, params, day)` | Every morning at 06:00, anywhere in the world. | ignored | - -`block` is `{ id, x, y, z, data }`. `data` is tile data: any JSON value, `undefined` until a handler sets it, saved with -the world and **never sent to clients**. To show tile data to a player, open a screen with it (see [GUIs](#guis)). -`on_tick`, `on_second` and `on_new_day` only run for blocks that have tile data, so a component that ticks from the -start sets `block.data` in `on_create`. `on_new_day` runs for every such block in the world, near a player or not, so -things like crops keep growing while nobody's around (see the base game's farming in `mods/bworld/scripts/server.ts`). -When time jumps forward past several mornings (`/time add`), each one runs, up to 64. They run within 6 chunks of a player. `dt` is in seconds: 0.05 for `on_tick`, 1 for -`on_second`. - -The server runs a fixed 20 ticks per second. When a tick takes too long, the next ones run back to back until it has -caught up, so game time keeps pace with real time. When it's more than ten ticks behind it skips the rest and logs a -warning. `/tps` shows how it's doing. Timers (`ctx.system`) count these ticks. - -When a block lists several components, each handler runs in the listed order. `on_interact` counts as handled if any -component returns `true`. - -Item components use -`ctx.components.register_item(id, { on_create(item, params), get_lore(item, params), on_use(item, -params, player) })`. -`on_use` runs when a player right clicks while holding the item, both at nothing and at a block. At a block, the block's -own interaction comes first, and an item with `on_use` is used instead of being placed. `get_lore` is extra tooltip text -for one stack, like the watering can's "Water: 12/32": the server works it out whenever it sends the item to a player -and shows it under the item's own `lore`. It isn't saved. - -### Events - -**Before events** fire before something happens. Handlers can read and change the event, or set `cancel = true` to stop -it. They can't change the world themselves; use the after event or `system.run_timeout(fn, 0)` for that. **After -events** fire once it has happened. - -| Event | before | after | Payload | -| ---------------- | ------ | ----- | -------------------------------------------------------- | -| `block_break` | ✓ | ✓ | `player`, `block`, `item` | -| `block_place` | ✓ | ✓ | `player`, `block`, `face`, `item` | -| `block_interact` | ✓ | ✓ | `player`, `block`, `item` | -| `chat_send` | ✓ | ✓ | `player`, `message` (before events can change `message`) | -| `player_damage` | ✓ | | `player`, `amount`, `cause` (before events 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 | -| `tick` | | ✓ | `dt` in seconds, 20 times per second | -| `new_day` | | ✓ | `day`, at 06:00 after every block's `on_new_day` | - -These fire for **every** player's actions, because they all go through the server. When a before event cancels a break -or place, the server tells that player's client to undo what it already showed. - -### World, players, system, storage - -```ts -interface ServerWorld { - get_block(x: number, y: number, z: number): string | undefined; // undefined when the chunk isn't loaded - set_block(x: number, y: number, z: number, id: string): boolean; // runs on_break / on_create, synced to everyone - break_block(x: number, y: number, z: number): boolean; // like breaking it by hand: on_break, then its drops - get_state(x: number, y: number, z: number, name: string): number | undefined; - set_state(x: number, y: number, z: number, name: string, value: number): boolean; - get_block_data(x: number, y: number, z: number): T | undefined; - drop_item(x: number, y: number, z: number, item: ItemStack): void; // pops out of the block, like drops - spawn_entity(id: string, x: number, y: number, z: number): EntityRef; // feet at x y z, see Entities - is_loaded(x: number, z: number): boolean; - readonly seed: string; - readonly time: number; // world time, see below - readonly day: number; // days since the world started, going up at 06:00, 0 on the first day - set_time(time: number): void; // synced to every player -} - -// once it's removed, by a script or anything else, it stays removed and teleporting it does nothing -interface EntityRef { - readonly id: string; - readonly type: string; - readonly position: { x: number; y: number; z: number }; - readonly removed: boolean; - teleport(x: number, y: number, z: number): void; - remove(): void; -} - -interface Player { - readonly id: string; - readonly name: string; - readonly position: { x: number; y: number; z: number }; - readonly inventory: Container; // 36 slots, hotbar is 0-8 - readonly selected_slot: number; - readonly held_item: ItemStack | undefined; - // what doesn't fit in the inventory drops at their feet - give_item(id: string, count?: number, data?: unknown): void; - send_message(text: string): void; - teleport(x: number, y: number, z: number): void; - readonly health: number; // out of max_health, 20 - readonly max_health: number; - readonly food: number; // hunger, out of 20 - readonly saturation: number; // never above food - damage(amount: number, cause?: string): void; // cause shows in events and the death message - heal(amount: number): void; - feed(nutrition: number, saturation_modifier: number): void; // like eating - add_exhaustion(amount: number): void; // 4 costs a point of saturation, or of hunger once it's gone -} - -interface PlayerList { - all(): Player[]; - get(id: string): Player | undefined; - by_name(name: string): Player | undefined; -} - -interface System { - run_timeout(fn: () => void, ticks: number): number; - run_interval(fn: () => void, ticks: number): number; - clear_run(handle: number): void; - readonly current_tick: number; -} - -// small key value store per mod, saved with the world -interface ModStorage { - get(key: string): T | undefined; - set(key: string, value: unknown): void; // JSON values only - delete(key: string): void; -} -``` - -**Health and hunger** follow Minecraft's rules (`server/game/vitals.ts`). Sprinting, swimming, jumping, breaking blocks, -taking damage and healing add exhaustion, and every 4 of it 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. Falls hurt 1 per block after the first 3, unless they land in water, -and below the world players die. Dying drops everything they carried and respawns them at spawn with full health and -hunger. - -**World time** counts ticks since 06:00 of day 1 and never wraps around. A day (06:00 to 18:00) is 36000 ticks, 30 -minutes, and a night (18:00 to 06:00) is 12000 ticks, 10 minutes, so in game hours are shorter at night. Dusk is the -first minute of the night and dawn the last, so it's bright all day. `common/time.ts` has `clock`, `format_clock`, -`is_day` and `daylight` for turning it into something readable. Client scripts can read it as `ctx.world.time`, and -players can use `/time`, `/time set ` and `/time add `. - -The server loads chunks around every player (its simulation distance) and generates them itself, then sends them to -players whole (see [Chunks](#chunks)). Blocks in unloaded chunks can't be read or changed, and don't tick. - -### Commands - -Commands work like Fabric's, which are Minecraft's Brigadier: a tree of literal words and typed arguments. Each -argument type reads its text and suggests what could go there, and players see those suggestions above the chat box as -they type (Tab puts one in, Up and Down pick). The tree is in `common/commands.ts`. - -```ts -const { literal, argument, types } = ctx.commands; -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("amount"))) - .then( - argument("target", types.player()) - .executes((context) => heal(context.get("target"), context.get("amount"))), - ), - ), -); -``` - -| 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`, then `context.get(name)` in `executes`. | -| `.then(node)` | What can come next. | -| `.executes(fn)` | Runs when the command ends here. Without it, ending here says what's missing. | -| `.requires(fn)` | Only for sources it's 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 it and `send_message(text)` to answer them. Throwing -`new CommandError(message)` tells the player what's wrong. Any other error is logged with the mod's id and the player -is told something went wrong. - -| `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()` and `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 | - -The simple form is still there, it's a command taking the rest of the line split on spaces: - -```ts -ctx.commands.register("heal", { - description: "Heal yourself", - usage: "/heal [amount]", - run(args, player) { - player.send_message(`healed ${args[0] ?? "all"}`); - }, -}); -``` - -Commands run on the server when a player types `/name` in chat, and the client asks the server for suggestions. Two -mods using the same name, or a mod using one of the engine's (`give`, `time`, `tps` and `help`), is a load error. -`/copper_tools:heal` always works as the unambiguous form. - -The engine's commands: - -| Command | What it does | -| --------------------------------------------------------- | ----------------------------------------------------------------------- | -| `/give []` | Gives you an item | -| `/time`, `/time set `, `/time add ` | Shows or changes the time. Times of day are the next one, time never goes back | -| `/tps` | How the game loop keeps up | -| `/help []` | Every command's usage, or one's | - -## Client scripts - -`scripts.client` exports `setup`, called after the client has downloaded the server's mods and before the world appears: - -```ts -import type { ClientContext } from "bworld/client"; - -export function setup(ctx: ClientContext) { - // register screens, HUD elements, keybinds, channel handlers -} -``` - -```ts -interface ClientContext { - mod: { id: string; version: string }; - ui: ClientUi; // see GUIs - hud: HudRegistry; - input: { bind(id: string, default_key: KeyCode, on_press: () => void): void }; - net: ClientNet; // see Mod channels - player: { readonly name: string; readonly position: { x: number; y: number; z: number } }; - world: { get_block(x: number, y: number, z: number): string | undefined }; // read only, what the client sees - // every item any mod registered, in load order: ids(), exists(id), name(id) ("Cooked Rice"), mod(id) (its mod's name) - items: ClientItems; - // every recipe as its json, including mods' own types, in load order - recipes: { list(type?: string): RecipeJson[] }; - log(...args: unknown[]): void; -} -``` - -`ctx.player`, `ctx.world`, `ctx.items`, `ctx.recipes`, `ctx.log` and `ctx.ui.add_inventory_overlay` work so far, the rest -is phase 4. - -### Inventory overlays - -`ctx.ui.add_inventory_overlay` draws on every inventory screen (the player's inventory, chests, furnaces and other -container screens) with [`Graphics`](#3-custom-screens-client-code), over the screen, like Just Enough Items' item list. -`mods/recipe_viewer` is one. - -```ts -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; - g.text(screen.hovered_item ? ctx.items.name(screen.hovered_item.id) : "", x, 16); - }, -}); -``` - -Overlays get the mouse before the slots. A click they use (`g.button`, or `g.consume_click()`) doesn't reach the slots, -and `g.block_mouse(x, y, w, h)` keeps the slots from taking 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 does: 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. - -Client scripts are for presentation. They can't change the world or inventories; they ask the server over a -[mod channel](#mod-channels). Anything they show should be treated as a view of the server's state. Everything in a -client script is visible to players and can be changed by them, so it must not be trusted for anything that matters. - -Keybinds registered with `ctx.input.bind` get an id (`copper_tools:open_smelter`) so a future controls menu can rebind -them. They only fire while no screen is open. - -## GUIs - -There are three ways to show a GUI. They're listed from least code to most. Pick the first one that's enough. - -### 1. Forms (server only) - -_Planned, phase 4._ - -Simple dialogs defined entirely by server code, like Bedrock's `@minecraft/server-ui`. The client draws them with the -game's UI style. No client script is needed. - -```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); -} - -const settings = await ctx.ui.modal_form(player, { - title: "Smelter settings", - fields: [ - { type: "toggle", label: "Auto-eject", default: true }, - { type: "slider", label: "Speed", min: 1, max: 4, step: 1, default: 1 }, - { type: "dropdown", label: "Output", options: ["Chest", "Ground"] }, - { type: "text", label: "Name", placeholder: "smelter", max_length: 32 }, - ], -}); -// settings.values = [true, 3, 0, "smelter"], checked against the fields before your code sees them -``` - -| Form | Shows | Resolves with | -| -------------- | ------------------------------ | ------------------------------------------------------- | -| `message_form` | title, body, two buttons | `{ canceled, selection: 0 \| 1 }` | -| `action_form` | title, body, a list of buttons | `{ canceled, selection: number }` | -| `modal_form` | title, input fields | `{ canceled, values: (boolean \| number \| string)[] }` | - -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 your -code sees it. - -### 2. Container screens (server only) - -For inventories and machines. The server owns the container's contents and syncs them to every player viewing it. Clicks -go to the server, which applies them. The base game's chest and furnace are built this way, see -`mods/bworld/scripts/server.ts`. - -```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 container = ctx.containers.get(block.data.container)!; - const screen = ctx.ui.open_container(player, { - container, - layout: [ - { slot: 0, x: 3, y: 0, filter: "smeltable" }, - { slot: 1, x: 3, y: 2, filter: (item) => ctx.recipes.is_fuel(item.id) }, - { 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; - }, - on_break(block) { - ctx.containers.delete(block.data.container); - }, -}); -``` - -- The screen is drawn below the player's inventory and hotbar. `x` / `y` are in slot units in the screen's own area and - can be fractional. `rows` sets its height, by default it fits the slots and bars. -- `filter` is a function `(item) => boolean` or one of the built-in filters `"smeltable"` (has a furnace recipe) and - `"fuel"`. It and `output_only` run **on the server**, so players can't put the wrong items in by editing their client. - `output_only` slots can only be taken from, all at once, like the furnace result. Their `on_take(item)` runs when a - player takes from one, before they get it: return `false` to stop them, or use up the inputs there so they're gone in - the same step (the smithing table does this). -- `bars` are progress bars filled with `value / max`, both names of properties set with `screen.set_property(id, n)`. - `direction` is `"up"` (like the furnace's fire) or `"right"` (like its arrow). Properties are synced when they change, - so a component can update them every tick. -- The screen handle has `player`, `open`, `set_property`, `close()` and `on_close(fn)`. It closes when the player closes - it, leaves, or opens another screen, and when its container is deleted. Changes to the container (from scripts, - other players) show up for everyone viewing it. -- Containers are saved with the world until they're deleted, so a block that has one deletes it in `on_break`. - -```ts -interface ContainerApi { - create(size: number): Container; // 1 to 256 slots, saved with the world - get(id: string): Container | undefined; - delete(id: string): void; // closes screens showing it -} - -interface Container { - readonly id: string; - readonly size: number; - get(slot: number): ItemStack | undefined; - set(slot: number, item: ItemStack | undefined): void; - add(item: ItemStack): ItemStack | undefined; // returns what didn't fit - on_change(fn: (slot: number) => void): () => void; -} - -interface ItemApi { - exists(id: string): boolean; - max_stack(id: string): number; -} -``` - -Items handed to scripts are live: setting `count` changes the stack, and a stack counted down to 0 is gone. - -### 3. Custom screens (client code) - -_Planned, phase 4._ - -For anything forms and containers can't do: maps, skill trees, minigames, custom layouts. The client script registers a -screen class, and the server opens it with some props: - -```ts -// client.ts -import type { ClientContext, Graphics, ModScreen } from "bworld/client"; - -export function setup(ctx: ClientContext) { - ctx.ui.register_screen("copper_tools:smelter_stats", (props) => new SmelterStats(ctx, props)); -} - -class SmelterStats implements ModScreen { - constructor(private ctx: ClientContext, private props: { total_smelted: number; top: [string, number][] }) {} - - on_render(g: Graphics) { - g.panel(g.width / 2 - 200, g.height / 2 - 150, 400, 300); - g.text(`Smelted: ${this.props.total_smelted}`, g.width / 2 - 180, g.height / 2 - 130, { scale: 2 }); - this.props.top.forEach(([id, count], i) => { - g.item(id, g.width / 2 - 180, g.height / 2 - 90 + i * 60); - g.text(`${count}`, g.width / 2 - 110, g.height / 2 - 75 + i * 60); - }); - if (g.button("Reset", g.width / 2 - 60, g.height / 2 + 100, 120, 32)) { - this.ctx.net.send("copper_tools:reset_stats", {}); - } - } - - // the server sent new props for this screen - on_props(props: SmelterStats["props"]) { - this.props = props; - } -} -``` - -```ts -// server.ts -const screen = ctx.ui.open_screen(player, "copper_tools:smelter_stats", { total_smelted: 42, top: [] }); -screen.update({ total_smelted: 43, top: [] }); // calls on_props on the client -screen.on_close(() => ctx.log("closed")); -``` - -```ts -interface ModScreen { - on_open?(): void; - on_tick?(dt: number): void; - on_render(g: Graphics): void; - on_props?(props: unknown): void; - on_close?(): void; - // return true to keep the screen open when escape is pressed - on_escape?(): boolean; -} - -// immediate mode, like the debug ui, styled with the gui sprites (assets/sprites/gui.png) -interface Graphics { - readonly width: number; - 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?: [number, number, number, number]): void; - panel(x: number, y: number, w: number, h: number): void; // nine slice background - text(text: string, x: number, y: number, options?: { scale?: number; color?: number[] }): void; - measure_text(text: string, scale?: number): number; - texture(id: string, x: number, y: number, w: number, h: number): void; // any atlas texture - item(id: string, x: number, y: number, count?: number): void; - clip(x: number, y: number, w: number, h: number, draw: () => void): void; - button(label: string, x: number, y: number, w: number, h: number): boolean; // true on the frame it's clicked - text_input(id: string, x: number, y: number, w: number): string; - slider(id: string, x: number, y: number, w: number, min: number, max: number): number; - // server synced slots, same behavior as container screens - slots(container: string, layout: { slot: number; x: number; y: number }[], x: number, y: number): void; - key_pressed(key: KeyCode): boolean; // 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 the click - block_mouse(x: number, y: number, w: number, h: number): void; // the screen underneath ignores the mouse there -} -``` - -Everything but `slider` and `slots` works, for [inventory overlays](#inventory-overlays). - -Custom screens can also show server containers. The server passes them in when opening: -`ctx.ui.open_screen(player, id, props, { containers: { input: container } })`, and the screen draws them with -`g.slots("input", layout, x, y)`. Clicks still go to the server and follow the container rules, so a custom screen can't -bypass `filter`. - -A client script can also open its own screens with `ctx.ui.open(id, props)`, for things like a settings page that -doesn't involve the server. - -### HUD - -_Planned, phase 4._ - -```ts -ctx.hud.register("copper_tools:heat", { - on_render(g) { - g.text(`Heat: ${heat}`, 8, 8); - }, -}); -``` - -HUD elements draw every frame after the world, under open screens. They get their data from mod channels. - -## Mod channels - -_Planned, phase 4._ Client and server parts of a mod talk over named channels. Messages are JSON. - -```ts -// server.ts -ctx.net.on("copper_tools:reset_stats", (player, _data) => { - if (!is_admin(player)) return; - stats.clear(); -}); -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) => { - heat = data.value; -}); -ctx.net.send("copper_tools:reset_stats", {}); -``` - -- Channel ids are in the mod's namespace. A mod can listen to other mods' channels but only send on its own. -- A message is at most 16 KB of JSON. Each player can send at most 60 mod messages per second in total; the server drops - anything over that and logs it. -- **Everything a client sends is untrusted.** Check the player's permission, check every field's type and range, and - never use client data as an item id or amount without validating it. -- Messages to a channel nobody listens to are dropped, with a warning in development builds. -- On the wire this is one protocol message, `{ type: "mod", channel, data }`, in both directions. - -## World generation - -Chunks are generated from the world seed on the server only, and players get the finished chunks (see -[Chunks](#chunks)). Saves only keep what players changed on top of generated terrain, so a chunk has to come out the -same every time it's generated: worldgen scripts must be **deterministic**. - -Each chunk is generated in three passes: - -1. **Terrain.** One terrain generator fills in the ground, water and trees. -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 (`CHUNK_HEIGHT` and `SEA_LEVEL` in `common/constants.ts`). The -base overworld lives in `common/worldgen/` until phase 6 moves it into `mods/bworld`. It works like Minecraft 1.18+ and -the Terralith datapack: continentalness, erosion and weirdness noises feed nested splines that give every column a -height, jaggedness and roughness, a 3D density around that height is sampled on a coarse grid and interpolated, and -caves are cut out of it. On top of that come Terralith-style shapes: terraced plateaus, shattered hills, river valleys -and gorges, jagged peaks and rare sky islands. Its biome ids (`biome_at`) are the keys of `BIOMES` in -`common/worldgen/overworld.ts`, like `bworld:yosemite_cliffs` or `bworld:skylands`. Trees -(`common/worldgen/trees.ts`) are spread out like Poisson disk sampling, never closer than 4 blocks, and each biome sets -how many grow and which kinds. `deno run -A tools/worldgen_preview.ts [seed]` renders it to PNG files. - -### Terrain generators - -A world uses exactly one terrain generator, registered by a worldgen script. The base game's will be `bworld:overworld` -(phase 6); until then `register_terrain` throws and the engine's own overworld is used. -Which one a world uses is saved with the world. A new world uses the only one installed, or the server's `TERRAIN` -setting when there are several. A server with no terrain generator refuses to start. - -```ts -export function setup(gen: WorldgenContext) { - gen.register_terrain("bworld:overworld", (chunk) => { - const height_noise = chunk.noise_2d("height"); - for (let x = 0; x < 16; x++) { - for (let z = 0; z < 16; z++) { - const wx = chunk.x * 16 + x; - const wz = chunk.z * 16 + z; - const height = Math.floor((height_noise(wx * 0.01, wz * 0.01) + 1) * 15 + 50); - for (let y = 0; y <= height; y++) { - chunk.set_block(wx, y, wz, y === height ? "bworld:grass" : "bworld:stone"); - } - chunk.set_height(wx, wz, height); - chunk.set_biome(wx, wz, "bworld:plains"); - } - } - }); -} -``` - -A terrain generator gets a `TerrainChunk`: a `FeatureChunk` (below) plus `set_height(x, z, height)` and -`set_biome(x, z, biome)`, which feed `height_at` / `biome_at` in later passes. Its `set_block` can write up to one chunk -away, like trees. Writes into another chunk only fill air, so the result doesn't depend on which chunk generates first. - -Seeding is exact, so a generator ported from the current code produces the same terrain: - -- `noise_2d(name)` is `create_noise_2d(new Alea(seed + "_" + name))` from `@paulaboks/rng`, and `noise_3d` is the same - with `create_noise_3d`. Both are cached per seed and name. -- A terrain generator's `rng` is `new Alea(seed + "_chunk_" + x + "_" + z)`. -- A feature's `rng` is `new Alea(seed + "_feature_" + feature_id + "_" + x + "_" + z)`. - -### Ores - -`worldgen/ores.json` uses the same fields as the `BASE_ORES` table in `common/generation.ts`: - -```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 - } - ] -} -``` - -Each block in the chunk that is `replaces` and between `min_y` and `max_y` becomes the first ore whose `noise_3d(id)` at -`(x, y, z) * scale` is above `threshold`. - -### Features - -`scripts.worldgen` registers features, which run on each chunk after terrain and ores: - -```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"); - }); -} -``` - -```ts -interface FeatureChunk { - x: number; // chunk coordinates - z: number; - seed: string; - rng: { next(): number }; // seeded from the seed, chunk and feature id - noise_2d(name: string): (x: number, z: number) => number; // cached per seed and name - 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; - 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, like trees -} -``` - -- **No `Math.random`, `Date`, `performance.now` or network access.** Use `chunk.rng` and the noise helpers. -- Worldgen can't use server or client APIs, and generated blocks don't run `on_create`. -- Each feature's `rng` is seeded with its own id, so adding or removing another mod's feature doesn't change what this - one generates. - -## Engine access - -For what the Game API doesn't cover yet: a new kind of rendering, different player physics, a change to how lighting -spreads, an entity type. Like Fabric's mixins, a mod can reach the engine's own classes and hook their methods, on the -server and on the client. It's powerful and unstable at once, so a mod has to ask for it. _Planned, phase 3._ - -```json -{ "engine_access": true, "game_version": "~0.4.0" } -``` - -```ts -// client.ts: an outline around every dropped item -import type { ClientContext } from "bworld/client"; -import { engine, hook } from "bworld/engine"; - -export function setup(ctx: ClientContext) { - hook(engine.client.LevelRenderer.prototype, "render_entities", { - after(renderer, [level, camera_entity, partial_tick]) { - for (const entity of level.entities.values()) { - if (entity instanceof engine.client.ItemEntity) draw_outline(entity, partial_tick); - } - }, - }); -} -``` - -```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 -// client.ts: everything falls at half speed. physics is an object so its functions can be hooked, see below -import { engine, hook } from "bworld/engine"; - -export function setup() { - hook(engine.common.physics, "move_body", { - before(_physics, args) { - args[1] /= 2; // gravity - }, - }); -} -``` - -### What `bworld/engine` gives - -- `engine` holds the engine's modules as they run on that side: `engine.common` (registries, constants, inventory, - physics, generation, the protocol types) everywhere, `engine.server` (`GameServer`, `ServerWorld`, `ModRuntime`, the - running `game`) in server scripts, and `engine.client` (`Client`, `ClientLevel`, the renderer, GUI classes, the running - `client`) in client scripts. Worldgen scripts get `engine.common` only. -- They're the live classes and objects the game uses, not copies: the engine puts them on the global object at startup, - and `bworld/engine` in a mod's bundle is a small shim that reads them. So a hook on a prototype changes every instance - the engine already made. -- The types are the engine's own source, so `check-mods` typechecks a mod against exactly the engine it will run on, and - an engine change that breaks a mod shows up there first. - -### Hooks - -```ts -function hook(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): { result: ReturnType } | void; - // wraps the method, calling original (or not) - replace?(self: T, args: Parameters, original: T[K]): ReturnType; - // runs last, and returns the result the caller gets - after?(self: T, args: Parameters, result: ReturnType): ReturnType; - // lower runs earlier, the default is 1000. ties go in load order - priority?: number; -}): () => void; // unhook -``` - -- Hooks on a prototype apply to every instance, hooks on one object only to it. -- Several mods can hook the same method. `before` hooks run in priority order, `replace` hooks nest (the first one's - `original` is the next one's wrapper, the last one's is the engine's method), and `after` hooks run in priority order, - each getting the previous one's result. -- A hook that throws is logged under its mod and skipped, like event handlers. The method still runs. -- Functions exported from a module can't be hooked, because a module's exports can't be reassigned. The engine puts - functions mods may want to change on plain objects (like `engine.common.physics`) and calls them through those objects - itself, so a hook changes what the engine calls. Classes' methods are hookable on their prototype. -- JavaScript's `#private` members can't be hooked or read. The engine keeps things that mods should be able to change - as normal members, and `#private` for things with rules that must hold (like a container's slots). Making something - hookable is an ordinary engine change, and asking for one is how the Game API grows. -- Hooks reach one JavaScript realm: the game server worker for server and worldgen scripts, and the page for client - scripts. Each chunk worker runs its own copy of the engine, so a hook in a client script doesn't change meshing. - -### Rules - -- **It isn't a stable API.** Any game update can rename or change what a hook targets. A mod with `engine_access` must - set `game_version` to a range within one minor version (like `~0.4.0`). Loading it on another version is a load error - naming the mod, instead of a crash somewhere later. -- **Prefer the Game API.** When it can do something, it keeps working across updates. Engine access is for what it - can't do yet, and a mod that hooks the same thing as many others is a sign it should become part of the Game API. -- Without `engine_access`, importing `bworld/engine` is a `check-mods` error and a load error. -- See [Security](#security) for what it means for players and servers. - -## Delivery to clients - -### Mod files - -A mod is shipped as a `.bmod` file: the mod, built, in one zip. Servers load every `.bmod` in their `server_mods/` -folder, so installing a mod is dropping its file there and restarting. - -```sh -deno task pack-mod mods/copper_tools # writes copper_tools.bmod -deno task build # packs every mod in mods/ into server_mods/.bmod -``` - -``` -copper_tools.bmod - manifest.json # the mod's manifest, with scripts and credits pointing into the zip - data.json # every block, model, item, recipe and ore, checked when it was packed - scripts/server.js # each script bundled into one module - scripts/client.js - scripts/worldgen.js - textures/.png # the texture copper_tools: - credits.md -``` - -- A mod is a Deno project. When its folder has a `deno.json`, its scripts are bundled with it, so its own imports and - npm or JSR packages work and end up in the bundle. Mods without one use the `deno.json` of the folder the build runs - in, like the ones in this repository. -- Packing checks the mod first, like `check-mods`, and refuses to pack one with errors. -- Packing the same mod twice gives the same bytes, so the file's hash 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. - -When the server starts it opens every `.bmod`, checks it again (it may come from anyone): its manifest and data, its -textures, the ids it uses from other mods, and that its dependencies are there. A problem in any mod stops the server -from starting, saying which mod and what's wrong, so the game never runs with some mods missing. Then it sorts them so -dependencies load first. - -Players get each mod as a `.bmod` too, **without its server and worldgen scripts**: the server makes a copy without -`scripts/server.js` and `scripts/worldgen.js` and serves it at `/mods/.bmod`, named by its hash so it can be cached forever. The code is in -`common/bmod.ts` (reading and writing), `tools/pack_mod.ts` and `server/load_bmods.ts`. - -The engine's own files (the client, its UI sprites and font, and the `engine:` textures) aren't in any mod. They're in -`build/`, which the server serves as it is. - -### Joining - -``` -client server - │ hello { name, protocol } │ - ├────────────────────────────────────────►│ a different protocol gets rejected { reason } - │ welcome { protocol, mods[] } │ mods[i] = { id, name, version, sha256, file, size } - │◄────────────────────────────────────────┤ file is the .bmod's path on the server - │ │ - │ [cross-origin: confirm screen] │ - │ download every .bmod, check each one's │ - │ sha256, build the texture atlas, load │ - │ content in the listed order, run │ - │ client setup(), start chunk workers │ - │ │ - │ ready { view_distance, registry_hash } │ a different hash gets rejected { reason } - ├────────────────────────────────────────►│ - │ join { id, name, players, entities, │ the player is created here, player_join fires, - │ blocks, spawn, selected_slot } │ and their inventory follows as container messages - │◄────────────────────────────────────────┤ - │ set_center_chunk, then chunk batches │ see Chunks - │◄────────────────────────────────────────┤ -``` - -- The client registers each mod's data **in the order the server lists them**. -- Every `.bmod` is checked against its SHA-256 before it's opened, and scripts are imported from the checked bytes (as - `blob:` URLs), so what runs is exactly what was checked. The client code is in `client/handshake.ts` and - `client/mods.ts`. -- The client builds the texture atlas itself, from the engine's textures and the ones in the `.bmod` files - (`client/atlas.ts`). The server never needs to decode an image. -- If any download, hash check or `setup` fails, the client disconnects and shows which mod failed. It never joins with - some mods missing. -- The `protocol` in `hello` is the game's protocol version (`PROTOCOL_VERSION` in `common/protocol.ts`). A mismatch is - rejected before anything is downloaded. -- Until `ready`, the connection isn't a player: other players don't see it, and anything it sends besides `ready` is - ignored. A client that doesn't send `ready` within 60 seconds is rejected. -- `.bmod` files are served with `Access-Control-Allow-Origin: *` and cached for a year, since their paths change - whenever their content does. The engine's assets are served with `Access-Control-Allow-Origin: *` too, for pages - from other origins. -- Leaving a server reloads the page, so one server's mod code never stays loaded while playing on another. - -### Chunks - -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 and clients can't be handed a world that differs from the server's. 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 holding 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, clients light chunks themselves when they mesh them. -- **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 turn them into their own numbers as a chunk loads. -- **The view.** Players send their view distance with `ready` and `view_distance` when it changes. The server uses up - to 10 chunks, and sends chunks in a round area around the player plus the ring just past it, which clients need to - mesh and light the edge of what they show (Minecraft's `ChunkTrackingView`). When a player moves into another chunk - the server 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 - times how long it took to load them and 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 also stops - building chunks for a tick after 20 ms, so players loading far away don't slow the game down. -- **Changes.** `set_block` only goes to players that have the chunk. Everyone else gets the change with the chunk when - they come close. - -## Security - -**Client scripts.** Mod client code runs in the game page with the page's full access. How much that matters depends on -where the page came from: - -- **Page 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. -- **Page from one origin, game server on another** (a different server typed in the title screen, or `?server=`): mod - code from that server runs with _the page's_ origin, including its local storage. The client shows the server's mod - list and asks before loading anything, and remembers the answer per server and mod hash. The server needs CORS - headers on its `.bmod` downloads and assets, which it sends. -- The hash check confirms the files are the ones the server listed. It doesn't protect against a malicious server. - -**Engine access.** A server mod with engine access controls the game server worker completely, but the worker still -has no Deno permissions, so it can't reach files or the network any more than other server scripts. A client mod with -engine access changes nothing about what it _can_ reach, since client scripts already run with the page's full access, -but it can change how the game behaves for players in ways the Game API can't. The confirm screen for other servers -lists which mods use engine access. - -**Server scripts.** They run in a worker with **no Deno permissions** (Deno worker permissions; currently needs -`--unstable-worker-options`). They can't read files, open connections or run programs. Everything they need goes through -the mod API. Installing a server mod still means trusting it with the game world and everything players send. - -**Server scripts stay on the server.** Players get each mod's `.bmod` without its server script, so a mod can keep -anti-cheat logic or anything else private there. - -**Players.** Clients are untrusted. The server checks reach and the item being held for every break, place and interact, -applies container rules on the server, validates form responses, and rate-limits mod channels. Server script code and -tile data are never sent to clients. - -## Example mod - -A smelter block with a container screen, a stats screen written in client code, and a channel between them. - -`mods/copper_tools/manifest.json` - -```json -{ - "format_version": 1, - "id": "copper_tools", - "name": "Copper Tools", - "version": "1.0.0", - "dependencies": [{ "id": "bworld", "version": "*" }], - "scripts": { "server": "scripts/server.ts", "client": "scripts/client.ts" } -} -``` - -`mods/copper_tools/blocks/smelter.json` - -```json -{ - "format_version": 1, - "block": { - "id": "copper_tools:smelter", - "textures": { "front": "copper_tools:smelter_front", "side": "bworld:stone" }, - "mining": { "toughness": 5, "tool": "pickaxe", "requires_tool": true }, - "drops": "copper_tools:smelter", - "components": { "copper_tools:smelter": { "speed": 2 } } - } -} -``` - -`mods/copper_tools/scripts/server.ts` - -```ts -import type { ServerContext } from "bworld/server"; - -interface SmelterData { - container: string; - progress: number; - smelted: number; -} - -export function setup(ctx: ServerContext) { - ctx.components.register_block("copper_tools:smelter", { - on_create(block) { - block.data = { container: ctx.containers.create(3).id, progress: 0, smelted: 0 } satisfies SmelterData; - }, - on_break(block) { - ctx.containers.delete((block.data as SmelterData).container); - }, - on_interact(block, _params, player) { - const data = block.data as SmelterData; - ctx.ui.open_container(player, { - container: ctx.containers.get(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", - }], - }).set_property("progress", data.progress); - return true; - }, - on_tick(block, params) { - const data = block.data as SmelterData; - // ... smelt using ctx.recipes, data.progress += params.speed, data.smelted += 1 when done - }, - }); - - ctx.commands.register("smelterstats", { - description: "Show stats for the smelter you're looking at", - usage: "/smelterstats", - run(_args, player) { - ctx.ui.open_screen(player, "copper_tools:smelter_stats", { smelted: count_all_smelted() }); - }, - }); - - ctx.net.on("copper_tools:reset_stats", (player) => { - if (player.name !== ctx.storage.get("owner")) return; - reset_all_smelted(); - }); -} -``` - -`mods/copper_tools/scripts/client.ts` - -```ts -import type { ClientContext, Graphics, ModScreen } from "bworld/client"; - -export function setup(ctx: ClientContext) { - ctx.ui.register_screen("copper_tools:smelter_stats", (props) => new SmelterStats(ctx, props)); -} - -class SmelterStats implements ModScreen { - constructor(private ctx: ClientContext, private props: { smelted: number }) {} - - on_render(g: Graphics) { - const x = g.width / 2 - 150; - const y = g.height / 2 - 80; - g.panel(x, y, 300, 160); - g.text(`Smelted: ${this.props.smelted}`, x + 20, y + 20, { scale: 2 }); - if (g.button("Reset", x + 90, y + 100, 120, 32)) { - this.ctx.net.send("copper_tools:reset_stats", {}); - } - } - - on_props(props: { smelted: number }) { - this.props = props; - } -} -``` - -## 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. -This is how the API gets tested for real: if the base game can't be written as a mod, the API is missing something, and -other mods would hit the same wall. It also means there's one way content works, so mods can do anything the base game -does, and change any of it. - -**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; item entities; chat; world time; `/tps`; `bworld:air`; and -the engine assets in `assets/` (UI sprites, font, player sprite, and the `engine:` textures and block models). - -**`mods/bworld`** has everything else: - -| What | Where it is now | Status | -| ---------------------------------------------------- | ----------------------------------- | ----------------------- | -| Blocks, items, models, recipes, textures, credits | `mods/bworld` JSON and `textures/` | Done | -| Hoeing, chest, furnace, smithing table, crops, watering can | `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` and `/time` | 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 - -Worlds saved before any of this must load afterwards with nothing changed: - -1. **Ids don't change.** Saves store blocks and items by string id, including player 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: trees move and blocks players - broke reappear. The golden terrain test (phase 6) enforces this. -3. **Old saves are upgraded when loading.** The save format can change when it has to, like version 3 did for - containers, 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 asked to reload before anything - else happens. - -## Implementation plan - -**Done so far:** the mod loader, `.bmod` mod files (packing, loading them from `server_mods/`, sending players a copy -without the server script), delivery to clients (hashed downloads, the confirm screen for other servers, credits); the data layer (blocks, block models with variants, items, recipes, ores); server scripts with components, -events, commands, timers, storage, recipes, containers and container screens; worldgen features and ores; the base -game's block behavior as a mod; world time with day and night. The code is in `common/mod_loader.ts`, -`common/mod_data.ts`, `server/game/mod_runtime.ts`, `client/mods.ts` and `common/worldgen_loader.ts`. - -Each phase ends with every test passing and the game playable. Phases 1 to 3 are the foundation; 4 to 6 can happen in -any order after them. - -**Phase 1: loading and common scripts.** - -- `scripts.common`, bundled like the client script, run on the server and on clients between each mod's data and the - next mod. -- `CommonContext` with `ctx.blocks`, `ctx.items`, `ctx.models` and `ctx.recipes` (`register`, `get`, `ids`). The JSON - loader goes through the same functions, so there's one path for content. -- The freeze: registries close after content loads, and registering later throws. Numeric ids, block items and recipe - indexes are made at the freeze, not while registering. -- The registry hash: both sides hash their registries after the freeze, the client sends its hash with `ready`, and a - mismatch turns the player away naming the first difference. -- Recipe types become ids with `register_type` and `list`, with `shaped`, `furnace`, `fuel` and `smithing` as short - names for the base game's. Server scripts get `ctx.recipes.list(type)`. -- Check: a test mod registers blocks, items and recipes from code, and the server and a client end up with equal - registries and hashes. A common script that registers something different on each side is caught by the hash. - -**Phase 2: overrides.** - -- `override` and `extend` in common scripts, and `overrides/*.json` for the same thing as data. `recipes.remove`. -- `check-mods`: changing content of a mod that isn't a dependency is an error, two mods changing the same field is a - warning. -- Check: a test mod adds a component to `bworld:grass`, changes `bworld:glass`'s toughness and replaces the chest - recipe, and all of it works on both sides and in the registry hash. - -**Phase 3: engine access.** - -- The engine puts its modules on the global object at startup on each side (page, game server worker, chunk workers), - and the build turns `bworld/engine` imports into a shim that reads them. Types come from the engine's source. -- `hook` with `before`, `replace`, `after`, priorities and unhooking. -- `engine_access` in the manifest: `check-mods` and the loader refuse `bworld/engine` imports without it, and refuse - loading on a game version outside the mod's range. The confirm screen and the join screen say which mods use it. -- Go through the engine for things mods will want to change and make them hookable: move module functions like - `move_body` onto objects the engine calls through, and turn `#private` members that don't protect a rule into normal - ones. -- Check: test mods hook a server method, a client method and a worldgen method, several 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 (`ctx.net` on both sides, `{ type: "mod", channel, data }`, the size and rate limits). -- Keybinds (`ctx.input.bind`), forms (`message_form`, `action_form`, `modal_form`), custom screens with `Graphics`, and - HUD elements. -- More events: items picked up and dropped, containers clicked, players moving between chunks, entities. -- Check: the example mod below works end to end, and every server event has a test. - -**Phase 5: gameplay out of the engine.** - -- `/give` and `/time` become commands in `mods/bworld`. `/tps` stays, it's about the engine. -- The crafting grid's matching and the `shaped` recipe type move into `mods/bworld`, and the player's inventory screen - becomes a screen `mods/bworld` registers, opened by the engine's inventory key. -- The hotbar and crosshair become `mods/bworld` HUD elements. -- Mining rules (how long breaking takes, tool speed, `requires_tool`, what drops) become something `mods/bworld` sets, - with the engine asking it on both sides so clients still predict breaking. -- The day and night lengths and sky colors become settings `mods/bworld` makes in its common script. The engine keeps - counting ticks. -- Where new players spawn becomes `mods/bworld`'s choice. -- Check: all tests pass unchanged, and `world_v2.json` and a version 3 save still load. - -**Phase 6: world generation.** - -- First the golden fixture: `tests/fixtures/terrain.json`, a SHA-256 of the final blocks of 64 chunks for 3 seeds, - including negative coordinates and chunks with trees on their borders, recorded from the current code. -- Port `common/worldgen/` to `mods/bworld/scripts/worldgen.ts` as the `bworld:overworld` terrain generator. It only uses - named noises, which are exactly `noise_2d` / `noise_3d` in [Terrain generators](#terrain-generators). -- Move the ore table to `mods/bworld/worldgen/ores.json`, and take the content out of `common/generation.ts`, leaving - the passes and noise helpers. -- The server refuses to start without a terrain generator, naming the mods that could provide one. -- Check: `terrain.json` matches exactly, and old saves load unchanged. - -**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, instead of crashing - somewhere. -- The base game uses only the Game API, no engine access. If it needs a hook for something, that thing belongs in the - Game API. -- All tests pass, the golden fixtures are unchanged, and a world saved before any of this plays exactly the same. - -## Open questions - -- **Client-only mods.** Should players be able to install their own client mods (minimaps, UI tweaks, shaders) that work - on any server, like Fabric's client mods? They'd need a separate `"side": "client"` 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.** Custom block components only run on the server, so interacting with a mod block - always waits one round trip. Components could get optional handlers in common scripts that clients run to predict. -- **Engine access versions.** Tying engine access mods to one minor version is simple but strict. Fabric gets further - with mapped names and mixin error reporting; how much of that is worth building depends on how often the engine - changes under mods. -- **Game API versions.** The Game API only breaking with the game's major version is a promise that needs deprecation - warnings and a changelog to keep. -- **Screen scaling.** The GUI currently works in raw canvas pixels (`SLOT_SIZE` is 54). `Graphics` should probably use a - UI scale the player can change, with screens laid out in scaled units. -- **Entities.** Mods can define simple animals in `entities/`, but there's no Game API for entity types with their - own behavior, animations, or spawning them naturally yet. -- **Hot reload.** Restarting the server and reconnecting is the version 1 answer. +A few parts of those types aren't built yet and throw when used: forms, custom screens, HUD elements, keybinds and mod +channels. [`docs/modding_plan.md`](docs/modding_plan.md) covers those, what else is planned, and the design behind the +mod API. diff --git a/client/confirm_mods.ts b/client/confirm_mods.ts index 7ad1c76..0da1b51 100644 --- a/client/confirm_mods.ts +++ b/client/confirm_mods.ts @@ -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 { return new Promise((resolve) => { diff --git a/client/handshake.ts b/client/handshake.ts index 4bc5906..f2d4911 100644 --- a/client/handshake.ts +++ b/client/handshake.ts @@ -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"; diff --git a/client/main.ts b/client/main.ts index c4c136b..8b36ef1 100644 --- a/client/main.ts +++ b/client/main.ts @@ -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 { const { socket, welcome } = await connect(address, name); console.log(`Connected to ${address.ws_url}`); diff --git a/client/mods.ts b/client/mods.ts index 5d03e52..9d7fcf3 100644 --- a/client/mods.ts +++ b/client/mods.ts @@ -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("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; diff --git a/common/bmod.ts b/common/bmod.ts index 2321176..fa556c5 100644 --- a/common/bmod.ts +++ b/common/bmod.ts @@ -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"; diff --git a/common/chunk_streaming.ts b/common/chunk_streaming.ts index 8fd7823..97f3d32 100644 --- a/common/chunk_streaming.ts +++ b/common/chunk_streaming.ts @@ -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"; diff --git a/common/commands.ts b/common/commands.ts index a82dd91..183a72e 100644 --- a/common/commands.ts +++ b/common/commands.ts @@ -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 { diff --git a/common/generation.ts b/common/generation.ts index b5304a2..f31d206 100644 --- a/common/generation.ts +++ b/common/generation.ts @@ -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 }[]; diff --git a/common/mod_api/client.ts b/common/mod_api/client.ts index d0c4ddf..8824c70 100644 --- a/common/mod_api/client.ts +++ b/common/mod_api/client.ts @@ -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[]; diff --git a/common/mod_api/server.ts b/common/mod_api/server.ts index 7ba4f9a..a7eb647 100644 --- a/common/mod_api/server.ts +++ b/common/mod_api/server.ts @@ -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

(id: Id, component: ItemComponent

): 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 { diff --git a/common/mod_api/worldgen.ts b/common/mod_api/worldgen.ts index 1141c9d..5fe9065 100644 --- a/common/mod_api/worldgen.ts +++ b/common/mod_api/worldgen.ts @@ -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"; diff --git a/common/mod_data.ts b/common/mod_data.ts index 626a259..31cb14f 100644 --- a/common/mod_data.ts +++ b/common/mod_data.ts @@ -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 { diff --git a/common/protocol.ts b/common/protocol.ts index f9dda12..69e46e5 100644 --- a/common/protocol.ts +++ b/common/protocol.ts @@ -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; diff --git a/common/worldgen_loader.ts b/common/worldgen_loader.ts index 142cb70..da0f712 100644 --- a/common/worldgen_loader.ts +++ b/common/worldgen_loader.ts @@ -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)`, ); }, }; diff --git a/docs/modding/blocks/components.md b/docs/modding/blocks/components.md new file mode 100644 index 0000000..9c093d4 --- /dev/null +++ b/docs/modding/blocks/components.md @@ -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("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). diff --git a/docs/modding/blocks/crops.md b/docs/modding/blocks/crops.md new file mode 100644 index 0000000..0e0aae1 --- /dev/null +++ b/docs/modding/blocks/crops.md @@ -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. diff --git a/docs/modding/blocks/index.md b/docs/modding/blocks/index.md new file mode 100644 index 0000000..a64e963 --- /dev/null +++ b/docs/modding/blocks/index.md @@ -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. diff --git a/docs/modding/blocks/states.md b/docs/modding/blocks/states.md new file mode 100644 index 0000000..3b7810a --- /dev/null +++ b/docs/modding/blocks/states.md @@ -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. diff --git a/docs/modding/blocks/tiledata.md b/docs/modding/blocks/tiledata.md new file mode 100644 index 0000000..bd34de0 --- /dev/null +++ b/docs/modding/blocks/tiledata.md @@ -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(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. diff --git a/docs/modding/concepts/events.md b/docs/modding/concepts/events.md new file mode 100644 index 0000000..a2f6be9 --- /dev/null +++ b/docs/modding/concepts/events.md @@ -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. diff --git a/docs/modding/concepts/registries.md b/docs/modding/concepts/registries.md new file mode 100644 index 0000000..21984cc --- /dev/null +++ b/docs/modding/concepts/registries.md @@ -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. diff --git a/docs/modding/concepts/security.md b/docs/modding/concepts/security.md new file mode 100644 index 0000000..ccaaf85 --- /dev/null +++ b/docs/modding/concepts/security.md @@ -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. diff --git a/docs/modding/concepts/sides.md b/docs/modding/concepts/sides.md new file mode 100644 index 0000000..f0ef63f --- /dev/null +++ b/docs/modding/concepts/sides.md @@ -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. diff --git a/docs/modding/datastorage/index.md b/docs/modding/datastorage/index.md new file mode 100644 index 0000000..d32b7df --- /dev/null +++ b/docs/modding/datastorage/index.md @@ -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(key: string): T | undefined; + set(key: string, value: unknown): void; // JSON values only + delete(key: string): void; +} +``` + +```ts +const count = ctx.storage.get("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. diff --git a/docs/modding/entities/index.md b/docs/modding/entities/index.md new file mode 100644 index 0000000..d389a83 --- /dev/null +++ b/docs/modding/entities/index.md @@ -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 ` 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/.geo.json`, as Blockbench exports them for Bedrock (the "Bedrock Entity" format), and +get the id `:`. 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. diff --git a/docs/modding/entities/players.md b/docs/modding/entities/players.md new file mode 100644 index 0000000..be65e26 --- /dev/null +++ b/docs/modding/entities/players.md @@ -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. diff --git a/docs/modding/gettingstarted/index.md b/docs/modding/gettingstarted/index.md new file mode 100644 index 0000000..d900837 --- /dev/null +++ b/docs/modding/gettingstarted/index.md @@ -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/.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 [count]` | Gives you an item | +| `/summon ` | Spawns an entity where you stand | +| `/time set ` | Jumps to `day`, `noon`, `sunset`, `night` or `midnight` | +| `/time add ` | 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. diff --git a/docs/modding/gettingstarted/modfiles.md b/docs/modding/gettingstarted/modfiles.md new file mode 100644 index 0000000..032747f --- /dev/null +++ b/docs/modding/gettingstarted/modfiles.md @@ -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/.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). diff --git a/docs/modding/gui/index.md b/docs/modding/gui/index.md new file mode 100644 index 0000000..204025d --- /dev/null +++ b/docs/modding/gui/index.md @@ -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. diff --git a/docs/modding/inventories/containers.md b/docs/modding/inventories/containers.md new file mode 100644 index 0000000..09ddee2 --- /dev/null +++ b/docs/modding/inventories/containers.md @@ -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. diff --git a/docs/modding/inventories/menus.md b/docs/modding/inventories/menus.md new file mode 100644 index 0000000..8a1c30a --- /dev/null +++ b/docs/modding/inventories/menus.md @@ -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`. diff --git a/docs/modding/items/food.md b/docs/modding/items/food.md new file mode 100644 index 0000000..9fa929c --- /dev/null +++ b/docs/modding/items/food.md @@ -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 +``` diff --git a/docs/modding/items/index.md b/docs/modding/items/index.md new file mode 100644 index 0000000..df91c32 --- /dev/null +++ b/docs/modding/items/index.md @@ -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 +``` diff --git a/docs/modding/items/tools.md b/docs/modding/items/tools.md new file mode 100644 index 0000000..2a11ae0 --- /dev/null +++ b/docs/modding/items/tools.md @@ -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. diff --git a/docs/modding/misc/commands.md b/docs/modding/misc/commands.md new file mode 100644 index 0000000..b032321 --- /dev/null +++ b/docs/modding/misc/commands.md @@ -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("amount"))) + .then( + argument("target", types.player()) + .executes((context) => heal(context.get("target"), context.get("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 `/:`, like `/copper_tools:heal`. + +Commands can only be registered during `setup`. + +## The Engine's Commands + +| Command | What it does | +| ------------------------------------------------------- | -------------------------------------------------------- | +| `/give [count]` | Gives you an item | +| `/summon ` | Spawns an entity where you are | +| `/time` | Shows the time | +| `/time set ` | Jumps to the next time of day. Time never goes back | +| `/time add ` | 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 | diff --git a/docs/modding/misc/time.md b/docs/modding/misc/time.md new file mode 100644 index 0000000..8c33075 --- /dev/null +++ b/docs/modding/misc/time.md @@ -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 ` and `/time add `. diff --git a/docs/modding/networking/index.md b/docs/modding/networking/index.md new file mode 100644 index 0000000..805666c --- /dev/null +++ b/docs/modding/networking/index.md @@ -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. diff --git a/docs/modding/resources/models.md b/docs/modding/resources/models.md new file mode 100644 index 0000000..9972de9 --- /dev/null +++ b/docs/modding/resources/models.md @@ -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. diff --git a/docs/modding/resources/recipes.md b/docs/modding/resources/recipes.md new file mode 100644 index 0000000..85231be --- /dev/null +++ b/docs/modding/resources/recipes.md @@ -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 +``` diff --git a/docs/modding/resources/textures.md b/docs/modding/resources/textures.md new file mode 100644 index 0000000..1a931e5 --- /dev/null +++ b/docs/modding/resources/textures.md @@ -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 `:`. 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. diff --git a/docs/modding/worldgen/index.md b/docs/modding/worldgen/index.md new file mode 100644 index 0000000..ba010e3 --- /dev/null +++ b/docs/modding/worldgen/index.md @@ -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. diff --git a/docs/modding_plan.md b/docs/modding_plan.md new file mode 100644 index 0000000..edf4854 --- /dev/null +++ b/docs/modding_plan.md @@ -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; + items: ContentRegistry; + models: ContentRegistry; + recipes: RecipeRegistry; + log(...args: unknown[]): void; +} + +// T is the same shape as the JSON file's content, checked the same way +interface ContentRegistry { + register(definition: T): void; + get(id: string): Readonly | undefined; // what's registered so far, by any mod + ids(): string[]; + override(id: string, fields: Partial): void; // like "set" in an override file + extend(id: string, change: { components?: Record; 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(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): { result: ReturnType } | void; + // wraps the method, calling original (or not) + replace?(self: T, args: Parameters, original: T[K]): ReturnType; + // runs last, and returns the result the caller gets + after?(self: T, args: Parameters, result: ReturnType): ReturnType; + // 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. diff --git a/mods/bworld/README.md b/mods/bworld/README.md index a197d74..39fac0e 100644 --- a/mods/bworld/README.md +++ b/mods/bworld/README.md @@ -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`. diff --git a/mods/bworld/scripts/server.ts b/mods/bworld/scripts/server.ts index 56569de..e326ff8 100644 --- a/mods/bworld/scripts/server.ts +++ b/mods/bworld/scripts/server.ts @@ -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; diff --git a/server/game/game_server.ts b/server/game/game_server.ts index c2161e5..4c7ee09 100644 --- a/server/game/game_server.ts +++ b/server/game/game_server.ts @@ -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)) { diff --git a/server/game/mod_runtime.ts b/server/game/mod_runtime.ts index 015f075..45be2f8 100644 --- a/server/game/mod_runtime.ts +++ b/server/game/mod_runtime.ts @@ -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); }, diff --git a/templates/mod/README.md b/templates/mod/README.md index f59fa25..266fe66 100644 --- a/templates/mod/README.md +++ b/templates/mod/README.md @@ -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 diff --git a/tools/new_mod.ts b/tools/new_mod.ts index 1783973..75bd4de 100644 --- a/tools/new_mod.ts +++ b/tools/new_mod.ts @@ -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); diff --git a/tools/pack_mod.ts b/tools/pack_mod.ts index 5204930..d298d50 100644 --- a/tools/pack_mod.ts +++ b/tools/pack_mod.ts @@ -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";