Single module modding
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
# 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
|
||||
A block's JSON says what it is. Components say what it _does_. A component is a set of handlers the server phase
|
||||
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
|
||||
@@ -20,7 +20,7 @@ A block can list several. Their handlers run in the listed order.
|
||||
|
||||
## Registering a Component
|
||||
|
||||
In the server script:
|
||||
In the server phase:
|
||||
|
||||
```ts
|
||||
import type { ServerContext } from "cubi/server";
|
||||
@@ -30,7 +30,7 @@ interface OxidizesParams {
|
||||
into: string;
|
||||
}
|
||||
|
||||
export function setup(ctx: ServerContext) {
|
||||
export function server(ctx: ServerContext) {
|
||||
ctx.components.register_block<OxidizesParams>("copper_tools:oxidizes", {
|
||||
on_create(block) {
|
||||
block.data = { age: 0 };
|
||||
@@ -53,9 +53,9 @@ export function setup(ctx: ServerContext) {
|
||||
|
||||
Items have components the same way, and so do [status effects](../entities/effects.md#effect-components).
|
||||
|
||||
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.
|
||||
Components can only be registered while the server phase runs, and only in the mod's own namespace. Once every mod's
|
||||
server phase has run, a block or item that lists a component nobody registered stops the server from starting, naming
|
||||
the block and the component.
|
||||
|
||||
## Handlers
|
||||
|
||||
@@ -145,14 +145,14 @@ not in memory counts as loaded, and reading it reads it from the save.
|
||||
## Rules
|
||||
|
||||
A component's rules decide a block's states from where it's placed, what's around it and being right clicked. They're
|
||||
registered in the mod's [shared script](../concepts/sides.md#shared-scripts) instead, under the same id, because clients
|
||||
run them too: that's how a player sees a fence join its neighbors the moment they place it, instead of a moment later
|
||||
when the server answers. A component can have rules, handlers, or both, and a block can list one that only has rules.
|
||||
registered in the mod's [shared phase](../concepts/sides.md#shared) instead, under the same id, because clients run them
|
||||
too: that's how a player sees a fence join its neighbors the moment they place it, instead of a moment later when the
|
||||
server answers. A component can have rules, handlers, or both, and a block can list one that only has rules.
|
||||
|
||||
```ts
|
||||
import type { SharedContext } from "cubi/shared";
|
||||
|
||||
export function setup(ctx: SharedContext) {
|
||||
export function shared(ctx: SharedContext) {
|
||||
ctx.components.register_block("copper_tools:pipe", {
|
||||
state_for_placement(placement, params) {/* ... */},
|
||||
on_neighbor_change(block, params, neighbor) {/* ... */},
|
||||
@@ -167,7 +167,7 @@ export function setup(ctx: SharedContext) {
|
||||
| `on_neighbor_change(block, params, neighbor)` | A block on one of its 6 sides is placed, broken or changes its states. | |
|
||||
| `on_interact(block, params, interaction)` | A player right clicks it. | `true` if it did something |
|
||||
|
||||
Here `block` is `{ id, x, y, z }`, without tile data, which clients never have. `ctx.world` in a shared script has
|
||||
Here `block` is `{ id, x, y, z }`, without tile data, which clients never have. `ctx.world` in the shared phase has
|
||||
`get_block`, `get_state`, `set_state`, `is_face_sturdy`, `biome_at` and `season_at` (see
|
||||
[Seasons](../worldgen/biomes.md#seasons)), and only works inside rules. `ctx.blocks.components(id)` gives any block's
|
||||
components and their params, like on the server, for rules that look at what's around them, like a shaft lining up with
|
||||
@@ -329,7 +329,7 @@ catch up. If it's further behind than that, it skips the rest and logs a warning
|
||||
| `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` | `loot_table`? | The fishing rod's hook floats on it and fish bite there when it lands in it. What's caught is `loot_table`, `bworld:gameplay/fishing` when not given, built from the fish whose `fluid` is this block. |
|
||||
| `bworld:trapdoor` | none | Opens and closes when right clicked, and is placed like Minecraft's (both are rules, in the shared script). Needs `facing` (2 bits), `half` and `open` states, see `blocks/oak_trapdoor.json`. |
|
||||
| `bworld:trapdoor` | none | Opens and closes when right clicked, and is placed like Minecraft's (both are rules, in the shared phase). Needs `facing` (2 bits), `half` and `open` states, see `blocks/oak_trapdoor.json`. |
|
||||
| `bworld:fence` | `connects_to` | Joins the blocks in the tag `connects_to` and sturdy sides of other blocks, except leaves. Needs the `north`, `east`, `south` and `west` states. |
|
||||
|
||||
Item components work the same way, see [Items](../items/index.md#item-components).
|
||||
|
||||
@@ -4,7 +4,7 @@ Blocks make up the world. Each kind of block is defined once, in a JSON file in
|
||||
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.
|
||||
[components](components.md), which server phases register.
|
||||
|
||||
## A Basic Block
|
||||
|
||||
@@ -27,7 +27,7 @@ side, takes 5 seconds to break by hand, breaks faster with a pickaxe, and only d
|
||||
of tier 1 (stone or copper) or better.
|
||||
|
||||
A mod with many similar blocks, like every block of every kind of rock, can register them in code from a
|
||||
[content script](../concepts/sides.md#content-scripts) instead, with the same object a file holds under `"block"`.
|
||||
[content phase](../concepts/sides.md#content) instead, with the same object a file holds under `"block"`.
|
||||
|
||||
## Properties
|
||||
|
||||
@@ -225,8 +225,8 @@ plains' color.
|
||||
|
||||
## Raycasts
|
||||
|
||||
Server scripts find the first block on a line with `ctx.world.raycast`, like Minecraft's `Level.clip`. The fishing rod's
|
||||
hook uses it to see where it lands, and with a player's
|
||||
The server phase finds the first block on a line with `ctx.world.raycast`, like Minecraft's `Level.clip`. The fishing
|
||||
rod's hook uses it to see where it lands, and with a player's
|
||||
[`eye_position` and `look_direction`](../entities/players.md#the-player-api) it finds what they're looking at:
|
||||
|
||||
```ts
|
||||
|
||||
@@ -21,7 +21,7 @@ the defaults when it's placed or generated.
|
||||
|
||||
## Reading and Changing States
|
||||
|
||||
Server scripts use `ctx.world`:
|
||||
The server phase uses `ctx.world`:
|
||||
|
||||
```ts
|
||||
const age = ctx.world.get_state(x, y, z, "age") ?? 0;
|
||||
|
||||
@@ -78,7 +78,7 @@ ctx.components.register_block("copper_tools:shaft", {
|
||||
changes often doesn't resend the others, and setting a field to what it already is sends nothing.
|
||||
- `undefined` removes a field. All of them go when the block is broken or replaced.
|
||||
- It's saved with the world. `get_client_data` and `set_client_data` copy the value, so change it by setting it again.
|
||||
- Client scripts read it with `ctx.world.get_client_data<T>(x, y, z, field)`, see [GUI](../gui/index.md). A block's
|
||||
- Client phases read it with `ctx.world.get_client_data<T>(x, y, z, field)`, see [GUI](../gui/index.md). A block's
|
||||
[visual](visuals.md) reads it with `block.get_client_data`, and its `update` is called when a field changes.
|
||||
|
||||
Like NeoForge's `getUpdateTag`, but per field. Keep it to what clients need to draw the block: everything in it is sent
|
||||
@@ -92,7 +92,7 @@ A block with `item_display` draws one item lying on top of it, like the food on
|
||||
"item_display": { "surface": 1 }
|
||||
```
|
||||
|
||||
`surface` is the height in pixels the item lies at, 0 to 16. The server script sets the item:
|
||||
`surface` is the height in pixels the item lies at, 0 to 16. The server phase sets the item:
|
||||
|
||||
```ts
|
||||
ctx.world.set_block_item(x, y, z, { id: "bworld:cabbage", count: 1 });
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Visuals
|
||||
|
||||
A visual draws a block with code, for blocks that move or show what's in them: a shaft that turns, a press coming down,
|
||||
the items and fluid in a machine. A client script registers one for a block, and every block of that kind in a shown
|
||||
the items and fluid in a machine. The client phase registers one for a block, and every block of that kind in a shown
|
||||
chunk gets its own. It's bworld's version of Minecraft's block entity renderers, shaped like the Flywheel visuals Create
|
||||
draws its machines with.
|
||||
|
||||
@@ -10,7 +10,7 @@ draws its machines with.
|
||||
```ts
|
||||
import type { ClientContext } from "cubi/client";
|
||||
|
||||
export function setup(ctx: ClientContext) {
|
||||
export function client(ctx: ClientContext) {
|
||||
ctx.render.register_visual("copper_tools:shaft", (block, instances) => {
|
||||
const shaft = instances.rotating();
|
||||
const turn = () => shaft.set_rotation("y", block.get_client_data<number>("speed") ?? 0);
|
||||
@@ -20,7 +20,7 @@ export function setup(ctx: ClientContext) {
|
||||
}
|
||||
```
|
||||
|
||||
- Visuals can only be registered during `setup`, and a block has at most one.
|
||||
- Visuals can only be registered while the client phase runs, and a block has at most one.
|
||||
- With `replaces_model: true`, the block's model is left out of the terrain, for a visual that draws all of the block,
|
||||
like the shaft above. Without it, the model is drawn as usual and the visual adds to it, like a press's head over its
|
||||
casing. The model is still what the block's item, its outline and the cracks on it while it's broken are drawn with.
|
||||
@@ -145,7 +145,7 @@ ctx.render.register_visual("copper_tools:crank", (block, instances) => {
|
||||
});
|
||||
```
|
||||
|
||||
Only visuals in chunks in view get `on_frame`, so keep anything that has to happen out of view in the server script.
|
||||
Only visuals in chunks in view get `on_frame`, so keep anything that has to happen out of view in the server phase.
|
||||
|
||||
## Cost
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Events
|
||||
|
||||
Events let a server script react to what happens in the game, and stop some of it from happening. They're the
|
||||
Events let the server phase 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.
|
||||
|
||||
@@ -15,7 +15,7 @@ Every event is a signal you subscribe to. Events come in two kinds:
|
||||
```ts
|
||||
import type { ServerContext } from "cubi/server";
|
||||
|
||||
export function setup(ctx: ServerContext) {
|
||||
export function server(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;
|
||||
@@ -52,7 +52,7 @@ showed. These events fire for **every** player's actions, since they all go thro
|
||||
| `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 |
|
||||
| `server_start` | | ✓ | none. Every mod's server phase has run |
|
||||
| `tick` | | ✓ | `dt`, in seconds. 20 times a second |
|
||||
| `new_day` | | ✓ | `day`. At 06:00, after every block's `on_new_day` |
|
||||
|
||||
@@ -66,7 +66,7 @@ only when the entity was hurt, with the amount the before handlers left.
|
||||
|
||||
### Order
|
||||
|
||||
Handlers run in the order they subscribed, and mods' `setup` functions run in [load order](registries.md#loading). For
|
||||
Handlers run in the order they subscribed, and mods' server phases run in [load order](registries.md#loading). For
|
||||
`block_interact`, the before event runs first, then the block's own components' `on_interact`, rules before handlers,
|
||||
unless the player is [sneaking](../entities/players.md#sneaking) with an item in hand. If no component handled the click
|
||||
and the held item has no `on_use`, the held block is placed, which fires `block_place`. Cancelling it undoes what the
|
||||
|
||||
@@ -32,18 +32,18 @@ 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), including the ones its
|
||||
[content script](sides.md#content-scripts) registers, after its `blocks/` files, items, entity models, entities,
|
||||
effects and fluids. Then every mod's [tags](../resources/tags.md), merged in load order, then each mod's recipes and
|
||||
ores, which can use tags.
|
||||
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.
|
||||
[content phase](sides.md#content) registers, after its `blocks/` files, items, entity models, entities, effects and
|
||||
fluids. Then every mod's [tags](../resources/tags.md), merged in load order, then each mod's recipes and ores, which
|
||||
can use tags.
|
||||
3. **Scripts.** Every mod's shared phase runs, then its server phase on the server and its client phase on each client.
|
||||
The worldgen phase runs wherever the server makes chunks.
|
||||
|
||||
Scripts read the registries but can't add to them. Content comes from data files, and from content scripts, which the
|
||||
Scripts read the registries but can't add to them. Content comes from data files, and from content phases, which the
|
||||
server runs when it loads mods, before anything else, and whose blocks go to players as data.
|
||||
|
||||
> [!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. Content scripts only run on the server, and players get
|
||||
> only data, since both load the same files in the same order. Content phases only run on the server, and players get
|
||||
> what they made as data.
|
||||
|
||||
## Numeric Ids
|
||||
|
||||
@@ -9,24 +9,26 @@ Anything a client sends can be forged by a player who edits their client. The en
|
||||
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
|
||||
- Decide on the server. The client phase shows things. The server phase decides what happens.
|
||||
- Check permissions on the server, in the server phase, 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. Only
|
||||
the fields a script sets as [client data](../blocks/tiledata.md#client-data) are.
|
||||
Tile data is never sent to clients, only the fields a script sets as [client data](../blocks/tiledata.md#client-data). A
|
||||
mod's script is: players get all of it, its server phase too, and only run its shared and client phases. So a mod can
|
||||
keep secrets in the world, in tile data or [`ctx.storage`](../datastorage/index.md), but never in its code. Anti-cheat
|
||||
works by the server deciding, not by hiding how it decides.
|
||||
|
||||
## Server Scripts
|
||||
## The Server Phase
|
||||
|
||||
Server scripts run in the game worker with **no Deno permissions**: they can't read files, open connections or run
|
||||
The server phase runs 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
|
||||
## The Client Phase
|
||||
|
||||
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 client phase runs in the game page, like the rest of a mod's script there, 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.
|
||||
|
||||
@@ -10,81 +10,122 @@ slot 3". The server checks it (reach, the item being held, container rules), run
|
||||
happened.
|
||||
|
||||
For responsiveness, the client guesses the result of breaking, placing and right clicking blocks and shows it right
|
||||
away, with the states the server will give them: it runs the same [shared scripts](#shared-scripts) the server does.
|
||||
When the server disagrees, like when a before event cancels a placement, it sends that player the real block and the
|
||||
guess is undone. Like Minecraft, each click is numbered and the server says when it's done with it: until then the
|
||||
client keeps showing its guess, so the server's answer to an earlier click can't flicker a block a newer one changed,
|
||||
like a trapdoor clicked twice. Blocks with `"interactive": true` tell the client not to guess a placement, since right
|
||||
clicking them does something else.
|
||||
away, with the states the server will give them: it runs the same [shared phase](#shared) the server does. When the
|
||||
server disagrees, like when a before event cancels a placement, it sends that player the real block and the guess is
|
||||
undone. Like Minecraft, each click is numbered and the server says when it's done with it: until then the client keeps
|
||||
showing its guess, so the server's answer to an earlier click can't flicker a block a newer one changed, like a trapdoor
|
||||
clicked twice. Blocks with `"interactive": true` tell the client not to guess a placement, since right clicking them
|
||||
does something else.
|
||||
|
||||
```
|
||||
server process browser
|
||||
┌───────────────────────────────────────┐ ┌──────────────────────────────────┐
|
||||
│ host: http, websocket, files │ │ game client (rendering, input) │
|
||||
│ ┌───────────────────────────────────┐ │ ws │ + mods' client scripts │
|
||||
│ │ game server worker │◄├──────────┤► │
|
||||
│ ┌───────────────────────────────────┐ │ ws │ + mods' shared phases │
|
||||
│ │ game server worker │◄├──────────┤► + mods' client phases │
|
||||
│ │ world, inventories, tile data │ │ protocol │ chunk workers (meshing, light) │
|
||||
│ │ + mods' server scripts │ │ chunks │ + mods' shared scripts │
|
||||
│ │ + mods' shared scripts │ │ └──────────────────────────────────┘
|
||||
│ │ + mods' worldgen scripts │ │
|
||||
│ │ + mods' shared phases │ │ chunks └──────────────────────────────────┘
|
||||
│ │ + mods' server phases │ │
|
||||
│ └───────────────────────────────────┘ │
|
||||
│ worldgen workers │
|
||||
│ + mods' worldgen phases │
|
||||
│ content worker, while mods load │
|
||||
│ + mods' content phases │
|
||||
└───────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## The Five Scripts
|
||||
## One Script, Five Phases
|
||||
|
||||
| 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: screens, inventory overlays and the HUD |
|
||||
| `shared` | the server and every browser | yes | block rules: the states blocks are placed with, joining neighbors |
|
||||
| `worldgen` | the server, when it makes chunks | no | features that decorate terrain, deterministic |
|
||||
| `content` | the server, while it loads mods | no, only what it makes | blocks made in code, like one for every kind of rock |
|
||||
A mod has one script, named by `main` in its manifest. Each of its exports is a **phase**, a function the game calls
|
||||
with that phase's context where and when it runs:
|
||||
|
||||
```ts
|
||||
import type { ContentContext } from "cubi/content";
|
||||
import type { SharedContext } from "cubi/shared";
|
||||
import type { ServerContext } from "cubi/server";
|
||||
import type { ClientContext } from "cubi/client";
|
||||
import type { WorldgenContext } from "cubi/worldgen";
|
||||
|
||||
export function content(ctx: ContentContext) {/* blocks made in code */}
|
||||
export function shared(ctx: SharedContext) {/* block rules, fluid rules, recipe types */}
|
||||
export function server(ctx: ServerContext) {/* components, events, commands */}
|
||||
export function client(ctx: ClientContext) {/* screens, the HUD */}
|
||||
export function worldgen(gen: WorldgenContext) {/* features */}
|
||||
```
|
||||
|
||||
| Phase | Runs on | For |
|
||||
| ---------- | -------------------------------- | ------------------------------------------------------------------- |
|
||||
| `content` | the server, while it loads mods | blocks made in code, like one for every kind of rock |
|
||||
| `shared` | the server and every browser | block rules: the states blocks are placed with, joining neighbors |
|
||||
| `server` | the server, in the game worker | game logic: block and item components, events, commands, containers |
|
||||
| `client` | every player's browser | presentation: screens, inventory overlays and the HUD |
|
||||
| `worldgen` | the server, when it makes chunks | features that decorate terrain, deterministic |
|
||||
|
||||
Every export is optional: a mod leaves out the phases it doesn't need. A big mod can keep each phase in its own file and
|
||||
export them all from its main script, like the base game does:
|
||||
|
||||
```ts
|
||||
// scripts/main.ts
|
||||
export { content } from "./content.ts";
|
||||
export { shared } from "./shared.ts";
|
||||
export { server } from "./server.ts";
|
||||
export { client } from "./client.ts";
|
||||
export { worldgen } from "./worldgen.ts";
|
||||
```
|
||||
|
||||
Or it can keep a feature together, with its shared rules and its server handlers in one file, sharing what's at its top
|
||||
level. A side imports the script once, so every phase that side runs gets the same module.
|
||||
|
||||
The script is bundled into one module that goes everywhere: the server, every player, and the server's workers. Each
|
||||
only runs its own phases, but every one of them loads the whole module, so its top level must work anywhere. Keep what
|
||||
only one side has, like the browser's `document`, inside that side's phase, and import a library only one side needs
|
||||
with `await import()` inside its phase. Players can read all of it, the server phase too, so it's no place for secrets,
|
||||
see [Security](security.md).
|
||||
|
||||
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). Content scripts make more of it.
|
||||
on every client, before any phase runs. See [Registries](registries.md). The content phase makes more of it.
|
||||
|
||||
### Server Scripts
|
||||
### Server
|
||||
|
||||
```ts
|
||||
import type { ServerContext } from "cubi/server";
|
||||
|
||||
export function setup(ctx: ServerContext) {
|
||||
export function server(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.
|
||||
It runs once when the server starts, after every mod's data is registered and every mod's shared phase has run.
|
||||
Components and commands can only be registered while it runs. 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
|
||||
### Client
|
||||
|
||||
```ts
|
||||
import type { ClientContext } from "cubi/client";
|
||||
|
||||
export function setup(ctx: ClientContext) {
|
||||
export function client(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.
|
||||
It runs after the client has downloaded the server's mods and before the world appears. The client phase is for
|
||||
presentation. It 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).
|
||||
|
||||
### Shared Scripts
|
||||
### Shared
|
||||
|
||||
```ts
|
||||
import type { SharedContext } from "cubi/shared";
|
||||
|
||||
export function setup(ctx: SharedContext) {
|
||||
export function shared(ctx: SharedContext) {
|
||||
ctx.components.register_block("copper_tools:pipe", {
|
||||
state_for_placement(placement) {/* ... */},
|
||||
on_neighbor_change(block, params, neighbor) {/* ... */},
|
||||
@@ -93,32 +134,30 @@ export function setup(ctx: SharedContext) {
|
||||
}
|
||||
```
|
||||
|
||||
Shared scripts hold a block component's rules, the code Minecraft runs on both sides: what states a block is placed with
|
||||
(`state_for_placement`), how it changes with the blocks beside it (`on_neighbor_change`) and what right clicking it
|
||||
The shared phase holds a block component's rules, the code Minecraft runs on both sides: what states a block is placed
|
||||
with (`state_for_placement`), how it changes with the blocks beside it (`on_neighbor_change`) and what right clicking it
|
||||
changes (`on_interact`, like a trapdoor opening). See [Block Components](../blocks/components.md#rules). The server
|
||||
script registers the rest of the same component, like its `on_break` or an `on_interact` that opens a screen, under the
|
||||
same id. They also hold [fluids' rules](../resources/fluids.md#rules), which name and color a fluid by its data, and
|
||||
phase registers the rest of the same component, like its `on_break` or an `on_interact` that opens a screen, under the
|
||||
same id. It also holds [fluids' rules](../resources/fluids.md#rules), which name and color a fluid by its data, and
|
||||
[recipes made in code](../resources/recipes.md#recipes-from-scripts), which every side has without the server sending
|
||||
them.
|
||||
|
||||
On the server they run on the real world. On a client they run on what that client shows, when its player places, breaks
|
||||
or right clicks a block, so a fence joins its neighbors the moment it's placed. What they change there is a guess, and
|
||||
the server's answer replaces it a moment later, so a shared script that gives a different answer on a client only costs
|
||||
a flicker. `ctx.side` says which one it's running on.
|
||||
On the server it runs on the real world. On a client it runs on what that client shows, when its player places, breaks
|
||||
or right clicks a block, so a fence joins its neighbors the moment it's placed. What it changes there is a guess, and
|
||||
the server's answer replaces it a moment later, so a rule that gives a different answer on a client only costs a
|
||||
flicker. `ctx.side` says which one it's running on.
|
||||
|
||||
`setup` runs before the server or client script on each side, for every mod first, so their scripts can count on any
|
||||
mod's rules being there. Rules can only be registered during `setup`, and `ctx.world` only works in them.
|
||||
It runs before the server or client phase on each side, for every mod first, so their phases can count on any mod's
|
||||
rules being there. Rules can only be registered while it runs, and `ctx.world` only works in them.
|
||||
|
||||
Shared code is sent to players like client code, so it's for rules anyone may read, never anti-cheat or secrets.
|
||||
|
||||
### Content Scripts
|
||||
### Content
|
||||
|
||||
```ts
|
||||
import type { ContentContext } from "cubi/content";
|
||||
|
||||
const ROCKS = ["granite", "basalt", "slate"];
|
||||
|
||||
export function setup(ctx: ContentContext) {
|
||||
export function content(ctx: ContentContext) {
|
||||
for (const rock of ROCKS) {
|
||||
ctx.blocks.register({
|
||||
id: `rocks:${rock}`,
|
||||
@@ -130,25 +169,27 @@ export function setup(ctx: ContentContext) {
|
||||
}
|
||||
```
|
||||
|
||||
Content scripts make data in code, for content that's easier to generate than to write out file by file.
|
||||
`ctx.blocks.register` takes the same object a `blocks/` file holds under `"block"`. The blocks a content script
|
||||
registers become part of the mod's data, the same as its files:
|
||||
The content phase makes data in code, for content that's easier to generate than to write out file by file.
|
||||
`ctx.blocks.register` takes the same object a `blocks/` file holds under `"block"`. The blocks it registers become part
|
||||
of the mod's data, the same as its files:
|
||||
|
||||
- They're registered right after the mod's `blocks/` files, in the order of the calls.
|
||||
- They're checked the same way, so a mistake stops the mod loading and names the script. They have to be in the mod's
|
||||
own namespace.
|
||||
- The mod's files can name them: tags, recipes, drops, ores and the rest of worldgen.
|
||||
- Players get them with the rest of the mod's data and never run the script, so the server and its players always agree.
|
||||
- Players get them with the rest of the mod's data and never run the content phase, so the server and its players always
|
||||
agree.
|
||||
|
||||
The server runs content scripts when it loads mods, before anything else reads their data, in a worker with **no Deno
|
||||
permissions**, like the game's. `check-mods`, the build and tests run them from the mod's folder. Blocks can only be
|
||||
registered during `setup`. Content scripts don't see other mods' content or the server's [config](../misc/config.md),
|
||||
and can't import [`cubi/engine`](../misc/engine.md).
|
||||
The server runs it when it loads mods, before anything else reads their data, in a worker with **no Deno permissions**,
|
||||
like the game's. `check-mods`, the build and tests run it from the mod's folder. Blocks can only be registered while it
|
||||
runs. It doesn't see other mods' content or the server's [config](../misc/config.md), and only `engine.common` of
|
||||
[`cubi/engine`](../misc/engine.md) is there.
|
||||
|
||||
### Worldgen Scripts
|
||||
### Worldgen
|
||||
|
||||
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).
|
||||
The worldgen phase registers features that run on every chunk the server generates. It runs in each of the server's
|
||||
worldgen workers, and features must be deterministic: the same seed and chunk always give the same blocks. See
|
||||
[World Generation](../worldgen/index.md).
|
||||
|
||||
## What Each Side Knows
|
||||
|
||||
@@ -162,9 +203,7 @@ seed and chunk always give the same blocks. See [World Generation](../worldgen/i
|
||||
| Entities | yes | near the player |
|
||||
| `ctx.storage` | yes | no |
|
||||
| [Config](../misc/config.md) | yes | no |
|
||||
| Server script code | yes | **never** |
|
||||
| Shared script code | yes | yes, and runs it |
|
||||
| Content script code | yes | **never**, only the blocks it registers |
|
||||
| A mod's script | yes | yes, but only runs its shared and client |
|
||||
|
||||
When a client needs to see something only the server has, the server has to send it: open a
|
||||
[menu](../inventories/menus.md), put it in an item's `data`, or set a block state the block's model shows.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Saving Data
|
||||
|
||||
Server scripts have no file access, so everything a mod keeps goes through the world, and is saved with it. Pick the
|
||||
The server phase has 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 |
|
||||
@@ -37,8 +37,8 @@ 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.
|
||||
- Variables in a script. Everything in memory is gone when the server restarts, so rebuild it in the server phase 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.
|
||||
|
||||
@@ -4,7 +4,7 @@ Status effects change a player or a mob for a while, like speed or poison. They
|
||||
effect is defined once, and adding it to someone gives them an instance of it with a duration and a level.
|
||||
|
||||
Like blocks and items, an effect is data with components. Its JSON in the mod's `effects/` folder says what it is and
|
||||
which attributes it changes. Components, registered by the server script, say what it does over time. An effect can also
|
||||
which attributes it changes. Components, registered by the server phase, say what it does over time. An effect can also
|
||||
change things where they happen, through an [event](../concepts/events.md). Even the base game's effects are defined
|
||||
this way, in `mods/bworld/effects`.
|
||||
|
||||
@@ -46,12 +46,12 @@ An effect that does something each tick lists components, with their parameters:
|
||||
}
|
||||
```
|
||||
|
||||
The server script registers them during `setup`, in the mod's own namespace:
|
||||
The server phase registers them while it runs, in the mod's own namespace:
|
||||
|
||||
```ts
|
||||
import type { ServerContext } from "cubi/server";
|
||||
|
||||
export function setup(ctx: ServerContext) {
|
||||
export function server(ctx: ServerContext) {
|
||||
ctx.components.register_effect<{ every: number }>("copper_tools:rusting", {
|
||||
should_tick: (ticks, amplifier, params) => ticks % params.every === 0,
|
||||
on_tick(entity, amplifier) {
|
||||
@@ -102,7 +102,7 @@ Like block components, an effect that lists a component nobody registered stops
|
||||
|
||||
Some effects change something as it happens, like damage coming in, rather than over time. Those need no component: a
|
||||
handler checks whether the entity has the effect. `bworld:resistance` is one, subscribing to `entity_damage` in its
|
||||
server script:
|
||||
server phase:
|
||||
|
||||
```ts
|
||||
ctx.events.before.entity_damage.subscribe((event) => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Players
|
||||
|
||||
Server scripts see players as `Player` objects: in events, in component handlers, from `ctx.players`, and as the source
|
||||
of a command.
|
||||
The server phase sees players as `Player` objects: in events, in component handlers, from `ctx.players`, and as the
|
||||
source of a command.
|
||||
|
||||
## Finding Players
|
||||
|
||||
@@ -181,7 +181,7 @@ their eyes at 0.6, so they fit through 1-block gaps. Under a low ceiling they st
|
||||
stand up.
|
||||
|
||||
`player.is_swimming()` says whether a player is swimming, like NeoForge's `isSwimming()`. It works on the server and in
|
||||
client scripts, where `ctx.player.is_swimming()` is about the player on this client:
|
||||
the client phase, where `ctx.player.is_swimming()` is about the player on this client:
|
||||
|
||||
```ts
|
||||
if (player.is_swimming()) player.add_effect("bworld:speed", 20);
|
||||
@@ -190,7 +190,7 @@ if (player.is_swimming()) player.add_effect("bworld:speed", 20);
|
||||
## Sneaking
|
||||
|
||||
`player.is_sneaking()` says whether a player holds the sneak key, like NeoForge's `isShiftKeyDown()`. It's the key, not
|
||||
the pose: a player flying down holds it too. Their client tells the server as soon as it changes. In client scripts,
|
||||
the pose: a player flying down holds it too. Their client tells the server as soon as it changes. In the client phase,
|
||||
`ctx.player.is_sneaking()` is about the player on this client.
|
||||
|
||||
Sneaking changes what right clicking a block does, like Minecraft: with an item in hand, the block isn't used at all,
|
||||
|
||||
@@ -19,8 +19,8 @@ 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`.
|
||||
block with a custom component, an item, a shaped recipe, two textures, and a script with a server, client and worldgen
|
||||
phase. Delete what you don't need: a phase you don't need is an export you leave out.
|
||||
|
||||
The first argument is the mod's id, its [namespace](../concepts/registries.md#identifiers). It has to match the folder
|
||||
name.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Mod Files
|
||||
|
||||
A mod is a folder with a `manifest.json`, some data files, textures, and up to five scripts. The build packs it into a
|
||||
single `.cubi` file, which is what servers load.
|
||||
A mod is a folder with a `manifest.json`, some data files, textures, and a script. The build packs it into a single
|
||||
`.cubi` file, which is what servers load.
|
||||
|
||||
## Layout
|
||||
|
||||
@@ -32,11 +32,8 @@ mods/
|
||||
textures/*.png
|
||||
textures/*.json # animations, see resources/textures.md
|
||||
scripts/
|
||||
server.ts # game logic, never sent to players
|
||||
client.ts # sent to players
|
||||
shared.ts # block rules, run on the server and sent to players
|
||||
worldgen.ts # terrain features, never sent to players
|
||||
content.ts # blocks made in code, run by the server while it loads mods, never sent to players
|
||||
main.ts # the mod's script, its exports are its phases. sent to players, see concepts/sides.md
|
||||
*.ts # whatever else it imports
|
||||
```
|
||||
|
||||
Data folders can have subfolders. Every data file holds one definition, wrapped with the format version:
|
||||
@@ -63,13 +60,7 @@ matter, the `id` inside does, except for [tags](../resources/tags.md), whose id
|
||||
"authors": ["paula"],
|
||||
"game_version": ">=0.1.0",
|
||||
"dependencies": [{ "id": "bworld", "version": "*" }],
|
||||
"scripts": {
|
||||
"server": "scripts/server.ts",
|
||||
"client": "scripts/client.ts",
|
||||
"worldgen": "scripts/worldgen.ts",
|
||||
"shared": "scripts/shared.ts",
|
||||
"content": "scripts/content.ts"
|
||||
},
|
||||
"main": "scripts/main.ts",
|
||||
"credits": "CREDITS.md"
|
||||
}
|
||||
```
|
||||
@@ -83,29 +74,29 @@ matter, the `id` inside does, except for [tags](../resources/tags.md), whose id
|
||||
| `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. Only checked for mods with `engine_access`. |
|
||||
| `engine_access` | no | `true` lets the scripts import `cubi/engine` and hook the engine. See [Engine Access](../misc/engine.md). |
|
||||
| `engine_access` | no | `true` lets the script import `cubi/engine` and hook the engine. See [Engine Access](../misc/engine.md). |
|
||||
| `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`, `shared`, `worldgen` and `content` scripts. See [Sides](../concepts/sides.md). |
|
||||
| `main` | no | The path of the mod's script, whose exports are its phases. 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
|
||||
## The Script
|
||||
|
||||
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.
|
||||
A mod's script is an ES module whose exports are its phases: `content`, `shared`, `server`, `client` and `worldgen`,
|
||||
each a function called with its context where and when it runs. See [Sides](../concepts/sides.md). The build bundles it
|
||||
with everything it imports into one module, so it can import other files and packages.
|
||||
|
||||
> [!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.
|
||||
> The whole script is sent to every player who joins, its server phase too. Don't put secrets in it.
|
||||
|
||||
### 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
|
||||
When a mod's folder has a `deno.json`, its script is 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 `cubi/server`, `cubi/client`, `cubi/shared`,
|
||||
`cubi/worldgen` and `cubi/content`, and [`cubi/engine`](../misc/engine.md):
|
||||
this repository. That config maps the API types, which the script imports as `cubi/server`, `cubi/client`,
|
||||
`cubi/shared`, `cubi/worldgen` and `cubi/content`, and [`cubi/engine`](../misc/engine.md):
|
||||
|
||||
```ts
|
||||
import type { ServerContext } from "cubi/server";
|
||||
@@ -123,13 +114,9 @@ deno task build # packs every mod in mods/ into server_mo
|
||||
|
||||
```
|
||||
copper_tools.cubi
|
||||
manifest.json # with scripts and credits pointing into the zip
|
||||
manifest.json # with main and credits pointing into the zip
|
||||
data.json # every block, model, item, entity, recipe, ore, tag and loot table, and the config
|
||||
scripts/server.js # each script bundled into one module
|
||||
scripts/client.js
|
||||
scripts/worldgen.js
|
||||
scripts/shared.js
|
||||
scripts/content.js
|
||||
script.js # the script bundled into one module
|
||||
textures/<name>.png
|
||||
textures/<name>.json # for animated textures
|
||||
credits.md
|
||||
@@ -139,6 +126,6 @@ copper_tools.cubi
|
||||
- Packing the same mod twice gives the same bytes, so the file only changes when the mod does.
|
||||
- `deno task build` leaves other `.cubi` files in `server_mods/` alone, so mods from elsewhere can sit next to the ones
|
||||
it builds.
|
||||
- `data.json` doesn't hold the blocks `scripts/content.js` registers. The server runs it when it loads the `.cubi`.
|
||||
- Players get a copy **without** `scripts/server.js`, `scripts/worldgen.js`, `scripts/content.js` and the config, but
|
||||
with the blocks the content script registered in its `data.json`. See [Networking](../networking/index.md).
|
||||
- `data.json` doesn't hold the blocks the content phase registers. The server runs it when it loads the `.cubi`.
|
||||
- Players get a copy **without** the terrain's data and the config, but with the blocks the content phase registered in
|
||||
its `data.json`. See [Networking](../networking/index.md).
|
||||
|
||||
@@ -7,12 +7,12 @@ above them.
|
||||
|
||||
## Layers
|
||||
|
||||
A client script registers layers during `setup`, with ids in its namespace:
|
||||
The client phase registers layers while it runs, with ids in its namespace:
|
||||
|
||||
```ts
|
||||
import type { ClientContext } from "cubi/client";
|
||||
|
||||
export function setup(ctx: ClientContext) {
|
||||
export function client(ctx: ClientContext) {
|
||||
ctx.hud.register("thirst:water", {
|
||||
on_render(g, hud) {
|
||||
// a row of drops above the hunger, on the right
|
||||
@@ -48,7 +48,7 @@ side without raising it, and chat goes above that.
|
||||
|
||||
## Overlay Messages
|
||||
|
||||
A server script's message with `{ overlay: true }` (see `Player.send_message`) isn't chat: it goes to the client scripts
|
||||
The server phase's message with `{ overlay: true }` (see `Player.send_message`) isn't chat: it goes to the client phases
|
||||
that listen for it, and the base game shows it above the hotbar for a few seconds:
|
||||
|
||||
```ts
|
||||
|
||||
@@ -43,8 +43,8 @@ interface Screen {
|
||||
```
|
||||
|
||||
The server can't open one directly. Like a NeoForge payload handler calling `setScreen`, the server sends a
|
||||
[mod channel](../networking/index.md) message, and the client script's handler opens it, as above. A screen that needs
|
||||
to tell the server something sends a message back the same way. `ctx.ui.close()` closes the screen on top. A screen that
|
||||
[mod channel](../networking/index.md) message, and the client phase's handler opens it, as above. A screen that needs to
|
||||
tell the server something sends a message back the same way. `ctx.ui.close()` closes the screen on top. A screen that
|
||||
throws is closed, with the error in the console.
|
||||
|
||||
## Inventory Overlays
|
||||
@@ -56,7 +56,7 @@ game's fishing minigame. `mods/recipe_viewer` is one.
|
||||
```ts
|
||||
import type { ClientContext } from "cubi/client";
|
||||
|
||||
export function setup(ctx: ClientContext) {
|
||||
export function client(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
|
||||
@@ -168,7 +168,7 @@ pushes its own:
|
||||
```ts
|
||||
import { type ClientContext, TOOLTIP_PRIORITY } from "cubi/client";
|
||||
|
||||
export function setup(ctx: ClientContext) {
|
||||
export function client(ctx: ClientContext) {
|
||||
ctx.ui.add_item_tooltip((item, lines) => {
|
||||
const value = ctx.items.sell_value(item.id, item.data);
|
||||
if (value === undefined) return;
|
||||
@@ -203,7 +203,7 @@ so a mod's can go between them:
|
||||
|
||||
## Reading Game State
|
||||
|
||||
Client scripts can read what the client knows, to show it:
|
||||
The client phase can read what the client knows, to show it:
|
||||
|
||||
```ts
|
||||
ctx.player.name;
|
||||
@@ -226,12 +226,12 @@ ctx.blocks.components(id); // the same for a block, like what a crab pot catches
|
||||
ctx.fluids.ids(); // every fluid, in load order
|
||||
ctx.fluids.mod(id); // the name of the mod that added it
|
||||
ctx.fluids.name(fluid); // and color, exists and same, see ../resources/fluids.md#using-fluids
|
||||
ctx.loot.table(id); // a loot table file's JSON, or undefined. tables server scripts make aren't here
|
||||
ctx.loot.table(id); // a loot table file's JSON, or undefined. tables server phases make aren't here
|
||||
ctx.recipes.list(type?); // every recipe as its JSON, including mods' own types
|
||||
ctx.options.key_inventory; // the key the player has bound, like Minecraft's Options key mappings
|
||||
```
|
||||
|
||||
`ctx.player`, `ctx.world` and `ctx.options` only work once the player is in the world, not during `setup`.
|
||||
`ctx.player`, `ctx.world` and `ctx.options` only work once the player is in the world, not while the client phase runs.
|
||||
|
||||
To draw blocks that move, like a shaft that turns, register a [visual](../blocks/visuals.md) with
|
||||
`ctx.render.register_visual`.
|
||||
@@ -245,7 +245,7 @@ checks `g.key_pressed(ctx.options.key_inventory)` and calls `ctx.ui.close()`, th
|
||||
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. They'll be menus whose screens the engine draws.
|
||||
the server phase, like Bedrock's server forms. They'll be menus whose screens the engine draws.
|
||||
- **Keybinds** (`ctx.input.bind`). Until then, an inventory overlay can check `g.key_pressed` while an inventory is
|
||||
open.
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# 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`.
|
||||
result, a player's inventory. The server phase makes and uses them through `ctx.containers`.
|
||||
|
||||
## Making Containers
|
||||
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
Menus are how players use [containers](containers.md), like NeoForge's. A GUI has two halves:
|
||||
|
||||
- The **menu** lives in the server script. It decides which slots the player can click, what goes in them, the numbers
|
||||
- The **menu** lives in the server phase. It decides which slots the player can click, what goes in them, the numbers
|
||||
the screen shows, what its buttons do, and when it closes.
|
||||
- The **screen** lives in the client script. It only draws the menu and sends the player's clicks.
|
||||
- The **screen** lives in the client phase. It only draws the menu and sends the player's clicks.
|
||||
|
||||
Every click goes to the server, which applies it following the menu's rules, so a modified client can only do what the
|
||||
menu allows. Chests, furnaces, the smithing table and cooking pot are all menus, and the base game's curios slots are
|
||||
@@ -12,13 +12,13 @@ part of [the player's inventory](#the-players-inventory).
|
||||
|
||||
## Registering a Menu Type
|
||||
|
||||
A menu type is registered in the server script with a function that builds each menu when it opens, like NeoForge's
|
||||
A menu type is registered in the server phase with a function that builds each menu when it opens, like NeoForge's
|
||||
`MenuType` and its server menu constructor. It gets the menu to build, whatever the code opening it passes, and the
|
||||
player:
|
||||
|
||||
```ts
|
||||
// server.ts
|
||||
export function setup(ctx: ServerContext) {
|
||||
export function server(ctx: ServerContext) {
|
||||
const smelter = ctx.menus.register<BlockRef>("copper_tools:smelter", (menu, block, player) => {
|
||||
const container = ctx.containers.get(block.data.container)!;
|
||||
menu.title = "Smelter";
|
||||
@@ -158,12 +158,12 @@ interface MenuHandle {
|
||||
|
||||
## Screens
|
||||
|
||||
The client script gives each of the mod's menu types a screen, like NeoForge's `RegisterMenuScreensEvent` and
|
||||
The client phase gives each of the mod's menu types a screen, like NeoForge's `RegisterMenuScreensEvent` and
|
||||
`AbstractContainerScreen`. The function runs each time one opens, with the client's copy of the menu:
|
||||
|
||||
```ts
|
||||
// client.ts
|
||||
export function setup(ctx: ClientContext) {
|
||||
export function client(ctx: ClientContext) {
|
||||
ctx.ui.register_menu_screen("copper_tools:smelter", (menu) => ({
|
||||
width: 176,
|
||||
height: 166,
|
||||
@@ -215,8 +215,8 @@ console. A screen that throws is closed the same way.
|
||||
## The Player's Inventory
|
||||
|
||||
The player's own inventory screen is a menu too, menu 0, like Minecraft's `InventoryMenu`: their inventory and crafting
|
||||
grid, always there while they play. Mods can add slots to it with `ctx.menus.extend_player_menu` during setup. The
|
||||
function runs when each player joins:
|
||||
grid, always there while they play. Mods can add slots to it with `ctx.menus.extend_player_menu` while the server phase
|
||||
runs. The function runs when each player joins:
|
||||
|
||||
```ts
|
||||
ctx.menus.extend_player_menu((menu, player) => {
|
||||
|
||||
@@ -63,7 +63,7 @@ Hunger and health work like Minecraft's:
|
||||
- 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).
|
||||
The server phase 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
|
||||
|
||||
@@ -12,7 +12,7 @@ Like blocks, each kind of item is defined once. What players hold are **item sta
|
||||
interface ItemStack {
|
||||
readonly id: string;
|
||||
count: number;
|
||||
data?: unknown; // any JSON value, set by server scripts
|
||||
data?: unknown; // any JSON value, set by server phases
|
||||
}
|
||||
```
|
||||
|
||||
@@ -22,7 +22,7 @@ tool. It's saved, and synced to clients as part of the container the stack is in
|
||||
Two stacks of one item only merge into one when their `data` is the same, whatever order its keys are in, in an
|
||||
inventory or on the ground. No data is the same as `{}`.
|
||||
|
||||
Stacks handed to server scripts are live: setting `count` or `data` on one changes the real stack, and a stack counted
|
||||
Stacks handed to server phases are live: setting `count` or `data` on one changes the real stack, and a stack counted
|
||||
down to 0 is gone.
|
||||
|
||||
## A Basic Item
|
||||
@@ -97,7 +97,7 @@ they should stay inside the item's own shape, and an item drawn with a `model` c
|
||||
|
||||
### Worn Models
|
||||
|
||||
`worn` says how an item looks on a player who wears it, like Bedrock's attachables. A server script says what a player
|
||||
`worn` says how an item looks on a player who wears it, like Bedrock's attachables. The server phase says what a player
|
||||
wears with [`set_worn`](../entities/players.md#worn-items), and every client draws it on them. There's no third person
|
||||
view, so players see what others wear, and what's on their own right arm in first person. Artifacts' power glove and
|
||||
feral claws (`mods/artifacts`) and the base game's giant chestplate are examples.
|
||||
@@ -154,7 +154,7 @@ load the mod.
|
||||
|
||||
## Item Components
|
||||
|
||||
Like [block components](../blocks/components.md), item components give items behavior. The server script registers them:
|
||||
Like [block components](../blocks/components.md), item components give items behavior. The server phase registers them:
|
||||
|
||||
```ts
|
||||
ctx.components.register_item<{ max_water: number }>("bworld:watering_can", {
|
||||
@@ -257,6 +257,6 @@ player.give_item("bworld:carrot", 3); // what doesn't fit drops at their feet
|
||||
player.exchange_held({ id: "bworld:bucket", count: 1, data }); // one of the held item becomes this
|
||||
```
|
||||
|
||||
Client and shared scripts have `ctx.items.sell_value(id, data)` too, worked out the same way with that side's
|
||||
Client and shared phases have `ctx.items.sell_value(id, data)` too, worked out the same way with that side's
|
||||
[fluid rules](../resources/fluids.md#rules), so a client can show what a full bottle of juice is worth, like the base
|
||||
game's [tooltip line](../gui/index.md#item-tooltips) does.
|
||||
|
||||
@@ -38,7 +38,7 @@ The base game's tiers:
|
||||
| `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
|
||||
server phase can check a held item's type with `ctx.items.tool(id)`, like the base game's `bworld:hoeable` does for
|
||||
hoes. The base game's watering cans are tools of type `"watering_can"` that no block is mined with: they come in the
|
||||
same five tiers with the same durability, and each holds more water than the last (16, 24, 32, 48 and 64), set by its
|
||||
`bworld:watering_can` component.
|
||||
@@ -52,5 +52,5 @@ dropping.
|
||||
The damage a tool has taken is kept in its stack's `data.damage`, and a worn tool shows a bar under it in its slot,
|
||||
going from green to red as it wears down. Upgrading a tool at the smithing table keeps its data, damage included.
|
||||
|
||||
A server script wears a tool down with `ctx.items.damage(item, amount)`, which adds to the stack's `data.damage` and
|
||||
The server phase wears a tool down with `ctx.items.damage(item, amount)`, which adds to the stack's `data.damage` and
|
||||
returns true when that used it up. It does nothing to items that aren't tools. The base game's death drops use it.
|
||||
|
||||
@@ -8,12 +8,12 @@ Each argument type reads its part of the text and suggests what could go there.
|
||||
|
||||
## Registering a Command
|
||||
|
||||
In the server script's `setup`:
|
||||
In the server phase:
|
||||
|
||||
```ts
|
||||
import type { Player, ServerContext } from "cubi/server";
|
||||
|
||||
export function setup(ctx: ServerContext) {
|
||||
export function server(ctx: ServerContext) {
|
||||
const { literal, argument, types } = ctx.commands;
|
||||
const heal = (player: Player, amount: number) => player.heal(amount);
|
||||
|
||||
@@ -102,7 +102,7 @@ ctx.commands.register("hello", {
|
||||
Command names are `a-z`, `0-9` and `_`. Two mods registering the same name, or a mod registering one of the engine's,
|
||||
stops the server from starting. Every mod command can also be run as `/<mod id>:<name>`, like `/copper_tools:heal`.
|
||||
|
||||
Commands can only be registered during `setup`.
|
||||
Commands can only be registered while the server phase runs.
|
||||
|
||||
## The Engine's Commands
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
A mod's config is its settings: the numbers and switches a server might want different without changing the mod, like
|
||||
how fast a machine works, how far something reaches, or whether a feature is on. The mod lists them with their defaults
|
||||
in `config.json`, a server changes the ones it wants in a file of its own, and the server script reads the result as
|
||||
in `config.json`, a server changes the ones it wants in a file of its own, and the server phase reads the result as
|
||||
`ctx.config`. It's like NeoForge's server configs.
|
||||
|
||||
## `config.json`
|
||||
@@ -26,7 +26,7 @@ can change has to be in this file with its default.
|
||||
|
||||
## Reading It
|
||||
|
||||
`ctx.config` in the server script holds the settings, with the server's changes made:
|
||||
`ctx.config` in the server phase holds the settings, with the server's changes made:
|
||||
|
||||
```ts
|
||||
import type { ServerContext } from "cubi/server";
|
||||
@@ -36,17 +36,17 @@ interface Config {
|
||||
fan: { push_distance: number; pull_distance: number };
|
||||
}
|
||||
|
||||
export function setup(ctx: ServerContext) {
|
||||
export function server(ctx: ServerContext) {
|
||||
const config: Config = ctx.config;
|
||||
ctx.log(`fans push things up to ${config.fan.push_distance} blocks away`);
|
||||
}
|
||||
```
|
||||
|
||||
It's there from `setup` on, and stays the same for as long as the server runs. It's typed `any`, so give it a type of
|
||||
your own like `Config` above.
|
||||
It's there from the server phase on, and stays the same for as long as the server runs. It's typed `any`, so give it a
|
||||
type of your own like `Config` above.
|
||||
|
||||
Only the server script has it. The copy of a mod players download leaves its config out, since a server's settings
|
||||
aren't always the defaults. When players need to see one, the server sends it, like any other
|
||||
Only the server phase has it. The copy of a mod players download leaves its config out, since a server's settings aren't
|
||||
always the defaults. When players need to see one, the server sends it, like any other
|
||||
[server data](../concepts/sides.md#what-each-side-knows): in a block's [client data](../blocks/tiledata.md), an item's
|
||||
`data`, or over a [channel](../networking/index.md#mod-channels).
|
||||
|
||||
|
||||
+13
-12
@@ -21,10 +21,10 @@ runs. When players join from another site, the confirm screen marks mods that ch
|
||||
## Hooking
|
||||
|
||||
```ts
|
||||
// server.ts: broken blocks drop twice
|
||||
// broken blocks drop twice
|
||||
import { engine, hook } from "cubi/engine";
|
||||
|
||||
export function setup() {
|
||||
export function server() {
|
||||
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());
|
||||
@@ -48,16 +48,17 @@ made changes too. It returns a function that unhooks it.
|
||||
outermost, and `after` hooks chain results.
|
||||
- A hook that throws is logged under its mod (`[my_mod] an after hook on GameServer.pop_item threw: ...`) and skipped. A
|
||||
`replace` hook that throws after calling `original` gives what `original` returned, so the method doesn't run twice.
|
||||
- `hook` only works while the mod's script loads or runs `setup`. Unhooking works any time.
|
||||
- `hook` only works while a phase runs. Unhooking works any time. Hook inside a phase, not at the script's top level,
|
||||
which runs once on each side, in whichever phase imports the script first.
|
||||
- Unhooking a method's last hook puts the original back, so a method nobody hooks costs nothing.
|
||||
|
||||
## What's in `engine`
|
||||
|
||||
| Side | Where | Like |
|
||||
| -------- | -------------- | ----------------------------------------------------------------------------------------- |
|
||||
| `common` | every script | `EverythingRegistry`, `ItemStack`, `Container`, `BlockRules`, `NoiseTerrain`, `physics` |
|
||||
| `server` | server scripts | `GameServer`, `ServerWorld`, `ServerPlayer`, `Entity`, `Mob`, `ModRuntime`, the mob goals |
|
||||
| `client` | client scripts | `Client`, `LocalPlayer`, `ClientLevel`, `GameRenderer`, `Camera`, `GuiScreen` |
|
||||
| Side | Where | Like |
|
||||
| -------- | ------------ | ----------------------------------------------------------------------------------------- |
|
||||
| `common` | every phase | `EverythingRegistry`, `ItemStack`, `Container`, `BlockRules`, `NoiseTerrain`, `physics` |
|
||||
| `server` | server phase | `GameServer`, `ServerWorld`, `ServerPlayer`, `Entity`, `Mob`, `ModRuntime`, the mob goals |
|
||||
| `client` | client phase | `Client`, `LocalPlayer`, `ClientLevel`, `GameRenderer`, `Camera`, `GuiScreen` |
|
||||
|
||||
The full lists are in `common/engine_modules.ts`, `server/game/engine_modules.ts` and `client/engine_modules.ts`. The
|
||||
types are the engine's own source, so `check-mods` typechecks against exactly the engine the mod runs on. `cubi/engine`
|
||||
@@ -67,13 +68,13 @@ also exports `game_version`, the version of the game that's running.
|
||||
through: `engine.common.physics.move_body` is how every entity moves, on the server and on clients.
|
||||
- `#private` members can't be hooked. 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. The server generates chunks in worldgen workers, and each loads the worldgen scripts into its own copy, so
|
||||
hooks on the terrain (`engine.common.NoiseTerrain`) go in the worldgen script. A server script's hooks there only
|
||||
meshing. The server generates chunks in worldgen workers, and each loads the worldgen phases into its own copy, so
|
||||
hooks on the terrain (`engine.common.NoiseTerrain`) go in the worldgen phase. The server phase's hooks there only
|
||||
reach the few chunks the game generates itself, so the world would come out different in places.
|
||||
|
||||
## Performance
|
||||
|
||||
Hooking is cheap to set up: hook in `setup`, before the game is running. Each call to a hooked method then goes through
|
||||
Hooking is cheap to set up: hook in a phase, before the game is running. Each call to a hooked method then goes through
|
||||
a wrapper that runs its hooks, which is fine for something that happens now and then, like a block breaking. On
|
||||
something called many times a tick, like `physics.move_body` or a method of every entity, the wrapper's cost adds up,
|
||||
and the engine can no longer inline the method into its callers.
|
||||
@@ -81,5 +82,5 @@ and the engine can no longer inline the method into its callers.
|
||||
## Security
|
||||
|
||||
A server mod with engine access controls the game worker completely, but the worker still has no Deno permissions. A
|
||||
client mod with it can change anything in the game page, which every client script can already reach. See
|
||||
client mod with it can change anything in the game page, which every client phase can already reach. See
|
||||
[Security](../concepts/security.md).
|
||||
|
||||
@@ -16,7 +16,7 @@ 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`.
|
||||
after it. Timers aren't saved: they're gone after a restart, so set them up again in the server phase.
|
||||
|
||||
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`.
|
||||
|
||||
@@ -15,8 +15,8 @@ client server
|
||||
│ [another site: confirm screen] │
|
||||
│ download every .cubi, check each one's │
|
||||
│ sha256, build the texture atlas, load │
|
||||
│ data in the listed order, run client │
|
||||
│ scripts' setup, start chunk workers │
|
||||
│ data in the listed order, run shared │
|
||||
│ and client phases, start chunk workers │
|
||||
│ │
|
||||
│ ready { view_distance } │
|
||||
├────────────────────────────────────────►│
|
||||
@@ -30,10 +30,10 @@ client server
|
||||
- The client loads mods **in the order the server lists them**, so both sides register the same content the same way.
|
||||
- Every `.cubi` 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 `.cubi` **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.
|
||||
- Players get each mod's `.cubi` **without its terrain data and config**. Its script is all there, and players run its
|
||||
shared and client phases. The server makes that copy when it starts, named by its hash so it can be cached forever.
|
||||
- If any download, hash check, shared or client phase 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.
|
||||
@@ -43,8 +43,8 @@ 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.
|
||||
The server sends the world the way Minecraft Java does since 1.20.2. Clients never generate terrain, so they never run
|
||||
the worldgen phase.
|
||||
|
||||
- Chunks are 16×16 and as tall as the dimension, sent whole, compressed, in batches, nearest first. The server paces
|
||||
batches by how fast each client says it loads them.
|
||||
@@ -54,12 +54,12 @@ stay on the server.
|
||||
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).
|
||||
For a mod, this means: what a client knows about the world is what's near its player. Tile data and `ctx.storage` are
|
||||
never sent at all. See [Sides](../concepts/sides.md#what-each-side-knows).
|
||||
|
||||
## Mod Channels
|
||||
|
||||
Mod channels let a mod's client and server scripts send each other JSON messages:
|
||||
Mod channels let a mod's client and server phases send each other JSON messages:
|
||||
|
||||
```ts
|
||||
// server.ts
|
||||
|
||||
@@ -48,8 +48,8 @@ a tank.
|
||||
|
||||
## Rules
|
||||
|
||||
A fluid's name, color and value can depend on its data. The mod's [shared script](../concepts/sides.md#shared-scripts)
|
||||
gives one of its fluids rules for that, like NeoForge's `FluidType.getDescription` and `FluidTintSource.colorAsStack`:
|
||||
A fluid's name, color and value can depend on its data. The mod's [shared phase](../concepts/sides.md#shared) gives one
|
||||
of its fluids rules for that, like NeoForge's `FluidType.getDescription` and `FluidTintSource.colorAsStack`:
|
||||
|
||||
```ts
|
||||
import type { SharedContext } from "cubi/shared";
|
||||
@@ -58,7 +58,7 @@ interface SyrupData {
|
||||
tree?: string;
|
||||
}
|
||||
|
||||
export function setup(ctx: SharedContext) {
|
||||
export function shared(ctx: SharedContext) {
|
||||
ctx.fluids.register("copper_tools:syrup", {
|
||||
name(data) {
|
||||
const { tree } = (data ?? {}) as SyrupData;
|
||||
@@ -86,15 +86,15 @@ export function setup(ctx: SharedContext) {
|
||||
|
||||
`data` is the variant's, `undefined` when it has none, and mustn't be changed. A rule that throws, or returns something
|
||||
that isn't a name, a color or a value, is logged and the JSON's is used. A fluid has one set of rules, from its own mod,
|
||||
and they can only be registered during `setup`.
|
||||
and they can only be registered while the shared phase runs.
|
||||
|
||||
The rules are in the shared script because both sides need them: the server for tooltips, and clients to draw the fluid.
|
||||
Shared scripts have `ctx.items.exists(id)`, `ctx.items.name(id)`, `ctx.items.components(id)` and
|
||||
The rules are in the shared phase because both sides need them: the server for tooltips, and clients to draw the fluid.
|
||||
The shared phase has `ctx.items.exists(id)`, `ctx.items.name(id)`, `ctx.items.components(id)` and
|
||||
`ctx.items.sell_value(id, data?)` for rules that read an item, like syrup named after its tree.
|
||||
|
||||
## Using Fluids
|
||||
|
||||
Server and client scripts have `ctx.fluids`, which goes through the rules:
|
||||
Server and client phases have `ctx.fluids`, which goes through the rules:
|
||||
|
||||
```ts
|
||||
const birch = { id: "copper_tools:syrup", data: { tree: "bworld:birch_log" } };
|
||||
@@ -106,10 +106,10 @@ ctx.fluids.same(birch, { id: "copper_tools:syrup" }); // false, the data is diff
|
||||
```
|
||||
|
||||
`ids` gives each fluid once, without data, so a fluid that's many things by its data, like syrup from each tree, is only
|
||||
there as plain `copper_tools:syrup`. Client scripts also have `ctx.fluids.mod(id)`, the name of the mod that added it,
|
||||
there as plain `copper_tools:syrup`. The client phase also has `ctx.fluids.mod(id)`, the name of the mod that added it,
|
||||
like `ctx.items.mod`.
|
||||
|
||||
Shared scripts have `ctx.fluids.exists` and `ctx.fluids.same` too, which don't depend on rules, like a
|
||||
The shared phase has `ctx.fluids.exists` and `ctx.fluids.same` too, which don't depend on rules, like a
|
||||
[recipe type](recipes.md#custom-recipe-types) that's found by a fluid.
|
||||
|
||||
## Containers
|
||||
@@ -146,11 +146,11 @@ tooltip says what's in it and how much, like "Birch Log Syrup, 250 mB".
|
||||
|
||||
A full one sells for its own `base_sell_value` and what its fluid is worth on top: the fluid's value for 1000 mB times
|
||||
how much it holds, rounded up to a whole number. A jar of maple syrup worth 40 a bucket sells for 10, and the jar's own
|
||||
value when it has one. It can't be sold if neither has a value. Server scripts get this from
|
||||
`ctx.items.sell_value(id, data)`, which the base game's shipping bin sells by. Client and shared scripts have it too,
|
||||
and the base game shows it in [tooltips](../gui/index.md#item-tooltips).
|
||||
value when it has one. It can't be sold if neither has a value. The server phase gets this from
|
||||
`ctx.items.sell_value(id, data)`, which the base game's shipping bin sells by. Client and shared phases have it too, and
|
||||
the base game shows it in [tooltips](../gui/index.md#item-tooltips).
|
||||
|
||||
A server script fills and empties one through its [fluid handler](#fluid-handlers), and `ctx.items.fluid_capacity(id)`
|
||||
The server phase fills and empties one through its [fluid handler](#fluid-handlers), and `ctx.items.fluid_capacity(id)`
|
||||
says how much one holds.
|
||||
|
||||
## Fluid Handlers
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
A loot table says what something gives, as data: a block when it's broken, a mob when it dies, a fishing rod when it
|
||||
reels something in, a crop when it's picked, and a container a script fills, like a chest in a ruin. They work like
|
||||
Minecraft's, and mods can add their own conditions and functions from a server script.
|
||||
Minecraft's, and mods can add their own conditions and functions from the server phase.
|
||||
|
||||
## Files and Ids
|
||||
|
||||
@@ -174,12 +174,12 @@ Those become the `bworld:season`, `bworld:biome` and `bworld:time` conditions, w
|
||||
|
||||
## From a Script
|
||||
|
||||
Server scripts roll tables, fill containers, and add conditions, functions and changes of their own:
|
||||
The server phase rolls tables, fills containers, and adds conditions, functions and changes of its own:
|
||||
|
||||
```ts
|
||||
import type { ServerContext } from "cubi/server";
|
||||
|
||||
export function setup(ctx: ServerContext) {
|
||||
export function server(ctx: ServerContext) {
|
||||
// "condition": "my_mod:night" in any table
|
||||
ctx.loot.register_condition("my_mod:night", (_params, context) => ctx.world.time % 24000 > 13000);
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ pattern fits anywhere in the grid.
|
||||
|
||||
## Smelting: `bworld:smelting` and `bworld:fuel`
|
||||
|
||||
For the furnace. They're the base game's own types, registered by its shared script like
|
||||
For the furnace. They're the base game's own types, registered by its shared phase like
|
||||
[any mod's](#custom-recipe-types):
|
||||
|
||||
```json
|
||||
@@ -53,7 +53,7 @@ long something burns.
|
||||
|
||||
## Smithing: `bworld:smithing`
|
||||
|
||||
For the smithing table, which upgrades a tool. It's the base game's own type, registered by its shared script like
|
||||
For the smithing table, which upgrades a tool. It's the base game's own type, registered by its shared phase like
|
||||
[any mod's](#custom-recipe-types):
|
||||
|
||||
```json
|
||||
@@ -76,7 +76,7 @@ are an error.
|
||||
|
||||
## Stonecutting: `bworld:stonecutting`
|
||||
|
||||
For the stonecutter, which cuts one item into another. It's the base game's own type, registered by its shared script:
|
||||
For the stonecutter, which cuts one item into another. It's the base game's own type, registered by its shared phase:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -95,9 +95,8 @@ uses up one of the input.
|
||||
## Juicing: `bworld:juicing`
|
||||
|
||||
For the juicer, which presses an item into a fluid. The base game registers one from its
|
||||
[shared script](#recipes-from-scripts) for every item with [`bworld:juiceable`](../items/food.md#juice), making the
|
||||
juice named after it, so most mods never write one. A file can add one for anything else, or make something other than
|
||||
juice:
|
||||
[shared phase](#recipes-from-scripts) for every item with [`bworld:juiceable`](../items/food.md#juice), making the juice
|
||||
named after it, so most mods never write one. A file can add one for anything else, or make something other than juice:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -118,7 +117,7 @@ makes. The juicer uses the first recipe that takes the item.
|
||||
## Fermenting: `bworld:fermentable`
|
||||
|
||||
A fluid that ferments into another over time, like juice into wine. The base game registers one from its
|
||||
[shared script](#recipes-from-scripts) for every [juice](../items/food.md#juice), into wine from the same item. A file
|
||||
[shared phase](#recipes-from-scripts) for every [juice](../items/food.md#juice), into wine from the same item. A file
|
||||
can add one for anything else:
|
||||
|
||||
```json
|
||||
@@ -165,7 +164,7 @@ Use a tag rather than listing ids when other mods might have more of the same th
|
||||
|
||||
Any `type` with a namespace is a mod's own, like `bworld:smithing` for the smithing table. The engine only stores these
|
||||
recipes. What their fields mean is up to the mod, which registers the type from its
|
||||
[shared script](../concepts/sides.md#shared-scripts), like NeoForge's `RecipeType` with its serializer:
|
||||
[shared phase](../concepts/sides.md#shared), like NeoForge's `RecipeType` with its serializer:
|
||||
|
||||
```ts
|
||||
import type { ItemStack, SharedContext } from "cubi/shared";
|
||||
@@ -176,7 +175,7 @@ interface SmithingRecipe {
|
||||
result: string;
|
||||
}
|
||||
|
||||
export function setup(ctx: SharedContext) {
|
||||
export function shared(ctx: SharedContext) {
|
||||
ctx.recipes.register_type<SmithingRecipe, { tool: ItemStack; material: ItemStack }>("bworld:smithing", {
|
||||
// the json checked and turned into what matches and the machine use
|
||||
parse: (json, read) => ({
|
||||
@@ -205,7 +204,7 @@ are checked, throwing with the name it's given, like `"result"` or `"ingredients
|
||||
| `read.fluid_stack(value, name)` | `{ fluid: { id, data }, amount }` of a fluid that exists, in mB. |
|
||||
| `read.positive_int(value, name)` | A whole number, at least 1, like a time in ticks. |
|
||||
|
||||
Then server, client and shared scripts look recipes up by what's in the machine, like NeoForge's
|
||||
Then server, client and shared phases look recipes up by what's in the machine, like NeoForge's
|
||||
`RecipeManager.getRecipeFor`:
|
||||
|
||||
```ts
|
||||
@@ -214,25 +213,25 @@ ctx.recipes.all<SmithingRecipe>("bworld:smithing"); // every one, in load order
|
||||
```
|
||||
|
||||
`find` gives the first recipe, in load order, that `matches` says the input makes. Both give the recipes as `parse` made
|
||||
them, not copies, so they aren't to be changed. A type can only be registered during `setup`, in the mod's own
|
||||
namespace. Other mods can add recipes of your type too, as long as they depend on your mod.
|
||||
them, not copies, so they aren't to be changed. A type can only be registered while the shared phase runs, in the mod's
|
||||
own namespace. Other mods can add recipes of your type too, as long as they depend on your mod.
|
||||
|
||||
A recipe of a type no mod registers, like a misspelled one, stops the first mod with one from loading once every shared
|
||||
script has set up, since nothing would ever read it.
|
||||
|
||||
`ctx.recipes.list(type?)` gives recipes as their JSON instead, copies in load order. It's how the recipe viewer shows
|
||||
every mod's types, and how a shared script makes recipes from another type's, see below.
|
||||
every mod's types, and how the shared phase makes recipes from another type's, see below.
|
||||
|
||||
## Recipes From Scripts
|
||||
|
||||
A recipe that follows from other data, like one for every item with a component, can be made in the mod's
|
||||
[shared script](../concepts/sides.md#shared-scripts) instead of written out as files. `ctx.recipes.register(type, json)`
|
||||
adds one like a file in `recipes/` with that `type` would, with the rest of its fields from `json`:
|
||||
[shared phase](../concepts/sides.md#shared) instead of written out as files. `ctx.recipes.register(type, json)` adds one
|
||||
like a file in `recipes/` with that `type` would, with the rest of its fields from `json`:
|
||||
|
||||
```ts
|
||||
import type { SharedContext } from "cubi/shared";
|
||||
|
||||
export function setup(ctx: SharedContext) {
|
||||
export function shared(ctx: SharedContext) {
|
||||
// a sieve recipe for every item that says what it sifts into
|
||||
for (const id of ctx.items.ids()) {
|
||||
const sifts = ctx.items.components(id)["copper_tools:siftable"] as { into: string } | undefined;
|
||||
@@ -241,15 +240,15 @@ export function setup(ctx: SharedContext) {
|
||||
}
|
||||
```
|
||||
|
||||
Shared scripts run on the server and on every player's client, from the same data, so every side makes the same recipes
|
||||
and nothing is sent: the crafting grid, `ctx.recipes.list` in server and client scripts, and recipe viewers see them
|
||||
like any other. That's also why it's only in shared scripts. Recipes can only be registered during `setup`, before any
|
||||
server or client script sets up, and one is checked like a file would be: a broken one, or a second smelting recipe for
|
||||
the same input, throws, which stops the mod loading.
|
||||
The shared phase runs on the server and on every player's client, from the same data, so every side makes the same
|
||||
recipes and nothing is sent: the crafting grid, `ctx.recipes.list` in server and client phases, and recipe viewers see
|
||||
them like any other. That's also why it's only in the shared phase. Recipes can only be registered while it runs, before
|
||||
any server or client phase sets up, and one is checked like a file would be: a broken one, or a second smelting recipe
|
||||
for the same input, throws, which stops the mod loading.
|
||||
|
||||
`ctx.recipes.list(type?)` reads the recipes there are so far, copies in load order, like the client's: every mod's
|
||||
`recipes/` files, and what the shared scripts that set up before this one registered. Dependencies set up first, so a
|
||||
mod can make recipes of its own from another mod's, like a machine of its own for every one of the base game's juicing
|
||||
`recipes/` files, and what the shared phases that set up before this one registered. Dependencies set up first, so a mod
|
||||
can make recipes of its own from another mod's, like a machine of its own for every one of the base game's juicing
|
||||
recipes:
|
||||
|
||||
```ts
|
||||
|
||||
@@ -89,7 +89,7 @@ A tag nobody defines is a check-mods error there.
|
||||
|
||||
## Using Tags in Scripts
|
||||
|
||||
Server and client scripts both have `ctx.tags`. Tags can be written with or without their `#`:
|
||||
Server and client phases both have `ctx.tags`. Tags can be written with or without their `#`:
|
||||
|
||||
```ts
|
||||
ctx.tags.has("items", "bworld:planks", item.id); // whether it's in the tag
|
||||
@@ -102,7 +102,7 @@ ctx.tags.expand(["#bworld:planks", "bworld:stick"]); // every item a recipe's ch
|
||||
`has` and `get` treat a tag nobody defines as empty.
|
||||
|
||||
Mods' own [recipe types](recipes.md#custom-recipe-types) should take tags like the base game's do. `expand` turns a
|
||||
choice into the items it stands for, so the mod's server script can check and match them:
|
||||
choice into the items it stands for, so the mod's server phase can check and match them:
|
||||
|
||||
```ts
|
||||
const ingredient = ctx.tags.expand(json.ingredient); // "#bworld:planks" -> ["bworld:oak_planks", "bworld:spruce_planks", ...]
|
||||
|
||||
@@ -93,19 +93,19 @@ summer in `desert`.
|
||||
|
||||
Scripts read the season where something is:
|
||||
|
||||
| Where | Biome | Season |
|
||||
| ----------------------------------------------- | ----------------------------- | ------------------------------ |
|
||||
| a block in a server component, like `on_tick` | `block.biome` | `block.season` |
|
||||
| an entity from `ctx.world.spawn_entity` | `entity.biome` | `entity.season` |
|
||||
| a player, on the server | `player.biome` | `player.season` |
|
||||
| any block, in server, shared and client scripts | `ctx.world.biome_at(x, y, z)` | `ctx.world.season_at(x, y, z)` |
|
||||
| the player on this client | `ctx.player.biome` | `ctx.player.season` |
|
||||
| a feature's chunk, see [Features](index.md) | `chunk.biome_at(x, y, z)` | |
|
||||
| Where | Biome | Season |
|
||||
| ---------------------------------------------- | ----------------------------- | ------------------------------ |
|
||||
| a block in a server component, like `on_tick` | `block.biome` | `block.season` |
|
||||
| an entity from `ctx.world.spawn_entity` | `entity.biome` | `entity.season` |
|
||||
| a player, on the server | `player.biome` | `player.season` |
|
||||
| any block, in server, shared and client phases | `ctx.world.biome_at(x, y, z)` | `ctx.world.season_at(x, y, z)` |
|
||||
| the player on this client | `ctx.player.biome` | `ctx.player.season` |
|
||||
| a feature's chunk, see [Features](index.md) | `chunk.biome_at(x, y, z)` | |
|
||||
|
||||
`biome_at` is NeoForge's `level.getBiome(pos)`. Entities and players go by the block their feet are in, like
|
||||
`level.getBiome(entity.blockPosition())`. Above and below the world it's the biome at its top or bottom. On the server
|
||||
every block has a biome: in a chunk that isn't loaded it's what generation makes there, which takes a while the first
|
||||
time. In shared rules and client scripts it's what that client has loaded, and `undefined` where it has nothing.
|
||||
time. In shared rules and client phases it's what that client has loaded, and `undefined` where it has nothing.
|
||||
|
||||
```ts
|
||||
ctx.components.register_block("my_mod:crop", {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# 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).
|
||||
with ores (data) and features (the worldgen phase).
|
||||
|
||||
## Determinism
|
||||
|
||||
@@ -13,7 +13,7 @@ isn't the same, trees are cut off at chunk borders.
|
||||
- **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, and in several worldgen workers at once, each with its
|
||||
own copy of the worldgen scripts (and the game generates a few itself).
|
||||
own copy of the worldgen phases (and the game generates a few itself).
|
||||
- Adding or removing a mod's features only changes chunks that haven't been generated yet, with seams where they meet
|
||||
saved ones.
|
||||
|
||||
@@ -76,12 +76,12 @@ order they were registered. The base game's trees are in `vegetal_decoration`, s
|
||||
|
||||
### Code Features
|
||||
|
||||
The worldgen script registers them:
|
||||
The worldgen phase registers them:
|
||||
|
||||
```ts
|
||||
import type { WorldgenContext } from "cubi/worldgen";
|
||||
|
||||
export function setup(gen: WorldgenContext) {
|
||||
export function worldgen(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);
|
||||
@@ -125,7 +125,7 @@ cell agrees on where its tree is.
|
||||
`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.
|
||||
Generated blocks don't run `on_create`, and worldgen phases can't use the server or client API.
|
||||
|
||||
### Data Features
|
||||
|
||||
@@ -185,7 +185,7 @@ Built in names work with or without `minecraft:`.
|
||||
|
||||
### Types and Modifiers in Code
|
||||
|
||||
A worldgen script can add types and placement modifiers for data features to use, by id:
|
||||
The worldgen phase can add types and placement modifiers for data features to use, by id:
|
||||
|
||||
```ts
|
||||
gen.register_feature_type<{ block: string; height: number }>("copper_tools:pillar", (chunk, config, origin) => {
|
||||
|
||||
+49
-44
@@ -24,11 +24,11 @@ A mod is built from up to three layers. Most mods only need the first one or two
|
||||
## Status
|
||||
|
||||
**Built:** the mod loader and `.cubi` 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
|
||||
terrain's data and the config), delivery to clients (hashed downloads, the confirm screen for other sites, credits), the
|
||||
data layer (blocks, block models with variants, items, recipes including mods' own types, entities and entity models,
|
||||
ores), server scripts (components, events, commands, timers, storage, recipes, containers, displayed items), menus like
|
||||
NeoForge's (menu types, slots, data, buttons and `still_valid` on the server, menu screens on the client, and the
|
||||
player's inventory as menu 0, which mods can add slots to), client scripts (item and recipe lookups, plain screens,
|
||||
ores), the server phase (components, events, commands, timers, storage, recipes, containers, displayed items), menus
|
||||
like NeoForge's (menu types, slots, data, buttons and `still_valid` on the server, menu screens on the client, and the
|
||||
player's inventory as menu 0, which mods can add slots to), the client phase (item and recipe lookups, plain screens,
|
||||
inventory overlays, `Graphics` in GUI pixels), mod channels, worldgen features and ores, the base game's block behavior
|
||||
and screens as a mod, world time, and worn items (an item's `worn` model, `player.set_worn`, synced to every client and
|
||||
drawn on other players and on the first person arm). See [Menus](modding/inventories/menus.md),
|
||||
@@ -41,12 +41,17 @@ The code is in `common/mod_loader.ts`, `common/mod_data.ts`, `common/mod_check.t
|
||||
|
||||
**In the API types but throwing:** forms, keybinds, `g.slider`, `register_terrain`.
|
||||
|
||||
**Content scripts** are built, the first part of common scripts: `scripts.content` with `ctx.blocks.register`, see
|
||||
[Content Scripts](#content-scripts-as-built). The code is in `common/content_scripts.ts`, `common/mod_api/content.ts`,
|
||||
`server/content_worker.ts`, `server/load_mods.ts` and `tools/check_mods.ts`.
|
||||
**One script per mod** is built: the manifest's `main` names it, and its exports are its phases (`content`, `shared`,
|
||||
`server`, `client`, `worldgen`), like NeoForge's one jar with setup events by phase and by dist. It's bundled into one
|
||||
module that goes everywhere, players included, and each side runs only its own phases through `run_phase` in
|
||||
`common/mod_loader.ts`. See [Sides](modding/concepts/sides.md).
|
||||
|
||||
**Not built at all:** the rest of common scripts (items and models from code, reading other mods' content), the registry
|
||||
freeze and hash, overrides.
|
||||
**The content phase** is built, the first part of the common phase: `content` with `ctx.blocks.register`, see
|
||||
[The Content Phase](#the-content-phase-as-built). The code is in `common/content_scripts.ts`,
|
||||
`common/mod_api/content.ts`, `server/content_worker.ts`, `server/load_mods.ts` and `tools/check_mods.ts`.
|
||||
|
||||
**Not built at all:** the rest of the common phase (items and models from code, reading other mods' content), the
|
||||
registry freeze and hash, overrides.
|
||||
|
||||
**Engine access** is built (phase 3): `cubi/engine`, `hook`, `engine_access` and its checks, and `physics` as the first
|
||||
plain object mods can hook. See [Engine Access](modding/misc/engine.md). The code is in `common/hooks.ts`,
|
||||
@@ -66,37 +71,37 @@ plain object mods can hook. See [Engine Access](modding/misc/engine.md). The cod
|
||||
|
||||
## Planned API
|
||||
|
||||
### Common Scripts
|
||||
### The Common Phase
|
||||
|
||||
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
|
||||
A phase, `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.
|
||||
|
||||
#### Content Scripts, as Built
|
||||
#### The Content Phase, as Built
|
||||
|
||||
The first part is built differently from the rest of this section: `scripts.content` with only `ctx.blocks.register`,
|
||||
run **once, on the server**, while it loads mods, instead of on both sides. What it registers is added to the mod's data
|
||||
as if it were files, so everything downstream needs no change:
|
||||
The first part is built differently from the rest of this section: `content` with only `ctx.blocks.register`, run
|
||||
**once, on the server**, while it loads mods, instead of on both sides. What it registers is added to the mod's data as
|
||||
if it were files, so everything downstream needs no change:
|
||||
|
||||
- `check-mods` runs it from the mod's folder before checking references, so tags, recipes and worldgen files can name
|
||||
its blocks. Packing leaves its blocks out of `data.json`.
|
||||
- The server runs it on each `.cubi` before its reference check, in a worker without permissions, since the host that
|
||||
loads mods has file access.
|
||||
- Players get the blocks in the copy of `data.json` they download and never run the script, like Luanti's clients get
|
||||
- Players get the blocks in the copy of `data.json` they download and never run the phase, like Luanti's clients get
|
||||
node definitions from the server. The server and its players can't disagree, so this part needs no freeze or hash.
|
||||
- Worldgen workers get the blocks in the worldgen bundle, which is built from the mods' data, and number them the same
|
||||
way, like Luanti's mapgen threads get a copy of the finished registrations instead of running mods' code again.
|
||||
|
||||
Since it runs per mod, before any registry exists, it can't read other mods' content or the server's config yet. Reading
|
||||
other mods' content would mean running content scripts in load order with a view of what came before.
|
||||
other mods' content would mean running content phases in load order with a view of what came before.
|
||||
|
||||
```ts
|
||||
import type { CommonContext } from "bworld/common";
|
||||
|
||||
const COLORS = ["white", "red", "green", "blue", "black"];
|
||||
|
||||
export function setup(ctx: CommonContext) {
|
||||
export function common(ctx: CommonContext) {
|
||||
for (const color of COLORS) {
|
||||
ctx.blocks.register({
|
||||
id: `wool:${color}_wool`,
|
||||
@@ -140,10 +145,10 @@ interface RecipeRegistry {
|
||||
```
|
||||
|
||||
- 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.
|
||||
- The common phase only runs during loading and can't reach the world or players. They get the same `ctx` on both sides,
|
||||
so they can't accidentally register different things.
|
||||
- `register_type` would let `check-mods` and the loader validate mods' own recipe types, instead of each mod checking
|
||||
its recipes in `setup`. `shaped` becomes short for `bworld:shaped`. Shared scripts can now register types with
|
||||
its recipes itself. `shaped` becomes short for `bworld:shaped`. The shared phase can now register types with
|
||||
`ctx.recipes.register_type`, and every one of the base game's and create's are.
|
||||
|
||||
### The Freeze and the Registry Hash
|
||||
@@ -151,7 +156,7 @@ interface RecipeRegistry {
|
||||
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.
|
||||
mismatched blocks. This matters once the common phase exists, since code can register different things on each side.
|
||||
|
||||
### Overrides
|
||||
|
||||
@@ -192,10 +197,10 @@ asks for it in its manifest:
|
||||
```
|
||||
|
||||
```ts
|
||||
// server.ts: broken blocks drop twice
|
||||
// broken blocks drop twice
|
||||
import { engine, hook } from "cubi/engine";
|
||||
|
||||
export function setup() {
|
||||
export function server() {
|
||||
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());
|
||||
@@ -218,13 +223,13 @@ function hook<T, K extends keyof T>(target: T, method: K, handlers: {
|
||||
}): () => void; // unhook
|
||||
```
|
||||
|
||||
- `engine` holds the live modules on each side: `engine.common` everywhere, `engine.server` in server scripts,
|
||||
`engine.client` in client scripts. The engine puts them on the global object at startup, and `cubi/engine` in a mod's
|
||||
bundle is a shim that reads them, so a hook on a prototype changes every instance already made.
|
||||
- `engine` holds the live modules on each side: `engine.common` everywhere, `engine.server` in the server phase,
|
||||
`engine.client` in the client phase. The engine puts them on the global object at startup, and `cubi/engine` in a
|
||||
mod's bundle is a shim that reads them, so a hook on a prototype changes every instance already made.
|
||||
- Types are the engine's own source, so `check-mods` typechecks against exactly the engine the mod will run on.
|
||||
- Several mods can hook one method: `before` hooks run in priority order, `replace` hooks nest, `after` hooks chain
|
||||
results. A hook that throws is logged under its mod and skipped.
|
||||
- `hook` only works while a mod's script loads or runs `setup`, which is how it knows the mod. Each side clears every
|
||||
- `hook` only works while a mod's script loads or runs a phase, which is how it knows the mod. Each side clears every
|
||||
hook before it loads mods, so tests and a client joining another server start clean.
|
||||
- The wrapper is rebuilt when hooks change, with only the steps they use, and the last unhook puts the original back.
|
||||
- Module exports can't be reassigned, so functions mods may want to change move onto plain objects the engine calls
|
||||
@@ -345,23 +350,23 @@ How the server sends the world, like Minecraft Java since 1.20.2. The code is in
|
||||
`WORLDGEN_WORKERS` on the dedicated server, 0 for none. Each tick the game asks them for what the nearest chunks each
|
||||
player is waiting for are built from, nearest first, and only sends a chunk once they've made it; entities and players
|
||||
in a chunk they haven't made yet wait for it, like Minecraft's in chunks that aren't loaded. Each worker gets the
|
||||
worldgen bundle (`common/worldgen_bundle.ts`: the mods' data generation reads and their worldgen scripts), so it makes
|
||||
the same chunks as the game. The host starts them, since the game has no permissions to (see
|
||||
`server/worldgen_workers.ts`), and they talk to the game through ports. Whatever needs a chunk right away, like a mod
|
||||
script reading a block somewhere far, still generates it on the game thread: `/tps` shows how many chunks that was in
|
||||
the last minute. `tools/chunk_loading_bench.ts` measures a player arriving somewhere new.
|
||||
worldgen bundle (`common/worldgen_bundle.ts`: the mods' data generation reads and their scripts, whose worldgen phase
|
||||
it runs), so it makes the same chunks as the game. The host starts them, since the game has no permissions to (see
|
||||
`server/worldgen_workers.ts`), and they talk to the game through ports. Whatever needs a chunk right away, like a
|
||||
mod's server phase reading a block somewhere far, still generates it on the game thread: `/tps` shows how many chunks
|
||||
that was in the last minute. `tools/chunk_loading_bench.ts` measures a player arriving somewhere new.
|
||||
|
||||
## Phases
|
||||
|
||||
Each phase ends with every test passing and the game playable.
|
||||
|
||||
**Phase 1: loading and common scripts.** Partly done: content scripts register blocks, see
|
||||
[Content Scripts](#content-scripts-as-built). `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 1: loading and the common phase.** Partly done: the content phase registers blocks, see
|
||||
[The Content Phase](#the-content-phase-as-built). `common` 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
|
||||
**Phase 2: overrides.** `override` and `extend` in the common phase, `overrides/*.json`, `recipes.remove`, and the
|
||||
`check-mods` rules. Check: a test mod adds a component to `bworld:grass_block`, changes `bworld:glass`'s toughness and
|
||||
replaces the chest recipe, on both sides and in the hash.
|
||||
|
||||
@@ -377,9 +382,9 @@ and dropped, containers clicked, players moving between chunks, entities.
|
||||
rules become something `mods/bworld` sets, with the engine asking it on both sides so clients still predict breaking.
|
||||
Check: all tests pass unchanged, and old saves still load.
|
||||
|
||||
**Phase 6: world generation.** Done, as data instead of a worldgen script with `register_terrain`: noises, density
|
||||
**Phase 6: world generation.** Done, as data instead of `register_terrain` in the worldgen phase: noises, density
|
||||
functions, noise settings and biome sources in `mods/bworld/worldgen/` (see [Terrain](modding/worldgen/terrain.md)),
|
||||
features that are code or data (bworld's trees and cacti are code, in its worldgen script), and generation in worldgen
|
||||
features that are code or data (bworld's trees and cacti are code, in its worldgen phase), and generation in worldgen
|
||||
workers (see [Chunk Streaming](#chunk-streaming)). The golden fixture checked every step made the same world block for
|
||||
block, and the server refuses to start without the `bworld:overworld` generator.
|
||||
|
||||
@@ -404,8 +409,8 @@ saved before any of this plays exactly the same.
|
||||
every biome border. A `minecraft:multi_noise` source could exist next to the rules, for mods and imported datapacks
|
||||
that want it.
|
||||
- **Should `register_terrain` stay?** It's still in the worldgen API, and only throws. Data covers bworld's terrain, but
|
||||
a mod might want a generator that isn't density functions at all, like a flat or skyblock world. Keeping it means the
|
||||
worldgen bundle also carries a terrain script, which workers can load the same way as features. Otherwise it goes.
|
||||
a mod might want a generator that isn't density functions at all, like a flat or skyblock world. Keeping it costs
|
||||
little, since workers already run each mod's worldgen phase, where it would be registered. Otherwise it goes.
|
||||
- **Importing Minecraft's terrain.** Datapacks' noise settings assume a world from -64 to 320 and Minecraft's noises.
|
||||
The formats are close enough that an importer could translate them, but the result wouldn't look like Minecraft's. Not
|
||||
a goal for now.
|
||||
|
||||
Reference in New Issue
Block a user