diff --git a/MODS.md b/MODS.md index 5744d4b..96e535a 100644 --- a/MODS.md +++ b/MODS.md @@ -7,9 +7,9 @@ install anything themselves. The base game is a mod too: `mods/bworld` is written against the same API as any other mod, so anything it does, your mod can do, and it's the best place to look for examples. -A mod is mostly data: JSON files for blocks, items, recipes and entities, and PNG textures. Behavior comes from -TypeScript scripts: a server script for game logic, a client script for what players see, and a worldgen script for -terrain features. +A mod is mostly data: JSON files for blocks, items, recipes and entities, and PNG textures. Behavior comes from one +TypeScript script, whose exports are its phases: `server` for game logic, `client` for what players see, and `worldgen` +for terrain features. ```sh deno task new-mod copper_tools "Copper Tools" # a new mod in mods/copper_tools, from templates/mod @@ -35,7 +35,7 @@ deno task build && deno task server # packs the mods and starts a se - [Blocks](docs/modding/blocks/index.md): looks, mining, drops and placement - [Block States](docs/modding/blocks/states.md): state bits, variants and facing -- [Block Components](docs/modding/blocks/components.md): giving blocks behavior from a server script +- [Block Components](docs/modding/blocks/components.md): giving blocks behavior from the server phase - [Tile Data](docs/modding/blocks/tiledata.md): data kept for one block, the part clients see, and blocks that hold or show items - [Visuals](docs/modding/blocks/visuals.md): blocks drawn with code, like a shaft that turns or the items and fluid in a diff --git a/client/engine_modules.ts b/client/engine_modules.ts index fa6d98a..fa78650 100644 --- a/client/engine_modules.ts +++ b/client/engine_modules.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// what engine access mods get as engine.client, in client scripts. see docs/modding/misc/engine.md +// what engine access mods get as engine.client, in client phases. see docs/modding/misc/engine.md import { Client } from "./client.ts"; import { Entity } from "./entity/entity.ts"; import { LocalPlayer } from "./entity/local_player.ts"; diff --git a/client/fluid_rules.ts b/client/fluid_rules.ts index 137e7de..a9d72a9 100644 --- a/client/fluid_rules.ts +++ b/client/fluid_rules.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// the fluids' rules from the mods' shared scripts on this client, the same as the server's (see common/fluids.ts), for +// the fluids' rules from the mods' shared phases on this client, the same as the server's (see common/fluids.ts), for // drawing fluids and naming them in tooltips. its own module so those don't import client/mods.ts, which loads the mods // and makes it again for each server's import { FluidRules } from "@/common/fluids.ts"; diff --git a/client/gui/gui_mod_screens.ts b/client/gui/gui_mod_screens.ts index 652e642..4b603cf 100644 --- a/client/gui/gui_mod_screens.ts +++ b/client/gui/gui_mod_screens.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// screens mods' client scripts make, see docs/modding/gui/index.md: the screens of their menus, and screens with no +// screens mods' client phases make, see docs/modding/gui/index.md: the screens of their menus, and screens with no // menu. a mod's screen that throws is closed, with the error in the console import { TICK_DELTA } from "@/common/constants.ts"; import type { ClientMenu as ModClientMenu, MenuScreen, Screen } from "@/common/mod_api/client.ts"; @@ -98,7 +98,7 @@ export class GuiModMenuScreen extends GuiMenuScreen { } } -// a screen with no menu, opened by a client script +// a screen with no menu, opened by a mod's client phase export class GuiModScreen extends GuiScreen { #mod: string; #screen: Screen; diff --git a/client/gui/mod_graphics.ts b/client/gui/mod_graphics.ts index d0b124e..1443987 100644 --- a/client/gui/mod_graphics.ts +++ b/client/gui/mod_graphics.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// the immediate mode drawing mods' client scripts get (Graphics in common/mod_api/client.ts), on top of the renderer. +// the immediate mode drawing mods' client phases get (Graphics in common/mod_api/client.ts), on top of the renderer. // one per screen, so text inputs keep their text and focus while it's open. mods work in gui pixels, GUI_SCALE canvas // pixels each import { EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts"; diff --git a/client/gui/tooltip.ts b/client/gui/tooltip.ts index 478ed75..8e3cf6c 100644 --- a/client/gui/tooltip.ts +++ b/client/gui/tooltip.ts @@ -31,7 +31,7 @@ const ICON_GAP = 4; // from the mouse, so the cursor doesn't cover it const OFFSET = 16; -// what client scripts add to every item's tooltip, in load order, see ctx.ui.add_item_tooltip. client/mods.ts fills it, +// what client phases add to every item's tooltip, in load order, see ctx.ui.add_item_tooltip. client/mods.ts fills it, // each wrapped so one throwing is logged under its mod export const item_tooltips: ((item: ApiItemStack, lines: TooltipLine[]) => void)[] = []; diff --git a/client/mods.ts b/client/mods.ts index 8cc7f35..f0aca9a 100644 --- a/client/mods.ts +++ b/client/mods.ts @@ -1,8 +1,8 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// loads the mods the server lists: downloads their .cubi files, registers their data, then runs their client scripts. -// see docs/modding/networking/index.md +// loads the mods the server lists: downloads their .cubi files, registers their data, then runs their scripts' shared +// and client phases. see docs/modding/networking/index.md import { AIR } from "@/common/constants.ts"; import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts"; import type { @@ -19,9 +19,11 @@ import { check_recipe_types, ModListing, ModLoadError, + type Phase, recipe_lookup, RecipeBook, register_mod_data, + run_phase, shared_recipes_api, } from "@/common/mod_loader.ts"; import { type Mod, read_mod } from "@/common/mod.ts"; @@ -37,7 +39,7 @@ import type { Client } from "./client.ts"; import { code_url, fetch_verified } from "./handshake.ts"; import { GuiModScreen } from "./gui/gui_mod_screens.ts"; import { item_tooltips } from "./gui/tooltip.ts"; -import { clear_hooks, expose_engine, loading_mod } from "@/common/hooks.ts"; +import { clear_hooks, expose_engine } from "@/common/hooks.ts"; import { common_engine } from "@/common/engine_modules.ts"; import { client_engine } from "./engine_modules.ts"; import { block_visuals } from "./rendering/visuals.ts"; @@ -130,11 +132,11 @@ const rules_world: SharedWorld = { }, }; -// what the mods' shared scripts registered, run to guess ahead of the server, see common/block_rules.ts +// what the mods' shared phases registered, run to guess ahead of the server, see common/block_rules.ts export let block_rules = new BlockRules(run_mod, rules_world.get_block); -// whether shared scripts are being set up, the only time they can register rules +// whether shared phases are being set up, the only time they can register rules let rules_setup = false; -// whether client scripts are being set up, the only time they can register visuals, since chunk workers are told +// whether client phases are being set up, the only time they can register visuals, since chunk workers are told // which blocks have them when the level starts let client_setup = false; @@ -186,7 +188,7 @@ export async function download_mods(listings: ModListing[], base: URL): Promise< })); } -// registers the mods' data and runs their client scripts, in the order the server listed them +// registers the mods' data and runs their scripts' shared and client phases, in the order the server listed them export async function load_client_mods(listings: ModListing[], mods: Mod[]) { for (const [i, mod] of mods.entries()) { if (mod.credits) { @@ -209,39 +211,28 @@ export async function load_client_mods(listings: ModListing[], mods: Mod[]) { // for engine access mods. the last server's hooks go first clear_hooks(); expose_engine({ common: common_engine(), client: client_engine() }); - const as_mod = (mod: Mod, fn: () => Promise) => - loading_mod(mod.manifest.id, mod.manifest.engine_access ?? false, fn); - // every mod's shared rules first, so client scripts can count on any mod's being there + // one url for each mod's script, so its phases share one module + const urls = mods.map((mod) => mod.script === undefined ? undefined : script_url(mod.script)); + const run = async (phase: Phase, context: (i: number) => unknown) => { + for (const [i, mod] of mods.entries()) { + const url = urls[i]; + if (url === undefined) continue; + const as = { id: mod.manifest.id, engine_access: mod.manifest.engine_access }; + await run_phase(as, url, phase, () => context(i)); + } + }; + + // every mod's shared rules first, so client phases can count on any mod's being there block_rules = new BlockRules(run_mod, rules_world.get_block); set_fluid_rules(new FluidRules(run_mod)); rules_setup = true; - for (const [i, mod] of mods.entries()) { - const code = mod.scripts.shared; - if (!code) continue; - await as_mod(mod, async () => { - const module = await import(script_url(code)); - if (typeof module.setup !== "function") { - throw new ModLoadError(mod.manifest.id, "the shared script doesn't export a setup function"); - } - await module.setup(shared_context(listings[i])); - }); - } + await run("shared", (i) => shared_context(listings[i])); rules_setup = false; check_recipe_types(recipe_book); client_setup = true; - for (const [i, mod] of mods.entries()) { - const code = mod.scripts.client; - if (!code) continue; - await as_mod(mod, async () => { - const module = await import(script_url(code)); - if (typeof module.setup !== "function") { - throw new ModLoadError(mod.manifest.id, "the client script doesn't export a setup function"); - } - await module.setup(client_context(listings[i])); - }); - } + await run("client", (i) => client_context(listings[i])); client_setup = false; } @@ -249,7 +240,7 @@ function script_url(code: string) { return code_url(new TextEncoder().encode(code)); } -// ctx.blocks, the same in shared and client scripts +// ctx.blocks, the same in shared and client phases function blocks_api(mod: string): SharedContext["blocks"] { return { exists: (id) => EverythingRegistry.get("blocks", id) !== undefined, diff --git a/common/block_rules.ts b/common/block_rules.ts index fbc93f3..a052a5c 100644 --- a/common/block_rules.ts +++ b/common/block_rules.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// the block rules shared scripts register (see BlockRules in mod_api/shared.ts), run the same way on the server and on +// the block rules shared phases register (see BlockRules in mod_api/shared.ts), run the same way on the server and on // clients: what states a placed block gets, and how blocks change with the blocks beside them. each side has its own // BlockRules, with its own world: the server's is the real one, a client's is what it shows and guesses ahead with import type { diff --git a/common/content_scripts.ts b/common/content_scripts.ts index 1b71dda..a7751e7 100644 --- a/common/content_scripts.ts +++ b/common/content_scripts.ts @@ -1,33 +1,42 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// runs a mod's content script, see common/mod_api/content.ts. check-mods runs it on the mod's folder, the server on -// its .cubi in a worker without permissions (server/content_worker.ts), and both add what it registers to the mod's -// data before anything else reads it +// runs the content phase of a mod's script, see common/mod_api/content.ts. check-mods runs it on the mod's folder, the +// server on its .cubi in a worker without permissions (server/content_worker.ts), and both add what it registers to +// the mod's data before anything else reads it import { type BlockJson, validate_block } from "./mod_data.ts"; import type { ContentContext } from "./mod_api/content.ts"; +import { ModLoadError, run_phase } from "./mod_loader.ts"; +import { expose_engine } from "./hooks.ts"; +import { common_engine } from "./engine_modules.ts"; export interface ContentScript { mod: string; version: string; + engine_access?: boolean; // importable url of the script url: string; } -// a .cubi's bundled content script, what server/content_worker.ts is sent +// a .cubi's bundled script, what server/content_worker.ts is sent export interface ContentScriptCode { mod: string; version: string; + engine_access?: boolean; code: string; } -// what a content script registered, in order, and what was wrong. with problems the mod doesn't load +// what a content phase registered, in order, and what was wrong. with problems the mod doesn't load export interface RegisteredContent { blocks: BlockJson[]; problems: string[]; } -export async function run_content_script({ mod, version, url }: ContentScript): Promise { +export async function run_content_script( + { mod, version, engine_access, url }: ContentScript, +): Promise { + // the whole script loads here, and one with engine access can import cubi/engine. only engine.common is here + expose_engine({ common: common_engine() }); const blocks: BlockJson[] = []; let setting_up = true; const ctx: ContentContext = { @@ -48,12 +57,11 @@ export async function run_content_script({ mod, version, url }: ContentScript): }, }; try { - const module = await import(url); - if (typeof module.setup !== "function") throw new Error("the content script doesn't export a setup function"); - await module.setup(ctx); + await run_phase({ id: mod, engine_access }, url, "content", () => ctx); return { blocks, problems: [] }; } catch (e) { - return { blocks, problems: [e instanceof Error ? e.message : String(e)] }; + const problem = e instanceof ModLoadError ? e.problem : e instanceof Error ? e.message : String(e); + return { blocks, problems: [problem] }; } finally { setting_up = false; } diff --git a/common/everything_registry.ts b/common/everything_registry.ts index 7e4af76..1c71e13 100644 --- a/common/everything_registry.ts +++ b/common/everything_registry.ts @@ -170,7 +170,7 @@ export interface BlockRegistry { place_in?: string[]; // custom components from mods and their params, the server runs them components?: Record; - // draws the item a server script gives it (ServerWorld.set_block_item) on top of it, like the + // draws the item a mod's server phase gives it (ServerWorld.set_block_item) on top of it, like the // cutting board. surface is the height in pixels it lies on. turned with the variant's y item_display?: { surface: number }; // a fluid like water, drawn like luanti's: its top slopes down towards where it flows. see FluidProperties diff --git a/common/fluids.ts b/common/fluids.ts index f08d0c8..7c0fa6b 100644 --- a/common/fluids.ts +++ b/common/fluids.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// fluids with their data (see FluidVariant in mod_api/shared.ts) and the rules shared scripts give them, which name, +// fluids with their data (see FluidVariant in mod_api/shared.ts) and the rules shared phases give them, which name, // color and value a fluid by its data. each side has its own FluidRules from the same scripts, so the server's tooltips // and a client's drawing agree import type { FluidApi, FluidRules as Rules, FluidVariant } from "./mod_api/shared.ts"; @@ -44,7 +44,7 @@ export class FluidRules { return this.#ask(fluid, "sell_value", "a number of 0 or more", valid) ?? json.base_sell_value; } - // ctx.fluids for server and client scripts + // ctx.fluids for server and client phases api(): FluidApi { return { ids: () => EverythingRegistry.entries("fluids").map(([id]) => id), diff --git a/common/inventory.ts b/common/inventory.ts index aff1aca..3794347 100644 --- a/common/inventory.ts +++ b/common/inventory.ts @@ -12,7 +12,7 @@ export interface ItemData { id: string; count: number; data?: unknown; - // what server scripts say about it (get_lore), only sent to players, never saved + // what server phases say about it (get_lore), only sent to players, never saved lore?: string; } diff --git a/common/loot.ts b/common/loot.ts index 48ccdcf..96c4807 100644 --- a/common/loot.ts +++ b/common/loot.ts @@ -4,7 +4,7 @@ // loot tables, like minecraft's: what something gives when it's broken, killed, fished or opened, as data. a table // has pools, each rolled some number of times, each roll picking one of the pool's entries by weight. conditions // decide whether a table, pool or entry counts, functions change the items it gives. mods can add their own -// conditions and functions (ctx.loot in server scripts), which are ids in their namespace. +// conditions and functions (ctx.loot in server phases), which are ids in their namespace. // see docs/modding/resources/loot_tables.md import * as z from "zod"; import { EverythingRegistry, type ItemRegistry } from "./everything_registry.ts"; diff --git a/common/mod.ts b/common/mod.ts index c85db45..6668ab6 100644 --- a/common/mod.ts +++ b/common/mod.ts @@ -59,14 +59,11 @@ const MAX_UNZIPPED_BYTES = 64 * 1024 * 1024; // written into every entry, so packing the same mod twice gives the same bytes and the same hash const FIXED_TIME = new Date(Date.UTC(2020, 0, 1)); -export type ScriptSide = "server" | "client" | "worldgen" | "shared" | "content"; -export const SCRIPT_SIDES: ScriptSide[] = ["server", "client", "worldgen", "shared", "content"]; - export interface Mod { manifest: ManifestJson; data: ModData; - // bundled javascript, one module per side - scripts: Partial>; + // its script bundled into one javascript module, which every side runs the phases of, see run_phase + script?: string; // png bytes by texture id, like copper_tools:copper_block textures: Map; // the .json of the textures that have one, like animated ones, by texture id @@ -82,27 +79,24 @@ export class ModError extends Error { } // the zip's layout: -// manifest.json the mod's manifest, with "scripts" and "credits" pointing into the zip +// manifest.json the mod's manifest, with "main" and "credits" pointing into the zip // data.json every block, model, item, recipe, ore, entity, entity model, effect, fluid, tag, loot // table and biome, and the mod's config -// scripts/.js +// script.js // textures/.png the texture : // textures/.json its animation, if it has one // credits.md export function write_mod(mod: Mod): Uint8Array { const text = (value: string) => new TextEncoder().encode(value); - const manifest: ManifestJson = { ...mod.manifest, scripts: {} }; + const manifest: ManifestJson = { ...mod.manifest }; + delete manifest.main; delete manifest.credits; const files: Record = {}; - for (const side of SCRIPT_SIDES) { - const code = mod.scripts[side]; - if (code !== undefined) { - files[`scripts/${side}.js`] = text(code); - manifest.scripts![side] = `scripts/${side}.js`; - } + if (mod.script !== undefined) { + files["script.js"] = text(mod.script); + manifest.main = "script.js"; } - if (Object.keys(manifest.scripts!).length === 0) delete manifest.scripts; if (mod.credits !== undefined) { files["credits.md"] = text(mod.credits); manifest.credits = "credits.md"; @@ -233,18 +227,13 @@ export function read_mod(bytes: Uint8Array, file: string): Mod { if (typeof id === "string" && id.split(":")[0] !== mod) problems.push(`${id} isn't in this mod's namespace`); } - const scripts: Mod["scripts"] = {}; - for (const [side, path] of Object.entries(manifest.scripts ?? {})) { - const code = text(path); - if (!SCRIPT_SIDES.includes(side as ScriptSide) || code === undefined) { - problems.push(`manifest.json: scripts.${side} ${path} isn't in the file`); - } else { - scripts[side as ScriptSide] = code; - } + const script = manifest.main === undefined ? undefined : text(manifest.main); + if (manifest.main !== undefined && script === undefined) { + problems.push(`manifest.json: main ${manifest.main} isn't in the file`); } - // what the cubi/engine shim reads, so it's in the bundle of every script that imports it - if (!manifest.engine_access && Object.values(scripts).some((code) => code.includes(ENGINE_GLOBAL))) { - problems.push(`a script uses cubi/engine, which needs "engine_access": true in manifest.json`); + // what the cubi/engine shim reads, so it's in the bundle of a script that imports it + if (!manifest.engine_access && script?.includes(ENGINE_GLOBAL)) { + problems.push(`its script uses cubi/engine, which needs "engine_access": true in manifest.json`); } const credits = manifest.credits === undefined ? undefined : text(manifest.credits); if (manifest.credits !== undefined && credits === undefined) { @@ -293,17 +282,12 @@ export function read_mod(bytes: Uint8Array, file: string): Mod { } if (problems.length > 0) throw new ModError(file, problems); - return { manifest, data, scripts, textures, texture_json, credits }; + return { manifest, data, script, textures, texture_json, credits }; } -// the same mod without its server and worldgen scripts, the terrain's data and its config, what players get. the -// server sends them the world +// the same mod without the terrain's data and its config, what players get. the server sends them the world. its +// script goes with it whole, and players only run its shared and client phases export function client_copy(mod: Mod): Mod { - const scripts = { ...mod.scripts }; - delete scripts.server; - delete scripts.worldgen; - // players get what it registered in data, see common/mod_api/content.ts - delete scripts.content; const { noises: _n, density_functions: _d, @@ -314,7 +298,7 @@ export function client_copy(mod: Mod): Mod { config: _c, ...data } = mod.data; - return { ...mod, scripts, data }; + return { ...mod, data }; } function checked(list: unknown, name: string, validate: (json: unknown) => string[], problems: string[]): unknown[] { diff --git a/common/mod_api/client.ts b/common/mod_api/client.ts index 642519f..c297ce1 100644 --- a/common/mod_api/client.ts +++ b/common/mod_api/client.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// what client scripts get, see docs/modding/gui/index.md +// what client phases get, see docs/modding/gui/index.md import type { FluidApi, FluidVariant, @@ -66,7 +66,7 @@ export interface ClientContext { // read only, what this client sees world: { get_block(x: number, y: number, z: number): Id | undefined; - // a field of the block's client data, what server scripts set with BlockRef.set_client_data, a copy. + // a field of the block's client data, what server phases set with BlockRef.set_client_data, a copy. // undefined when it isn't set or the chunk isn't loaded get_client_data(x: number, y: number, z: number, field: string): T | undefined; // the biome at a block and its season, like the server's. undefined when the chunk isn't loaded @@ -115,7 +115,7 @@ export interface ClientContext { table(id: Id): LootTableJson | undefined; }; // every recipe as its json (see docs/modding/resources/recipes.md), including mods' own types, in load order. copies. - // find and all read the recipes of types shared scripts registered + // find and all read the recipes of types shared phases registered recipes: { // deno-lint-ignore no-explicit-any list(type?: Id): any[]; @@ -376,7 +376,7 @@ export interface HudRegistry { // a layer, drawn every frame in the order they're registered, mods in load order, like RegisterGuiLayersEvent's // registerAboveAll. only during setup. one that throws is removed, with the error in the console register(id: Id, layer: HudLayer): void; - // a server script sent an overlay message (MessageOptions.overlay), for a layer to show + // a mod's server phase sent an overlay message (MessageOptions.overlay), for a layer to show on_overlay_message(fn: (text: string) => void): void; } diff --git a/common/mod_api/content.ts b/common/mod_api/content.ts index 504fb9c..47c83db 100644 --- a/common/mod_api/content.ts +++ b/common/mod_api/content.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// content scripts: blocks made in code, for content that's easier to generate than to write out file by file, like +// content phases: blocks made in code, for content that's easier to generate than to write out file by file, like // every block of every kind of rock. the server runs them while it loads mods, before anything else reads their data, // and what they register becomes part of the mod's data just like its files: checked the same way, sent to players // with the rest, and generated by worldgen workers. see docs/modding/gettingstarted/modfiles.md diff --git a/common/mod_api/engine.ts b/common/mod_api/engine.ts index c9c6d53..1ea042b 100644 --- a/common/mod_api/engine.ts +++ b/common/mod_api/engine.ts @@ -13,8 +13,8 @@ import type { client_engine } from "../../client/engine_modules.ts"; export type { HookHandlers } from "../hooks.ts"; -// the engine's live classes and objects. common is on every side, server only in server scripts, client only in -// client scripts +// the engine's live classes and objects. common is on every side, server only in server phases, client only in +// client phases export interface Engine { common: ReturnType; server: ReturnType; diff --git a/common/mod_api/server.ts b/common/mod_api/server.ts index f236685..cff05f8 100644 --- a/common/mod_api/server.ts +++ b/common/mod_api/server.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// what server scripts get, see docs/modding/ +// what server phases get, see docs/modding/ import type { EventSignal, Face, @@ -118,7 +118,7 @@ export interface BlockComponent

