From 69c5c187dbf669167575419a307ab019d17b1483 Mon Sep 17 00:00:00 2001 From: Paula Date: Tue, 6 Oct 2026 20:27:17 -0300 Subject: [PATCH] Engine api --- MODS.md | 2 + client/confirm_mods.ts | 4 +- client/engine_modules.ts | 38 +++ client/entity/entity.ts | 8 +- client/entity/local_player.ts | 10 +- client/mods.ts | 43 ++- common/bmod.ts | 5 + common/constants.ts | 3 + common/engine_modules.ts | 25 ++ common/hooks.ts | 248 +++++++++++++++++ common/mod_api/engine.ts | 30 +++ common/mod_data.ts | 24 ++ common/mod_loader.ts | 2 + common/physics.ts | 4 + common/worldgen_loader.ts | 20 +- deno.json | 1 + docs/modding/gettingstarted/modfiles.md | 5 +- docs/modding/misc/engine.md | 84 ++++++ docs/modding_plan.md | 15 +- server/game/engine_modules.ts | 52 ++++ server/game/entity/entity.ts | 8 +- server/game/load_mods.ts | 23 +- server/game/mod_runtime.ts | 107 ++++---- server/load_bmods.ts | 1 + tests/engine_access_test.ts | 339 ++++++++++++++++++++++++ tests/helpers.ts | 1 + tools/check_mods.ts | 14 + 27 files changed, 1026 insertions(+), 90 deletions(-) create mode 100644 client/engine_modules.ts create mode 100644 common/engine_modules.ts create mode 100644 common/hooks.ts create mode 100644 common/mod_api/engine.ts create mode 100644 docs/modding/misc/engine.md create mode 100644 server/game/engine_modules.ts create mode 100644 tests/engine_access_test.ts diff --git a/MODS.md b/MODS.md index 83a51f0..9b20021 100644 --- a/MODS.md +++ b/MODS.md @@ -70,6 +70,8 @@ deno task build && deno task server # packs the mods and starts a se - [Saving Data](docs/modding/datastorage/index.md): where a mod keeps what should last - [Commands](docs/modding/misc/commands.md) - [Time](docs/modding/misc/time.md): ticks, timers, days and nights +- [Engine Access](docs/modding/misc/engine.md): reaching into the engine and hooking its methods, for what the API + doesn't cover yet ## API Types diff --git a/client/confirm_mods.ts b/client/confirm_mods.ts index 0da1b51..f8a52e5 100644 --- a/client/confirm_mods.ts +++ b/client/confirm_mods.ts @@ -25,7 +25,9 @@ export function confirm_mods(address: ServerAddress, welcome: Welcome): Promise< list.style.cssText = "margin:0;padding-left:20px;"; for (const mod of welcome.mods) { const item = document.createElement("li"); - item.textContent = `${mod.name} ${mod.version} (${mod.id})`; + // it can change anything about the game, not just add to it + const access = mod.engine_access ? ", changes the engine" : ""; + item.textContent = `${mod.name} ${mod.version} (${mod.id}${access})`; list.append(item); } diff --git a/client/engine_modules.ts b/client/engine_modules.ts new file mode 100644 index 0000000..0847d09 --- /dev/null +++ b/client/engine_modules.ts @@ -0,0 +1,38 @@ +// what engine access mods get as engine.client, in client scripts. see docs/modding/misc/engine.md +import { Client } from "./client.ts"; +import { Entity } from "./entity/entity.ts"; +import { LocalPlayer } from "./entity/local_player.ts"; +import { Player } from "./entity/player.ts"; +import { RemoteEntity } from "./entity/remote_entity.ts"; +import { RemotePlayer } from "./entity/remote_player.ts"; +import { ItemEntity } from "./entity/item_entity.ts"; +import { ClientLevel } from "./level/client_level.ts"; +import { GameRenderer } from "./rendering/game_renderer.ts"; +import { LevelRenderer } from "./rendering/level_renderer.ts"; +import { HandRenderer } from "./rendering/hand_renderer.ts"; +import { Camera } from "./camera.ts"; +import { InputManager } from "./input_manager.ts"; +import { ClientMenu } from "./menu.ts"; +import { GuiMenuScreen, GuiScreen } from "./gui/gui_screen.ts"; + +// built when it's exposed, not when this module loads, so import cycles can't leave anything undefined +export function client_engine() { + return { + Client, + Entity, + LocalPlayer, + Player, + RemoteEntity, + RemotePlayer, + ItemEntity, + ClientLevel, + GameRenderer, + LevelRenderer, + HandRenderer, + Camera, + InputManager, + ClientMenu, + GuiScreen, + GuiMenuScreen, + }; +} diff --git a/client/entity/entity.ts b/client/entity/entity.ts index 579baf7..5cecb02 100644 --- a/client/entity/entity.ts +++ b/client/entity/entity.ts @@ -1,4 +1,4 @@ -import { eyes_in_water, in_water, move_body } from "$/common/physics.ts"; +import { physics } from "$/common/physics.ts"; import type { ClientLevel } from "../level/client_level.ts"; // anything that exists in the level and moves, like minecraft's Entity. position is the middle of its feet. @@ -61,12 +61,12 @@ export abstract class Entity { // in water, like the server's Entity.in_water get in_water() { - return in_water(this, (x, y, z) => this.level.is_liquid(x, y, z)); + return physics.in_water(this, (x, y, z) => this.level.is_liquid(x, y, z)); } // its eyes are in water get eyes_in_water() { - return eyes_in_water(this, this.eye_height, (x, y, z) => this.level.is_liquid(x, y, z)); + return physics.eyes_in_water(this, this.eye_height, (x, y, z) => this.level.is_liquid(x, y, z)); } // after moving each tick. full speed is 5 blocks per second, a bit faster than walking @@ -130,7 +130,7 @@ export abstract class Entity { const is_solid = (x: number, y: number, z: number) => this.level.collision_shape(x, y, z); const can_step = this.#air_ticks <= this.step_grace_ticks && this.vy <= 0; const friction = this.horizontal_friction(); - const collisions = move_body(this, this.gravity, is_solid, this.step_height, can_step); + const collisions = physics.move_body(this, this.gravity, is_solid, this.step_height, can_step); this.colliding_x = collisions.x; this.colliding_y = collisions.y; this.colliding_z = collisions.z; diff --git a/client/entity/local_player.ts b/client/entity/local_player.ts index 5e80c56..8550f41 100644 --- a/client/entity/local_player.ts +++ b/client/entity/local_player.ts @@ -1,5 +1,5 @@ import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_SWIM_EYE_HEIGHT, TICK_DELTA } from "$/common/constants.ts"; -import { back_off_from_edge, box_is_free } from "$/common/physics.ts"; +import { physics } from "$/common/physics.ts"; import type { Client } from "../client.ts"; import { InputManager } from "../input_manager.ts"; import { ClientInventories } from "../inventory.ts"; @@ -158,7 +158,7 @@ export class LocalPlayer extends Player { // not while jumping, so it can still jump off a ledge if (this.sneaking && this.on_ground && this.vy <= 0) { const is_solid = (x: number, y: number, z: number) => this.level.collision_shape(x, y, z); - const [dx, dz] = back_off_from_edge( + const [dx, dz] = physics.back_off_from_edge( this, this.vx * TICK_DELTA, this.vz * TICK_DELTA, @@ -195,7 +195,9 @@ export class LocalPlayer extends Player { vy: 0, vz: 0, }; - if (box_is_free(standing, 0, 0, 0, (x, y, z) => this.level.collision_shape(x, y, z))) this.set_swimming(false); + if (physics.box_is_free(standing, 0, 0, 0, (x, y, z) => this.level.collision_shape(x, y, z))) { + this.set_swimming(false); + } } // turns up or down toward where it's looking. not up once its head is out, so it swims along the surface instead @@ -234,7 +236,7 @@ export class LocalPlayer extends Player { const blocked = (x: number, y: number, z: number) => this.level.is_liquid(x, y, z) || this.level.collision_shape(x, y, z); const dy = from_y - this.y + this.vy * TICK_DELTA + WATER_HOP_HEIGHT; - if (box_is_free(this, this.vx * TICK_DELTA, dy, this.vz * TICK_DELTA, blocked)) this.vy = WATER_HOP; + if (physics.box_is_free(this, this.vx * TICK_DELTA, dy, this.vz * TICK_DELTA, blocked)) this.vy = WATER_HOP; } // how much wider the view is than the fov option, between the last tick and this one diff --git a/client/mods.ts b/client/mods.ts index 8220fd7..f6a2d8e 100644 --- a/client/mods.ts +++ b/client/mods.ts @@ -14,6 +14,9 @@ import { AIR_ID } from "$/common/protocol.ts"; import type { Client } from "./client.ts"; import { code_url, fetch_verified } from "./handshake.ts"; import { GuiModScreen } from "./gui/gui_mod_screens.ts"; +import { clear_hooks, expose_engine, loading_mod } from "$/common/hooks.ts"; +import { common_engine } from "$/common/engine_modules.ts"; +import { client_engine } from "./engine_modules.ts"; // each loaded mod's credits file, for the credits screen export const mod_credits: { name: string; version: string; text: string }[] = []; @@ -110,6 +113,10 @@ export async function download_mods(listings: ModListing[], base: URL): Promise< const bytes = await fetch_verified(new URL(listing.file, base), listing.sha256, `${listing.name}`); const bmod = read_bmod(bytes, `${listing.id}.bmod`); if (bmod.manifest.id !== listing.id) throw new Error(`the server listed it as ${listing.id}`); + // the confirm screen said whether it has engine access, going by the listing + if ((bmod.manifest.engine_access ?? false) !== (listing.engine_access ?? false)) { + throw new Error("its engine access isn't what the server listed"); + } return bmod; } catch (e) { throw new ModLoadError(listing.id, (e as Error).message); @@ -133,26 +140,38 @@ export async function load_client_mods(listings: ModListing[], bmods: Bmod[]) { mod_names.clear(); for (const listing of listings) mod_names.set(listing.id, listing.name); + // for engine access mods. the last server's hooks go first + clear_hooks(); + expose_engine({ common: common_engine(), client: client_engine() }); + const as_mod = (bmod: Bmod, fn: () => Promise) => + loading_mod(bmod.manifest.id, bmod.manifest.engine_access ?? false, fn); + // every mod's shared rules first, so client scripts can count on any mod's being there block_rules = new BlockRules(run_mod); rules_setup = true; for (const [i, bmod] of bmods.entries()) { - if (!bmod.scripts.shared) continue; - const module = await import(script_url(bmod.scripts.shared)); - if (typeof module.setup !== "function") { - throw new ModLoadError(bmod.manifest.id, "the shared script doesn't export a setup function"); - } - await module.setup(shared_context(listings[i])); + const code = bmod.scripts.shared; + if (!code) continue; + await as_mod(bmod, async () => { + const module = await import(script_url(code)); + if (typeof module.setup !== "function") { + throw new ModLoadError(bmod.manifest.id, "the shared script doesn't export a setup function"); + } + await module.setup(shared_context(listings[i])); + }); } rules_setup = false; for (const [i, bmod] of bmods.entries()) { - if (!bmod.scripts.client) continue; - const module = await import(script_url(bmod.scripts.client)); - if (typeof module.setup !== "function") { - throw new ModLoadError(bmod.manifest.id, "the client script doesn't export a setup function"); - } - await module.setup(client_context(listings[i])); + const code = bmod.scripts.client; + if (!code) continue; + await as_mod(bmod, async () => { + const module = await import(script_url(code)); + if (typeof module.setup !== "function") { + throw new ModLoadError(bmod.manifest.id, "the client script doesn't export a setup function"); + } + await module.setup(client_context(listings[i])); + }); } } diff --git a/common/bmod.ts b/common/bmod.ts index a2ec69b..c8b3add 100644 --- a/common/bmod.ts +++ b/common/bmod.ts @@ -28,6 +28,7 @@ import { validate_tag, } from "./mod_data.ts"; import type { ModData } from "./mod_loader.ts"; +import { ENGINE_GLOBAL } from "./hooks.ts"; export const BMOD_EXTENSION = ".bmod"; @@ -169,6 +170,10 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod { scripts[side as ScriptSide] = code; } } + // what the bworld/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 bworld/engine, which needs "engine_access": true in manifest.json`); + } const credits = manifest.credits === undefined ? undefined : text(manifest.credits); if (manifest.credits !== undefined && credits === undefined) { problems.push(`manifest.json: credits ${manifest.credits} isn't in the file`); diff --git a/common/constants.ts b/common/constants.ts index d49477e..6ede867 100644 --- a/common/constants.ts +++ b/common/constants.ts @@ -4,6 +4,9 @@ export const TEXTURE_SIZE = 16; // the most a texture can be on either side, entity sprites are bigger than blocks' export const MAX_TEXTURE_SIZE = 256; +// the game's version, what mods' game_version is checked against. mods with engine_access are tied to its minor version +export const GAME_VERSION = "0.1.0"; + export const TICKS_PER_SECOND = 20; export const TICK_DELTA = 1 / TICKS_PER_SECOND; diff --git a/common/engine_modules.ts b/common/engine_modules.ts new file mode 100644 index 0000000..64abacf --- /dev/null +++ b/common/engine_modules.ts @@ -0,0 +1,25 @@ +// what engine access mods get as engine.common, on every side. see docs/modding/misc/engine.md +import { EverythingRegistry } from "./everything_registry.ts"; +import { Container, ContainerSlot, ItemStack } from "./inventory.ts"; +import { BlockRules } from "./block_rules.ts"; +import { Tags } from "./tags.ts"; +import { CommandDispatcher } from "./commands.ts"; +import { OverworldTerrain } from "./worldgen/terrain.ts"; +import { BIOMES } from "./worldgen/overworld.ts"; +import { physics } from "./physics.ts"; + +// built when it's exposed, not when this module loads, so import cycles can't leave anything undefined +export function common_engine() { + return { + EverythingRegistry, + ItemStack, + Container, + ContainerSlot, + BlockRules, + Tags, + CommandDispatcher, + OverworldTerrain, + BIOMES, + physics, + }; +} diff --git a/common/hooks.ts b/common/hooks.ts new file mode 100644 index 0000000..39d1175 --- /dev/null +++ b/common/hooks.ts @@ -0,0 +1,248 @@ +// engine access: hooks on the engine's own methods, like neoforge's mixins, and the global the bworld/engine shim reads. +// see docs/modding/misc/engine.md and docs/modding_plan.md +import { GAME_VERSION } from "./constants.ts"; + +// deno-lint-ignore no-explicit-any +type Method = (...args: any[]) => any; +type MethodOf = T[K] extends Method ? T[K] : never; + +export interface HookHandlers { + // runs first. change args in place, or return { result } to skip the method and everything after + before?(self: T, args: Parameters>): { result: ReturnType> } | void; + // wraps the method, calling original (or not) + replace?( + self: T, + args: Parameters>, + original: (...args: Parameters>) => ReturnType>, + ): ReturnType>; + // runs last, and returns the result the caller gets. returning undefined keeps the result it was given + after?( + self: T, + args: Parameters>, + result: ReturnType>, + ): ReturnType> | void; + // lower runs earlier, the default is 1000. ties go in load order + priority?: number; +} + +export type Hook = ( + target: T, + method: K, + handlers: HookHandlers, +) => () => void; + +// deno-lint-ignore no-explicit-any +type AnyHandlers = HookHandlers; + +interface Entry { + mod: string; + handlers: AnyHandlers; + priority: number; + // when it was hooked, for ties + order: number; +} + +// one hooked method. the original goes back once its last hook is gone, so a method nobody hooks costs nothing +interface Hooked { + target: object; + key: PropertyKey; + name: string; + // how it was before the first hook: its own property on target, or inherited when undefined + descriptor: PropertyDescriptor | undefined; + original: Method; + entries: Entry[]; +} + +const hooked = new Map>(); +let next_order = 0; + +// the mod whose script is loading or running setup. hooks are made then, so each one knows its mod +let loading: { mod: string; engine_access: boolean } | undefined; + +function log(mod: string, what: string, e: unknown) { + console.error(`[${mod}] ${what} threw:`, e); +} + +// the wrapper that replaces the method. it's made again whenever the hooks change, with only the steps they need, so +// a method with only after hooks doesn't walk empty before and replace lists every call +function wrapper(state: Hooked): Method { + const { original, name } = state; + const before = state.entries.filter((e) => e.handlers.before); + const replace = state.entries.filter((e) => e.handlers.replace); + const after = state.entries.filter((e) => e.handlers.after); + + // the replace hooks, the first outermost, around the original + // deno-lint-ignore no-explicit-any + const call = (self: any, args: any[], i: number): any => { + if (i === replace.length) return original.apply(self, args); + const { mod, handlers } = replace[i]; + let called = false; + let inner: unknown; + const next = (...next_args: unknown[]) => { + called = true; + inner = call(self, next_args, i + 1); + return inner; + }; + try { + return handlers.replace!(self, args, next); + } catch (e) { + log(mod, `a replace hook on ${name}`, e); + // skipped: what it got from the method if it called it, so the method doesn't run twice + return called ? inner : call(self, args, i + 1); + } + }; + + // deno-lint-ignore no-explicit-any + return function (this: any, ...args: any[]) { + for (const { mod, handlers } of before) { + try { + const skip = handlers.before!(this, args); + if (skip) return skip.result; + } catch (e) { + log(mod, `a before hook on ${name}`, e); + } + } + let result = call(this, args, 0); + for (const { mod, handlers } of after) { + try { + const changed = handlers.after!(this, args, result); + if (changed !== undefined) result = changed; + } catch (e) { + log(mod, `an after hook on ${name}`, e); + } + } + return result; + }; +} + +function install(state: Hooked) { + if (state.entries.length > 0) { + Object.defineProperty(state.target, state.key, { + value: wrapper(state), + writable: true, + configurable: true, + enumerable: state.descriptor?.enumerable ?? false, + }); + return; + } + if (state.descriptor) { + Object.defineProperty(state.target, state.key, state.descriptor); + } else { + delete (state.target as Record)[state.key]; + } + hooked.get(state.target)?.delete(state.key); +} + +function method_name(target: object, key: PropertyKey) { + const owner = typeof target === "function" ? target.name : target.constructor?.name; + return owner && owner !== "Object" ? `${owner}.${String(key)}` : String(key); +} + +// hooks target's method for the mod that's loading. see HookHandlers +export const hook: Hook = (target, method, handlers) => { + if (!loading) throw new Error("hook can only be called while a mod's script loads or runs its setup"); + if (!loading.engine_access) { + throw new Error(`${loading.mod} hooks the engine without "engine_access" in its manifest`); + } + const key = method as PropertyKey; + let by_key = hooked.get(target); + let state = by_key?.get(key); + if (!state) { + const original = (target as Record)[key]; + if (typeof original !== "function") throw new Error(`${method_name(target, key)} isn't a method`); + if (!Object.isExtensible(target)) throw new Error(`${method_name(target, key)} can't be hooked`); + state = { + target, + key, + name: method_name(target, key), + descriptor: Object.getOwnPropertyDescriptor(target, key), + original: original as Method, + entries: [], + }; + if (state.descriptor && !state.descriptor.configurable) { + throw new Error(`${state.name} can't be hooked`); + } + if (!by_key) hooked.set(target, by_key = new Map()); + by_key.set(key, state); + } + const entry: Entry = { + mod: loading.mod, + handlers: handlers as AnyHandlers, + priority: handlers.priority ?? 1000, + order: next_order++, + }; + state.entries.push(entry); + state.entries.sort((a, b) => a.priority - b.priority || a.order - b.order); + install(state); + + const hooked_state = state; + return () => { + const i = hooked_state.entries.indexOf(entry); + if (i === -1) return; + hooked_state.entries.splice(i, 1); + install(hooked_state); + }; +}; + +// puts every hooked method back, before a game loads its mods. tests start many games in one realm, and a client +// joining another server leaves the last one's mods behind +export function clear_hooks() { + for (const by_key of [...hooked.values()]) { + for (const state of [...by_key.values()]) { + state.entries = []; + install(state); + } + } + hooked.clear(); +} + +// runs fn as the mod: hook knows whose hooks it makes, and bworld/engine refuses mods without engine_access +export async function loading_mod(mod: string, engine_access: boolean, fn: () => Promise): Promise { + const previous = loading; + loading = { mod, engine_access }; + try { + return await fn(); + } finally { + loading = previous; + } +} + +// the engine's modules on each side, what mods get as engine +export interface EngineModules { + common?: Record; + server?: Record; + client?: Record; +} + +// what bworld/engine reads, see common/mod_api/engine.ts +export interface EngineGlobal { + version: string; + engine: EngineModules; + hook: Hook; + // throws unless the mod that's loading has engine_access + check_access(): void; +} + +export const ENGINE_GLOBAL = "__bworld_engine"; + +// puts a side's modules where bworld/engine finds them. a realm with the server and a client in it, like tests, gets +// both +export function expose_engine(modules: EngineModules) { + const global = globalThis as unknown as Record; + const existing = global[ENGINE_GLOBAL]; + if (existing) { + Object.assign(existing.engine, modules); + return; + } + global[ENGINE_GLOBAL] = { + version: GAME_VERSION, + engine: { ...modules }, + hook, + check_access() { + if (!loading) throw new Error("bworld/engine can only be imported by a mod's script"); + if (!loading.engine_access) { + throw new Error(`${loading.mod} imports bworld/engine without "engine_access" in its manifest`); + } + }, + }; +} diff --git a/common/mod_api/engine.ts b/common/mod_api/engine.ts new file mode 100644 index 0000000..2875e3b --- /dev/null +++ b/common/mod_api/engine.ts @@ -0,0 +1,30 @@ +// bworld/engine: engine access, for what the game api doesn't cover yet. a mod needs "engine_access": true and a +// game_version within one minor version in its manifest. see docs/modding/misc/engine.md +// +// this is bundled into each mod that imports it, so it only imports types: the engine and hook are the game's own, +// read from the global the game sets up before it loads mods +import type { EngineGlobal, Hook } from "../hooks.ts"; +import type { common_engine } from "../engine_modules.ts"; +import type { server_engine } from "../../server/game/engine_modules.ts"; +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 +export interface Engine { + common: ReturnType; + server: ReturnType; + client: ReturnType; +} + +const api = (globalThis as unknown as Record)["__bworld_engine"]; +if (!api) throw new Error("bworld/engine only works in a mod's script, loaded by the game"); +api.check_access(); + +export const engine = api.engine as Engine; +// the version of the game that's running, like "0.4.2" +export const game_version: string = api.version; +// hooks a method of target, usually a class's prototype, so every instance already made changes too. returns a +// function that unhooks it +export const hook: Hook = api.hook; diff --git a/common/mod_data.ts b/common/mod_data.ts index a649c96..0375b86 100644 --- a/common/mod_data.ts +++ b/common/mod_data.ts @@ -13,6 +13,7 @@ import { } from "./everything_registry.ts"; import { type BlockPart, type BlockVariant, MODEL_FACES, type ModelFace } from "./block_models.ts"; import { expand_items, list_matches } from "./tags.ts"; +import { GAME_VERSION } from "./constants.ts"; export const FORMAT_VERSION = 1; export const ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+$/; @@ -35,6 +36,8 @@ export interface ManifestJson { version: string; authors?: string[]; game_version?: string; + // imports bworld/engine to reach into the engine and hook its methods. needs game_version within one minor version + engine_access?: boolean; dependencies?: { id: string; version: string }[]; scripts?: { server?: string; client?: string; worldgen?: string; shared?: string }; credits?: string; @@ -448,6 +451,13 @@ export function validate_manifest(json: unknown, folder_name: string): Problems if (typeof json.version !== "string" || !/^\d+\.\d+\.\d+/.test(json.version)) { problems.push("version must be semver, like 1.0.0"); } + if (json.engine_access !== undefined && typeof json.engine_access !== "boolean") { + problems.push("engine_access must be true or false"); + } + if (json.engine_access === true) { + const problem = engine_version_problem(json.game_version); + if (problem) problems.push(problem); + } if (json.dependencies !== undefined) { if (!Array.isArray(json.dependencies)) { problems.push("dependencies must be a list"); @@ -474,6 +484,20 @@ export function validate_manifest(json: unknown, folder_name: string): Problems return problems; } +// engine access isn't a stable api: a mod using it names one minor version of the game, like "~0.4.0" or "0.4.2", and +// loading it on another is an error. game is the version it's loading on +export function engine_version_problem(range: unknown, game = GAME_VERSION): string | undefined { + const [major, minor, patch] = game.split(".").map(Number); + const match = typeof range === "string" ? range.match(/^(~?)(\d+)\.(\d+)\.(\d+)$/) : null; + if (!match) { + return `engine_access needs game_version to be one minor version, like "~${major}.${minor}.0"`; + } + const [, tilde, m, n, p] = match; + const fits = Number(m) === major && Number(n) === minor && + (tilde ? Number(p) <= patch : Number(p) === patch); + if (!fits) return `uses engine_access for game_version ${range}, this is the game's ${game}`; +} + export function validate_block(json: unknown): Problems { if (!is_object(json)) return ["block must be an object"]; const problems = validate_id(json.id, "id"); diff --git a/common/mod_loader.ts b/common/mod_loader.ts index da564c1..06334f0 100644 --- a/common/mod_loader.ts +++ b/common/mod_loader.ts @@ -52,6 +52,8 @@ export interface ModListing { // where it's served from, relative to the server's root. named by its hash, so it never changes file: string; size: number; + // it imports bworld/engine, see docs/modding/misc/engine.md. the confirm screen for other sites says so + engine_access?: boolean; } export class RecipeBook { diff --git a/common/physics.ts b/common/physics.ts index 5e95d94..d8962d1 100644 --- a/common/physics.ts +++ b/common/physics.ts @@ -243,3 +243,7 @@ export function eyes_in_water( ): boolean { return is_liquid(Math.floor(body.x), Math.floor(body.y + eye_height), Math.floor(body.z)); } + +// what the engine calls through, so engine access mods can hook these like methods (module exports can't be +// reassigned). see docs/modding/misc/engine.md +export const physics = { move_body, back_off_from_edge, box_is_free, in_water, eyes_in_water }; diff --git a/common/worldgen_loader.ts b/common/worldgen_loader.ts index da0f712..4db22a9 100644 --- a/common/worldgen_loader.ts +++ b/common/worldgen_loader.ts @@ -3,11 +3,15 @@ import type { WorldgenContext } from "$/common/mod_api/worldgen.ts"; import type { OreJson } from "$/common/mod_data.ts"; import type { WorldgenSetup } from "./generation.ts"; import { ModLoadError } from "./mod_loader.ts"; +import { loading_mod } from "./hooks.ts"; -export async function load_worldgen(scripts: { mod: string; url: string }[], ores: OreJson[]): Promise { +export async function load_worldgen( + scripts: { mod: string; url: string; engine_access?: boolean }[], + ores: OreJson[], +): Promise { const setup: WorldgenSetup = { ores, features: [] }; - for (const { mod, url } of scripts) { + for (const { mod, url, engine_access } of scripts) { const ctx: WorldgenContext = { register_feature(id, generate) { if (!id.startsWith(`${mod}:`)) { @@ -26,11 +30,13 @@ export async function load_worldgen(scripts: { mod: string; url: string }[], ore }, }; - 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 loading_mod(mod, engine_access ?? false, async () => { + 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); + }); } return setup; diff --git a/deno.json b/deno.json index d386052..9df440d 100644 --- a/deno.json +++ b/deno.json @@ -26,6 +26,7 @@ "bworld/client": "./common/mod_api/client.ts", "bworld/worldgen": "./common/mod_api/worldgen.ts", "bworld/shared": "./common/mod_api/shared.ts", + "bworld/engine": "./common/mod_api/engine.ts", "@gfx/canvas-wasm": "jsr:@gfx/canvas-wasm@^0.4.2", "@paulaboks/rng": "jsr:@paulaboks/rng@^0.0.3", "@std/assert": "jsr:@std/assert@^1.0.0", diff --git a/docs/modding/gettingstarted/modfiles.md b/docs/modding/gettingstarted/modfiles.md index 2117b16..f6b1c3b 100644 --- a/docs/modding/gettingstarted/modfiles.md +++ b/docs/modding/gettingstarted/modfiles.md @@ -71,7 +71,8 @@ matter, the `id` inside does, except for [tags](../resources/tags.md), whose id | `description` | no | A sentence or two. | | `version` | yes | The mod's own version, semver like `1.0.0`. | | `authors` | no | A list of names. | -| `game_version` | no | The bworld versions the mod works with, as a semver range. Not checked yet. | +| `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 `bworld/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` and `worldgen` scripts. See [Sides](../concepts/sides.md). | | `credits` | no | A markdown file for licenses and thanks, shown on the Credits screen. Raw HTML in it is shown as text. | @@ -93,7 +94,7 @@ so they can import other files and packages, but code imported by several script When a mod's folder has a `deno.json`, its scripts are bundled and typechecked with it, so the mod can have its own imports and npm or JSR packages. Mods without one use the `deno.json` of the folder the build runs in, like the mods in this repository. That config maps the API types, which scripts import as `bworld/server`, `bworld/client`, -`bworld/shared` and `bworld/worldgen`: +`bworld/shared` and `bworld/worldgen`, and [`bworld/engine`](../misc/engine.md): ```ts import type { ServerContext } from "bworld/server"; diff --git a/docs/modding/misc/engine.md b/docs/modding/misc/engine.md new file mode 100644 index 0000000..1eea567 --- /dev/null +++ b/docs/modding/misc/engine.md @@ -0,0 +1,84 @@ +# Engine Access + +For what the Game API doesn't cover yet, like a new kind of rendering, different player physics or a new entity type, a +mod can reach into the engine itself and hook its methods, like NeoForge's mixins. It isn't a stable API: anything in +the engine can change in any version, so a mod using it is tied to one minor version of the game. + +Prefer the Game API. Many mods hooking the same thing is a sign it should become part of it. + +## Asking for It + +```json +{ "engine_access": true, "game_version": "~0.1.0" } +``` + +`game_version` has to be one minor version: `~0.1.0` (0.1.0 and later 0.1 patches) or an exact `0.1.2`. Loading the mod +on another version is a load error, so the server doesn't start with it. + +Without `engine_access`, importing `bworld/engine` is an error in `check-mods`, when a `.bmod` loads, and when the +script runs. When players join from another site, the confirm screen marks mods that change the engine. + +## Hooking + +```ts +// server.ts: broken blocks drop twice +import { engine, hook } from "bworld/engine"; + +export function setup() { + hook(engine.server.GameServer.prototype, "pop_item", { + after(game, [x, y, z, stack], entity) { + game.spawn_item(entity.x, entity.y, entity.z, stack.clone()); + return entity; + }, + }); +} +``` + +`hook(target, method, handlers)` changes `target[method]`, usually on a class's prototype, so every instance already +made changes too. It returns a function that unhooks it. + +| Handler | Runs | +| ------------------------------- | ------------------------------------------------------------------------------------------------------- | +| `before(self, args)` | First. Change `args` in place, or return `{ result }` to skip the method and every other hook after it. | +| `replace(self, args, original)` | Instead of the method. Call `original(...args)` to run it, or don't. | +| `after(self, args, result)` | Last. Returns the result the caller gets. Returning `undefined` keeps the result it was given. | +| `priority` | Lower runs earlier, the default is `1000`. Ties go in load order. | + +- Several mods can hook one method. `before` hooks run in priority order, `replace` hooks nest with the earliest + 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. +- 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`, `OverworldTerrain`, `physics` | +| `server` | server scripts | `GameServer`, `ServerWorld`, `ServerPlayer`, `Entity`, `Mob`, `ModRuntime`, the mob goals | +| `client` | client scripts | `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. +`bworld/engine` also exports `game_version`, the version of the game that's running. + +- Module exports can't be reassigned, so functions mods may want to change are on plain objects the engine calls + 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. Worldgen scripts run on the server, next to the server script, so hooking `engine.common.OverworldTerrain` + from either changes the terrain. + +## Performance + +Hooking is cheap to set up: hook in `setup`, 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. + +## 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 +[Security](../concepts/security.md). diff --git a/docs/modding_plan.md b/docs/modding_plan.md index 4630152..48beb04 100644 --- a/docs/modding_plan.md +++ b/docs/modding_plan.md @@ -41,11 +41,15 @@ The code is in `common/mod_loader.ts`, `common/mod_data.ts`, `common/mod_check.t **In the API types but throwing:** forms, HUD elements, keybinds, `g.slider`, `register_terrain`. -**Not built at all:** common scripts, the registry freeze and hash, overrides, engine access. +**Not built at all:** common scripts, the registry freeze and hash, overrides. + +**Engine access** is built (phase 3): `bworld/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`, +`common/mod_api/engine.ts` and the `engine_modules.ts` of each side. **Known gaps:** -- Manifest `dependencies` version ranges and `game_version` aren't checked. +- Manifest `dependencies` version ranges aren't checked, and `game_version` only is for engine access mods. - Mods can't throw a `CommandError` the server recognizes: it's checked with `instanceof`, and the class isn't in the API, so a mod's bundled copy is a different class. Export it from `bworld/server`, or recognize it by `name`. - Tools only lose durability when their owner dies. Nothing else uses it. @@ -183,8 +187,8 @@ function hook(target: T, method: K, handlers: { before?(self: T, args: Parameters): { result: ReturnType } | void; // wraps the method, calling original (or not) replace?(self: T, args: Parameters, original: T[K]): ReturnType; - // runs last, and returns the result the caller gets - after?(self: T, args: Parameters, result: ReturnType): ReturnType; + // runs last, and returns the result the caller gets. undefined keeps the result it was given + after?(self: T, args: Parameters, result: ReturnType): ReturnType | void; // lower runs earlier, the default is 1000. ties go in load order priority?: number; }): () => void; // unhook @@ -196,6 +200,9 @@ function hook(target: T, method: K, handlers: { - 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 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 through (like `engine.common.physics.move_body`). `#private` members can't be hooked, so they're kept for things with rules that must hold, like a container's slots. diff --git a/server/game/engine_modules.ts b/server/game/engine_modules.ts new file mode 100644 index 0000000..1356372 --- /dev/null +++ b/server/game/engine_modules.ts @@ -0,0 +1,52 @@ +// what engine access mods get as engine.server, in server scripts. see docs/modding/misc/engine.md +import { GameServer } from "./game_server.ts"; +import { ServerWorld } from "./world.ts"; +import { ServerPlayer } from "./player.ts"; +import { ModRuntime } from "./mod_runtime.ts"; +import { Menu, PlayerMenu } from "./menu.ts"; +import { NaturalSpawner } from "./natural_spawner.ts"; +import { Entity } from "./entity/entity.ts"; +import { LivingEntity } from "./entity/living_entity.ts"; +import { Mob } from "./entity/mob.ts"; +import { ItemEntity } from "./entity/item_entity.ts"; +import { EntityManager } from "./entity/entity_manager.ts"; +import { + FloatGoal, + Goal, + GoalSelector, + HurtByTargetGoal, + LookAtPlayerGoal, + MeleeAttackGoal, + NearestAttackablePlayerGoal, + PanicGoal, + RandomLookAroundGoal, + RandomStrollGoal, +} from "./entity/goals.ts"; + +// built when it's exposed, not when this module loads, so import cycles can't leave anything undefined +export function server_engine() { + return { + GameServer, + ServerWorld, + ServerPlayer, + ModRuntime, + Menu, + PlayerMenu, + NaturalSpawner, + Entity, + LivingEntity, + Mob, + ItemEntity, + EntityManager, + Goal, + GoalSelector, + FloatGoal, + RandomStrollGoal, + PanicGoal, + LookAtPlayerGoal, + RandomLookAroundGoal, + MeleeAttackGoal, + NearestAttackablePlayerGoal, + HurtByTargetGoal, + }; +} diff --git a/server/game/entity/entity.ts b/server/game/entity/entity.ts index e4f7771..d9458db 100644 --- a/server/game/entity/entity.ts +++ b/server/game/entity/entity.ts @@ -8,7 +8,7 @@ import { TICKS_PER_SECOND } from "$/common/constants.ts"; import type { BlockRegistry } from "$/common/everything_registry.ts"; import type { ItemStack } from "$/common/inventory.ts"; import type { Shape } from "$/common/block_shapes.ts"; -import { type Collisions, eyes_in_water, in_water, move_body } from "$/common/physics.ts"; +import { type Collisions, physics } from "$/common/physics.ts"; import type { EntityData, EntityEvent, EntityInfo } from "$/common/protocol.ts"; import type { ServerPlayer } from "../player.ts"; @@ -247,19 +247,19 @@ export abstract class Entity { } update_in_water() { - this.in_water = in_water(this, (x, y, z) => this.level.is_liquid(x, y, z)); + this.in_water = physics.in_water(this, (x, y, z) => this.level.is_liquid(x, y, z)); } // its eyes are in water, so it can't breathe get eyes_in_water() { - return eyes_in_water(this, this.eye_height, (x, y, z) => this.level.is_liquid(x, y, z)); + return physics.eyes_in_water(this, this.eye_height, (x, y, z) => this.level.is_liquid(x, y, z)); } // falls and moves by its velocity for one tick (see move_body), and counts how far it fell. returns what it hit move(): Collisions { const is_solid = (x: number, y: number, z: number) => this.level.collision_shape(x, y, z); const from_y = this.y; - const collisions = move_body( + const collisions = physics.move_body( this, this.no_gravity ? 0 : this.gravity, is_solid, diff --git a/server/game/load_mods.ts b/server/game/load_mods.ts index b0e57dc..cea96a3 100644 --- a/server/game/load_mods.ts +++ b/server/game/load_mods.ts @@ -9,6 +9,9 @@ import { ModRuntime } from "./mod_runtime.ts"; import { register_entity_type } from "./entity/entity_types.ts"; import { mod_entity_factory } from "./entity/mod_entity.ts"; import { set_effect_types } from "./entity/effects.ts"; +import { clear_hooks, expose_engine } from "$/common/hooks.ts"; +import { common_engine } from "$/common/engine_modules.ts"; +import { server_engine } from "./engine_modules.ts"; export interface ServerModSource { listing: ModListing; @@ -25,13 +28,19 @@ export async function start_game( default_seed: string, mods: ServerModSource[], ): Promise { + // for engine access mods. the last game's hooks go first, a realm only runs one game at a time + clear_hooks(); + expose_engine({ common: common_engine(), server: server_engine() }); + const recipes = register_mod_data(mods.map((mod) => ({ id: mod.listing.id, data: mod.data }))); for (const mod of mods) { for (const json of mod.data.entities) register_entity_type(json.id, mod_entity_factory(json)); } const worldgen_scripts = mods.flatMap((mod) => - mod.worldgen_url ? [{ mod: mod.listing.id, url: mod.worldgen_url }] : [] + mod.worldgen_url + ? [{ mod: mod.listing.id, url: mod.worldgen_url, engine_access: mod.listing.engine_access }] + : [] ); const worldgen = await load_worldgen(worldgen_scripts, recipes.ores); @@ -48,15 +57,11 @@ export async function start_game( // 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 ? [{ mod: mod.listing.id, version: mod.listing.version, url: mod.shared_url }] : [] - ), + mods.flatMap((mod) => mod.shared_url ? [{ ...script_of(mod), url: mod.shared_url }] : []), ); await runtime.load_scripts( game, - mods.flatMap((mod) => - mod.server_url ? [{ mod: mod.listing.id, version: mod.listing.version, url: mod.server_url }] : [] - ), + mods.flatMap((mod) => mod.server_url ? [{ ...script_of(mod), url: mod.server_url }] : []), ); runtime.finish_setup(); runtime.after.server_start.emit({}); @@ -64,6 +69,10 @@ export async function start_game( return game; } +function script_of(mod: ServerModSource) { + return { mod: mod.listing.id, version: mod.listing.version, engine_access: mod.listing.engine_access ?? false }; +} + export function data_url(code: string) { const bytes = new TextEncoder().encode(code); let binary = ""; diff --git a/server/game/mod_runtime.ts b/server/game/mod_runtime.ts index afbe689..feb0386 100644 --- a/server/game/mod_runtime.ts +++ b/server/game/mod_runtime.ts @@ -7,6 +7,7 @@ import { covers_face } from "$/common/block_shapes.ts"; import { BlockRules } from "$/common/block_rules.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, @@ -87,6 +88,14 @@ 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 bworld/engine +interface ScriptSource { + mod: string; + version: string; + url: string; + engine_access: boolean; +} + export function run_guarded(mod: string, what: string, fn: () => T): T | undefined { const previous = running_mod; running_mod = mod; @@ -213,56 +222,64 @@ export class ModRuntime { // 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 - async load_shared_scripts(game: GameServer, scripts: { mod: string; version: string; url: string }[]) { + async load_shared_scripts(game: GameServer, scripts: ScriptSource[]) { this.game = game; - for (const { mod, version, url } of scripts) { - const module = await import(url); - if (typeof module.setup !== "function") { - throw new ModLoadError(mod, "the shared script doesn't export a setup function"); - } - const { world } = this.#context(mod, version); - const ctx: SharedContext = { - mod: { id: mod, version }, - side: "server", - tags: tag_api(), - world: { - get_block: world.get_block, - get_state: world.get_state, - set_state: world.set_state, - is_face_sturdy: world.is_face_sturdy, - }, - components: { - register_block: (id, rules) => { - if (!this.#setting_up) throw new ModLoadError(mod, "rules can only be registered during setup"); - if (!id.startsWith(`${mod}:`)) { - throw new ModLoadError(mod, `component ${id} must be in the namespace "${mod}"`); - } - this.rules.register(mod, id, rules); - }, - }, - }; - running_mod = mod; - try { - await module.setup(ctx); - } finally { - running_mod = ""; - } + for (const { mod, version, url, engine_access } of scripts) { + await loading_mod(mod, engine_access, () => this.#load_shared_script(mod, version, url)); } } - async load_scripts(game: GameServer, scripts: { mod: string; version: string; url: string }[]) { + async #load_shared_script(mod: string, version: string, url: string) { + const module = await import(url); + if (typeof module.setup !== "function") { + throw new ModLoadError(mod, "the shared script doesn't export a setup function"); + } + const { world } = this.#context(mod, version); + const ctx: SharedContext = { + mod: { id: mod, version }, + side: "server", + tags: tag_api(), + world: { + get_block: world.get_block, + get_state: world.get_state, + set_state: world.set_state, + is_face_sturdy: world.is_face_sturdy, + }, + components: { + register_block: (id, rules) => { + if (!this.#setting_up) throw new ModLoadError(mod, "rules can only be registered during setup"); + if (!id.startsWith(`${mod}:`)) { + throw new ModLoadError(mod, `component ${id} must be in the namespace "${mod}"`); + } + this.rules.register(mod, id, rules); + }, + }, + }; + 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 } of scripts) { - 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)); - } finally { - running_mod = ""; - } + for (const { mod, version, url, engine_access } of scripts) { + await loading_mod(mod, engine_access, () => this.#load_script(mod, version, url)); + } + } + + async #load_script(mod: string, version: string, url: string) { + 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)); + } finally { + running_mod = ""; } } diff --git a/server/load_bmods.ts b/server/load_bmods.ts index 859d549..3140cf3 100644 --- a/server/load_bmods.ts +++ b/server/load_bmods.ts @@ -82,6 +82,7 @@ export async function load_bmods(dir: string, engine_textures: Iterable) sha256, file: `mods/${sha256}${BMOD_EXTENSION}`, size: client_bytes.length, + ...(bmod.manifest.engine_access ? { engine_access: true } : {}), }, }; })); diff --git a/tests/engine_access_test.ts b/tests/engine_access_test.ts new file mode 100644 index 0000000..0b9d6ad --- /dev/null +++ b/tests/engine_access_test.ts @@ -0,0 +1,339 @@ +// engine access: mods importing bworld/engine and hooking the engine's methods. see docs/modding/misc/engine.md +import { assert, assertEquals, assertStringIncludes, assertThrows } from "@std/assert"; +import { clear_hooks, expose_engine, hook, loading_mod } from "$/common/hooks.ts"; +import { GAME_VERSION } from "$/common/constants.ts"; +import { engine_version_problem, validate_manifest } from "$/common/mod_data.ts"; +import { ItemStack } from "$/common/inventory.ts"; +import { EverythingRegistry } from "$/common/everything_registry.ts"; +import { read_bmod } from "$/common/bmod.ts"; +import { load_and_check } from "$/tools/check_mods.ts"; +import { pack_mod } from "$/tools/pack_mod.ts"; +import { load_client_mods } from "$/client/mods.ts"; +import { LocalPlayer } from "$/client/entity/local_player.ts"; +import { Options } from "$/client/options.ts"; +import type { Client } from "$/client/client.ts"; +import type { ModListing } from "$/common/mod_loader.ts"; +import { copy_dir, test_game } from "./helpers.ts"; + +const [MAJOR, MINOR] = GAME_VERSION.split("."); +const THIS_MINOR = `~${MAJOR}.${MINOR}.0`; + +// a mod in dir with these scripts, as { side: [file, code] } +function write_mod( + dir: string, + id: string, + scripts: Record, + 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}/manifest.json`, + JSON.stringify({ format_version: 1, id, name: id, version: "1.0.0", scripts: paths, ...manifest }), + ); +} + +// mods/bworld and the mods write adds, in a temp folder +function mods_dir(write: (dir: string) => void) { + const dir = Deno.makeTempDirSync({ prefix: "bworld_engine_" }); + copy_dir("mods/bworld", `${dir}/bworld`); + write(dir); + return dir; +} + +// a class to hook in the tests that call hook directly, made again for each so their hooks don't meet +function counter_class() { + return class Counter { + count = 0; + add(amount: number) { + this.count += amount; + return this.count; + } + }; +} + +// runs fn as a mod with engine access, the way the loaders do +function as_mod(mod: string, fn: () => T, engine_access = true): Promise { + return loading_mod(mod, engine_access, () => Promise.resolve(fn())); +} + +// what console.error got while fn ran +async function errors_during(fn: () => unknown): Promise { + const errors: string[] = []; + const original = console.error; + console.error = (...args: unknown[]) => errors.push(args.map(String).join(" ")); + try { + await fn(); + } finally { + console.error = original; + } + return errors; +} + +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 "bworld/engine"; + export function setup() { + hook(engine.server.GameServer.prototype, "pop_item", { + after(game, [x, y, z, stack], entity) { + game.spawn_item(entity.x, entity.y, entity.z, stack.clone()); + return entity; + }, + }); + }`, + ], + }) + ); + const { game } = await test_game(dir); + const items = () => game.entities.entities_near(0.5, 100, 0.5, 4).length; + const before = items(); + game.pop_item(0, 100, 0, new ItemStack("bworld:stone", 1)); + assertEquals(items(), before + 2); + Deno.removeSync(dir, { recursive: true }); +}); + +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 "bworld/engine"; + // no ground anywhere, so it's all sea + export function setup() { + hook(engine.common.OverworldTerrain.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"); + Deno.removeSync(dir, { recursive: true }); + + // the next game doesn't have it + const { game: plain } = await test_game("mods", undefined, "engine-access-flat-sea"); + assert(plain.world.get_block_id(8, 10, 8) !== "bworld:water"); +}); + +Deno.test("a client mod hooks LocalPlayer from its .bmod", async () => { + const dir = Deno.makeTempDirSync({ prefix: "bworld_engine_" }); + write_mod(dir, "floaty", { + client: [ + "client.ts", + `import { engine, hook } from "bworld/engine"; + // everyone is a block higher than they think + export function setup() { + hook(engine.client.LocalPlayer.prototype, "set_position", { + before(_player, args) { + args[1] += 1; + }, + }); + }`, + ], + }); + const mod = load_and_check(dir)[0]; + assertEquals(mod.report.errors, []); + const bmod = read_bmod(await pack_mod(mod), "floaty.bmod"); + const listing: ModListing = { + id: "floaty", + name: "floaty", + version: "1.0.0", + sha256: "", + file: "", + size: 0, + engine_access: true, + }; + EverythingRegistry.clear(); + await load_client_mods([listing], [bmod]); + + const client = { options: new Options(), level: {}, connection: { send() {} } }; + const player = new LocalPlayer(client as unknown as Client, "id", "alice"); + player.set_position(0, 10, 0); + assertEquals(player.y, 11); + clear_hooks(); + Deno.removeSync(dir, { recursive: true }); +}); + +Deno.test("hooks on one method run in priority order, then load order", async () => { + const Counter = counter_class(); + const order: string[] = []; + const add = (name: string, priority?: number) => + hook(Counter.prototype, "add", { + priority, + before() { + order.push(`${name} before`); + }, + replace(_self, args, original) { + order.push(`${name} replace`); + return original(...args); + }, + after() { + order.push(`${name} after`); + }, + }); + await as_mod("late", () => add("late", 2000)); + await as_mod("first", () => add("first")); + await as_mod("second", () => add("second")); + await as_mod("early", () => add("early", 0)); + + assertEquals(new Counter().add(1), 1); + assertEquals(order, [ + "early before", + "first before", + "second before", + "late before", + // the first is outermost + "early replace", + "first replace", + "second replace", + "late replace", + "early after", + "first after", + "second after", + "late after", + ]); + clear_hooks(); +}); + +Deno.test("before can change args or skip the method, after chains the result", async () => { + const Counter = counter_class(); + await as_mod("a", () => { + hook(Counter.prototype, "add", { + before(_self, args) { + args[0] *= 10; + }, + }); + hook(Counter.prototype, "add", { + before: (_self, [amount]) => amount < 0 ? { result: -1 } : undefined, + }); + hook(Counter.prototype, "add", { after: (_self, _args, result) => result + 1 }); + hook(Counter.prototype, "add", { after: (_self, _args, result) => result * 2 }); + }); + const counter = new Counter(); + assertEquals(counter.add(1), 22); + assertEquals(counter.count, 10); + // skipped: no method, no after hooks + assertEquals(counter.add(-5), -1); + assertEquals(counter.count, 10); + clear_hooks(); +}); + +Deno.test("a throwing hook is logged under its mod and skipped", async () => { + const Counter = counter_class(); + await as_mod("broken", () => { + hook(Counter.prototype, "add", { + before() { + throw new Error("before"); + }, + }); + hook(Counter.prototype, "add", { + replace(_self, args, original) { + original(...args); + throw new Error("replace"); + }, + }); + hook(Counter.prototype, "add", { + after() { + throw new Error("after"); + }, + }); + }); + const counter = new Counter(); + let result = 0; + const errors = await errors_during(() => result = counter.add(3)); + // the method ran once, with what the throwing replace hook got from it + assertEquals(result, 3); + assertEquals(counter.count, 3); + assertEquals(errors.length, 3); + for (const error of errors) assertStringIncludes(error, "[broken]"); + assertStringIncludes(errors[0], "a before hook on Counter.add threw"); + clear_hooks(); +}); + +Deno.test("unhooking puts the original method back", async () => { + const Counter = counter_class(); + const original = Counter.prototype.add; + const unhook = await as_mod("a", () => hook(Counter.prototype, "add", { after: () => 100 })); + assertEquals(new Counter().add(1), 100); + unhook(); + assertEquals(Counter.prototype.add, original); + assert(!Object.hasOwn(Counter.prototype, "add") || Counter.prototype.add === original); + assertEquals(new Counter().add(1), 1); + + // a plain object's function too, like engine.common.physics + const object = { double: (n: number) => n * 2 }; + const unhook_object = await as_mod("a", () => hook(object, "double", { after: (_self, _args, result) => -result })); + assertEquals(object.double(2), -4); + unhook_object(); + assertEquals(object.double(2), 4); +}); + +Deno.test("hook needs a loading mod with engine access", async () => { + const Counter = counter_class(); + assertThrows(() => hook(Counter.prototype, "add", {}), Error, "while a mod's script loads"); + let error: Error | undefined; + try { + await as_mod("sneaky", () => hook(Counter.prototype, "add", {}), false); + } catch (e) { + error = e as Error; + } + assertStringIncludes(String(error), `sneaky hooks the engine without "engine_access"`); + // and not something that isn't a method + await as_mod("a", () => { + assertThrows(() => hook(new Counter(), "count", {}), Error, "isn't a method"); + }); + + // importing bworld/engine at all + expose_engine({}); + const shim = new URL("../common/mod_api/engine.ts", import.meta.url).href; + let import_error: Error | undefined; + try { + await loading_mod("sneaky", false, () => import(`${shim}?sneaky`)); + } catch (e) { + import_error = e as Error; + } + assertStringIncludes(String(import_error), `sneaky imports bworld/engine without "engine_access"`); +}); + +Deno.test("bworld/engine without engine_access is an error in check-mods and in a .bmod", async () => { + const dir = Deno.makeTempDirSync({ prefix: "bworld_engine_" }); + const script = `import { engine } from "bworld/engine"; + export function setup() { + console.log(engine.common.physics); + }`; + write_mod(dir, "sneaky", { server: ["server.ts", script] }, {}); + const [mod] = load_and_check(dir); + assertEquals(mod.report.errors, [ + `scripts/server.ts imports bworld/engine, which needs "engine_access": true in manifest.json`, + ]); + + // packed anyway, the bundle gives it away + const bytes = await pack_mod(mod); + assertThrows(() => read_bmod(bytes, "sneaky.bmod"), Error, "a script uses bworld/engine"); + Deno.removeSync(dir, { recursive: true }); +}); + +Deno.test("engine access ties a mod to one minor version of the game", () => { + assertEquals(engine_version_problem("~0.4.0", "0.4.2"), undefined); + assertEquals(engine_version_problem("~0.4.2", "0.4.2"), undefined); + assertEquals(engine_version_problem("0.4.2", "0.4.2"), undefined); + assertStringIncludes(engine_version_problem("~0.4.3", "0.4.2")!, "this is the game's 0.4.2"); + assertStringIncludes(engine_version_problem("~0.3.0", "0.4.2")!, "this is the game's 0.4.2"); + assertStringIncludes(engine_version_problem("0.4.1", "0.4.2")!, "this is the game's 0.4.2"); + for (const range of [undefined, ">=0.4.0", "^0.4.0", "*", "0.4"]) { + assertStringIncludes(engine_version_problem(range, "0.4.2")!, "needs game_version to be one minor version"); + } + + const manifest = { format_version: 1, id: "a", name: "A", version: "1.0.0", engine_access: true }; + assertEquals(validate_manifest({ ...manifest, game_version: THIS_MINOR }, "a"), []); + assertEquals(validate_manifest({ ...manifest, game_version: ">=0.1.0" }, "a").length, 1); + assertEquals(validate_manifest({ ...manifest, engine_access: "yes" }, "a"), [ + "engine_access must be true or false", + ]); +}); diff --git a/tests/helpers.ts b/tests/helpers.ts index 7fe0e99..b3a5bd9 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -25,6 +25,7 @@ export function mod_sources(mods_dir: string): ServerModSource[] { sha256: "source", file: `mods/${mod.id}.bmod`, size: 0, + ...(mod.manifest?.engine_access === true ? { engine_access: true } : {}), }, data: { blocks: mod.blocks.map((b) => b.json), diff --git a/tools/check_mods.ts b/tools/check_mods.ts index 2d09494..a35fb2f 100644 --- a/tools/check_mods.ts +++ b/tools/check_mods.ts @@ -19,6 +19,7 @@ import { } from "$/common/mod_data.ts"; import { check_references, load_order, type LoadedMod, type ModReport } from "$/common/mod_check.ts"; import { png_size, texture_size_problem } from "$/common/bmod.ts"; +import { dirname } from "@std/path"; export { load_order, type LoadedMod, type ModReport }; @@ -98,6 +99,19 @@ function load_mod(mods_dir: string, id: string): LoadedMod { error(`manifest.json: scripts.${side} ${path} doesn't exist`); } } + // bworld/engine needs engine_access, it's checked again on the bundled code when a .bmod 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 (/["']bworld\/engine["']/.test(Deno.readTextFileSync(`${dir}/${folder}/${file}`))) { + error( + `${folder}/${file} imports bworld/engine, which needs "engine_access": true in manifest.json`, + ); + } + } + } + } const credits = mod.manifest?.credits; if (typeof credits === "string" && !exists(`${dir}/${credits}`)) { error(`manifest.json: credits ${credits} doesn't exist`);