{ // particular when it's undefined, like neoforge's Capabilities.FluidHandler.BLOCK. undefined when it has none // there. see ServerFluidApi.block_handler fluid_handler?(block: BlockRef, params: P, face: Face | undefined): FluidHandler | undefined; - // placing and neighbor rules are in shared scripts, see BlockRules in cubi/shared + // placing and neighbor rules are in shared phases, see BlockRules in cubi/shared } // deno-lint-ignore no-explicit-any @@ -638,7 +638,7 @@ export interface TankHandlerOptions { set(tanks: FluidStack[]): void; } -// ctx.fluids in server scripts: FluidApi, and fluid handlers +// ctx.fluids in server phases: FluidApi, and fluid handlers export interface ServerFluidApi extends FluidApi { // the handler of the block at x y z reached from face, from the first of its components with one, like // level.getCapability(Capabilities.FluidHandler.BLOCK, pos, side). undefined for a block without one there @@ -660,7 +660,7 @@ export interface ServerFluidApi extends FluidApi { interact(player: Player, handler: FluidHandler): boolean; } -// find and all read the recipes of types shared scripts registered +// find and all read the recipes of types shared phases registered export interface RecipeApi extends RecipeLookup { // every recipe of a mod's own type, like "bworld:cooking", as its json. copies, in load order // deno-lint-ignore no-explicit-any @@ -817,7 +817,7 @@ export interface MenuRegistry { // adds slots to every player's own inventory menu, always there while they play, like the curios slots next to the // inventory. build runs when each player joins. only during setup extend_player_menu(build: (menu: PlayerMenuBuilder, player: Player) => void): void; - // like registering a MenuType. the client script gives it a screen with ctx.ui.register_menu_screen + // like registering a MenuType. the client phase gives it a screen with ctx.ui.register_menu_screen register( id: Id, build: (menu: MenuBuilder, args: Args, player: Player) => void, diff --git a/common/mod_api/shared.ts b/common/mod_api/shared.ts index 31f6c45..8411aa8 100644 --- a/common/mod_api/shared.ts +++ b/common/mod_api/shared.ts @@ -12,7 +12,7 @@ export type Season = "spring" | "summer" | "autumn" | "winter"; export interface ItemStack { readonly id: Id; count: number; - // any json value, set by server scripts + // any json value, set by server phases data?: unknown; } @@ -30,7 +30,7 @@ export interface FluidStack { amount: number; } -// ctx.fluids in server and client scripts: every fluid any mod defines, the same on the server and every client +// ctx.fluids in server and client phases: every fluid any mod defines, the same on the server and every client export interface FluidApi { // every fluid's id, in load order, like ctx.items.ids. each without data, which a fluid like juice has many of ids(): Id[]; @@ -44,7 +44,7 @@ export interface FluidApi { same(a: FluidVariant, b: FluidVariant): boolean; } -// what a fluid's data makes it, registered by a shared script, like neoforge's FluidType.getDescription and +// what a fluid's data makes it, registered by a mod's shared phase, like neoforge's FluidType.getDescription and // FluidTintSource.colorAsStack without the amount. data is the variant's, undefined for none, and isn't to be changed. // returning undefined keeps what the fluid's json says export interface FluidRules { @@ -127,7 +127,7 @@ export interface EventSignal { subscribe(handler: (event: T) => void): Unsubscribe; } -// shared scripts: block rules that run on the server and on every client, so a client places blocks the way the +// shared phases: block rules that run on the server and on every client, so a client places blocks the way the // server will, like minecraft's Block code that both sides run. see docs/modding/gettingstarted/modfiles.md export interface SharedContext { @@ -169,21 +169,21 @@ export interface SharedContext { readonly recipes: { // adds a recipe of type, like "shaped" or "bworld:cooking", as a file in the mod's recipes/ with that // json would, only during setup. for recipes made from other data, like one for every item with a component. - // shared scripts run on the server and every client alike, so they all have it without it being sent. it's - // there for server and client scripts, which set up after, and it throws when it's broken like a file would + // shared phases run on the server and every client alike, so they all have it without it being sent. it's + // there for server and client phases, which set up after, and it throws when it's broken like a file would // stop the mod loading register(type: string, json: Record): void; // every recipe, or every one of type, as its json, copies, in load order: the mods' recipes/ files, and what the - // shared scripts that set up before this one registered, which are the dependencies'. like the client's + // shared phases that set up before this one registered, which are the dependencies'. like the client's // deno-lint-ignore no-explicit-any list(type?: string): any[]; // a recipe type of the mod's own, in its namespace, only during setup: its recipes, from files and register, // are parsed by it then, and find and all read them from there on every side. a recipe of a type no mod - // registers stops its mod loading once every shared script has set up. see RecipeType + // registers stops its mod loading once every shared phase has set up. see RecipeType register_type(type: Id, rules: RecipeType): void; } & RecipeLookup; readonly components: { - // the rules of a block component, the same id the server script registers the rest of it under + // the rules of a block component, the same id the server phase registers the rest of it under // deno-lint-ignore no-explicit-any register_block

(id: Id, rules: BlockRules

): void; }; @@ -246,6 +246,6 @@ export interface BlockRules

{ on_neighbor_change?(block: SharedBlock, params: P, neighbor: SharedBlock): void; // a player right clicks it, like minecraft's useWithoutItem: changes only its states and its neighbors', which // the clicking client shows right away instead of waiting for the server. return true if it did something, then - // nothing is placed. the server runs the server script's on_interact too + // nothing is placed. the server runs the server phase's on_interact too on_interact?(block: SharedBlock, params: P, interaction: BlockInteraction): boolean | void; } diff --git a/common/mod_api/worldgen.ts b/common/mod_api/worldgen.ts index 3541a5a..75b3a05 100644 --- a/common/mod_api/worldgen.ts +++ b/common/mod_api/worldgen.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// what worldgen scripts get, see docs/modding/worldgen/index.md. runs on the server and must be deterministic +// what worldgen phases get, see docs/modding/worldgen/index.md. runs on the server and must be deterministic import type { Id, Position } from "./shared.ts"; export type { Id, Position } from "./shared.ts"; diff --git a/common/mod_check.ts b/common/mod_check.ts index 106d261..4ba0034 100644 --- a/common/mod_check.ts +++ b/common/mod_check.ts @@ -487,7 +487,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable // imports cubi/engine to reach into the engine and hook its methods. needs game_version within one minor version engine_access: z.boolean().optional(), dependencies: z.array(z.object({ id: z.string(), version: z.string() })).optional(), - scripts: z.strictObject({ - server: z.string().optional(), - client: z.string().optional(), - worldgen: z.string().optional(), - shared: z.string().optional(), - content: z.string().optional(), - }).optional(), + // the mod's script, whose exports are its phases, see common/mod_loader.ts's PHASES + main: z.string().optional(), credits: z.string().optional(), }).superRefine((manifest, ctx) => { const problem = manifest.engine_access ? engine_version_problem(manifest.game_version) : undefined; diff --git a/common/mod_loader.ts b/common/mod_loader.ts index edc39f8..52dc122 100644 --- a/common/mod_loader.ts +++ b/common/mod_loader.ts @@ -44,6 +44,7 @@ import type { import type { FeatureJson } from "./worldgen/features.ts"; import { register_block_item } from "./utils.ts"; import { find_model, type ModelFileJson, type ModelJson, resolve_models } from "./block_models.ts"; +import { loading_mod } from "./hooks.ts"; // everything a mod's json files hold, merged into one file by the build (build/mods///data.json) export interface ModData { @@ -81,7 +82,7 @@ export interface ModData { config?: Record; } -// a mod as the server lists it to clients, in load order: the .cubi players download, without its server script +// a mod as the server lists it to clients, in load order: the .cubi players download, without its terrain or config export interface ModListing { id: string; name: string; @@ -100,7 +101,7 @@ export class RecipeBook { // recipes of mods' own types, by type, and the mod with the first one of each, for the error when nothing registers it by_type = new Map(); first_used_by = new Map(); - // the types shared scripts registered, and their recipes as parse made them, see SharedContext.recipes.register_type + // the types shared phases registered, and their recipes as parse made them, see SharedContext.recipes.register_type types = new Map>(); parsed = new Map(); // every recipe as its json, in load order, for recipe viewers @@ -111,12 +112,42 @@ export class RecipeBook { } export class ModLoadError extends Error { + // the message without the mod's id + readonly problem: string; + constructor(mod: string, message: string) { super(`${mod}: ${message}`); this.name = "ModLoadError"; + this.problem = message; } } +// what a mod's script can export, each called with its context where and when it runs: content on the server while +// it loads mods, shared on the server and every client, then server or client, and worldgen wherever chunks are +// generated. see docs/modding/concepts/sides.md +export const PHASES = ["content", "shared", "server", "client", "worldgen"] as const; +export type Phase = typeof PHASES[number]; + +// imports a mod's script and calls its export for phase, if it has one, with the context context makes. a realm +// imports the same url once, so every phase there gets the same module and what it keeps at its top level +export async function run_phase( + mod: { id: string; engine_access?: boolean }, + url: string, + phase: Phase, + context: () => unknown, +): Promise { + await loading_mod(mod.id, mod.engine_access ?? false, async () => { + const module = await import(url); + if (!PHASES.some((name) => name in module)) { + throw new ModLoadError(mod.id, `its script exports none of ${PHASES.join(", ")}`); + } + const run = module[phase]; + if (run === undefined) return; + if (typeof run !== "function") throw new ModLoadError(mod.id, `its script's ${phase} export isn't a function`); + await run(context()); + }); +} + // whether a block, item, entity or biome is registered, for tags. air isn't a registered block, but tags can hold it export function is_registered(registry: TagRegistry, id: string): boolean { return (registry === "blocks" && id === "cubi:air") || EverythingRegistry.get(registry, id) !== undefined; @@ -183,7 +214,7 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe } for (const json of data.noise_settings ?? []) EverythingRegistry.register("noise_settings", json.id, json); for (const json of data.biome_sources ?? []) EverythingRegistry.register("biome_sources", json.id, json); - // compiled with the types worldgen scripts register, see common/worldgen_loader.ts + // compiled with the types worldgen phases register, see common/worldgen_loader.ts for (const json of data.features ?? []) EverythingRegistry.register("features", json.id, json); } catch (e) { throw new ModLoadError(id, (e as Error).message); @@ -212,7 +243,7 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe return recipes; } -// puts mod's recipe in the book, from its recipes/ or its shared script. throws when its registered type's parse throws +// puts mod's recipe in the book, from its recipes/ or its shared phase. throws when its registered type's parse throws export function add_recipe(recipes: RecipeBook, recipe: RecipeJson, mod: string) { recipes.all.push(recipe); if (is_mod_recipe(recipe)) { @@ -276,7 +307,7 @@ function checked_item(name: string, problems: string[], id: string): string { return id; } -// once every shared script has set up: a recipe of a type no mod registered, which nothing would read, is an error +// once every shared phase has set up: a recipe of a type no mod registered, which nothing would read, is an error // for the first mod with one, like a misspelled type export function check_recipe_types(recipes: RecipeBook) { for (const [type, mod] of recipes.first_used_by) { @@ -297,7 +328,7 @@ export function recipe_lookup(recipes: () => RecipeBook): RecipeLookup { }; } -// ctx.recipes for shared scripts, the same on the server and every client: a recipe registered there is in the book +// ctx.recipes for shared phases, the same on the server and every client: a recipe registered there is in the book // on every side without being sent, like one from the mod's recipes/. checked like a data file's. fail throws, as the // side's error for the mod. list reads the book as it is, so a script sees the recipes of the ones before it export function shared_recipes_api( diff --git a/common/protocol.ts b/common/protocol.ts index 62b4b43..3bcd5d7 100644 --- a/common/protocol.ts +++ b/common/protocol.ts @@ -166,7 +166,7 @@ export type ClientMessage = | { type: "chat"; text: string } // what could come next in a command being typed, answered with suggestions. id matches them up | { type: "suggest"; id: number; text: string } - // a mod's client script talking to its server script, see ctx.net + // a mod's client phase talking to its server phase, see ctx.net | { type: "mod"; channel: string; data: unknown }; export type ServerMessage = @@ -304,7 +304,7 @@ export type ServerMessage = // the player's own effects that show an icon, when they change. duration is in ticks, -1 for forever, and the // client counts it down itself, so it isn't sent every tick | { type: "effects"; effects: { id: string; amplifier: number; duration: number }[] } - // a mod's server script talking to its client script, see ctx.net + // a mod's server phase talking to its client phase, see ctx.net | { type: "mod"; channel: string; data: unknown }; export const MAX_NAME_LENGTH = 16; diff --git a/common/tags.ts b/common/tags.ts index 09af638..98dd07b 100644 --- a/common/tags.ts +++ b/common/tags.ts @@ -181,7 +181,7 @@ export function expand_items(list: readonly string[]): string[] { return [...new Set(list.flatMap((id) => id.startsWith("#") ? Tags.get("items", id) : [id]))]; } -// ctx.tags for server and client scripts. everything it returns is a copy +// ctx.tags for server and client phases. everything it returns is a copy export function tag_api(): TagApi { const registry = (name: string): TagRegistry => { if (!TAG_REGISTRIES.includes(name as TagRegistry)) { diff --git a/common/utils.ts b/common/utils.ts index 5ff04a8..4b53a7c 100644 --- a/common/utils.ts +++ b/common/utils.ts @@ -88,7 +88,7 @@ export function display_name(item_id: string): string { return EverythingRegistry.get("items", item_id)?.name || name_from_id(item_id); } -// ctx.items for shared scripts, and the part of the client's that's the same. fluids are this side's rules, which +// ctx.items for shared phases, and the part of the client's that's the same. fluids are this side's rules, which // price full fluid containers export function shared_items_api(mod: string, fluids: FluidRules): SharedContext["items"] { const known = (id: string) => { diff --git a/common/worldgen/features.ts b/common/worldgen/features.ts index c8a998d..bc855ee 100644 --- a/common/worldgen/features.ts +++ b/common/worldgen/features.ts @@ -3,7 +3,7 @@ // data features: worldgen/features/.json in a mod, a feature's type and config (what) with a list of placement // modifiers (where), see docs/modding/worldgen/index.md. like minecraft's configured and placed features joined into -// one file. the types and modifiers here are built in, worldgen scripts register more +// one file. the types and modifiers here are built in, worldgen phases register more import { EverythingRegistry } from "../everything_registry.ts"; import type { BlockRegistry } from "../everything_registry.ts"; import { CHUNK_SIZE } from "../constants.ts"; @@ -42,7 +42,7 @@ export const DEFAULT_STEP: FeatureStep = "top_layer_modification"; export interface FeatureJson { id: string; - // a built in type, like "minecraft:block_column", or one a worldgen script registers + // a built in type, like "minecraft:block_column", or one a mod's worldgen phase registers type: string; config?: Record; placement?: PlacementJson[]; @@ -73,7 +73,7 @@ export function builtin_name(type: string): string | undefined { export interface FeatureRefs { blocks: Set; biomes: Set; - // types and modifiers that aren't built in, which a worldgen script has to register + // types and modifiers that aren't built in, which a mod's worldgen phase has to register custom: Set; } @@ -141,7 +141,7 @@ const block_predicate_schema: z.ZodType = z.lazy(() => ], "must be matching_blocks, solid, replaceable, would_survive, not, all_of, any_of or true") ); -// a mod's own modifier is checked by the worldgen script that registers it +// a mod's own modifier is checked by the worldgen phase that registers it const placement_modifier = by_kind("type", (type) => { const name = builtin_name(type); if (name === undefined) return json_object; @@ -156,7 +156,7 @@ const feature_schema: z.ZodType = z.object({ biomes: z.union([biome_id, z.array(biome_id)], "must be a biome's id or a list of them").optional(), step: z.enum(FEATURE_STEPS).optional(), }).superRefine((feature, ctx) => { - // a built in type's config. a mod's own type is checked by the worldgen script that registers it, like modifiers + // a built in type's config. a mod's own type is checked by the worldgen phase that registers it, like modifiers const name = builtin_name(feature.type); if (name === undefined) return; if (!Object.hasOwn(FEATURE_TYPES, name)) { @@ -205,7 +205,7 @@ export function compile_feature( const type = types.get(json.type); if (!type) { throw new Error( - `feature ${json.id}: type ${json.type} isn't built in, and no worldgen script registered it`, + `feature ${json.id}: type ${json.type} isn't built in, and no mod's worldgen phase registered it`, ); } place = (chunk, origin) => type(chunk, config, origin); @@ -216,7 +216,7 @@ export function compile_feature( const custom = modifiers.get(modifier.type); if (!custom) { throw new Error( - `feature ${json.id}: placement[${i}] ${modifier.type} isn't built in, and no worldgen script registered it`, + `feature ${json.id}: placement[${i}] ${modifier.type} isn't built in, and no mod's worldgen phase registered it`, ); } return (chunk: FeatureChunk, positions: Position[]) => custom(chunk, modifier, positions); diff --git a/common/worldgen_bundle.ts b/common/worldgen_bundle.ts index e0d1e04..6f822f6 100644 --- a/common/worldgen_bundle.ts +++ b/common/worldgen_bundle.ts @@ -2,9 +2,9 @@ // SPDX-License-Identifier: AGPL-3.0-or-later // everything generating a chunk reads, as one plain object a worker can be sent: the seed, the generator, and each -// mod's data generation needs with its worldgen script's url. loading it registers the data in this realm and loads -// the scripts, which gives the same numeric block ids and the same generator as the game, so chunks come out the same -// block for block. tests/worldgen_bundle_test.ts checks it with the golden fixture +// mod's data generation needs with its script's url. loading it registers the data in this realm and runs the +// scripts' worldgen phases, which gives the same numeric block ids and the same generator as the game, so chunks come +// out the same block for block. tests/worldgen_bundle_test.ts checks it with the golden fixture import type { ModData } from "./mod_loader.ts"; import { register_mod_data } from "./mod_loader.ts"; import { type BlockRegistry, EverythingRegistry } from "./everything_registry.ts"; @@ -35,20 +35,21 @@ export interface WorldgenBundle { // the dimension's, see WorldShape shape: WorldShapeJson; // in load order - mods: { id: string; data: WorldgenModData; worldgen_url?: string; engine_access?: boolean }[]; + // url is the mod's script, which worldgen workers run the worldgen phase of + mods: { id: string; data: WorldgenModData; url?: string; engine_access?: boolean }[]; } export function worldgen_bundle( seed: string, generator: string, shape: WorldShapeJson, - mods: { id: string; data: ModData; worldgen_url?: string; engine_access?: boolean }[], + mods: { id: string; data: ModData; url?: string; engine_access?: boolean }[], ): WorldgenBundle { return { seed, generator, shape: { min_y: shape.min_y, max_y: shape.max_y, sky_light: shape.sky_light }, - mods: mods.map(({ id, data, worldgen_url, engine_access }) => ({ + mods: mods.map(({ id, data, url, engine_access }) => ({ id, data: { blocks: data.blocks, @@ -62,7 +63,7 @@ export function worldgen_bundle( biome_sources: data.biome_sources ?? [], features: data.features ?? [], }, - ...(worldgen_url ? { worldgen_url } : {}), + ...(url ? { url } : {}), ...(engine_access ? { engine_access } : {}), })), }; @@ -105,7 +106,7 @@ export async function load_bundle(bundle: WorldgenBundle): Promise const setup = await load_worldgen({ mods: bundle.mods.map((mod) => mod.id), scripts: bundle.mods.flatMap((mod) => - mod.worldgen_url ? [{ mod: mod.id, url: mod.worldgen_url, engine_access: mod.engine_access }] : [] + mod.url ? [{ mod: mod.id, url: mod.url, engine_access: mod.engine_access }] : [] ), ores: recipes.ores, generator: bundle.generator, diff --git a/common/worldgen_loader.ts b/common/worldgen_loader.ts index 2296516..de1dece 100644 --- a/common/worldgen_loader.ts +++ b/common/worldgen_loader.ts @@ -1,14 +1,13 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// imports mods' worldgen scripts and collects what they and mods' data add to generation: the generator, ores, and +// runs mods' worldgen phases and collects what they and mods' data add to generation: the generator, ores, and // features, code and data, in the order they run. used by the game server import type { FeatureChunk, FeatureStep, WorldgenContext } from "@/common/mod_api/worldgen.ts"; import type { OreJson } from "@/common/mod_data.ts"; import type { SetupFeature, WorldgenSetup } from "./generation.ts"; import { EverythingRegistry } from "./everything_registry.ts"; -import { ModLoadError } from "./mod_loader.ts"; -import { loading_mod } from "./hooks.ts"; +import { ModLoadError, run_phase } from "./mod_loader.ts"; import { compile_generator } from "./worldgen/generator.ts"; import type { WorldShape } from "./world_shape.ts"; import { @@ -97,13 +96,7 @@ export async function load_worldgen(sources: WorldgenSources): Promise { - const module = await import(url); - if (typeof module.setup !== "function") { - throw new ModLoadError(mod, "the worldgen script doesn't export a setup function"); - } - await module.setup(ctx); - }); + await run_phase({ id: mod, engine_access }, url, "worldgen", () => ctx); } // data features last, so they can use the types and modifiers every script registered diff --git a/docs/modding/blocks/components.md b/docs/modding/blocks/components.md index ab5baa0..bece134 100644 --- a/docs/modding/blocks/components.md +++ b/docs/modding/blocks/components.md @@ -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("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). diff --git a/docs/modding/blocks/index.md b/docs/modding/blocks/index.md index a5f21c3..7d7e2a9 100644 --- a/docs/modding/blocks/index.md +++ b/docs/modding/blocks/index.md @@ -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 diff --git a/docs/modding/blocks/states.md b/docs/modding/blocks/states.md index 14e73f5..5483c66 100644 --- a/docs/modding/blocks/states.md +++ b/docs/modding/blocks/states.md @@ -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; diff --git a/docs/modding/blocks/tiledata.md b/docs/modding/blocks/tiledata.md index 5ad0209..d79d119 100644 --- a/docs/modding/blocks/tiledata.md +++ b/docs/modding/blocks/tiledata.md @@ -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(x, y, z, field)`, see [GUI](../gui/index.md). A block's +- Client phases read it with `ctx.world.get_client_data(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 }); diff --git a/docs/modding/blocks/visuals.md b/docs/modding/blocks/visuals.md index a8278f6..d34c781 100644 --- a/docs/modding/blocks/visuals.md +++ b/docs/modding/blocks/visuals.md @@ -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("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 diff --git a/docs/modding/concepts/events.md b/docs/modding/concepts/events.md index 7833ced..54efe71 100644 --- a/docs/modding/concepts/events.md +++ b/docs/modding/concepts/events.md @@ -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 diff --git a/docs/modding/concepts/registries.md b/docs/modding/concepts/registries.md index 347628c..f8c6d2c 100644 --- a/docs/modding/concepts/registries.md +++ b/docs/modding/concepts/registries.md @@ -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 diff --git a/docs/modding/concepts/security.md b/docs/modding/concepts/security.md index 519fa76..4540de2 100644 --- a/docs/modding/concepts/security.md +++ b/docs/modding/concepts/security.md @@ -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. diff --git a/docs/modding/concepts/sides.md b/docs/modding/concepts/sides.md index f95b8e6..7bb3e22 100644 --- a/docs/modding/concepts/sides.md +++ b/docs/modding/concepts/sides.md @@ -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. diff --git a/docs/modding/datastorage/index.md b/docs/modding/datastorage/index.md index 78a073d..25e6583 100644 --- a/docs/modding/datastorage/index.md +++ b/docs/modding/datastorage/index.md @@ -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. diff --git a/docs/modding/entities/effects.md b/docs/modding/entities/effects.md index fd8bd26..d7f9952 100644 --- a/docs/modding/entities/effects.md +++ b/docs/modding/entities/effects.md @@ -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) => { diff --git a/docs/modding/entities/players.md b/docs/modding/entities/players.md index a8399a6..eed93fb 100644 --- a/docs/modding/entities/players.md +++ b/docs/modding/entities/players.md @@ -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, diff --git a/docs/modding/gettingstarted/index.md b/docs/modding/gettingstarted/index.md index 6c55127..69aa7fb 100644 --- a/docs/modding/gettingstarted/index.md +++ b/docs/modding/gettingstarted/index.md @@ -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. diff --git a/docs/modding/gettingstarted/modfiles.md b/docs/modding/gettingstarted/modfiles.md index eb7557a..334ae73 100644 --- a/docs/modding/gettingstarted/modfiles.md +++ b/docs/modding/gettingstarted/modfiles.md @@ -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/.png textures/.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). diff --git a/docs/modding/gui/hud.md b/docs/modding/gui/hud.md index 5201947..535f46a 100644 --- a/docs/modding/gui/hud.md +++ b/docs/modding/gui/hud.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 diff --git a/docs/modding/gui/index.md b/docs/modding/gui/index.md index a84721f..ac9cfbf 100644 --- a/docs/modding/gui/index.md +++ b/docs/modding/gui/index.md @@ -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. diff --git a/docs/modding/inventories/containers.md b/docs/modding/inventories/containers.md index f2f417d..b960676 100644 --- a/docs/modding/inventories/containers.md +++ b/docs/modding/inventories/containers.md @@ -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 diff --git a/docs/modding/inventories/menus.md b/docs/modding/inventories/menus.md index 85e867a..c483134 100644 --- a/docs/modding/inventories/menus.md +++ b/docs/modding/inventories/menus.md @@ -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("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) => { diff --git a/docs/modding/items/food.md b/docs/modding/items/food.md index 214c5a6..7ccd181 100644 --- a/docs/modding/items/food.md +++ b/docs/modding/items/food.md @@ -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 diff --git a/docs/modding/items/index.md b/docs/modding/items/index.md index e401768..72fc7d1 100644 --- a/docs/modding/items/index.md +++ b/docs/modding/items/index.md @@ -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. diff --git a/docs/modding/items/tools.md b/docs/modding/items/tools.md index a68d946..e9b36f3 100644 --- a/docs/modding/items/tools.md +++ b/docs/modding/items/tools.md @@ -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. diff --git a/docs/modding/misc/commands.md b/docs/modding/misc/commands.md index 5a4f849..baea326 100644 --- a/docs/modding/misc/commands.md +++ b/docs/modding/misc/commands.md @@ -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 `/:`, 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 diff --git a/docs/modding/misc/config.md b/docs/modding/misc/config.md index 8798c21..85bee12 100644 --- a/docs/modding/misc/config.md +++ b/docs/modding/misc/config.md @@ -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). diff --git a/docs/modding/misc/engine.md b/docs/modding/misc/engine.md index dd7948f..2c0bcb1 100644 --- a/docs/modding/misc/engine.md +++ b/docs/modding/misc/engine.md @@ -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). diff --git a/docs/modding/misc/time.md b/docs/modding/misc/time.md index 9a4c859..7f0fb72 100644 --- a/docs/modding/misc/time.md +++ b/docs/modding/misc/time.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`. diff --git a/docs/modding/networking/index.md b/docs/modding/networking/index.md index 0a527f4..9887906 100644 --- a/docs/modding/networking/index.md +++ b/docs/modding/networking/index.md @@ -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 diff --git a/docs/modding/resources/fluids.md b/docs/modding/resources/fluids.md index c831ed5..b4d0622 100644 --- a/docs/modding/resources/fluids.md +++ b/docs/modding/resources/fluids.md @@ -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 diff --git a/docs/modding/resources/loot_tables.md b/docs/modding/resources/loot_tables.md index 6d729bf..9787bff 100644 --- a/docs/modding/resources/loot_tables.md +++ b/docs/modding/resources/loot_tables.md @@ -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); diff --git a/docs/modding/resources/recipes.md b/docs/modding/resources/recipes.md index bdb5d1f..a4ce56c 100644 --- a/docs/modding/resources/recipes.md +++ b/docs/modding/resources/recipes.md @@ -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("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("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 diff --git a/docs/modding/resources/tags.md b/docs/modding/resources/tags.md index 48d876a..9e147bf 100644 --- a/docs/modding/resources/tags.md +++ b/docs/modding/resources/tags.md @@ -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", ...] diff --git a/docs/modding/worldgen/biomes.md b/docs/modding/worldgen/biomes.md index 9fd5153..a39139d 100644 --- a/docs/modding/worldgen/biomes.md +++ b/docs/modding/worldgen/biomes.md @@ -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", { diff --git a/docs/modding/worldgen/index.md b/docs/modding/worldgen/index.md index dd7a340..df44f3c 100644 --- a/docs/modding/worldgen/index.md +++ b/docs/modding/worldgen/index.md @@ -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) => { diff --git a/docs/modding_plan.md b/docs/modding_plan.md index b3b2c5a..f56ed61 100644 --- a/docs/modding_plan.md +++ b/docs/modding_plan.md @@ -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(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. diff --git a/mods/bworld/manifest.json b/mods/bworld/manifest.json index b578aad..3b7a3c0 100644 --- a/mods/bworld/manifest.json +++ b/mods/bworld/manifest.json @@ -9,11 +9,5 @@ ], "game_version": ">=0.1.0", "credits": "CREDITS.md", - "scripts": { - "server": "scripts/server.ts", - "client": "scripts/client.ts", - "shared": "scripts/shared.ts", - "worldgen": "scripts/worldgen.ts", - "content": "scripts/content.ts" - } + "main": "scripts/main.ts" } diff --git a/mods/bworld/scripts/client.ts b/mods/bworld/scripts/client.ts index b13e063..ae08db5 100644 --- a/mods/bworld/scripts/client.ts +++ b/mods/bworld/scripts/client.ts @@ -29,7 +29,7 @@ const HEIGHT = 166; // what an item sells for, after its food line in its tooltip const VALUE_COLOR: Color = [0.95, 0.8, 0.3, 1]; -export function setup(ctx: ClientContext) { +export function client(ctx: ClientContext) { ctx.ui.register_menu_screen("bworld:storage", chest_screen); ctx.ui.register_menu_screen("bworld:furnace", furnace_screen); ctx.ui.register_menu_screen("bworld:crabpot", (menu) => container_screen(menu, HEIGHT)); diff --git a/mods/bworld/scripts/content.ts b/mods/bworld/scripts/content.ts index 4a6ffdf..89c9d63 100644 --- a/mods/bworld/scripts/content.ts +++ b/mods/bworld/scripts/content.ts @@ -41,7 +41,7 @@ const FORMS: { form: string; id: (rock: string) => string }[] = [ const STONE_MINING = { toughness: 3, tool: "pickaxe", requires_tool: true } as const; -export function setup(ctx: ContentContext) { +export function content(ctx: ContentContext) { const texture = (form: string, rock: string) => `bworld:rock_${form}_${rock}`; for (const rock of ROCKS) { for (const { form, id } of FORMS) { diff --git a/mods/bworld/scripts/cooking_recipes.ts b/mods/bworld/scripts/cooking_recipes.ts index 7435d21..25c66e0 100644 --- a/mods/bworld/scripts/cooking_recipes.ts +++ b/mods/bworld/scripts/cooking_recipes.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// the kitchen's recipe types, registered by the shared script: what the cooking pot cooks, found by the items in its +// the kitchen's recipe types, registered by the shared phase: what the cooking pot cooks, found by the items in its // ingredient slots, and what the cutting board cuts, found by the item on it. see cooking.ts import type { SharedContext } from "cubi/shared"; diff --git a/mods/bworld/scripts/fermenting.ts b/mods/bworld/scripts/fermenting.ts index 66dfc50..f3fb1c2 100644 --- a/mods/bworld/scripts/fermenting.ts +++ b/mods/bworld/scripts/fermenting.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later // fermentable recipes: a fluid that ferments into another over a number of ticks, like juice into wine in the keg. the -// shared script registers one for every juice, and mods can add more like any recipe, as files or from their shared +// shared phase registers one for every juice, and mods can add more like any recipe, as files or from their shared // scripts. they're found by the fluid that ferments import type { FluidStack, FluidVariant, SharedContext } from "cubi/shared"; import type { JuiceableParams } from "./shared.ts"; diff --git a/mods/bworld/scripts/juicing.ts b/mods/bworld/scripts/juicing.ts index ad7f708..611b82b 100644 --- a/mods/bworld/scripts/juicing.ts +++ b/mods/bworld/scripts/juicing.ts @@ -1,8 +1,8 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// juicing recipes: what the juicer presses an item into. the shared script registers one for every item with -// bworld:juiceable, its own juice, and mods can add more like any recipe, as files or from their shared scripts. +// juicing recipes: what the juicer presses an item into. the shared phase registers one for every item with +// bworld:juiceable, its own juice, and mods can add more like any recipe, as files or from their shared phases. // whatever makes juice finds them by the item, like the juicer. with create installed, each is also a create:compacting // recipe, so its press can make juice in a basin import type { FluidStack, SharedContext } from "cubi/shared"; @@ -44,7 +44,7 @@ export function register_juicing(ctx: SharedContext) { // a create:compacting recipe for every juicing recipe there is so far, so create's press squashes the item into its // juice in a basin under it. create's recipes take a list of item choices and give a list of results, a fluid's as -// { fluid, amount }. juicing recipes other mods' shared scripts register later aren't seen here +// { fluid, amount }. juicing recipes other mods' shared phases register later aren't seen here function register_compacting(ctx: SharedContext) { for (const juicing of ctx.recipes.list(JUICING)) { ctx.recipes.register("create:compacting", { diff --git a/mods/bworld/scripts/main.ts b/mods/bworld/scripts/main.ts new file mode 100644 index 0000000..b0359d0 --- /dev/null +++ b/mods/bworld/scripts/main.ts @@ -0,0 +1,9 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// the base game's script. each phase is in its own file, see docs/modding/concepts/sides.md +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"; diff --git a/mods/bworld/scripts/server.ts b/mods/bworld/scripts/server.ts index 84bac81..f847a28 100644 --- a/mods/bworld/scripts/server.ts +++ b/mods/bworld/scripts/server.ts @@ -15,7 +15,7 @@ import { JUICING, type JuicingRecipe } from "./juicing.ts"; import { FERMENTABLE, type FermentableRecipe } from "./fermenting.ts"; import { register_cooking_pot, register_cutting_board, register_stove } from "./cooking.ts"; -export function setup(ctx: ServerContext) { +export function server(ctx: ServerContext) { register_hoeable(ctx); register_strippable(ctx); const storage_menu = register_storage(ctx); diff --git a/mods/bworld/scripts/shared.ts b/mods/bworld/scripts/shared.ts index 778b896..bb98989 100644 --- a/mods/bworld/scripts/shared.ts +++ b/mods/bworld/scripts/shared.ts @@ -14,7 +14,7 @@ import { register_smithing } from "./smithing.ts"; import { register_stonecutting } from "./stonecutting.ts"; import { register_verdigris_rules } from "./verdigris/shared.ts"; -export function setup(ctx: SharedContext) { +export function shared(ctx: SharedContext) { register_fence(ctx); register_trapdoor(ctx); register_door(ctx); diff --git a/mods/bworld/scripts/smelting.ts b/mods/bworld/scripts/smelting.ts index 5f6ccde..1053511 100644 --- a/mods/bworld/scripts/smelting.ts +++ b/mods/bworld/scripts/smelting.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later // smelting and fuel recipes: the furnace cooks one item into another, burning fuel to do it. both are found by an item -// id, and registered by the shared script like smithing.ts +// id, and registered by the shared phase like smithing.ts import type { SharedContext } from "cubi/shared"; export const SMELTING = "bworld:smelting"; diff --git a/mods/bworld/scripts/smithing.ts b/mods/bworld/scripts/smithing.ts index fe6a648..a49a87e 100644 --- a/mods/bworld/scripts/smithing.ts +++ b/mods/bworld/scripts/smithing.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later // smithing recipes: the smithing table upgrades a tool with some of a material and maybe some of one more item. the -// type is registered by the shared script, so the server's menu and anything on a client find them the same way +// type is registered by the shared phase, so the server's menu and anything on a client find them the same way import type { ItemStack, RecipeReader, SharedContext } from "cubi/shared"; export const SMITHING = "bworld:smithing"; diff --git a/mods/bworld/scripts/stonecutting.ts b/mods/bworld/scripts/stonecutting.ts index 6f19079..9569dcc 100644 --- a/mods/bworld/scripts/stonecutting.ts +++ b/mods/bworld/scripts/stonecutting.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later // stonecutting recipes: the stonecutter cuts one item into another, picked from every recipe that takes it. the type is -// registered by the shared script, so the server's menu and the client's screen both list them from ctx.recipes.all, in +// registered by the shared phase, so the server's menu and the client's screen both list them from ctx.recipes.all, in // the same order, so a button's number means the same recipe to both import type { SharedContext } from "cubi/shared"; diff --git a/mods/bworld/scripts/verdigris/signals.ts b/mods/bworld/scripts/verdigris/signals.ts index 78f0d02..4a6873e 100644 --- a/mods/bworld/scripts/verdigris/signals.ts +++ b/mods/bworld/scripts/verdigris/signals.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later // the power blocks give each other, see docs/modding/blocks/verdigris.md. every signal is a block state, so this only -// reads states, through a small world instead of ctx so it runs the same in shared scripts, server scripts and tests +// reads states, through a small world instead of ctx so it runs the same in shared phases, server phases and tests import type { Face, Id } from "cubi/shared"; import { FACES, type FacingParam, front_of, named_sides, OPPOSITE, type SideName, step } from "./sides.ts"; diff --git a/mods/bworld/scripts/worldgen.ts b/mods/bworld/scripts/worldgen.ts index eeb3d75..6fe9688 100644 --- a/mods/bworld/scripts/worldgen.ts +++ b/mods/bworld/scripts/worldgen.ts @@ -6,7 +6,7 @@ import type { FeatureChunk, WorldgenContext } from "cubi/worldgen"; import { register_trees } from "./trees.ts"; -export function setup(gen: WorldgenContext) { +export function worldgen(gen: WorldgenContext) { // trees grow in vegetal_decoration, before the cactus looks for air in the last step register_trees(gen); gen.register_feature("bworld:cactus", cactus); diff --git a/mods/create/manifest.json b/mods/create/manifest.json index 3ab5f1c..ca4b39c 100644 --- a/mods/create/manifest.json +++ b/mods/create/manifest.json @@ -16,9 +16,5 @@ } ], "credits": "CREDITS.md", - "scripts": { - "server": "scripts/server.ts", - "client": "scripts/client.ts", - "shared": "scripts/shared.ts" - } + "main": "scripts/main.ts" } diff --git a/mods/create/scripts/client.ts b/mods/create/scripts/client.ts index ef17bbc..480d037 100644 --- a/mods/create/scripts/client.ts +++ b/mods/create/scripts/client.ts @@ -49,7 +49,7 @@ const half_shaft = (facing: Face) => HALF_SHAFT_TURNS[OPPOSITE[facing]]; // how a model made along y is turned to an axis, the way the kinetic blocks' variants turn theirs const AXIS_TURNS: Record = { x: { x: 90, y: 90 }, y: {}, z: { x: 90, y: 180 } }; -export function setup(ctx: ClientContext) { +export function client(ctx: ClientContext) { const shape_of = (block: VisualBlock): KineticShape => { const params = ctx.blocks.components(block.id)["create:kinetic"] as KineticParams; return kinetic_shape(params, (name) => block.states[name]); diff --git a/mods/create/scripts/main.ts b/mods/create/scripts/main.ts new file mode 100644 index 0000000..7b3f40c --- /dev/null +++ b/mods/create/scripts/main.ts @@ -0,0 +1,7 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// create's script. each phase is in its own file, see docs/modding/concepts/sides.md +export { shared } from "./shared.ts"; +export { server } from "./server.ts"; +export { client } from "./client.ts"; diff --git a/mods/create/scripts/recipes/processing.ts b/mods/create/scripts/recipes/processing.ts index c561d65..4c7c623 100644 --- a/mods/create/scripts/recipes/processing.ts +++ b/mods/create/scripts/recipes/processing.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later // create's processing recipes, the shape its machines' recipe types share, like ProcessingRecipe: item choices in, and -// stacks out, each with a chance, and for the types that can, fluids out as { fluid, amount }. the shared script +// stacks out, each with a chance, and for the types that can, fluids out as { fluid, amount }. the shared phase // registers each type, so a broken recipe stops the mod loading instead of a machine later. no ctx, tests give what it // needs import type { FluidStack, Id, RecipeType } from "cubi/shared"; diff --git a/mods/create/scripts/server.ts b/mods/create/scripts/server.ts index 2d53eb6..3131fc3 100644 --- a/mods/create/scripts/server.ts +++ b/mods/create/scripts/server.ts @@ -79,7 +79,7 @@ interface PressData extends KineticData { scan?: number; } -export function setup(ctx: ServerContext) { +export function server(ctx: ServerContext) { const config: Config = ctx.config; const world = kinetic_world(ctx, config); diff --git a/mods/create/scripts/shared.ts b/mods/create/scripts/shared.ts index 55155c0..c2bf896 100644 --- a/mods/create/scripts/shared.ts +++ b/mods/create/scripts/shared.ts @@ -20,7 +20,7 @@ import { OPPOSITE, } from "./kinetics/connections.ts"; -export function setup(ctx: SharedContext) { +export function shared(ctx: SharedContext) { const lookup = { expand: ctx.tags.expand, item_exists: ctx.items.exists, fluid_exists: ctx.fluids.exists }; ctx.recipes.register_type(PRESSING.id, processing_type(PRESSING, lookup)); ctx.recipes.register_type(COMPACTING.id, processing_type(COMPACTING, lookup)); diff --git a/mods/recipe_viewer/manifest.json b/mods/recipe_viewer/manifest.json index 0ef1e7e..47d0c84 100644 --- a/mods/recipe_viewer/manifest.json +++ b/mods/recipe_viewer/manifest.json @@ -8,7 +8,5 @@ "paula" ], "game_version": ">=0.1.0", - "scripts": { - "client": "scripts/client.ts" - } + "main": "scripts/client.ts" } diff --git a/mods/recipe_viewer/scripts/client.ts b/mods/recipe_viewer/scripts/client.ts index 856a3e6..5330ca7 100644 --- a/mods/recipe_viewer/scripts/client.ts +++ b/mods/recipe_viewer/scripts/client.ts @@ -8,7 +8,7 @@ import type { ClientContext } from "cubi/client"; import { type Entry, ItemList, type Mode } from "./item_list.ts"; import { RecipeIndex, RecipesScreen } from "./recipes_screen.ts"; -export function setup(ctx: ClientContext) { +export function client(ctx: ClientContext) { const index = new RecipeIndex(ctx); const list = new ItemList(ctx); // like jei's IRecipesGui.show, only when there's something to show diff --git a/server/content_worker.ts b/server/content_worker.ts index 4add867..5d24323 100644 --- a/server/content_worker.ts +++ b/server/content_worker.ts @@ -3,15 +3,16 @@ /// -// runs the mods' content scripts for server/load_mods.ts, without permissions like the game's worker, since the host -// that loads mods can read and write files. gets each one's script and answers with what each registered, in order +// runs the content phase of the mods' scripts for server/load_mods.ts, without permissions like the game's worker, +// since the host that loads mods can read and write files. gets each one's script and answers with what each +// registered, in order import { type ContentScriptCode, run_content_script } from "@/common/content_scripts.ts"; import { data_url } from "@/common/mod.ts"; self.onmessage = async (event: MessageEvent) => { const results = []; - for (const { mod, version, code } of event.data) { - results.push(await run_content_script({ mod, version, url: data_url(code) })); + for (const { code, ...script } of event.data) { + results.push(await run_content_script({ ...script, url: data_url(code) })); } self.postMessage(results); }; diff --git a/server/game/engine_modules.ts b/server/game/engine_modules.ts index 4d79aff..4f4fa1c 100644 --- a/server/game/engine_modules.ts +++ b/server/game/engine_modules.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// what engine access mods get as engine.server, in server scripts. see docs/modding/misc/engine.md +// what engine access mods get as engine.server, in server phases. see docs/modding/misc/engine.md import { GameServer } from "./game_server.ts"; import { ServerWorld } from "./world.ts"; import { ServerPlayer } from "./player.ts"; diff --git a/server/game/fluid_handlers.ts b/server/game/fluid_handlers.ts index 1f5ecdb..f371a17 100644 --- a/server/game/fluid_handlers.ts +++ b/server/game/fluid_handlers.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// the fluid handlers the engine makes for server scripts, see ServerFluidApi in mod_api/server.ts: fluid containers', +// the fluid handlers the engine makes for server phases, see ServerFluidApi in mod_api/server.ts: fluid containers', // tanks scripts keep, and pouring from one handler into another import { EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts"; import { contained_fluid } from "@/common/inventory.ts"; diff --git a/server/game/game_server.ts b/server/game/game_server.ts index d4d9448..ac15527 100644 --- a/server/game/game_server.ts +++ b/server/game/game_server.ts @@ -587,7 +587,7 @@ export class GameServer { this.#send(player, overlay ? { type: "chat", text, overlay } : { type: "chat", text }); } - // a mod's server script to its client script, see ctx.net + // a mod's server phase to its client phase, see ctx.net send_mod_message(player: ServerPlayer, channel: string, data: unknown) { this.#send(player, { type: "mod", channel, data }); } @@ -1372,7 +1372,7 @@ export class GameServer { return; } - // the shared rules first, the ones the client guessed, then the server script's. sneaking with an item skips the + // the shared rules first, the ones the client guessed, then the server phase's. sneaking with an item skips the // block, like minecraft's secondary use, so a block can be placed against a chest const sneaking = player.sneaking; let handled = false; diff --git a/server/game/host_protocol.ts b/server/game/host_protocol.ts index d96aa83..f29787d 100644 --- a/server/game/host_protocol.ts +++ b/server/game/host_protocol.ts @@ -19,14 +19,8 @@ export type HostToGame = // level.json, and where the saved chunks are. the game reads them with read_chunk when it needs them save: { level?: string; chunks: [number, number][] }; default_seed: string; - // in load order, with the scripts' code since the worker can't read files - mods: { - listing: ModListing; - data: ModData; - server_code?: string; - worldgen_code?: string; - shared_code?: string; - }[]; + // in load order, with their script's code since the worker can't read files + mods: { listing: ModListing; data: ModData; code?: string }[]; // the game's ends of channels to the worldgen workers the host started, see worldgen_pool.ts. none means // generating on the game's thread worldgen_ports: MessagePort[]; diff --git a/server/game/load_mods.ts b/server/game/load_mods.ts index 39e5eec..bf17616 100644 --- a/server/game/load_mods.ts +++ b/server/game/load_mods.ts @@ -1,8 +1,8 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// starts a game server with its mods: registers their data, then imports worldgen and server scripts. -// the worker loads built mods, tests can load mods straight from their source folders +// starts a game server with its mods: registers their data, then runs the worldgen, shared and server phases of their +// scripts. the worker loads built mods, tests can load mods straight from their source folders import { register_mod_data } from "@/common/mod_loader.ts"; import type { ModData, ModListing } from "@/common/mod_loader.ts"; import { load_worldgen } from "@/common/worldgen_loader.ts"; @@ -22,10 +22,8 @@ import { server_engine } from "./engine_modules.ts"; export interface ServerModSource { listing: ModListing; data: ModData; - // importable urls of the scripts: data: urls in the worker, file urls in tests - server_url?: string; - worldgen_url?: string; - shared_url?: string; + // importable url of its script: a data: url in the worker, a file url in tests + url?: string; } export async function start_game( @@ -47,9 +45,7 @@ export async function start_game( const generator = dimension.generator; const shape = dimension_shape(dimension); const worldgen_scripts = mods.flatMap((mod) => - mod.worldgen_url - ? [{ mod: mod.listing.id, url: mod.worldgen_url, engine_access: mod.listing.engine_access }] - : [] + mod.url ? [{ mod: mod.listing.id, url: mod.url, engine_access: mod.listing.engine_access }] : [] ); const worldgen = await load_worldgen({ mods: mods.map((mod) => mod.listing.id), @@ -72,15 +68,10 @@ export async function start_game( runtime, }); - // every mod's shared rules first, so server scripts can count on any mod's being there - await runtime.load_shared_scripts( - game, - mods.flatMap((mod) => mod.shared_url ? [{ ...script_of(mod), url: mod.shared_url }] : []), - ); - await runtime.load_scripts( - game, - mods.flatMap((mod) => mod.server_url ? [{ ...script_of(mod), url: mod.server_url }] : []), - ); + const scripts = mods.flatMap((mod) => mod.url ? [{ ...script_of(mod), url: mod.url }] : []); + // every mod's shared rules first, so server phases can count on any mod's being there + await runtime.load_shared_scripts(game, scripts); + await runtime.load_scripts(game, scripts); runtime.finish_setup(); game.find_ticking_tiles(); // what a worldgen worker needs to generate the same chunks, see worldgen_pool.ts @@ -91,7 +82,7 @@ export async function start_game( mods.map((mod) => ({ id: mod.listing.id, data: mod.data, - worldgen_url: mod.worldgen_url, + url: mod.url, engine_access: mod.listing.engine_access, })), ); diff --git a/server/game/mod_runtime.ts b/server/game/mod_runtime.ts index ea75075..f1cffe9 100644 --- a/server/game/mod_runtime.ts +++ b/server/game/mod_runtime.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// runs mods' server scripts: builds each one's ServerContext and keeps what they register. +// runs mods' server phases: builds each one's ServerContext and keeps what they register. // see docs/modding/. parts not built yet throw when used, saying so import { BlockRegistry, EverythingRegistry, fluid_height, ItemRegistry } from "@/common/everything_registry.ts"; import { Container as EngineContainer, ItemStack as EngineItemStack, max_stack } from "@/common/inventory.ts"; @@ -23,7 +23,6 @@ import { fluid_exists, FluidRules, same_fluid } from "@/common/fluids.ts"; import { interact, item_handler, tank_handler, transfer, use_container } from "./fluid_handlers.ts"; import type { SharedContext } from "@/common/mod_api/shared.ts"; import { tag_api } from "@/common/tags.ts"; -import { loading_mod } from "@/common/hooks.ts"; import type { BlockComponent, BlockRef, @@ -52,7 +51,14 @@ import type { ServerContext, SlotOptions, } from "@/common/mod_api/server.ts"; -import { check_recipe_types, ModLoadError, recipe_lookup, shared_recipes_api } from "@/common/mod_loader.ts"; +import { + check_recipe_types, + ModLoadError, + type Phase, + recipe_lookup, + run_phase, + shared_recipes_api, +} from "@/common/mod_loader.ts"; import { argument, block as block_argument, @@ -114,7 +120,6 @@ export class Signal { // the mod whose code is running right now, for apis shared between mods that need to know who called let running_mod = ""; -// a mod's script, imported from url. engine_access lets it import cubi/engine // a component a block lists, with its params from the block's json export interface BlockComponentOf { mod: string; @@ -123,6 +128,7 @@ export interface BlockComponentOf { params: unknown; } +// a mod's script, imported from url. engine_access lets it import cubi/engine interface ScriptSource { mod: string; version: string; @@ -159,13 +165,13 @@ interface Timer { export class ModRuntime { block_components = new Map(); - // what shared scripts registered, see common/block_rules.ts, running on the game's world + // what shared phases registered, see common/block_rules.ts, running on the game's world rules = new BlockRules( run_guarded, (x, y, z) => this.game.world.get_block_id(x, y, z), (x, y, z, from) => this.#neighbor_changed(x, y, z, from), ); - // the fluids' rules from shared scripts, see common/fluids.ts + // the fluids' rules from shared phases, see common/fluids.ts fluid_rules = new FluidRules(run_guarded); item_components = new Map(); effect_components = new Map(); @@ -264,30 +270,45 @@ export class ModRuntime { } game!: GameServer; - // imports each server script and calls its setup, in load order - // shared scripts, the block rules clients run too. their world is the server's + // runs each script's shared phase in load order: the block rules clients run too. their world is the server's async load_shared_scripts(game: GameServer, scripts: ScriptSource[]) { this.game = game; this.#shared_setup = true; try { - for (const { mod, version, url, engine_access, config } of scripts) { - await loading_mod(mod, engine_access, () => this.#load_shared_script(mod, version, url, config)); - } + await this.#run_phase(scripts, "shared", (script) => this.#shared_context(script)); check_recipe_types(game.recipes); } finally { this.#shared_setup = false; } } - // while shared scripts set up, the only time they can register recipes, as on clients + // while shared phases run, the only time they can register recipes, as on clients #shared_setup = false; - async #load_shared_script(mod: string, version: string, url: string, config: Record) { - const module = await import(url); - if (typeof module.setup !== "function") { - throw new ModLoadError(mod, "the shared script doesn't export a setup function"); + // runs each script's server phase in load order + async load_scripts(game: GameServer, scripts: ScriptSource[]) { + this.game = game; + await this.#run_phase(scripts, "server", ({ mod, version, config }) => this.#context(mod, version, config)); + } + + async #run_phase(scripts: ScriptSource[], phase: Phase, context: (script: ScriptSource) => unknown) { + for (const script of scripts) { + running_mod = script.mod; + try { + await run_phase( + { id: script.mod, engine_access: script.engine_access }, + script.url, + phase, + () => context(script), + ); + } finally { + running_mod = ""; + } } + } + + #shared_context({ mod, version, config }: ScriptSource): SharedContext { const { world, blocks } = this.#context(mod, version, config); - const ctx: SharedContext = { + return { mod: { id: mod, version }, side: "server", tags: tag_api(), @@ -322,32 +343,6 @@ export class ModRuntime { }, }, }; - running_mod = mod; - try { - await module.setup(ctx); - } finally { - running_mod = ""; - } - } - - async load_scripts(game: GameServer, scripts: ScriptSource[]) { - this.game = game; - for (const { mod, version, url, engine_access, config } of scripts) { - await loading_mod(mod, engine_access, () => this.#load_script(mod, version, url, config)); - } - } - - async #load_script(mod: string, version: string, url: string, config: Record) { - const module = await import(url); - if (typeof module.setup !== "function") { - throw new ModLoadError(mod, "the server script doesn't export a setup function"); - } - running_mod = mod; - try { - await module.setup(this.#context(mod, version, config)); - } finally { - running_mod = ""; - } } // every effect mods define, from their json. they're made before scripts run, since the world loads first and diff --git a/server/game/worker.ts b/server/game/worker.ts index 64edd77..3570154 100644 --- a/server/game/worker.ts +++ b/server/game/worker.ts @@ -120,9 +120,7 @@ async function init(message: Extract) { listing: mod.listing, data: mod.data, // the worker has no file access, so the host sends the code and it's imported from memory - server_url: mod.server_code ? data_url(mod.server_code) : undefined, - worldgen_url: mod.worldgen_code ? data_url(mod.worldgen_code) : undefined, - shared_url: mod.shared_code ? data_url(mod.shared_code) : undefined, + url: mod.code ? data_url(mod.code) : undefined, })), ); } catch (e) { diff --git a/server/game/worldgen_worker.ts b/server/game/worldgen_worker.ts index 738da56..33f85c8 100644 --- a/server/game/worldgen_worker.ts +++ b/server/game/worldgen_worker.ts @@ -19,7 +19,7 @@ self.onmessage = (event: MessageEvent<{ port: MessagePort }>) => { port.onmessage = async (event: MessageEvent) => { const message = event.data; if (message.type === "init") { - // worldgen scripts with engine access hook engine.common here, in this worker's own copy of the engine + // worldgen phases with engine access hook engine.common here, in this worker's own copy of the engine expose_engine({ common: common_engine() }); loaded = load_bundle(message.bundle); try { diff --git a/server/host.ts b/server/host.ts index adf664b..b757f82 100644 --- a/server/host.ts +++ b/server/host.ts @@ -151,9 +151,7 @@ export async function start_host(options: HostOptions): Promise { mods: mods.map(({ listing, mod }) => ({ listing, data: mod.data, - server_code: mod.scripts.server, - worldgen_code: mod.scripts.worldgen, - shared_code: mod.scripts.shared, + code: mod.script, })), worldgen_ports: worldgen.ports, } satisfies HostToGame, diff --git a/server/load_mods.ts b/server/load_mods.ts index 67a5f69..c72cc94 100644 --- a/server/load_mods.ts +++ b/server/load_mods.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later // the server's mods: every .cubi in server_mods/, checked, with the server's changes to their config, sorted so -// dependencies load first, and with the copy players download (the same mod without its server script) ready to serve +// dependencies load first, and with the copy players download (the same mod without its server phase) ready to serve import { join } from "@std/path"; import { client_copy, type Mod, MOD_EXTENSION, read_mod, write_mod } from "@/common/mod.ts"; import { check_references, load_order, type LoadedMod } from "@/common/mod_check.ts"; @@ -104,16 +104,17 @@ export async function load_mods( })); } -// runs the mods' content scripts in a worker without permissions and adds the blocks they register to their data, -// after their files' ones. from then on they're the mod's data like the rest: checked, in the copy players download, -// and in the worldgen bundle +// runs the content phase of the mods' scripts in a worker without permissions and adds the blocks they register to +// their data, after their files' ones. from then on they're the mod's data like the rest: checked, in the copy players +// download, and in the worldgen bundle async function add_registered_content(mods: { file: string; mod: Mod }[], problems: string[]) { - const with_scripts = mods.filter(({ mod }) => mod.scripts.content !== undefined); + const with_scripts = mods.filter(({ mod }) => mod.script !== undefined); if (with_scripts.length === 0) return; const scripts: ContentScriptCode[] = with_scripts.map(({ mod }) => ({ mod: mod.manifest.id, version: mod.manifest.version, - code: mod.scripts.content!, + engine_access: mod.manifest.engine_access, + code: mod.script!, })); const worker = new Worker(new URL("./content_worker.ts", import.meta.url), { type: "module", @@ -125,7 +126,7 @@ async function add_registered_content(mods: { file: string; mod: Mod }[], proble worker.onmessage = (event) => resolve(event.data); worker.onerror = (event) => { event.preventDefault(); - reject(new Error(`content scripts: ${event.message}`)); + reject(new Error(`content phases: ${event.message}`)); }; worker.postMessage(scripts); }); @@ -134,7 +135,7 @@ async function add_registered_content(mods: { file: string; mod: Mod }[], proble } with_scripts.forEach(({ file, mod }, i) => { mod.data.blocks.push(...results[i].blocks); - problems.push(...results[i].problems.map((problem) => `${file}: ${mod.manifest.scripts!.content}: ${problem}`)); + problems.push(...results[i].problems.map((problem) => `${file}: ${mod.manifest.main}: ${problem}`)); }); } diff --git a/server/worldgen_workers.ts b/server/worldgen_workers.ts index ca677bd..d0831de 100644 --- a/server/worldgen_workers.ts +++ b/server/worldgen_workers.ts @@ -27,7 +27,7 @@ export interface WorldgenWorkers { export function start_worldgen_workers( count: number, options: { - // "none" like the game, for the host. tests load worldgen scripts from files, which needs "inherit" + // "none" like the game, for the host. tests load worldgen phases from files, which needs "inherit" permissions: "none" | "inherit"; // a worker crashed and was started again: the game's end of its new channel on_restart(index: number, port: MessagePort): void; diff --git a/templates/mod/README.md b/templates/mod/README.md index 710381b..b1fd4ed 100644 --- a/templates/mod/README.md +++ b/templates/mod/README.md @@ -4,20 +4,18 @@ A bworld mod. `MODS.md` at the root of the bworld repo links to the modding docs ## Files -| Path | What it's for | -| --------------------- | ------------------------------------------------------------------------------------ | -| `manifest.json` | The mod's id, name, version, dependencies and scripts. | -| `blocks/*.json` | One block per file. Blocks get an item form with the same id unless `"item": false`. | -| `items/*.json` | Items that aren't a block's item form. | -| `recipes/*.json` | `shaped` crafting, `furnace` smelting and `fuel`. | -| `textures/*.png` | 16×16 textures, named `example_mod:`. | -| `worldgen/ores.json` | Ores to generate (optional, not included here). | -| `scripts/server.ts` | Game logic: block components, commands, events. Never sent to players. | -| `scripts/client.ts` | Sent to players: menu screens, screens, HUD, keybinds. | -| `scripts/worldgen.ts` | Terrain features. Runs on the server and every client and must be deterministic. | -| `CREDITS.md` | Licenses and thanks, shown on the About page. | +| Path | What it's for | +| -------------------- | ----------------------------------------------------------------------------------------------------------- | +| `manifest.json` | The mod's id, name, version, dependencies and script. | +| `blocks/*.json` | One block per file. Blocks get an item form with the same id unless `"item": false`. | +| `items/*.json` | Items that aren't a block's item form. | +| `recipes/*.json` | `shaped` crafting, `furnace` smelting and `fuel`. | +| `textures/*.png` | 16×16 textures, named `example_mod:`. | +| `worldgen/ores.json` | Ores to generate (optional, not included here). | +| `scripts/main.ts` | Its exports are phases: `server` for game logic, `client` for screens and the HUD, `worldgen` for features. | +| `CREDITS.md` | Licenses and thanks, shown on the About page. | -Delete what you don't use, including its entry in `manifest.json`. +Delete what you don't use. A phase you don't need is an export you leave out. ## Checking it diff --git a/templates/mod/manifest.json b/templates/mod/manifest.json index 43ea384..1ed9cfa 100644 --- a/templates/mod/manifest.json +++ b/templates/mod/manifest.json @@ -9,10 +9,6 @@ "dependencies": [ { "id": "bworld", "version": ">=0.1.0" } ], - "scripts": { - "server": "scripts/server.ts", - "client": "scripts/client.ts", - "worldgen": "scripts/worldgen.ts" - }, + "main": "scripts/main.ts", "credits": "CREDITS.md" } diff --git a/templates/mod/scripts/client.ts b/templates/mod/scripts/client.ts deleted file mode 100644 index 6b0c6f8..0000000 --- a/templates/mod/scripts/client.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ClientContext } from "cubi/client"; - -// called on every player's client after the mod is downloaded, before the world shows up. -// everything here is visible to players, so keep secrets and game rules in server.ts -export function setup(ctx: ClientContext) { - ctx.log("loaded"); - - // a HUD element, drawn every frame - // ctx.hud.register("example_mod:hint", { - // on_render(g) { - // g.text("example mod is here", 8, 8); - // }, - // }); -} diff --git a/templates/mod/scripts/main.ts b/templates/mod/scripts/main.ts new file mode 100644 index 0000000..a548603 --- /dev/null +++ b/templates/mod/scripts/main.ts @@ -0,0 +1,65 @@ +import type { ClientContext } from "cubi/client"; +import type { ServerContext } from "cubi/server"; +import type { WorldgenContext } from "cubi/worldgen"; + +// the mod's script. each export is a phase, called where and when it runs. this file goes to the server and to every +// player, and each runs only its own phases, so keep the top level free of anything only one side has + +// called once when the server starts. players never run it, so game rules belong here +export function server(ctx: ServerContext) { + // used by blocks/example_block.json, which passes { message } as params + ctx.components.register_block<{ message: string }>("example_mod:announce", { + // block data is saved with the world. on_tick and on_second only run for blocks that have some + on_create(block) { + block.data = { age: 0 }; + }, + // on_tick runs 20 times a second, on_second once, while a player is nearby + on_second(block) { + block.data.age += 1; + }, + on_interact(block, params, player) { + player.send_message(`${params.message} It's been here for ${block.data?.age ?? 0} seconds.`); + // handled, so right clicking it doesn't place a block + return true; + }, + }); + + // /example_mod:hello, or /hello when no other mod uses that name + ctx.commands.register("hello", { + description: "Say hello", + usage: "/hello", + run(_args, player) { + player.send_message(`Hello ${player.name}!`); + }, + }); + + ctx.events.after.player_join.subscribe(({ player }) => { + ctx.log(`${player.name} joined`); + }); +} + +// called on every player's client after the mod is downloaded, before the world shows up +export function client(ctx: ClientContext) { + ctx.log("loaded"); + + // a HUD element, drawn every frame + // ctx.hud.register("example_mod:hint", { + // on_render(g) { + // g.text("example mod is here", 8, 8); + // }, + // }); +} + +// runs wherever the server generates chunks, which must always give the same world. only use chunk.rng and the noise +// helpers, never Math.random or the time +export function worldgen(gen: WorldgenContext) { + // a boulder on one chunk in ten + gen.register_feature("example_mod:boulders", (chunk) => { + if (chunk.rng.next() > 0.1) { + return; + } + const x = chunk.x * 16 + Math.floor(chunk.rng.next() * 16); + const z = chunk.z * 16 + Math.floor(chunk.rng.next() * 16); + chunk.set_block(x, chunk.height_at(x, z) + 1, z, "bworld:stone"); + }); +} diff --git a/templates/mod/scripts/server.ts b/templates/mod/scripts/server.ts deleted file mode 100644 index 6842211..0000000 --- a/templates/mod/scripts/server.ts +++ /dev/null @@ -1,34 +0,0 @@ -import type { ServerContext } from "cubi/server"; - -// called once when the server starts -export function setup(ctx: ServerContext) { - // used by blocks/example_block.json, which passes { message } as params - ctx.components.register_block<{ message: string }>("example_mod:announce", { - // block data is saved with the world. on_tick and on_second only run for blocks that have some - on_create(block) { - block.data = { age: 0 }; - }, - // on_tick runs 20 times a second, on_second once, while a player is nearby - on_second(block) { - block.data.age += 1; - }, - on_interact(block, params, player) { - player.send_message(`${params.message} It's been here for ${block.data?.age ?? 0} seconds.`); - // handled, so right clicking it doesn't place a block - return true; - }, - }); - - // /example_mod:hello, or /hello when no other mod uses that name - ctx.commands.register("hello", { - description: "Say hello", - usage: "/hello", - run(_args, player) { - player.send_message(`Hello ${player.name}!`); - }, - }); - - ctx.events.after.player_join.subscribe(({ player }) => { - ctx.log(`${player.name} joined`); - }); -} diff --git a/templates/mod/scripts/worldgen.ts b/templates/mod/scripts/worldgen.ts deleted file mode 100644 index 1255fd6..0000000 --- a/templates/mod/scripts/worldgen.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { WorldgenContext } from "cubi/worldgen"; - -// runs in chunk workers on the server and every client, which must all generate the same world. -// only use chunk.rng and the noise helpers, never Math.random or the time -export function setup(gen: WorldgenContext) { - // a boulder on one chunk in ten - gen.register_feature("example_mod:boulders", (chunk) => { - if (chunk.rng.next() > 0.1) { - return; - } - const x = chunk.x * 16 + Math.floor(chunk.rng.next() * 16); - const z = chunk.z * 16 + Math.floor(chunk.rng.next() * 16); - chunk.set_block(x, chunk.height_at(x, z) + 1, z, "bworld:stone"); - }); -} diff --git a/tests/content_script_test.ts b/tests/content_script_test.ts index 81f0f35..cc61c2b 100644 --- a/tests/content_script_test.ts +++ b/tests/content_script_test.ts @@ -1,8 +1,8 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// blocks a content script registers in code are the mod's data like its files': checked, registered on the server, -// sent to players and generated by worldgen workers. see common/mod_api/content.ts +// blocks a script's content phase registers in code are the mod's data like its files': checked, registered on the +// server, sent to players and generated by worldgen workers. see common/mod_api/content.ts import { assert, assertEquals, assertRejects, assertStringIncludes, assertThrows } from "@std/assert"; import { EverythingRegistry } from "@/common/everything_registry.ts"; import { ID_MASK } from "@/common/constants.ts"; @@ -19,7 +19,7 @@ import { copy_dir, GROUND_BLOCKS, test_game } from "./helpers.ts"; // a block for every rock and its bricks, and one more where the script can't read files, like the server's worker const CONTENT = ` import type { ContentContext } from "cubi/content"; - export function setup(ctx: ContentContext) { + export function content(ctx: ContentContext) { for (const rock of ["granite", "basalt"]) { ctx.blocks.register({ id: \`rocks:\${rock}\`, textures: "cubi:missing", drops: \`rocks:\${rock}\` }); ctx.blocks.register({ id: \`rocks:\${rock}_bricks\`, textures: "cubi:missing" }); @@ -36,7 +36,7 @@ const CONTENT = ` const CODE_BLOCKS = ["rocks:granite", "rocks:granite_bricks", "rocks:basalt", "rocks:basalt_bricks"]; -// the base game, and rocks: a block file, the content script above, and a tag and an ore that name its blocks +// the base game, and rocks: a block file, the content phase above, and a tag and an ore that name its blocks function rocks_mod(extra = "") { const dir = Deno.makeTempDirSync({ prefix: "bworld_content_" }); copy_dir("mods/bworld", `${dir}/bworld`); @@ -50,7 +50,7 @@ function rocks_mod(extra = "") { name: "Rocks", version: "1.0.0", dependencies: [{ id: "bworld", version: "*" }], - scripts: { content: "scripts/content.ts" }, + main: "scripts/content.ts", }); write("blocks/lamp.json", { format_version: 1, block: { id: "rocks:lamp", textures: "cubi:missing" } }); write("scripts/content.ts", CONTENT.replace("EXTRA", extra)); @@ -62,7 +62,7 @@ function rocks_mod(extra = "") { return dir; } -Deno.test("check-mods runs a mod's content script, and its files can name the blocks it registers", async () => { +Deno.test("check-mods runs a mod's content phase, and its files can name the blocks it registers", async () => { const dir = rocks_mod(); const rocks = (await load_and_check(dir)).find((mod) => mod.id === "rocks")!; Deno.removeSync(dir, { recursive: true }); @@ -80,7 +80,7 @@ Deno.test("check-mods runs a mod's content script, and its files can name the bl ); }); -Deno.test("the server registers a content script's blocks, and a worldgen worker numbers and generates them alike", async () => { +Deno.test("the server registers a mod's content phase's blocks, and a worldgen worker numbers and generates them alike", async () => { const dir = rocks_mod(); const { game } = await test_game(dir); Deno.removeSync(dir, { recursive: true }); @@ -99,7 +99,7 @@ Deno.test("the server registers a content script's blocks, and a worldgen worker assert(generated.some((value) => (value & ID_MASK) === basalt), "the ore of a block made in code is generated"); }); -Deno.test("a packed mod leaves its content script's blocks out, the server registers them without permissions, and players get them as data", async () => { +Deno.test("a packed mod leaves its content phase's blocks out, the server registers them without permissions, and players get them as data", async () => { const sources = rocks_mod(); const folder = Deno.makeTempDirSync({ prefix: "bworld_content_mods_" }); for (const mod of await load_and_check(sources)) { @@ -108,7 +108,7 @@ Deno.test("a packed mod leaves its content script's blocks out, the server regis Deno.removeSync(sources, { recursive: true }); const packed = read_mod(Deno.readFileSync(`${folder}/rocks.cubi`), "rocks.cubi"); assertEquals(packed.data.blocks.map((block) => block.id), ["rocks:lamp"]); - assert(packed.scripts.content); + assert(packed.script); const rocks = (await load_mods(folder, ["cubi:missing"])).find((mod) => mod.listing.id === "rocks")!; Deno.removeSync(folder, { recursive: true }); @@ -117,14 +117,14 @@ Deno.test("a packed mod leaves its content script's blocks out, the server regis assertEquals(rocks.mod.data.blocks.map((block) => block.id), ids); const copy = read_mod(rocks.client_bytes, rocks.listing.file); - assertEquals(copy.scripts.content, undefined, "players don't run it, they get what it registered"); + // players get the script too, but never run its content phase: they get what it registered as data assertEquals(copy.data.blocks, client_copy(rocks.mod).data.blocks); EverythingRegistry.clear(); await load_client_mods([rocks.listing], [copy]); for (const id of ids) assert(EverythingRegistry.get("blocks", id), `${id} is a block on the client`); }); -Deno.test("a content script's mistakes stop its mod loading, naming the script", async () => { +Deno.test("a content phase's mistakes stop its mod loading, naming the script", async () => { const cases: [string, string][] = [ [ `ctx.blocks.register({ id: "bworld:granite", textures: "cubi:missing" });`, @@ -155,6 +155,6 @@ Deno.test("a content script's mistakes stop its mod loading, naming the script", Deno.removeSync(folder, { recursive: true }); assertStringIncludes( (rejected as Error).message, - `rocks.cubi: scripts/content.js: block bworld:granite isn't in this mod's namespace "rocks"`, + `rocks.cubi: script.js: block bworld:granite isn't in this mod's namespace "rocks"`, ); }); diff --git a/tests/create/helpers.ts b/tests/create/helpers.ts index bfc617b..d2ce17a 100644 --- a/tests/create/helpers.ts +++ b/tests/create/helpers.ts @@ -6,7 +6,7 @@ import { AIR_ID } from "@/common/protocol.ts"; import { get_state_value, set_state_value } from "@/common/utils.ts"; import type { Face } from "@/common/mod_api/shared.ts"; import type { ClientContext, Instances, ModelRef, Visual, VisualBlock } from "@/common/mod_api/client.ts"; -import { setup as setup_client } from "@/mods/create/scripts/client.ts"; +import { client as setup_client } from "@/mods/create/scripts/client.ts"; import { stone_floor, test_game } from "../helpers.ts"; // facing and axis states, in the order the importer numbers them @@ -49,7 +49,7 @@ export async function setup(config: Record = {}) { return { ...t, move, place, speed, overstressed, state, use, ticks, crank }; } -// create's client script with only what its visuals need, and a block for one to draw that records what its instances +// create's client phase with only what its visuals need, and a block for one to draw that records what its instances // do, by model ("own" for the block's own model): how rotating ones turn, and where transformed ones are moved. and the // items and fluid boxes it draws now, by item and fluid id export async function visual_for( diff --git a/tests/engine_access_test.ts b/tests/engine_access_test.ts index 7507ccb..dd39ecc 100644 --- a/tests/engine_access_test.ts +++ b/tests/engine_access_test.ts @@ -22,22 +22,18 @@ import { game_with_pool } from "./chunk_loading.ts"; const [MAJOR, MINOR] = GAME_VERSION.split("."); const THIS_MINOR = `~${MAJOR}.${MINOR}.0`; -// a mod in dir with these scripts, as { side: [file, code] } +// a mod in dir whose script is code function write_mod( dir: string, id: string, - scripts: Record, + code: string, manifest: Record = { engine_access: true, game_version: THIS_MINOR }, ) { Deno.mkdirSync(`${dir}/${id}/scripts`, { recursive: true }); - const paths: Record = {}; - for (const [side, [file, code]] of Object.entries(scripts)) { - Deno.writeTextFileSync(`${dir}/${id}/scripts/${file}`, code); - paths[side] = `scripts/${file}`; - } + Deno.writeTextFileSync(`${dir}/${id}/scripts/main.ts`, code); Deno.writeTextFileSync( `${dir}/${id}/manifest.json`, - JSON.stringify({ format_version: 1, id, name: id, version: "1.0.0", scripts: paths, ...manifest }), + JSON.stringify({ format_version: 1, id, name: id, version: "1.0.0", main: "scripts/main.ts", ...manifest }), ); } @@ -80,11 +76,11 @@ async function errors_during(fn: () => unknown): Promise { Deno.test("a server mod hooks GameServer to drop twice, like the plan's example", async () => { const dir = mods_dir((dir) => - write_mod(dir, "double_drops", { - server: [ - "server.ts", - `import { engine, hook } from "cubi/engine"; - export function setup() { + write_mod( + dir, + "double_drops", + `import { engine, hook } from "cubi/engine"; + 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()); @@ -92,8 +88,7 @@ Deno.test("a server mod hooks GameServer to drop twice, like the plan's example" }, }); }`, - ], - }) + ) ); const { game } = await test_game(dir); const items = () => game.entities.entities_near(0.5, 100, 0.5, 4).length; @@ -105,16 +100,15 @@ Deno.test("a server mod hooks GameServer to drop twice, like the plan's example" Deno.test("a worldgen mod hooks the terrain in engine.common", async () => { const dir = mods_dir((dir) => - write_mod(dir, "flat_sea", { - worldgen: [ - "worldgen.ts", - `import { engine, hook } from "cubi/engine"; + write_mod( + dir, + "flat_sea", + `import { engine, hook } from "cubi/engine"; // no ground anywhere, so it's all sea - export function setup() { + export function worldgen() { hook(engine.common.NoiseTerrain.prototype, "density", { replace: () => -1 }); }`, - ], - }) + ) ); const { game } = await test_game(dir, undefined, "engine-access-flat-sea"); assertEquals(game.world.get_block_id(8, 10, 8), "bworld:water"); @@ -126,20 +120,19 @@ Deno.test("a worldgen mod hooks the terrain in engine.common", async () => { }); Deno.test({ - name: "a worldgen mod's hook reaches the worldgen workers too, since each loads the worldgen scripts", + name: "a worldgen mod's hook reaches the worldgen workers too, since each runs the worldgen phase", sanitizeOps: false, sanitizeResources: false, fn: async () => { const dir = mods_dir((dir) => - write_mod(dir, "flat_sea", { - worldgen: [ - "worldgen.ts", - `import { engine, hook } from "cubi/engine"; - export function setup() { + write_mod( + dir, + "flat_sea", + `import { engine, hook } from "cubi/engine"; + export function worldgen() { hook(engine.common.NoiseTerrain.prototype, "density", { replace: () => -1 }); }`, - ], - }) + ) ); // it's all sea, so no spawn search const t = await game_with_pool(1, "engine-access-flat-sea-pool", dir, false); @@ -159,20 +152,19 @@ Deno.test({ Deno.test("a client mod hooks LocalPlayer from its .cubi", async () => { const dir = Deno.makeTempDirSync({ prefix: "bworld_engine_" }); - write_mod(dir, "floaty", { - client: [ - "client.ts", - `import { engine, hook } from "cubi/engine"; + write_mod( + dir, + "floaty", + `import { engine, hook } from "cubi/engine"; // everyone is a block higher than they think - export function setup() { + export function client() { hook(engine.client.LocalPlayer.prototype, "set_position", { before(_player, args) { args[1] += 1; }, }); }`, - ], - }); + ); const mod = (await load_and_check(dir))[0]; assertEquals(mod.report.errors, []); const packed = read_mod(await pack_mod(mod), "floaty.cubi"); @@ -340,18 +332,18 @@ Deno.test("hook needs a loading mod with engine access", async () => { Deno.test("cubi/engine without engine_access is an error in check-mods and in a .cubi", async () => { const dir = Deno.makeTempDirSync({ prefix: "bworld_engine_" }); const script = `import { engine } from "cubi/engine"; - export function setup() { + export function server() { console.log(engine.common.physics); }`; - write_mod(dir, "sneaky", { server: ["server.ts", script] }, {}); + write_mod(dir, "sneaky", script, {}); const [mod] = await load_and_check(dir); assertEquals(mod.report.errors, [ - `scripts/server.ts imports cubi/engine, which needs "engine_access": true in manifest.json`, + `scripts/main.ts imports cubi/engine, which needs "engine_access": true in manifest.json`, ]); // packed anyway, the bundle gives it away const bytes = await pack_mod(mod); - assertThrows(() => read_mod(bytes, "sneaky.cubi"), Error, "a script uses cubi/engine"); + assertThrows(() => read_mod(bytes, "sneaky.cubi"), Error, "its script uses cubi/engine"); Deno.removeSync(dir, { recursive: true }); }); diff --git a/tests/features_test.ts b/tests/features_test.ts index 0a61f1e..40c1583 100644 --- a/tests/features_test.ts +++ b/tests/features_test.ts @@ -11,7 +11,7 @@ import { copy_dir, test_game } from "./helpers.ts"; const SCRIPT = ` import type { WorldgenContext } from "cubi/worldgen"; -export function setup(gen: WorldgenContext) { +export function worldgen(gen: WorldgenContext) { // a type for data features: a pillar of a block gen.register_feature_type<{ block: string; height: number }>("testmod:pillar", (chunk, config, origin) => { for (let i = 0; i < config.height; i++) chunk.set_block(origin.x, origin.y + i, origin.z, config.block); @@ -50,7 +50,7 @@ function with_mod(files: Record, script = SCRIPT) { name: "Test", version: "1.0.0", dependencies: [{ id: "bworld", version: "*" }], - scripts: { worldgen: "scripts/worldgen.ts" }, + main: "scripts/worldgen.ts", }), ); write("scripts/worldgen.ts", script); @@ -135,7 +135,7 @@ Deno.test("a data feature whose type no script registers stops the server", asyn await assertRejects( () => test_game(dir), Error, - "type testmod:nothing isn't built in, and no worldgen script registered it", + "type testmod:nothing isn't built in, and no mod's worldgen phase registered it", ); } finally { Deno.removeSync(dir, { recursive: true }); @@ -146,7 +146,7 @@ Deno.test("a feature can't be both code and data", async () => { const clash = with_mod( { "worldgen/features/glass_pillar.json": GLASS_PILLAR }, `import type { WorldgenContext } from "cubi/worldgen"; - export function setup(gen: WorldgenContext) { + export function worldgen(gen: WorldgenContext) { gen.register_feature("testmod:glass_pillar", () => {}); }`, ); diff --git a/tests/fluid_handler_test.ts b/tests/fluid_handler_test.ts index f4b94a5..aff03f7 100644 --- a/tests/fluid_handler_test.ts +++ b/tests/fluid_handler_test.ts @@ -14,7 +14,7 @@ const JAR = "testmod:jar"; const SERVER_SCRIPT = ` import type { FluidStack, ServerContext } from "cubi/server"; -export function setup(ctx: ServerContext) { +export function server(ctx: ServerContext) { // two tanks kept in its data, reached from every side but the bottom ctx.components.register_block("testmod:tank", { fluid_handler(block, _params, face) { @@ -48,7 +48,7 @@ async function setup() { name: "Test", version: "1.0.0", dependencies: [{ id: "bworld", version: "*" }], - scripts: { server: "scripts/server.ts" }, + main: "scripts/server.ts", }); write("fluids/syrup.json", { format_version: 1, fluid: { id: SYRUP.id, color: "#a0522d" } }); write("fluids/honey.json", { format_version: 1, fluid: { id: HONEY.id, color: "#e0a030" } }); diff --git a/tests/fluid_registry_test.ts b/tests/fluid_registry_test.ts index fbd81c4..9ac94ed 100644 --- a/tests/fluid_registry_test.ts +++ b/tests/fluid_registry_test.ts @@ -14,7 +14,7 @@ import { load_and_check } from "@/tools/check_mods.ts"; import { pack_mod } from "@/tools/pack_mod.ts"; import { copy_dir, test_game } from "./helpers.ts"; -// testfluids: a manifest, the given fluids/ files by file name, and maybe a shared script and an item for it to read +// testfluids: a manifest, the given fluids/ files by file name, and maybe a shared phase and an item for it to read function fluid_mod(dir: string, fluids: Record, shared_script?: string) { const mod = `${dir}/testfluids`; const write = (path: string, json: unknown) => { @@ -26,7 +26,7 @@ function fluid_mod(dir: string, fluids: Record, shared_script?: id: "testfluids", name: "Test Fluids", version: "1.0.0", - ...(shared_script && { scripts: { shared: "scripts/shared.ts" } }), + ...(shared_script && { main: "scripts/shared.ts" }), }); for (const [file, fluid] of Object.entries(fluids)) write(`fluids/${file}`, { format_version: 1, fluid }); if (shared_script) { @@ -66,7 +66,7 @@ Deno.test("a fluid with a bad color fails loading", async () => { // syrup is named after the tree in its data and has the color its data says, sap has no rules const RULES = ` import type { SharedContext } from "cubi/shared"; - export function setup(ctx: SharedContext) { + export function shared(ctx: SharedContext) { ctx.fluids.register("testfluids:syrup", { name: (data: any) => data?.tree && ctx.items.name(data.tree) + " Syrup", color: (data: any) => data?.color, diff --git a/tests/helpers.ts b/tests/helpers.ts index 64a0d4e..a24108f 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -31,7 +31,7 @@ import { collision_shape_at, covers_face, is_solid } from "@/common/block_shapes import { tag_api } from "@/common/tags.ts"; import { get_state_value, set_state_value, shared_items_api } from "@/common/utils.ts"; import type { Face, SharedWorld } from "@/common/mod_api/shared.ts"; -import { setup as setup_shared } from "@/mods/bworld/scripts/shared.ts"; +import { shared as setup_shared } from "@/mods/bworld/scripts/shared.ts"; // the repo's own mods/, read once: reading and checking every mod's files is most of starting a game in a test. only // mods/ is kept, since tests change the temporary folders they make between games @@ -50,8 +50,7 @@ async function read_mod_sources(mods_dir: string): Promise { const errors = mods.flatMap((mod) => mod.report.errors.map((e) => `${mod.id}: ${e}`)); if (errors.length) throw new Error(errors.join("\n")); return load_order(mods).map((mod) => { - const scripts = (mod.manifest?.scripts ?? {}) as Record; - const url = (path?: string) => path ? toFileUrl(resolve(mod.dir, path)).href : undefined; + const main = mod.manifest?.main as string | undefined; return { listing: { id: mod.id, @@ -63,9 +62,7 @@ async function read_mod_sources(mods_dir: string): Promise { ...(mod.manifest?.engine_access === true ? { engine_access: true } : {}), }, data: mod_data(mod), - server_url: url(scripts.server), - worldgen_url: url(scripts.worldgen), - shared_url: url(scripts.shared), + url: main ? toFileUrl(resolve(mod.dir, main)).href : undefined, }; }); } @@ -284,7 +281,7 @@ export const GROUND_BLOCKS = "#bworld:raw_rocks"; export const ENGINE_TEXTURES = ["cubi:missing", ...Array.from({ length: 9 }, (_, i) => `cubi:break_${i}`)]; // registers a folder of mod sources the way a player gets them: packed, loaded by a server, which adds the blocks -// content scripts register, and the copies it serves loaded on the client +// content phases register, and the copies it serves loaded on the client export async function load_as_player(sources: string) { const folder = Deno.makeTempDirSync({ prefix: "bworld_player_mods_" }); try { @@ -369,7 +366,7 @@ export function server_blocks(game: GameServer, area: Area) { return blocks_in(area, (x, y, z) => [game.world.get_block_id(x, y, z), game.world.get_block_value(x, y, z) >>> 16]); } -// a client: its copy of the area, and the bworld shared script's rules running on it the way client/mods.ts does +// a client: its copy of the area, and the bworld shared phase's rules running on it the way client/mods.ts does export function client_of(game: GameServer, area: Area) { const copy = new Map(); for (const line of server_blocks(game, area)) { diff --git a/tests/hud_test.ts b/tests/hud_test.ts index 24d0337..8225b9a 100644 --- a/tests/hud_test.ts +++ b/tests/hud_test.ts @@ -22,7 +22,7 @@ async function load(script: string) { id: "testmod", name: "Test", version: "1.0.0", - scripts: { client: "scripts/client.ts" }, + main: "scripts/client.ts", }), ); Deno.writeTextFileSync(`${dir}/testmod/scripts/client.ts`, script); @@ -39,7 +39,7 @@ async function load(script: string) { Deno.test("hud layers draw in order on the same space, and one that throws is removed", async () => { await load(` import type { ClientContext } from "cubi/client"; - export function setup(ctx: ClientContext) { + export function client(ctx: ClientContext) { ctx.hud.register("testmod:bar", { on_render(_g, hud) { hud.left_height += 10; } }); ctx.hud.register("testmod:broken", { on_render() { throw new Error("broken"); } }); const above = { @@ -75,13 +75,13 @@ Deno.test("hud layers draw in order on the same space, and one that throws is re Deno.test("hud layers are in the mod's namespace, one to an id", async () => { const layer = `{ on_render() {} }`; await assertRejects( - () => load(`export function setup(ctx) { ctx.hud.register("bworld:hotbar", ${layer}); }`), + () => load(`export function client(ctx) { ctx.hud.register("bworld:hotbar", ${layer}); }`), Error, `must be in the namespace "testmod"`, ); await assertRejects( () => - load(`export function setup(ctx) { + load(`export function client(ctx) { ctx.hud.register("testmod:bar", ${layer}); ctx.hud.register("testmod:bar", ${layer}); }`), diff --git a/tests/juice_test.ts b/tests/juice_test.ts index e0050fd..6e11215 100644 --- a/tests/juice_test.ts +++ b/tests/juice_test.ts @@ -12,7 +12,7 @@ import { sell_value } from "@/common/inventory.ts"; import { block_visuals, Visuals } from "@/client/rendering/visuals.ts"; import { AssetManager } from "@/client/assets.ts"; import { fluid_rules, set_fluid_rules } from "@/client/fluid_rules.ts"; -import { setup as setup_client } from "@/mods/bworld/scripts/client.ts"; +import { client as setup_client } from "@/mods/bworld/scripts/client.ts"; import { JUICE_VALUE, type JuiceableParams, WINE_VALUE } from "@/mods/bworld/scripts/shared.ts"; import type { FermentableRecipe } from "@/mods/bworld/scripts/fermenting.ts"; import { copy_dir, stone_floor, test_game } from "./helpers.ts"; @@ -277,14 +277,14 @@ Deno.test("a broken bworld:fermentable recipe stops the server from starting", a } }); -// a juicer at 1 100 1 drawn by bworld's client script, and a way to set a field of its client data. its fluids have the +// a juicer at 1 100 1 drawn by bworld's client phase, and a way to set a field of its client data. its fluids have the // server's rules, the same as a client's async function drawn_juicer() { const { game } = await setup(); AssetManager.instance.assets["cubi:textures_info"] = {}; const client_rules = fluid_rules; set_fluid_rules(game.mods.fluid_rules); - // bworld's client script, with only what it needs for its visuals + // bworld's client phase, with only what it needs for its visuals const made = new Map Visual>(); setup_client({ ui: { register_menu_screen() {}, add_item_tooltip() {} }, diff --git a/tests/loot_test.ts b/tests/loot_test.ts index 5057a56..2357f09 100644 --- a/tests/loot_test.ts +++ b/tests/loot_test.ts @@ -187,7 +187,7 @@ function loot_mod(dir: string) { name: "Test Loot", version: "1.0.0", dependencies: [{ id: "bworld", version: "*" }], - scripts: { server: "scripts/server.ts" }, + main: "scripts/server.ts", }); for (const id of ["gem", "charm"]) { write(`items/${id}.json`, { format_version: 1, item: { id: `testloot:${id}`, texture: `testloot:${id}` } }); @@ -233,7 +233,7 @@ function loot_mod(dir: string) { Deno.writeTextFileSync( `${mod}/scripts/server.ts`, `import type { ServerContext } from "cubi/server"; -export function setup(ctx: ServerContext) { +export function server(ctx: ServerContext) { ctx.loot.register_condition("testloot:high", (_params, context) => (context.position?.y ?? 0) > 120); ctx.loot.register_function("testloot:double", (item) => ({ ...item, count: item.count * 2 })); ctx.loot.modify("testloot:chests/treasure", (items) => { items.push({ id: "testloot:charm", count: 1 }); }); diff --git a/tests/machines_test.ts b/tests/machines_test.ts index b784db5..880f6b2 100644 --- a/tests/machines_test.ts +++ b/tests/machines_test.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// what machines do to the world through server scripts: read which way water flows, find items lying around and +// what machines do to the world through server phases: read which way water flows, find items lying around and // change them, push things, break blocks over time, and use items on blocks like a player would import { assert, assertEquals, assertThrows } from "@std/assert"; import type { ServerContext } from "cubi/server"; @@ -11,7 +11,7 @@ import { copy_dir, stone_floor, test_game } from "./helpers.ts"; // hands the test its context, and has a block that says who right clicked it and an item that gives a stick when used const SERVER_SCRIPT = ` import type { ServerContext } from "cubi/server"; -export function setup(ctx: ServerContext) { +export function server(ctx: ServerContext) { (globalThis as any).machines_ctx = ctx; ctx.components.register_block("testmod:button", { on_interact(block, _params, player) { @@ -39,7 +39,7 @@ async function setup() { name: "Test", version: "1.0.0", dependencies: [{ id: "bworld", version: "*" }], - scripts: { server: "scripts/server.ts" }, + main: "scripts/server.ts", }); write("blocks/button.json", { format_version: 1, diff --git a/tests/mod_config_test.ts b/tests/mod_config_test.ts index 103dd68..532dde7 100644 --- a/tests/mod_config_test.ts +++ b/tests/mod_config_test.ts @@ -32,14 +32,14 @@ Deno.test("changing a mod's config only changes settings it has, to the same kin ]); }); -Deno.test("a server script reads its mod's config, with the changes a test makes", async () => { +Deno.test("a mod's server phase reads its mod's config, with the changes a test makes", async () => { const dir = Deno.makeTempDirSync({ prefix: "bworld_config_" }); copy_dir("mods/bworld", `${dir}/bworld`); create_mod("copper_tools", "Copper Tools", dir); Deno.writeTextFileSync( - `${dir}/copper_tools/scripts/server.ts`, + `${dir}/copper_tools/scripts/main.ts`, `import type { ServerContext } from "cubi/server"; -export function setup(ctx: ServerContext) { +export function server(ctx: ServerContext) { ctx.components.register_block("copper_tools:announce", {}); ctx.commands.register("settings", { description: "Shows the settings", @@ -94,7 +94,6 @@ Deno.test("a server changes a mod's settings with config/.json, and play write_mod({ manifest: { format_version: 1, id: "tiny", name: "Tiny", version: "1.0.0" }, data, - scripts: {}, textures: new Map(), }), ); diff --git a/tests/mod_loading_test.ts b/tests/mod_loading_test.ts index 79bc7a7..1d59fcb 100644 --- a/tests/mod_loading_test.ts +++ b/tests/mod_loading_test.ts @@ -146,12 +146,12 @@ Deno.test("the template's worldgen feature places boulders, the same way every t } assert(boulders >= 1 && boulders <= 8, `${boulders} of 20 chunks got a boulder, expected about 2`); - // loading the script again (like a client does) gives the same terrain + // loading the script again (like a worldgen worker does) gives the same terrain const again = await load_worldgen({ mods: ["bworld", "copper_tools"], scripts: ["bworld", "copper_tools"].map((mod) => ({ mod, - url: new URL(`file://${Deno.realPathSync(dir)}/${mod}/scripts/worldgen.ts`).href, + url: new URL(`file://${Deno.realPathSync(dir)}/${mod}/scripts/main.ts`).href, })), ores: worldgen.ores, generator: "bworld:overworld", @@ -202,11 +202,11 @@ Deno.test("mod ores generate into the block they replace", async () => { Deno.test("mod storage and block data are saved with the world", async () => { const dir = mods_with_template(); - // a server script that uses storage and block data + // a mod's server phase that uses storage and block data Deno.writeTextFileSync( - `${dir}/copper_tools/scripts/server.ts`, + `${dir}/copper_tools/scripts/main.ts`, `import type { ServerContext } from "cubi/server"; -export function setup(ctx: ServerContext) { +export function server(ctx: ServerContext) { ctx.components.register_block("copper_tools:announce", { on_create(block) { block.data = { placed_at: ctx.system.current_tick }; }, on_interact(block, _params, player) { @@ -237,7 +237,7 @@ export function setup(ctx: ServerContext) { Deno.test("broken mods stop the game from starting", async () => { const dir = mods_with_template(); // the block uses a component the script no longer registers - Deno.writeTextFileSync(`${dir}/copper_tools/scripts/server.ts`, "export function setup() {}\n"); + Deno.writeTextFileSync(`${dir}/copper_tools/scripts/main.ts`, "export function server() {}\n"); let error = ""; try { await test_game(dir); diff --git a/tests/mod_test.ts b/tests/mod_test.ts index 32b1e25..59ba276 100644 --- a/tests/mod_test.ts +++ b/tests/mod_test.ts @@ -32,7 +32,7 @@ async function packed_mods() { return { sources, folder, mods }; } -Deno.test("packing a mod keeps its data, scripts, textures and credits, and gives the same bytes every time", async () => { +Deno.test("packing a mod keeps its data, script, textures and credits, and gives the same bytes every time", async () => { const { sources, folder, mods } = await packed_mods(); const template = mods.find((mod) => mod.id === "copper_tools")!; const bytes = Deno.readFileSync(`${folder}/copper_tools.cubi`); @@ -43,13 +43,12 @@ Deno.test("packing a mod keeps its data, scripts, textures and credits, and give assertEquals(mod.data.blocks.map((b) => b.id), template.blocks.map((b) => b.json.id)); assertEquals(mod.data.recipes, template.recipes.map((r) => r.json)); assertEquals([...mod.textures.keys()].sort(), [...template.textures].sort()); - assertEquals(Object.keys(mod.scripts).sort(), ["client", "server", "worldgen"]); - assertStringIncludes(mod.scripts.server!, "setup"); + assertStringIncludes(mod.script!, "function server"); assert(mod.credits); const bworld = read_mod(Deno.readFileSync(`${folder}/bworld.cubi`), "bworld.cubi"); assertEquals(bworld.data.blocks.length, [...Deno.readDirSync("mods/bworld/blocks")].length); - assertEquals(Object.keys(bworld.scripts), ["server", "client", "worldgen", "shared", "content"]); + assert(bworld.script); Deno.removeSync(sources, { recursive: true }); Deno.removeSync(folder, { recursive: true }); @@ -78,13 +77,13 @@ Deno.test("broken .cubi files are turned away, saying why", () => { () => read_mod( zip({ - "manifest.json": text({ ...manifest, scripts: { server: "scripts/server.js" } }), + "manifest.json": text({ ...manifest, main: "script.js" }), "data.json": text({}), }), "d.cubi", ), Error, - "scripts.server scripts/server.js isn't in the file", + "main script.js isn't in the file", ); // a texture bigger than MAX_TEXTURE_SIZE. only its header is read const big = new Uint8Array(24); @@ -109,7 +108,7 @@ Deno.test("broken .cubi files are turned away, saying why", () => { ); }); -Deno.test("the server loads every .cubi in its folder, dependencies first, and players get them without server scripts", async () => { +Deno.test("the server loads every .cubi in its folder, dependencies first, and players get them without the terrain", async () => { const { sources, folder } = await packed_mods(); const mods = await load_mods(folder, ENGINE_TEXTURES); assertEquals(mods.map((mod) => mod.listing.id), ["bworld", "copper_tools"]); @@ -119,9 +118,11 @@ Deno.test("the server loads every .cubi in its folder, dependencies first, and p const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", mod.client_bytes)); assertEquals([...digest].map((b) => b.toString(16).padStart(2, "0")).join(""), mod.listing.sha256); const copy = read_mod(mod.client_bytes, mod.listing.file); - assertEquals(copy.scripts.server, undefined, "server scripts never go to players"); - assertEquals(copy.scripts.worldgen, undefined, "players get the world from the server, not its generator"); - assertEquals(copy.scripts.shared, mod.mod.scripts.shared, "players run the shared rules too"); + assertEquals( + copy.script, + mod.mod.script, + "players get the whole script, and only run its shared and client phases", + ); // the terrain's data stays on the server too, the rest is the same const { noises, density_functions, noise_settings, biome_sources, dimensions, ...data } = mod.mod.data; const none = { noises: [], density_functions: [], noise_settings: [], biome_sources: [], dimensions: [] }; @@ -131,7 +132,6 @@ Deno.test("the server loads every .cubi in its folder, dependencies first, and p assert(terrain.every((list) => list!.length > 0)); } } - assert(mods[1].mod.scripts.server, "the server still has it"); // the same mod twice, and a mod whose dependency isn't there Deno.copyFileSync(`${folder}/copper_tools.cubi`, `${folder}/copper_tools_again.cubi`); @@ -173,7 +173,7 @@ Deno.test("the host serves each mod's player copy by its hash, and a game made f } assertEquals((await host.handle(new Request("http://localhost/mods/nope.cubi"))).status, 404); - // the game worker loaded both mods, including the template's server script, and saves + // the game worker loaded both mods, including the template's server phase, and saves await host.shutdown(); const saved = JSON.parse(Deno.readTextFileSync(`${world}/level.json`)); assertEquals(saved.seed, "mod-seed"); @@ -193,7 +193,7 @@ Deno.test("a mod with its own deno.json is bundled with it", async () => { id: "project", name: "Project", version: "1.0.0", - scripts: { server: "scripts/server.ts" }, + main: "scripts/server.ts", }), ); // only the mod's own import map knows "lib/" @@ -201,13 +201,13 @@ Deno.test("a mod with its own deno.json is bundled with it", async () => { Deno.writeTextFileSync(`${mod}/scripts/lib/greeting.ts`, `export const GREETING = "hello from a deno project";\n`); Deno.writeTextFileSync( `${mod}/scripts/server.ts`, - `import { GREETING } from "lib/greeting.ts";\n// deno-lint-ignore no-explicit-any\nexport function setup(ctx: any) {\n\tctx.log(GREETING);\n}\n`, + `import { GREETING } from "lib/greeting.ts";\n// deno-lint-ignore no-explicit-any\nexport function server(ctx: any) {\n\tctx.log(GREETING);\n}\n`, ); const project = (await load_and_check(sources)).find((m) => m.id === "project")!; assertEquals(project.report.errors, []); const packed = read_mod(await pack_mod(project), "project.cubi"); - assertStringIncludes(packed.scripts.server!, "hello from a deno project"); + assertStringIncludes(packed.script!, "hello from a deno project"); Deno.removeSync(sources, { recursive: true }); }); @@ -438,7 +438,6 @@ Deno.test("a mod with only data packs and reads", () => { fluids: [], tags: [], }, - scripts: {}, textures: new Map(), }; assertEquals(read_mod(write_mod(mod), "tiny.cubi").manifest.id, "tiny"); diff --git a/tests/mod_tools_test.ts b/tests/mod_tools_test.ts index a7b8ac7..b0f511a 100644 --- a/tests/mod_tools_test.ts +++ b/tests/mod_tools_test.ts @@ -128,7 +128,7 @@ Deno.test("check-mods finds broken mods", async () => { new DataView(huge.buffer).setUint32(20, 16); Deno.writeFileSync(`${mod}/textures/huge.png`, huge); // a script that doesn't typecheck - Deno.writeTextFileSync(`${mod}/scripts/client.ts`, "export function setup(ctx: number) { ctx.nope(); }\n"); + Deno.writeTextFileSync(`${mod}/scripts/main.ts`, "export function client(ctx: number) { ctx.nope(); }\n"); // a dependency that isn't installed, and no longer depending on bworld const manifest = JSON.parse(Deno.readTextFileSync(`${mod}/manifest.json`)); manifest.dependencies = [{ id: "missing_mod", version: "1.0.0" }]; @@ -147,7 +147,7 @@ Deno.test("check-mods finds broken mods", async () => { has(report.errors, `elements[0].faces can't have "up"`); has(report.errors, `key needs "B", which pattern uses`); has(report.errors, "textures/huge.png: is"); - has(report.errors, "scripts don't typecheck"); + has(report.errors, "its script doesn't typecheck"); has(report.errors, `depends on "missing_mod", which isn't installed`); has(report.errors, "entity model broken:no_such_worn doesn't exist"); has(report.errors, "worn must be { model, texture }"); diff --git a/tests/neighbor_hooks_test.ts b/tests/neighbor_hooks_test.ts index 6a8762f..8703812 100644 --- a/tests/neighbor_hooks_test.ts +++ b/tests/neighbor_hooks_test.ts @@ -12,7 +12,7 @@ import { copy_dir, stone_floor, test_game } from "./helpers.ts"; const SERVER_SCRIPT = ` import type { ServerContext } from "cubi/server"; -export function setup(ctx: ServerContext) { +export function server(ctx: ServerContext) { const log = (event: unknown[]) => ctx.storage.set("log", [...ctx.storage.get("log") ?? [], event]); const at = ({ x, y, z }: { x: number; y: number; z: number }) => x + " " + y + " " + z; ctx.components.register_block("testmod:watcher", { @@ -57,7 +57,7 @@ export function setup(ctx: ServerContext) { const SHARED_SCRIPT = ` import type { SharedContext } from "cubi/shared"; -export function setup(ctx: SharedContext) { +export function shared(ctx: SharedContext) { // marks the watcher once anything beside it changes ctx.components.register_block("testmod:watcher", { on_neighbor_change(block) { ctx.world.set_state(block.x, block.y, block.z, "seen", 1); }, @@ -93,7 +93,7 @@ function test_mods() { name: "Test", version: "1.0.0", dependencies: [{ id: "bworld", version: "*" }], - scripts: { server: "scripts/server.ts", shared: "scripts/shared.ts" }, + main: "scripts/main.ts", }); const block = (name: string, states: unknown[] = []) => write(`blocks/${name}.json`, { @@ -113,6 +113,10 @@ function test_mods() { block("flipper", [{ name: "on", bits: 1, default: 0 }]); Deno.writeTextFileSync(`${mod}/scripts/server.ts`, SERVER_SCRIPT); Deno.writeTextFileSync(`${mod}/scripts/shared.ts`, SHARED_SCRIPT); + Deno.writeTextFileSync( + `${mod}/scripts/main.ts`, + `export { server } from "./server.ts";\nexport { shared } from "./shared.ts";\n`, + ); return dir; } diff --git a/tests/player_actions_test.ts b/tests/player_actions_test.ts index afe1599..91747b1 100644 --- a/tests/player_actions_test.ts +++ b/tests/player_actions_test.ts @@ -8,7 +8,7 @@ import { copy_dir, stone_floor, test_game } from "./helpers.ts"; const SERVER_SCRIPT = ` import type { ServerContext } from "cubi/server"; -export function setup(ctx: ServerContext) { +export function server(ctx: ServerContext) { const log = (key: string, value: unknown = 1) => { const all = ctx.storage.get>("log") ?? {}; (all[key] ??= []).push(value); @@ -41,7 +41,7 @@ export function setup(ctx: ServerContext) { // a pillar placed upside down while sneaking, like a block whose placement reads sneaking const SHARED_SCRIPT = ` import type { SharedContext } from "cubi/shared"; -export function setup(ctx: SharedContext) { +export function shared(ctx: SharedContext) { ctx.components.register_block("testmod:pillar", { state_for_placement(placement) { return { flipped: placement.sneaking ? 1 : 0 }; }, }); @@ -60,7 +60,7 @@ function test_mods() { name: "Test", version: "1.0.0", dependencies: [{ id: "bworld", version: "*" }], - scripts: { server: "scripts/server.ts", shared: "scripts/shared.ts" }, + main: "scripts/main.ts", }); const block = (id: string, extra: Record) => ({ format_version: 1, @@ -82,6 +82,10 @@ function test_mods() { write("items/bow.json", item("testmod:bow", { "testmod:bow": { ticks: 5 } })); Deno.writeTextFileSync(`${mod}/scripts/server.ts`, SERVER_SCRIPT); Deno.writeTextFileSync(`${mod}/scripts/shared.ts`, SHARED_SCRIPT); + Deno.writeTextFileSync( + `${mod}/scripts/main.ts`, + `export { server } from "./server.ts";\nexport { shared } from "./shared.ts";\n`, + ); return dir; } diff --git a/tests/recipe_viewer_test.ts b/tests/recipe_viewer_test.ts index f2f124c..5a09f20 100644 --- a/tests/recipe_viewer_test.ts +++ b/tests/recipe_viewer_test.ts @@ -189,7 +189,7 @@ Deno.test("a crab pot's recipes are what each bait catches in fresh and salt wat }); Deno.test("each juiceable item has a juicing recipe that presses it into its own juice", async () => { - // registered by the base game's shared script, see mods/bworld/scripts/juicing.ts + // registered by the base game's shared phase, see mods/bworld/scripts/juicing.ts const { game } = await test_game("mods"); const index = new RecipeIndex(client_ctx(game.recipes.all)); diff --git a/tests/scheduled_ticks_test.ts b/tests/scheduled_ticks_test.ts index 948747f..329fe4a 100644 --- a/tests/scheduled_ticks_test.ts +++ b/tests/scheduled_ticks_test.ts @@ -9,7 +9,7 @@ import { copy_dir, stone_floor, test_game } from "./helpers.ts"; const SERVER_SCRIPT = ` import type { ServerContext } from "cubi/server"; -export function setup(ctx: ServerContext) { +export function server(ctx: ServerContext) { const log = (event: unknown[]) => ctx.storage.set("log", [...ctx.storage.get("log") ?? [], event]); ctx.components.register_block("testmod:clock", { on_scheduled_tick(block) { log([block.x, ctx.system.current_tick]); }, @@ -54,7 +54,7 @@ function test_mods() { name: "Test", version: "1.0.0", dependencies: [{ id: "bworld", version: "*" }], - scripts: { server: "scripts/server.ts" }, + main: "scripts/server.ts", }); const block = (name: string, states: unknown[] = []) => write(`blocks/${name}.json`, { diff --git a/tests/script_recipes_test.ts b/tests/script_recipes_test.ts index 6de4aaa..a684f87 100644 --- a/tests/script_recipes_test.ts +++ b/tests/script_recipes_test.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// recipes a shared script registers with ctx.recipes.register: there on the server and every client alike, for their +// recipes the shared phase registers with ctx.recipes.register: there on the server and every client alike, for their // scripts and the crafting grid, without being sent import { assert, assertEquals, assertRejects } from "@std/assert"; import { EverythingRegistry } from "@/common/everything_registry.ts"; @@ -16,7 +16,7 @@ import { copy_dir, load_as_player, test_game } from "./helpers.ts"; // types, found by the item put in const SHARED = ` import type { SharedContext } from "cubi/shared"; - export function setup(ctx: SharedContext) { + export function shared(ctx: SharedContext) { for (const id of ctx.items.ids()) { const sifts = ctx.items.components(id)["testrecipes:siftable"] as { into: string } | undefined; if (sifts) ctx.recipes.register("testrecipes:sifting", { input: id, result: { id: sifts.into, count: 1 } }); @@ -32,9 +32,9 @@ const SHARED = ` } `; -// what the server and client scripts see of them while they set up. the server's registers the siftable component +// what the server and client phases see of them while they run. the server's registers the siftable component const SEEN = (side: string) => ` - export function setup(ctx: any) { + export function ${side}(ctx: any) { ctx.components?.register_item?.("testrecipes:siftable", {}); (globalThis as any).testrecipes_${side} = ctx.recipes.list("testrecipes:sifting"); (globalThis as any).testrecipes_${side}_parsed = { @@ -59,7 +59,7 @@ function recipe_mod(shared_extra = "", recipes: Record = {}) { id: "testrecipes", name: "Test Recipes", version: "1.0.0", - scripts: { shared: "scripts/shared.ts", server: "scripts/server.ts", client: "scripts/client.ts" }, + main: "scripts/main.ts", }); const item = (id: string, components?: unknown) => write(`items/${id}.json`, { @@ -72,6 +72,10 @@ function recipe_mod(shared_extra = "", recipes: Record = {}) { write("scripts/shared.ts", SHARED.replace("SHARED_EXTRA", shared_extra)); write("scripts/server.ts", SEEN("server")); write("scripts/client.ts", SEEN("client")); + write( + "scripts/main.ts", + `export { shared } from "./shared.ts"; export { server } from "./server.ts"; export { client } from "./client.ts";`, + ); for (const [name, recipe] of Object.entries(recipes)) write(`recipes/${name}`, { format_version: 1, recipe }); return dir; } @@ -95,7 +99,7 @@ async function load_client(dir: string) { await load_client_mods([listing], [packed]); } -Deno.test("recipes a shared script registers are on the server and clients, for their scripts and crafting", async () => { +Deno.test("recipes a mod's shared phase registers are on the server and clients, for their scripts and crafting", async () => { const dir = recipe_mod(); const t = await test_game(dir); assertEquals(seen.testrecipes_server, SIFTING); @@ -180,7 +184,7 @@ Deno.test("a mod can only register recipe types in its own namespace", async () Deno.removeSync(dir, { recursive: true }); }); -Deno.test("a shared script lists the recipes there are so far, from files and the scripts before it", async () => { +Deno.test("a mod's shared phase lists the recipes there are so far, from files and the scripts before it", async () => { // a washing recipe for every sifting one, whatever made it const dir = recipe_mod( `for (const sifting of ctx.recipes.list("testrecipes:sifting")) { @@ -200,7 +204,7 @@ Deno.test("a shared script lists the recipes there are so far, from files and th assertEquals(washing as unknown, [{ id: "testrecipes:sand", count: 1 }, { id: "testrecipes:gravel", count: 1 }]); }); -Deno.test("a broken recipe from a shared script stops the mod loading, like a broken file", async () => { +Deno.test("a broken recipe from a mod's shared phase stops the mod loading, like a broken file", async () => { const dir = recipe_mod( `ctx.recipes.register("shaped", { pattern: ["#"], key: {}, result: { id: "testrecipes:sand", count: 1 } });`, ); @@ -208,7 +212,7 @@ Deno.test("a broken recipe from a shared script stops the mod loading, like a br Deno.removeSync(dir, { recursive: true }); }); -Deno.test("recipes can only be registered while shared scripts set up", async () => { +Deno.test("recipes can only be registered while shared phases set up", async () => { const dir = recipe_mod( `(globalThis as any).testrecipes_late = () => ctx.recipes.register("testrecipes:sifting", {});`, ); diff --git a/tests/season_test.ts b/tests/season_test.ts index 6b0eac5..056c87e 100644 --- a/tests/season_test.ts +++ b/tests/season_test.ts @@ -10,7 +10,7 @@ import { copy_dir, test_game } from "./helpers.ts"; const SCRIPT = ` import type { ServerContext } from "cubi/server"; -export function setup(ctx: ServerContext) { +export function server(ctx: ServerContext) { (globalThis as any).season_test = { ctx, created: [] }; ctx.components.register_block("testmod:thermometer", { on_create(block) { @@ -42,7 +42,7 @@ function season_mods() { name: "Test", version: "1.0.0", dependencies: [{ id: "bworld", version: "*" }], - scripts: { server: "scripts/server.ts" }, + main: "scripts/server.ts", }), ); Deno.writeTextFileSync( diff --git a/tests/server_scripts_test.ts b/tests/server_scripts_test.ts index aeddd92..56eca49 100644 --- a/tests/server_scripts_test.ts +++ b/tests/server_scripts_test.ts @@ -8,7 +8,7 @@ import type { WorldSave } from "@/server/game/saves.ts"; // a mod that uses every part of the server api worth testing, and writes down what happened in its storage const SERVER_SCRIPT = ` import type { BlockRef, ServerContext } from "cubi/server"; -export function setup(ctx: ServerContext) { +export function server(ctx: ServerContext) { const log = (key: string, value: unknown = 1) => { const all = ctx.storage.get>("log") ?? {}; (all[key] ??= []).push(value); @@ -153,7 +153,7 @@ function test_mods() { name: "Test", version: "1.0.0", dependencies: [{ id: "bworld", version: "*" }], - scripts: { server: "scripts/server.ts" }, + main: "scripts/server.ts", }), ); Deno.writeTextFileSync( diff --git a/tests/shared_rules_test.ts b/tests/shared_rules_test.ts index 65681c6..9423262 100644 --- a/tests/shared_rules_test.ts +++ b/tests/shared_rules_test.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// shared scripts' block rules run on clients too, so what a client shows the moment it places, breaks or right clicks +// shared phases' block rules run on clients too, so what a client shows the moment it places, breaks or right clicks // a block is what the server ends up with import { assertEquals } from "@std/assert"; import { AIR_ID } from "@/common/protocol.ts"; diff --git a/tests/tags_test.ts b/tests/tags_test.ts index 37fc3ba..eb0bc3a 100644 --- a/tests/tags_test.ts +++ b/tests/tags_test.ts @@ -224,6 +224,6 @@ Deno.test("tags survive packing into a .cubi", () => { tags: [tag], }; const manifest: ManifestJson = { format_version: 1, id: "x", name: "X", version: "1.0.0" }; - const mod = read_mod(write_mod({ manifest, data, scripts: {}, textures: new Map() }), "x.cubi"); + const mod = read_mod(write_mod({ manifest, data, textures: new Map() }), "x.cubi"); assertEquals(mod.data.tags, [tag]); }); diff --git a/tests/tooltip_test.ts b/tests/tooltip_test.ts index e6087f6..74487d7 100644 --- a/tests/tooltip_test.ts +++ b/tests/tooltip_test.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// item tooltips: the game's lines, the ones client scripts add and where they go +// item tooltips: the game's lines, the ones client phases add and where they go import { assertEquals } from "@std/assert"; import { item_tooltip } from "@/client/gui/tooltip.ts"; import { ItemStack } from "@/common/inventory.ts"; @@ -9,7 +9,7 @@ import { copy_dir, load_as_player } from "./helpers.ts"; const SNACK = "tips:snack"; -// mods/bworld, then tips: a snack with food and lore that sells for 4, and a client script adding lines to its tooltip +// mods/bworld, then tips: a snack with food and lore that sells for 4, and a client phase adding lines to its tooltip async function load(client_script: string) { const dir = Deno.makeTempDirSync({ prefix: "bworld_tooltips_" }); copy_dir("mods/bworld", `${dir}/bworld`); @@ -24,7 +24,7 @@ async function load(client_script: string) { id: "tips", name: "Tips", version: "1.0.0", - scripts: { client: "scripts/client.ts" }, + main: "scripts/client.ts", }), ); write( @@ -49,10 +49,10 @@ async function load(client_script: string) { return (id: string) => item_tooltip(new ItemStack(id)).map((line) => line.text); } -Deno.test("a client script's lines show in item tooltips, and bworld's sell value goes after the food", async () => { +Deno.test("a mod's client phase's lines show in item tooltips, and bworld's sell value goes after the food", async () => { const tooltip = await load(` import type { ClientContext } from "cubi/client"; - export function setup(ctx: ClientContext) { + export function client(ctx: ClientContext) { ctx.ui.add_item_tooltip((item, lines) => lines.push({ text: "from tips: " + item.id })); } `); @@ -63,7 +63,7 @@ Deno.test("a client script's lines show in item tooltips, and bworld's sell valu Deno.test("tooltip lines go where their priority says, and ones with the same priority keep their order", async () => { const tooltip = await load(` 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) => { if (item.id !== "${SNACK}") return; lines.push({ text: "last", priority: TOOLTIP_PRIORITY.lore + 1 }); diff --git a/tests/underground_biome_test.ts b/tests/underground_biome_test.ts index 9f03832..2fa9afe 100644 --- a/tests/underground_biome_test.ts +++ b/tests/underground_biome_test.ts @@ -24,7 +24,7 @@ function deep_mod() { name: "Deep", version: "1.0.0", dependencies: [{ id: "bworld", version: "*" }], - scripts: { worldgen: "scripts/worldgen.ts", server: "scripts/server.ts" }, + main: "scripts/main.ts", }); write("worldgen/biomes/caves.json", { format_version: 1, @@ -49,21 +49,18 @@ function deep_mod() { }, }); write( - "scripts/worldgen.ts", - `import type { WorldgenContext } from "cubi/worldgen"; - export function setup(gen: WorldgenContext) { + "scripts/main.ts", + `import type { ServerContext } from "cubi/server"; + import type { WorldgenContext } from "cubi/worldgen"; + export function worldgen(gen: WorldgenContext) { gen.register_feature("deep:look", (chunk) => { if (chunk.x !== 0 || chunk.z !== 0) return; const ground = chunk.height_at(8, 8); (globalThis as any).deep_seen = [chunk.biome_at(8, ground, 8), chunk.biome_at(8, ground - 40, 8)]; chunk.set_biome(9, 201, 9, "deep:caves"); }); - }`, - ); - write( - "scripts/server.ts", - `import type { ServerContext } from "cubi/server"; - export function setup(ctx: ServerContext) { + } + export function server(ctx: ServerContext) { (globalThis as any).deep_ctx = ctx; }`, ); diff --git a/tests/visuals_test.ts b/tests/visuals_test.ts index 603e9b8..4b26d20 100644 --- a/tests/visuals_test.ts +++ b/tests/visuals_test.ts @@ -28,7 +28,7 @@ const HALF = { }; // testmod: a shaft with an axis state and a model of half of one, syrup, a jar drawn with the syrup in it, and maybe a -// client script +// client phase function write_testmod(dir: string, client_script?: string) { const mod = `${dir}/testmod`; for (const folder of ["blocks", "models", "scripts", "fluids", "items"]) { @@ -40,7 +40,7 @@ function write_testmod(dir: string, client_script?: string) { id: "testmod", name: "Test", version: "1.0.0", - ...(client_script && { scripts: { client: "scripts/client.ts" } }), + ...(client_script && { main: "scripts/client.ts" }), }); write("blocks/shaft.json", { format_version: 1, @@ -473,7 +473,7 @@ Deno.test({ }, }); -Deno.test("client scripts register visuals during setup, for blocks that exist", async () => { +Deno.test("client phases register visuals during setup, for blocks that exist", async () => { const load = async (script: string) => { const dir = Deno.makeTempDirSync({ prefix: "bworld_visuals_" }); write_testmod(dir, script); @@ -486,7 +486,7 @@ Deno.test("client scripts register visuals during setup, for blocks that exist", }; await load(` import type { ClientContext } from "cubi/client"; - export function setup(ctx: ClientContext) { + export function client(ctx: ClientContext) { ctx.render.register_visual("testmod:shaft", (_block, instances) => { instances.rotating(); return {}; @@ -500,7 +500,7 @@ Deno.test("client scripts register visuals during setup, for blocks that exist", () => load(` import type { ClientContext } from "cubi/client"; - export function setup(ctx: ClientContext) { + export function client(ctx: ClientContext) { ctx.render.register_visual("testmod:gear", () => ({})); } `), diff --git a/tests/worldgen_bundle_test.ts b/tests/worldgen_bundle_test.ts index 69d87c7..e8bf373 100644 --- a/tests/worldgen_bundle_test.ts +++ b/tests/worldgen_bundle_test.ts @@ -20,7 +20,7 @@ Deno.test("a bundle, cloned like a message to a worker and loaded into an empty EverythingRegistry.clear(); const loaded = await load_bundle(bundle); assertEquals(loaded.block_ids, game_ids, "blocks are numbered like the game numbers them"); - assert(loaded.setup.features.some((f) => f.id === "bworld:trees"), "bworld's worldgen script was loaded"); + assert(loaded.setup.features.some((f) => f.id === "bworld:trees"), "bworld's worldgen phase was loaded"); const name = namer(loaded.block_ids); for (const [x, z] of golden_chunks()) { diff --git a/tests/worldgen_pool_test.ts b/tests/worldgen_pool_test.ts index 3d3780d..0351629 100644 --- a/tests/worldgen_pool_test.ts +++ b/tests/worldgen_pool_test.ts @@ -16,7 +16,7 @@ const options = { sanitizeOps: false, sanitizeResources: false }; async function pool_for(seed: string, workers: number) { const { game } = await test_game("mods", undefined, seed); - // tests load worldgen scripts from files, so the workers need to read them + // tests load worldgen phases from files, so the workers need to read them const started = start_worldgen_workers(workers, { permissions: "inherit", on_restart: () => {} }); const pool = new WorldgenPool(started.ports as unknown as WorkerPort[], game.worldgen_bundle!); const chunks = new Map(); diff --git a/tools/check_mods.ts b/tools/check_mods.ts index d96074b..387d75e 100644 --- a/tools/check_mods.ts +++ b/tools/check_mods.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: AGPL-3.0-or-later // deno task check-mods -// validates every mod in mods/: manifests, data files, textures, references between them, and typechecks scripts +// validates every mod in mods/: manifests, data files, textures, references between them, and typechecks their scripts import * as z from "zod"; import { data_file, @@ -25,7 +25,7 @@ import { } from "@/common/mod_data.ts"; import { json_object } from "@/common/schema.ts"; import { check_references, load_order, type LoadedMod, type ModReport } from "@/common/mod_check.ts"; -import { png_size, texture_size_problem } from "@/common/mod.ts"; +import { data_url, png_size, texture_size_problem } from "@/common/mod.ts"; import { type TextureJson, validate_texture_json } from "@/common/texture_animation.ts"; import { type LootTableJson, validate_loot_table } from "@/common/loot.ts"; import { validate_biome } from "@/common/worldgen/biomes.ts"; @@ -67,23 +67,35 @@ export async function load_and_check(mods_dir = "mods"): Promise { return mods; } -// runs the mod's content script and adds the blocks it registers after its files' ones, named after the script, like -// the server does with a .cubi's. packing leaves them out, the server registers them again +// runs its script's content phase and adds the blocks it registers after its files' ones, named after the script, +// like the server does with a .cubi's. packing leaves them out, the server registers them again async function add_registered_content(mod: LoadedMod) { - const path = content_script(mod); + const path = main_script(mod); if (path === undefined || !exists(`${mod.dir}/${path}`)) return; + // only this folder's deno.json is in this realm's import map, so a mod with its own is bundled first + let url = toFileUrl(resolve(mod.dir, path)).href; + if (mod_deno_config(mod.dir)) { + try { + url = data_url(await bundle_script(mod.dir, `${mod.dir}/${path}`)); + } catch (e) { + mod.report.errors.push((e as Error).message); + return; + } + } const { blocks, problems } = await run_content_script({ mod: mod.id, version: String(mod.manifest?.version), - url: toFileUrl(resolve(mod.dir, path)).href, + engine_access: mod.manifest?.engine_access === true, + url, }); for (const json of blocks) mod.blocks.push({ file: path, json }); for (const problem of problems) mod.report.errors.push(`${path}: ${problem}`); } -// the path of the mod's content script in its folder, which is also the file its blocks are listed under -export function content_script(mod: LoadedMod): string | undefined { - const path = (mod.manifest?.scripts as Record | undefined)?.content; +// the path of the mod's script in its folder, which is also the file the blocks its content phase registers are +// listed under +export function main_script(mod: LoadedMod): string | undefined { + const path = mod.manifest?.main; return typeof path === "string" ? path : undefined; } @@ -97,7 +109,7 @@ export async function check_mods(mods_dir = "mods", options = { typecheck: true if (options.typecheck) { for (const mod of mods) { - await typecheck_scripts(mod); + await typecheck_script(mod); } } @@ -144,22 +156,14 @@ function load_mod(mods_dir: string, id: string): LoadedMod { error(`"cubi" is reserved for the engine itself`); } - const scripts = (mod.manifest?.scripts ?? {}) as Record; - for (const [side, path] of Object.entries(scripts)) { - if (typeof path === "string" && !exists(`${dir}/${path}`)) { - error(`manifest.json: scripts.${side} ${path} doesn't exist`); - } - } + const main = main_script(mod); + if (main !== undefined && !exists(`${dir}/${main}`)) error(`manifest.json: main ${main} doesn't exist`); // cubi/engine needs engine_access, it's checked again on the bundled code when a .cubi loads - if (mod.manifest?.engine_access !== true) { - const folders = new Set(Object.values(scripts).filter((p) => typeof p === "string").map((p) => dirname(p))); - for (const folder of folders) { - for (const file of [...walk(`${dir}/${folder}`, ".ts"), ...walk(`${dir}/${folder}`, ".js")]) { - if (/["']cubi\/engine["']/.test(Deno.readTextFileSync(`${dir}/${folder}/${file}`))) { - error( - `${folder}/${file} imports cubi/engine, which needs "engine_access": true in manifest.json`, - ); - } + if (mod.manifest?.engine_access !== true && main !== undefined) { + const folder = dirname(main); + for (const file of [...walk(`${dir}/${folder}`, ".ts"), ...walk(`${dir}/${folder}`, ".js")]) { + if (/["']cubi\/engine["']/.test(Deno.readTextFileSync(`${dir}/${folder}/${file}`))) { + error(`${folder}/${file} imports cubi/engine, which needs "engine_access": true in manifest.json`); } } } @@ -308,22 +312,20 @@ function load_mod(mods_dir: string, id: string): LoadedMod { return mod; } -async function typecheck_scripts(mod: LoadedMod) { - const scripts = Object.values((mod.manifest?.scripts ?? {}) as Record) - .filter((path) => typeof path === "string" && exists(`${mod.dir}/${path}`)) - .map((path) => `${mod.dir}/${path}`); - if (scripts.length === 0) return; +async function typecheck_script(mod: LoadedMod) { + const path = main_script(mod); + if (path === undefined || !exists(`${mod.dir}/${path}`)) return; const config = mod_deno_config(mod.dir) ?? "deno.json"; const output = await new Deno.Command(Deno.execPath(), { - args: ["check", "--config", config, ...scripts], + args: ["check", "--config", config, `${mod.dir}/${path}`], stdout: "piped", stderr: "piped", env: { NO_COLOR: "1" }, }).output(); if (!output.success) { const text = new TextDecoder().decode(output.stderr).trim(); - mod.report.errors.push(`scripts don't typecheck:\n${text}`); + mod.report.errors.push(`its script doesn't typecheck:\n${text}`); } } @@ -366,7 +368,33 @@ function safe_read_dir(dir: string): Deno.DirEntry[] { } } -// a mod with its own deno.json is its own deno project, see pack_mod.ts +// a mod is a deno project: with its own deno.json its script is bundled with it (its imports, npm packages and so +// on), otherwise with the deno.json of the folder the build runs in. for browsers, since players run it too, and the +// server's realms have no permissions, so deno's own apis are no use there +export async function bundle_script(mod_dir: string, entry: string): Promise { + const platform = "browser"; + const config = mod_deno_config(mod_dir); + if (!config) { + const result = await Deno.bundle({ entrypoints: [entry], platform, write: false, minify: false }); + if (!result.success || !result.outputFiles?.length) { + throw new Error(`Couldn't bundle ${entry}:\n${result.errors.map((e) => e.text).join("\n")}`); + } + return result.outputFiles[0].text(); + } + + const result = await new Deno.Command(Deno.execPath(), { + args: ["bundle", "--config", config, "--platform", platform, entry], + stdout: "piped", + stderr: "piped", + env: { NO_COLOR: "1" }, + }).output(); + if (!result.success) { + throw new Error(`Couldn't bundle ${entry}:\n${new TextDecoder().decode(result.stderr).trim()}`); + } + return new TextDecoder().decode(result.stdout); +} + +// a mod with its own deno.json is its own deno project, see bundle_script export function mod_deno_config(mod_dir: string): string | undefined { return ["deno.json", "deno.jsonc"].map((name) => `${mod_dir}/${name}`).find(exists); } diff --git a/tools/pack_mod.ts b/tools/pack_mod.ts index 96eb66a..b64bcd1 100644 --- a/tools/pack_mod.ts +++ b/tools/pack_mod.ts @@ -2,32 +2,18 @@ // SPDX-License-Identifier: AGPL-3.0-or-later // deno task pack-mod mods/copper_tools [copper_tools.cubi] -// builds a mod folder into a .cubi: its data merged into data.json, each script bundled into one module, and its +// builds a mod folder into a .cubi: its data merged into data.json, its script bundled into one module, and its // textures and credits. deno task build does this for every mod in mods/, see docs/modding/gettingstarted/modfiles.md import { basename, dirname, resolve } from "@std/path"; -import { type Mod, MOD_EXTENSION, SCRIPT_SIDES, type ScriptSide, write_mod } from "@/common/mod.ts"; +import { MOD_EXTENSION, write_mod } from "@/common/mod.ts"; import type { ManifestJson } from "@/common/mod_data.ts"; -import { content_script, load_and_check, type LoadedMod, mod_deno_config } from "./check_mods.ts"; +import { bundle_script, load_and_check, type LoadedMod, main_script } from "./check_mods.ts"; import { mod_data } from "@/common/mod_check.ts"; -// what each script is bundled for: the server runs in deno, clients in browsers, worldgen and shared in both. content -// scripts only run on the server -const PLATFORMS: Record = { - server: "deno", - client: "browser", - worldgen: "browser", - shared: "browser", - content: "deno", -}; - // a mod that passed check-mods, as .cubi bytes export async function pack_mod(mod: LoadedMod): Promise> { const manifest = mod.manifest as unknown as ManifestJson; - const scripts: Mod["scripts"] = {}; - for (const side of SCRIPT_SIDES) { - const entry = manifest.scripts?.[side]; - if (entry) scripts[side] = await bundle_script(mod.dir, `${mod.dir}/${entry}`, PLATFORMS[side]); - } + const script = manifest.main ? await bundle_script(mod.dir, `${mod.dir}/${manifest.main}`) : undefined; const textures = new Map(); for (const [id, path] of [...mod.texture_files].sort(([a], [b]) => a.localeCompare(b))) { @@ -35,48 +21,19 @@ export async function pack_mod(mod: LoadedMod): Promise> } const texture_json = new Map([...mod.texture_json].sort(([a], [b]) => a.localeCompare(b))); - // without what the content script registered, which the server registers again when it loads the .cubi + // without what the content phase registered, which the server registers again when it loads the .cubi const data = mod_data(mod); - data.blocks = mod.blocks.filter(({ file }) => file !== content_script(mod)).map(({ json }) => json); + data.blocks = mod.blocks.filter(({ file }) => file !== main_script(mod)).map(({ json }) => json); return write_mod({ manifest, data, - scripts, + script, textures, texture_json, credits: manifest.credits ? Deno.readTextFileSync(`${mod.dir}/${manifest.credits}`) : undefined, }); } -// a mod is a deno project: with its own deno.json its scripts are bundled with it (its imports, npm packages and -// so on), otherwise with the deno.json of the folder the build runs in -async function bundle_script(mod_dir: string, entry: string, platform: "deno" | "browser"): Promise { - const config = mod_deno_config(mod_dir); - if (!config) { - const result = await Deno.bundle({ entrypoints: [entry], platform, write: false, minify: false }); - if (!result.success || !result.outputFiles?.length) { - throw new Error(`Couldn't bundle ${entry}:\n${result.errors.map((e) => e.text).join("\n")}`); - } - return result.outputFiles[0].text(); - } - - const output = await Deno.makeTempFile({ suffix: ".js" }); - try { - const result = await new Deno.Command(Deno.execPath(), { - args: ["bundle", "--config", config, "--platform", platform, "--output", output, entry], - stdout: "piped", - stderr: "piped", - env: { NO_COLOR: "1" }, - }).output(); - if (!result.success) { - throw new Error(`Couldn't bundle ${entry}:\n${new TextDecoder().decode(result.stderr).trim()}`); - } - return Deno.readTextFileSync(output); - } finally { - Deno.removeSync(output); - } -} - if (import.meta.main) { const [dir, out] = Deno.args; if (!dir) { diff --git a/tools/worldgen_preview.ts b/tools/worldgen_preview.ts index 46cdb6f..a40a5cf 100644 --- a/tools/worldgen_preview.ts +++ b/tools/worldgen_preview.ts @@ -19,7 +19,7 @@ const out = Deno.args[1] ?? "."; const [center_x, center_z] = [Number(Deno.args[2] ?? 0), Number(Deno.args[3] ?? 0)]; Deno.mkdirSync(out, { recursive: true }); -// the base game, from mods/bworld: its data registered like the game does, and its worldgen script for trees and the +// the base game, from mods/bworld: its data registered like the game does, and its worldgen phase for trees and the // rest of its features const bworld = (await load_and_check()).find((mod) => mod.id === "bworld")!; const jsons = (list: { json: T }[]) => list.map((entry) => entry.json); @@ -50,7 +50,7 @@ const dimension = jsons(bworld.dimensions).find((json) => json.default)!; const shape = dimension_shape(dimension); const worldgen = await load_worldgen({ mods: ["bworld"], - scripts: [{ mod: "bworld", url: new URL("../mods/bworld/scripts/worldgen.ts", import.meta.url).href }], + scripts: [{ mod: "bworld", url: new URL("../mods/bworld/scripts/main.ts", import.meta.url).href }], ores: [jsons(bworld.ores)], generator: dimension.generator, shape,