// 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. // 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, sell_value, } from "@/common/inventory.ts"; import { block_states, fluid_block, get_state_value, is_waterlogged, set_state_value, shared_items_api, } from "@/common/utils.ts"; import { LootTables } from "./loot.ts"; import { collision_shape_at, covers_face, is_solid, raycast_blocks, type Shape } from "@/common/block_shapes.ts"; import { AIR, CHUNK_SIZE, faces, ID_MASK } from "@/common/constants.ts"; import { physics } from "@/common/physics.ts"; import { clock } from "@/common/time.ts"; import { BlockRules } from "@/common/block_rules.ts"; 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, Command, CommandRegistry, CommandSource, Container, EffectComponent, EntityRef, EventSignal, Face, FluidHandler, FluidSlotOptions, ItemComponent, ItemStack, LivingRef, LootContext, MenuBuilder, MenuHandle, MenuType, Player, PlayerMenuBuilder, Position, ServerAfterEvents, ServerBeforeEvents, ServerContext, SlotOptions, } from "@/common/mod_api/server.ts"; import { check_recipe_types, ModLoadError, recipe_lookup, shared_recipes_api } from "@/common/mod_loader.ts"; import { argument, block as block_argument, boolean, choice, CommandDispatcher, CommandError, CommandNode, fluid as fluid_argument, greedy_string, integer, item, json, literal, number, word, } from "@/common/commands.ts"; import { AIR_ID } from "@/common/protocol.ts"; import type { GameServer } from "./game_server.ts"; import { MAX_PRIORITY, MIN_PRIORITY } from "./scheduled_ticks.ts"; import type { ServerPlayer } from "./player.ts"; import { Menu, type MenuFluidSlot, type MenuSlot } from "./menu.ts"; import { damage_source, type Entity } from "./entity/entity.ts"; import type { LivingEntity } from "./entity/living_entity.ts"; import type { EffectJson } from "@/common/mod_data.ts"; import { create_entity } from "./entity/entity_types.ts"; import { BLOCK_DROP_PICKUP_DELAY, ItemEntity } from "./entity/item_entity.ts"; import { attribute_type, type AttributeType, MODIFIER_OPERATIONS } from "./entity/attributes.ts"; import { effect_type, EffectInstance, type EffectType } from "./entity/effects.ts"; import { biome_season } from "@/common/worldgen/biomes.ts"; // a list of handlers that can't break each other: one throwing is logged under its mod and the rest still run export class Signal { #handlers: { mod: string; handler: (event: T) => void }[] = []; for_mod(mod: string): EventSignal { return { subscribe: (handler) => { const entry = { mod, handler }; this.#handlers.push(entry); return () => { this.#handlers = this.#handlers.filter((h) => h !== entry); }; }, }; } emit(event: T) { for (const { mod, handler } of [...this.#handlers]) { run_guarded(mod, "an event handler", () => handler(event)); } } get empty() { return this.#handlers.length === 0; } } // 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; id: string; component: BlockComponent; params: unknown; } interface ScriptSource { mod: string; version: string; url: string; engine_access: boolean; // its settings, see ServerContext.config config: Record; } export function run_guarded(mod: string, what: string, fn: () => T): T | undefined { const previous = running_mod; running_mod = mod; try { return fn(); } catch (e) { console.error(`[${mod}] ${what} threw:`, e); return undefined; } finally { running_mod = previous; } } type Before = { [K in keyof ServerBeforeEvents]: ServerBeforeEvents[K] extends EventSignal ? Signal : never; }; type After = { [K in keyof ServerAfterEvents]: ServerAfterEvents[K] extends EventSignal ? Signal : never }; interface Timer { mod: string; fn: () => void; at: number; every?: number; } export class ModRuntime { block_components = new Map(); // what shared scripts 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 fluid_rules = new FluidRules(run_guarded); item_components = new Map(); effect_components = new Map(); // every command, the engine's and mods', see common/commands.ts commands = new CommandDispatcher(); // who registered each command name: "cubi" or a mod's id command_owners = new Map(); before: Before = { block_break: new Signal(), block_place: new Signal(), block_interact: new Signal(), chat_send: new Signal(), player_damage: new Signal(), }; after: After = { block_break: new Signal(), block_place: new Signal(), block_interact: new Signal(), chat_send: new Signal(), player_join: new Signal(), player_leave: new Signal(), player_damage: new Signal(), player_death: new Signal(), server_start: new Signal(), tick: new Signal(), new_day: new Signal(), }; // per mod key value storage, saved with the world storage: Record> = {}; #timers = new Map(); // containers mods listen to with on_change, compared slot by slot every tick #watched: { mod: string; container: EngineContainer; last: string[]; fn: (slot: number) => void }[] = []; #next_timer = 1; #setting_up = true; #players = new WeakMap(); // loot tables with what mods registered for them, see ctx.loot readonly loot = new LootTables(); // mod channels, see ctx.net: who listens on each channel #net_handlers = new Map void }[]>(); // mod messages each player sent this second, to drop floods #net_counts = new WeakMap(); // a player's client sent a mod message. clients are untrusted: too big or too many are dropped receive(player: ServerPlayer, channel: string, data: unknown) { if (!this.#count_message(player)) return; if ((JSON.stringify(data) ?? "").length > MAX_MOD_MESSAGE_LENGTH) return; for (const { mod, handler } of this.#net_handlers.get(channel) ?? []) { run_guarded(mod, `a ${channel} handler`, () => handler(this.player(player), data)); } } // a client pressed a button of its open menu. buttons count as mod messages, clients are untrusted menu_button(player: ServerPlayer, menu: Menu, button: number) { if (!this.#count_message(player)) return; for (const fn of [...menu.on_button]) fn(button); } // false once a player has sent too many this second #count_message(player: ServerPlayer): boolean { const second = Math.floor(Date.now() / 1000); let counts = this.#net_counts.get(player); if (!counts || counts.second !== second) { counts = { second, count: 0 }; this.#net_counts.set(player, counts); } return ++counts.count <= MAX_MOD_MESSAGES_PER_SECOND; } // the other way, for apis that take a player #server_players = new WeakMap(); // menu types by id, every mod's #menu_types = new Set(); // what each mod adds to the player's own menu, in load order #player_menu_builders: { mod: string; build: (menu: PlayerMenuBuilder, player: Player) => void }[] = []; // a player joined: the mods' slots go after menu 0's own. one that throws is logged and the rest still run extend_player_menu(player: ServerPlayer) { const api = this.player(player); for (const { mod, build } of this.#player_menu_builders) { const menu = player.inventory_menu; const added: MenuSlot[] = []; const ok = run_guarded(mod, "an extend_player_menu", () => { build({ add_slot: (container, slot, options) => { added.push(menu_slot(mod, player, container, slot, options)); return menu.slots.length + added.length - 1; }, }, api); return true; }); // all of a mod's slots or none, so a half built set can't shift the next mod's if (ok) menu.slots.push(...added); } } 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 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)); } 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 #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"); } const { world, blocks } = this.#context(mod, version, config); const ctx: SharedContext = { mod: { id: mod, version }, side: "server", tags: tag_api(), blocks, items: shared_items_api(mod), fluids: { exists: fluid_exists, same: same_fluid, register: (id, rules) => { if (!this.#setting_up) throw new ModLoadError(mod, "rules can only be registered during setup"); this.fluid_rules.register(mod, id, rules); }, }, recipes: shared_recipes_api(mod, () => this.game.recipes, () => this.#shared_setup, (message) => { throw new ModLoadError(mod, message); }), world: { get_block: world.get_block, get_state: world.get_state, set_state: world.set_state, is_face_sturdy: world.is_face_sturdy, biome_at: world.biome_at, season_at: world.season_at, }, 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, 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 // its mobs can have effects, so their components are looked up as they tick effect_types(): EffectType[] { return EverythingRegistry.entries("effects").map(([id, json]) => { const modifiers = (json.modifiers ?? []).map(({ attribute, amount, operation }) => { const type = attribute_type(attribute); if (!type) { throw new ModLoadError( id.split(":")[0], `effect ${id} changes ${attribute}, which isn't an attribute`, ); } return { attribute: type, amount, operation }; }); const components = Object.entries(json.components ?? {}); const on_tick = (entity: LivingEntity, ticks: number | undefined, amplifier: number) => { let keep = true; for (const [component_id, params] of components) { const { mod, component } = this.effect_components.get(component_id)!; const due = ticks === undefined || !component.should_tick || run_guarded( mod, `${component_id} should_tick`, () => component.should_tick!(ticks, amplifier, params), ); if (!due || !component.on_tick) continue; const result = run_guarded( mod, `${component_id} on_tick`, () => component.on_tick!(living_ref(entity), amplifier, params), ); if (result === false) keep = false; } return keep; }; return { id, category: json.category ?? "neutral", instant: json.instant === true, modifiers, on_tick: components.length > 0 ? on_tick : undefined, }; }); } // after every setup ran: registration closes and every component blocks, items and effects use must exist finish_setup() { this.#setting_up = false; for (const [id, effect] of EverythingRegistry.entries("effects")) { for (const component of Object.keys(effect.components ?? {})) { if (!this.effect_components.has(component)) { throw new ModLoadError( id.split(":")[0], `effect ${id} uses component ${component}, which nothing registered`, ); } } } this.loot.check(); for (const [id, block] of EverythingRegistry.entries<{ components?: Record }>("blocks")) { for (const component of Object.keys(block.components ?? {})) { if (!this.block_components.has(component) && !this.rules.has(component)) { throw new ModLoadError( id.split(":")[0], `block ${id} uses component ${component}, which nothing registered`, ); } } } for (const [id, item] of EverythingRegistry.entries("items")) { const components = Object.entries(item.components ?? {}); if (components.length === 0) continue; for (const [component_id] of components) { if (!this.item_components.has(component_id)) { throw new ModLoadError( id.split(":")[0], `item ${id} uses component ${component_id}, which nothing registered`, ); } } const lore = components.filter(([component_id]) => this.item_components.get(component_id)!.component.get_lore ); if (lore.length > 0) { item.get_lore = (stack) => lore.map(([component_id, params]) => { const { mod, component } = this.item_components.get(component_id)!; return run_guarded(mod, `${component_id} get_lore`, () => component.get_lore!(item_api(stack), params)); }).filter((line) => typeof line === "string" ).join("\n"); } // items are created all over the engine, hook their creation once here const previous = item.on_create; item.on_create = (stack) => { previous?.(stack); for (const [component_id, params] of components) { const { mod, component } = this.item_components.get(component_id)!; if (component.on_create) { run_guarded( mod, `${component_id} on_create`, () => component.on_create!(item_api(stack), params), ); } } }; } } // adds a command, and for mods the same command as /mod:name so it can always be told apart register_command(owner: string, node: CommandNode) { if (!/^[a-z0-9_]+$/.test(node.name)) { throw new Error(`command name "${node.name}" must be a-z, 0-9 and _`); } const existing = this.command_owners.get(node.name); if (existing) { throw new Error( existing === "cubi" ? `/${node.name} belongs to the engine` : `/${node.name} is also registered by ${existing}`, ); } this.commands.register(node); this.command_owners.set(node.name, owner); if (owner !== "cubi") { const alias = new CommandNode(`${owner}:${node.name}`); alias.children.push(...node.children); alias.command = node.command; alias.requirement = node.requirement; alias.description = node.description; this.commands.root.then(alias); this.command_owners.set(alias.name, owner); } } // components on a block, with their params from its json // worked out once per block, blocks and components don't change after loading. shared, so callers don't change it components_of(block_id: string): readonly BlockComponentOf[] { let components = this.#components_of.get(block_id); if (!components) { const block = EverythingRegistry.get<{ components?: Record }>("blocks", block_id); // components that only have shared rules have nothing here components = Object.entries(block?.components ?? {}).flatMap(([id, params]) => { const registered = this.block_components.get(id); return registered ? [{ ...registered, id, params }] : []; }); this.#components_of.set(block_id, components); } return components; } #components_of = new Map(); // the ones with on_tick or on_second, for ticking blocks every tick. cached like components_of ticking_components_of(block_id: string): readonly BlockComponentOf[] { let components = this.#ticking_components_of.get(block_id); if (!components) { components = this.components_of(block_id).filter(({ component }) => component.on_tick || component.on_second ); this.#ticking_components_of.set(block_id, components); } return components; } #ticking_components_of = new Map(); // the ones with a handler, for handlers that run often, like on_neighbor_change. cached like components_of components_with(block_id: string, handler: keyof BlockComponent): readonly BlockComponentOf[] { let of_handler = this.#components_with.get(handler); if (!of_handler) this.#components_with.set(handler, of_handler = new Map()); let components = of_handler.get(block_id); if (!components) { components = this.components_of(block_id).filter(({ component }) => component[handler]); of_handler.set(block_id, components); } return components; } #components_with = new Map>(); // the fluid handler of the block at x y z reached from face, from the first of its components with one block_fluid_handler(x: number, y: number, z: number, face: Face | undefined): FluidHandler | undefined { if (face !== undefined && !faces.includes(face)) { throw new Error(`a face is one of ${faces.join(", ")}, not ${face}`); } const id = this.game.world.get_block_id(x, y, z); const components = this.components_with(id, "fluid_handler"); if (components.length === 0) return undefined; const block = this.block_ref(x, y, z, id); for (const { mod, id: component_id, component, params } of components) { const handler = run_guarded( mod, `${component_id} fluid_handler`, () => component.fluid_handler!(block, params, face), ); if (handler) return handler; } return undefined; } // the block at x y z was told the one at from changed, and its rules have had their say: its components' // on_neighbor_change #neighbor_changed(x: number, y: number, z: number, from: Position) { const world = this.game.world; // read again, a rule's state change can have had a component replace it const id = world.get_block_id(x, y, z); const components = this.components_with(id, "on_neighbor_change"); if (components.length === 0) return; const block = this.block_ref(x, y, z, id); const neighbor = { ...from, id: world.get_block_id(from.x, from.y, from.z) }; for (const { mod, id: component_id, component, params } of components) { run_guarded( mod, `${component_id} on_neighbor_change`, () => component.on_neighbor_change!(block, params, neighbor), ); } } // components on an item, with their params from its json item_components_of(item_id: string): { mod: string; id: string; component: ItemComponent; params: unknown }[] { const item = EverythingRegistry.get("items", item_id); return Object.entries(item?.components ?? {}).map(([id, params]) => ({ ...this.item_components.get(id)!, id, params, })); } watch_container(mod: string, container: EngineContainer, fn: (slot: number) => void) { const entry = { mod, container, fn, last: snapshot(container) }; this.#watched.push(entry); return () => { this.#watched = this.#watched.filter((w) => w !== entry); }; } // items change in many places (clicks, drops, crafting, scripts), so compare instead of hooking every one check_watched_containers() { for (const watch of [...this.#watched]) { const now = snapshot(watch.container); const changed = now.flatMap((slot, i) => slot !== watch.last[i] ? [i] : []); watch.last = now; for (const slot of changed) { run_guarded(watch.mod, "a container on_change", () => watch.fn(slot)); } } } tick() { const now = this.game.current_tick; for (const [handle, timer] of [...this.#timers]) { if (timer.at > now) continue; if (timer.every) { timer.at = now + timer.every; } else { this.#timers.delete(handle); } run_guarded(timer.mod, "a timer", timer.fn); } if (!this.after.tick.empty) { this.after.tick.emit({ dt: 1 / 20 }); } } player(player: ServerPlayer): Player { let api = this.#players.get(player); if (!api) { api = player_api(this.game, player); this.#players.set(player, api); this.#server_players.set(api, player); } return api; } block_ref(x: number, y: number, z: number, id: string): BlockRef { const game = this.game; return { id, x, y, z, get biome() { return game.world.biome_at(x, z); }, get season() { return biome_season(game.world.biome_at(x, z), game.world.time); }, get data() { return game.world.get_tile(x, y, z)?.mod_data; }, set data(value) { game.set_tile_data(x, y, z, value); }, get_client_data: (field) => structuredClone(game.world.get_tile(x, y, z)?.client_data?.[field]) as never, set_client_data(field, value) { if (typeof field !== "string" || field === "") throw new Error("a client data field needs a name"); game.set_tile_client_data(x, y, z, field, structuredClone(value)); }, set_ticking(ticking) { game.set_tile_ticking(x, y, z, ticking); }, }; } // a script's loot context with its block's states read from the world, when it didn't give them #loot_context(context: LootContext = {}): LootContext { const block = context.block; if (!block || block.states) return context; const world = this.game.world; const info = world.get_block_info(block.x, block.y, block.z); if (info?.id !== block.id) return context; return { ...context, block: { ...block, states: block_states(world.get_block_value(block.x, block.y, block.z), info) }, }; } #context(mod: string, version: string, config: Record): ServerContext { const setup_only = (what: string) => { if (!this.#setting_up) { throw new Error(`[${mod}] ${what} can only be registered during setup`); } }; const own = (id: string, what: string) => { if (!id.startsWith(`${mod}:`)) { throw new ModLoadError(mod, `${what} ${id} must be in the namespace "${mod}"`); } }; const game = () => this.game; const ctx: ServerContext = { mod: { id: mod, version }, config, components: { register_block: (id, component) => { setup_only("components"); own(id, "component"); if (this.block_components.has(id)) { throw new ModLoadError(mod, `component ${id} is registered twice`); } this.block_components.set(id, { mod, component: component as BlockComponent }); this.#components_of.clear(); this.#ticking_components_of.clear(); this.#components_with.clear(); }, register_item: (id, component) => { setup_only("components"); own(id, "component"); if (this.item_components.has(id)) { throw new ModLoadError(mod, `component ${id} is registered twice`); } this.item_components.set(id, { mod, component: component as ItemComponent }); }, register_effect: (id, component) => { setup_only("components"); own(id, "component"); if (this.effect_components.has(id)) { throw new ModLoadError(mod, `component ${id} is registered twice`); } this.effect_components.set(id, { mod, component: component as EffectComponent }); }, }, commands: { register: (name_or_node: string | CommandNode, command?: Command) => { setup_only("commands"); const node = typeof name_or_node === "string" ? simple_command(name_or_node, command!) : name_or_node as unknown as CommandNode; try { this.register_command(mod, node as CommandNode); } catch (e) { throw new ModLoadError(mod, (e as Error).message); } }, literal: (name) => literal(name), argument: (name, type) => argument(name, type), types: { integer, number, boolean, word, greedy_string, json, choice, item: () => item(), block: () => block_argument(), fluid: () => fluid_argument(), player: () => ({ parse: (text: string) => { const found = game().players().find((p) => p.name === text); if (!found) throw new CommandError(`${text} isn't online`); return this.player(found); }, suggest: (partial: string) => game().players().filter((p) => p.name.startsWith(partial)).map((p) => ({ text: p.name })), }), }, } as CommandRegistry, events: { before: map_signals(this.before, mod), after: map_signals(this.after, mod), }, system: { run_timeout: (fn, ticks) => this.#add_timer(mod, fn, ticks), run_interval: (fn, ticks) => this.#add_timer(mod, fn, ticks, Math.max(1, ticks)), clear_run: (handle) => void this.#timers.delete(handle), get current_tick() { return game().current_tick; }, }, world: { get_block: (x, y, z) => game().world.get_block_id(x, y, z), set_block: (x, y, z, id, states) => { const info = id === AIR_ID ? undefined : EverythingRegistry.get("blocks", id); if (id !== AIR_ID && !info) throw new Error(`unknown block ${id}`); let value = info && game().world.default_values[game().world.block_ids[id]]; for (const [name, state] of Object.entries(states ?? {})) { const bits = info?.states?.find((s) => s.name === name)?.bits; if (bits === undefined || !Number.isInteger(state) || state < 0 || state >= 2 ** bits) { throw new Error(`${id} has no state ${name} that fits ${state}`); } value = set_state_value(value!, info!, name, state)!; } game().set_block(x, y, z, id, undefined, states && value !== undefined ? value >>> 16 : undefined); return true; }, break_block: (x, y, z, options = {}) => { if (game().world.get_block_id(x, y, z) === AIR_ID) return undefined; const how = { harvest: options.harvest === true, collect: options.collect === true }; return game().destroy_block(x, y, z, undefined, how)?.map(item_copy); }, set_break_progress: (x, y, z, progress) => { if (progress !== undefined && !Number.isFinite(progress)) { throw new Error( `break progress is 0 to 1, or undefined to take the cracks off, not ${progress}`, ); } game().set_break_progress(x, y, z, progress); }, get_state: (x, y, z, name) => { const id = game().world.get_block_id(x, y, z); if (id === AIR_ID) return undefined; const info = state_owner(id, name); return get_state_value(game().world.get_block_value(x, y, z), info, name); }, set_state: (x, y, z, name, value, options) => { const id = game().world.get_block_id(x, y, z); if (id === AIR_ID) return false; const info = state_owner(id, name); const bits = info.states!.find((s) => s.name === name)!.bits; if (!Number.isInteger(value) || value < 0 || value >= 2 ** bits) { throw new Error(`${id} state "${name}" has ${bits} bits, ${value} doesn't fit`); } const new_value = set_state_value(game().world.get_block_value(x, y, z), info, name, value)!; game().set_block_state(x, y, z, new_value >>> 16, options?.update_neighbors !== false); return true; }, neighbor_changed: (x, y, z, from) => this.rules.neighbor_changed(x, y, z, { x: from.x, y: from.y, z: from.z }), schedule_tick: (x, y, z, delay, priority = 0) => { if (!Number.isInteger(delay) || delay < 1) { throw new Error(`a tick is scheduled at least 1 tick ahead, in whole ticks, not ${delay}`); } if (!Number.isInteger(priority) || priority < MIN_PRIORITY || priority > MAX_PRIORITY) { throw new Error(`a tick's priority is ${MIN_PRIORITY} to ${MAX_PRIORITY}, not ${priority}`); } game().schedule_tick(x, y, z, delay, priority); }, has_scheduled_tick: (x, y, z) => game().has_scheduled_tick(x, y, z), is_face_sturdy: (x, y, z, face) => covers_face(game().world.collision_shape(x, y, z), face), get_block_data: (x, y, z) => game().world.get_tile(x, y, z)?.mod_data as never, get_block_ref: (x, y, z) => { const id = game().world.get_block_id(x, y, z); return id === AIR_ID ? undefined : this.block_ref(x, y, z, id); }, set_block_ticking: (x, y, z, ticking) => game().set_tile_ticking(x, y, z, ticking), set_block_item: (x, y, z, item) => { const shown = item && item.count > 0 ? new_stack(item).to_data() : undefined; game().set_tile_client_data(x, y, z, "item", shown); }, get_block_item: (x, y, z) => structuredClone(game().world.get_tile(x, y, z)?.client_data?.item as ItemStack), drop_item: (x, y, z, item) => void game().pop_item(x, y, z, new_stack(item)), spawn_item: (x, y, z, item) => { if (!(item.count > 0)) throw new Error("an item lying around needs a count of 1 or more"); return entity_ref(game().spawn_item(x, y, z, new_stack(item), BLOCK_DROP_PICKUP_DELAY)); }, entities_in: (from, to, type) => { const [x0, x1] = [Math.min(from.x, to.x), Math.max(from.x, to.x)]; const [y0, y1] = [Math.min(from.y, to.y), Math.max(from.y, to.y)]; const [z0, z1] = [Math.min(from.z, to.z), Math.max(from.z, to.z)]; return game().entities.all().filter((entity) => { const half = entity.width / 2; return (type === undefined || entity.type === type) && entity.x - half < x1 && entity.x + half > x0 && entity.y < y1 && entity.y + entity.height > y0 && entity.z - half < z1 && entity.z + half > z0; }).map(entity_ref); }, use_item_on: (item, x, y, z, face) => { if (!faces.includes(face)) throw new Error(`a face is one of ${faces.join(", ")}, not ${face}`); if (!(item.count > 0)) throw new Error("using an item needs a count of 1 or more"); const { held, given } = game().use_item_on(new_stack(item), x, y, z, face); return { item: held && item_copy(held), given: given.map(item_copy) }; }, spawn_entity: (id, x, y, z) => { const entity = EverythingRegistry.get("entities", id) ? create_entity(game().entities, id) : undefined; if (!entity) throw new Error(`unknown entity ${id}`); entity.set_position(x, y, z); game().entities.add_entity(entity); return entity_ref(entity); }, raycast: (from, to, options) => { const fluids = options?.fluids ?? "none"; if (!["none", "source_only", "any"].includes(fluids)) { throw new Error(`fluids must be "none", "source_only" or "any", not ${fluids}`); } const origin = [from.x, from.y, from.z]; const length = Math.hypot(to.x - from.x, to.y - from.y, to.z - from.z); if (!Number.isFinite(length)) throw new Error("raycast needs two points with finite x, y and z"); if (length === 0) return undefined; const direction = [(to.x - from.x) / length, (to.y - from.y) / length, (to.z - from.z) / length]; const world = game().world; const hit = raycast_blocks( origin, direction, length, (x, y, z) => raycast_shape(world, x, y, z, fluids), ); if (!hit) return undefined; // what was hit in a waterlogged block with fluids on is its fluid, see raycast_shape const value = world.get_block_value(hit.x, hit.y, hit.z); const block = world.get_block_info(hit.x, hit.y, hit.z); const fluid = fluids === "none" ? undefined : fluid_block(value, block); return { id: fluid?.id ?? world.get_block_id(hit.x, hit.y, hit.z), x: hit.x, y: hit.y, z: hit.z, face: hit.face, position: { x: from.x + direction[0] * hit.distance, y: from.y + direction[1] * hit.distance, z: from.z + direction[2] * hit.distance, }, }; }, fluid_flow: (x, y, z) => { const [fx, fy, fz] = physics.fluid_flow( Math.floor(x), Math.floor(y), Math.floor(z), (x, y, z) => game().entities.fluid_at(x, y, z), (x, y, z) => game().world.collision_shape(x, y, z), ); // without any -0 return { x: fx + 0, y: fy + 0, z: fz + 0 }; }, is_loaded: (x, z) => game().world.is_generated(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE)), biome_at: (x, z) => game().world.biome_at(Math.floor(x), Math.floor(z)), season_at: (x, z) => biome_season(game().world.biome_at(Math.floor(x), Math.floor(z)), game().world.time), get seed() { return game().world.seed; }, get time() { return game().world.time; }, get day() { return game().world.day; }, get hour() { const { hour, minute } = clock(game().world.time); return hour + minute / 60; }, set_time: (time) => { if (!Number.isInteger(time) || time < 0) { throw new Error(`time must be a whole number of ticks, not ${time}`); } game().set_time(time); }, }, players: { all: () => game().players().map((p) => this.player(p)), get: (id) => { const p = game().players().find((p) => p.id === id); return p && this.player(p); }, by_name: (name) => { const p = game().players().find((p) => p.name === name); return p && this.player(p); }, }, items: { exists: (id) => EverythingRegistry.get("items", id) !== undefined, ids: () => EverythingRegistry.entries("items").map(([id]) => id), max_stack: (id, data) => { if (!EverythingRegistry.get("items", id)) throw new Error(`unknown item ${id}`); return max_stack(id, data); }, fluid_capacity: (id) => { const item = EverythingRegistry.get("items", id); if (!item) throw new Error(`unknown item ${id}`); return item.fluid_container?.capacity; }, tool: (id) => { const item = EverythingRegistry.get("items", id); if (!item) throw new Error(`unknown item ${id}`); return item.tool?.type; }, sell_value: (id, data) => { if (!EverythingRegistry.get("items", id)) throw new Error(`unknown item ${id}`); return sell_value(id, data, this.fluid_rules); }, components: (id) => { const item = EverythingRegistry.get("items", id); if (!item) throw new Error(`unknown item ${id}`); return structuredClone(item.components ?? {}); }, }, blocks: { exists: (id) => EverythingRegistry.get("blocks", id) !== undefined, toughness: (id) => { const block = EverythingRegistry.get("blocks", id); if (!block) throw new Error(`unknown block ${id}`); return block.toughness ?? Infinity; }, components: (id) => { const block = EverythingRegistry.get("blocks", id); if (!block) throw new Error(`unknown block ${id}`); return structuredClone(block.components ?? {}); }, solid: (id) => { if (id === AIR_ID) return false; const block = EverythingRegistry.get("blocks", id); if (!block) throw new Error(`unknown block ${id}`); return is_solid(block); }, }, fluids: { ...this.fluid_rules.api(), block_handler: (x, y, z, face) => this.block_fluid_handler(x, y, z, face), item_handler, tank_handler, transfer, interact, }, recipes: { ...recipe_lookup(() => game().recipes), list: (type) => structuredClone(game().recipes.by_type.get(type) ?? []), }, tags: tag_api(), loot: { exists: (id) => this.loot.exists(id), roll: (id, context) => this.loot.roll(id, this.#loot_context(context)), fill: (container, id, context) => { const items = this.loot.roll(id, this.#loot_context(context)); // empty slots in a random order, one item each, like minecraft's chests const empty = [...Array(container.size).keys()].filter((slot) => !container.get(slot)); for (let i = empty.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [empty[i], empty[j]] = [empty[j], empty[i]]; } const left: ItemStack[] = []; for (const item of items) { const slot = empty.pop(); if (slot === undefined) left.push(item); else container.set(slot, item); } return left; }, register_condition: (id, condition) => { setup_only("loot conditions"); this.loot.register_condition(mod, id, condition); }, register_function: (id, fn) => { setup_only("loot functions"); this.loot.register_function(mod, id, fn); }, modify: (table, fn) => { setup_only("loot modifiers"); this.loot.modify(mod, table, fn); }, register_table: (id, table) => { setup_only("loot tables"); this.loot.register_table(mod, id, table); }, }, containers: { create: (size) => { if (!Number.isInteger(size) || size < 1 || size > MAX_CONTAINER_SIZE) { throw new Error(`a container has 1 to ${MAX_CONTAINER_SIZE} slots, not ${size}`); } const { id, container } = game().create_container(size); return container_api(game(), id, container); }, get: (id) => { const container = game().containers.get(id); return container && container_api(game(), id, container); }, delete: (id) => game().delete_container(id), }, menus: { extend_player_menu: (build) => { setup_only("extend_player_menu"); this.#player_menu_builders.push({ mod, build }); }, register: (id: string, build: (menu: MenuBuilder, args: Args, player: Player) => void) => { own(id, "menu type"); if (this.#menu_types.has(id)) throw new Error(`[${mod}] menu type ${id} is already registered`); this.#menu_types.add(id); const type: MenuType = { id, open: (player, args) => this.#open_menu(mod, id, player, (menu) => build(menu, args, player)), }; return type; }, }, ui: { message_form: not_yet(mod, "ui.message_form", "see docs/modding_plan.md"), action_form: not_yet(mod, "ui.action_form", "see docs/modding_plan.md"), modal_form: not_yet(mod, "ui.modal_form", "see docs/modding_plan.md"), }, net: { on: (channel, handler) => { own(channel, "channel"); const handlers = this.#net_handlers.get(channel) ?? []; handlers.push({ mod, handler: handler as (player: Player, data: unknown) => void }); this.#net_handlers.set(channel, handlers); }, send: (player, channel, data) => { own(channel, "channel"); const server_player = this.#server_players.get(player); if (!server_player || !game().players().includes(server_player)) { throw new Error(`${player.name} isn't online`); } game().send_mod_message(server_player, channel, data); }, broadcast: (channel, data) => { own(channel, "channel"); for (const player of game().players()) game().send_mod_message(player, channel, data); }, }, storage: { get: (key) => structuredClone(this.storage[mod]?.[key]) as never, set: (key, value) => { (this.storage[mod] ??= {})[key] = structuredClone(value); game().world.dirty = true; }, delete: (key) => { delete this.storage[mod]?.[key]; game().world.dirty = true; }, }, log: (...args) => console.log(`[${mod}]`, ...args), }; return ctx; } // builds a menu with the mod's function and opens it. a build that throws opens nothing #open_menu(mod: string, type: string, player: Player, build: (menu: MenuBuilder) => void): MenuHandle { const game = this.game; const server_player = this.#server_players.get(player); if (!server_player || !game.players().includes(server_player)) { throw new Error(`${player.name} isn't online`); } const menu = new Menu(game.next_menu_id(server_player), type); const guarded = (what: string, fn: () => T) => run_guarded(mod, what, fn); build({ get title() { return menu.title; }, set title(value) { menu.title = String(value); }, get open_data() { return menu.open_data; }, set open_data(value) { menu.open_data = structuredClone(value) ?? null; }, add_slot(container, slot, options) { menu.slots.push(menu_slot(mod, server_player, container, slot, options)); return menu.slots.length - 1; }, add_fluid_slot(handler, tank, options) { menu.fluid_slots.push(menu_fluid_slot(game, mod, server_player, handler, tank, options)); return menu.fluid_slots.length - 1; }, add_player_inventory(x, y) { const first = menu.slots.length; for (let i = 0; i < server_player.inventory.size; i++) { // the rest of the inventory in rows from x and y, the hotbar under it like minecraft's const row = i < 9 ? 0 : Math.floor(i / 9) - 1; menu.slots.push({ container: server_player.inventory, index: i, x: x + (i % 9) * 18, y: i < 9 ? y + 58 : y + row * 18, inventory: i, }); } return first; }, add_data(name, get) { menu.data.set(String(name), () => guarded(`menu data ${name}`, get) ?? 0); }, still_valid(check) { menu.still_valid.push(() => guarded("a still_valid", () => check(player)) !== false); }, still_valid_near(block) { const { id, x, y, z } = block; menu.still_valid.push(() => { const [dx, dy, dz] = [ server_player.x - x - 0.5, server_player.y - y - 0.5, server_player.z - z - 0.5, ]; return dx * dx + dy * dy + dz * dz <= MENU_REACH * MENU_REACH && game.world.get_block_id(x, y, z) === id; }); }, on_button(fn) { menu.on_button.push((button) => guarded("an on_button", () => fn(player, button))); }, quick_move(fn) { menu.quick_move_order = (index) => { const order = guarded("a quick_move", () => fn(player, index)); return Array.isArray(order) ? order.filter((i) => Number.isInteger(i)) : []; }; }, on_tick(fn) { menu.on_tick.push(() => guarded("a menu on_tick", fn)); }, on_close(fn) { menu.on_close.push(() => guarded("a menu on_close", fn)); }, }); if ((JSON.stringify(menu.open_data) ?? "").length > MAX_MOD_MESSAGE_LENGTH) { throw new Error(`the open_data of ${type} is over 16 KB`); } let open = true; menu.on_close.unshift(() => open = false); game.open_menu(server_player, menu); return { player, get open() { return open; }, close() { if (server_player.menu === menu) game.close_menu(server_player); }, on_close(fn) { if (!open) { guarded("a menu on_close", fn); return; } menu.on_close.push(() => guarded("a menu on_close", fn)); }, }; } #add_timer(mod: string, fn: () => void, ticks: number, every?: number) { const handle = this.#next_timer++; this.#timers.set(handle, { mod, fn, at: this.game.current_tick + Math.max(0, ticks), every }); return handle; } } // each event's signal, as seen by one mod so errors say which mod threw // a block that has this state, or an error saying it doesn't function state_owner(id: string, name: string): BlockRegistry { const info = EverythingRegistry.get("blocks", id)!; if (!info.states?.some((s) => s.name === name)) { throw new Error(`${id} has no state "${name}"`); } return info; } function snapshot(container: EngineContainer): string[] { return container.to_data().map((item) => JSON.stringify(item)); } function map_signals( signals: T, mod: string, ): { [K in keyof T]: ReturnType } { return Object.fromEntries(Object.entries(signals).map(([name, signal]) => [name, signal.for_mod(mod)])) as { [K in keyof T]: ReturnType; }; } function not_yet(mod: string, name: string, why: string) { return () => { throw new Error(`[${mod}] ctx.${name} isn't implemented yet: ${why}`); }; } const MAX_CONTAINER_SIZE = 256; // how far a player can be from a block whose menu they have open, like minecraft's stillValid const MENU_REACH = 8; // what a client may send on mod channels, see docs/modding/networking/index.md const MAX_MOD_MESSAGE_LENGTH = 16 * 1024; const MAX_MOD_MESSAGES_PER_SECOND = 60; // who ran a command, as the engine sees it: what mods see plus the engine's player export interface ServerCommandSource extends CommandSource { server_player: ServerPlayer; } // register(name, { run }): the words after the name go to run, split on spaces function simple_command(name: string, command: Command): CommandNode { const run = (args: string[], source: ServerCommandSource) => command.run(args, source.player); return literal(name) .describe(command.description) .executes((context) => run([], context.source)) .then( argument("args", greedy_string()).executes((context) => run(context.get("args").split(/\s+/).filter((word) => word.length > 0), context.source) ), ); } // the engine's item stacks as mods see them: { id, count, data } export function item_api(stack: EngineItemStack): ItemStack { return { get id() { return stack.type_id; }, get count() { return stack.amount; }, set count(value) { stack.amount = value; }, get data() { return stack.data; }, set data(value) { stack.data = value; }, }; } // an engine stack as a script's item, a copy export function item_copy(stack: EngineItemStack): ItemStack { return structuredClone(stack.to_data()); } export function new_stack(item: ItemStack): EngineItemStack { if (!EverythingRegistry.get("items", item.id)) throw new Error(`unknown item ${item.id}`); const stack = new EngineItemStack(item.id, item.count); if (item.data !== undefined) stack.data = structuredClone(item.data); return stack; } // a menu's slot from what a mod's add_slot got function menu_slot( mod: string, player: ServerPlayer, container: Container, slot: number, options: SlotOptions, ): MenuSlot { const engine = engine_containers.get(container); if (!engine) throw new Error("add_slot needs a container from ctx.containers or player.inventory"); if (!Number.isInteger(slot) || slot < 0 || slot >= engine.size) { throw new Error(`slot ${slot} isn't in the container, it has ${engine.size}`); } if (![options?.x, options?.y].every((n) => typeof n === "number" && Number.isFinite(n))) { throw new Error(`slot ${slot} needs an x and y`); } const { filter, on_take } = options; const guarded = (what: string, fn: () => T) => run_guarded(mod, what, fn); const added: MenuSlot = { container: engine, index: slot, x: options.x, y: options.y }; if (typeof filter === "function") { added.filter = (item) => guarded("a slot filter", () => filter(item_api(item))) === true; } if (options.output_only) added.output = true; if (on_take) added.on_take = (item) => guarded("an on_take", () => on_take(item_api(item))) === true; if (options.icon) added.icon = String(options.icon); if (options.max_count !== undefined) { if (!Number.isInteger(options.max_count) || options.max_count < 1) { throw new Error(`slot ${slot}'s max_count must be a whole number, at least 1`); } added.max_count = options.max_count; } if (engine === player.inventory) added.inventory = slot; return added; } // a menu's fluid slot from what a mod's add_fluid_slot got function menu_fluid_slot( game: GameServer, mod: string, player: ServerPlayer, handler: FluidHandler, tank: number, options: FluidSlotOptions, ): MenuFluidSlot { if (typeof handler?.fluid_in_tank !== "function") throw new Error("add_fluid_slot needs a fluid handler"); const tanks = handler.tanks(); if (!Number.isInteger(tank) || tank < 0 || tank >= tanks) { throw new Error(`tank ${tank} isn't in the handler, it has ${tanks}`); } if (![options?.x, options?.y].every((n) => typeof n === "number" && Number.isFinite(n))) { throw new Error(`fluid slot ${tank} needs an x and y`); } const output = options.output_only === true; return { x: options.x, y: options.y, output, tank: () => run_guarded(mod, "a fluid slot's handler", () => { const fluid = handler.fluid_in_tank(tank); const capacity = handler.tank_capacity(tank); return fluid ? { fluid: structuredClone(fluid.fluid), amount: fluid.amount, capacity } : { amount: 0, capacity }; }) ?? { amount: 0, capacity: 0 }, click() { const cursor = player.cursor.item; if (!cursor) return; const result = run_guarded( mod, "a fluid slot's handler", () => use_container(item_copy(cursor), handler, { tank, drain_only: output }), ); if (!result) return; // the one used becomes what it was turned into, which goes in the inventory while there are more of it cursor.amount -= 1; if (cursor.amount <= 0) player.cursor.item = new_stack(result); else game.give_stack(player, new_stack(result)); }, }; } // the engine container behind each one mods get, for menus' slots const engine_containers = new WeakMap(); // an engine container as mods see it function container_api(game: GameServer, id: string, container: EngineContainer): Container { const api: Container = { id, size: container.size, get: (slot) => { const stack = container.get_item(slot); return stack && item_api(stack); }, set: (slot, item) => { if (!Number.isInteger(slot) || slot < 0 || slot >= container.size) { throw new Error(`slot ${slot} isn't in the container, it has ${container.size}`); } container.set_item(slot, item ? new_stack(item) : undefined); }, add: (item) => { const stack = new_stack(item); const left = container.add_item(stack); return left > 0 ? { id: item.id, count: left, data: stack.data } : undefined; }, on_change: (fn) => game.mods.watch_container(running_mod || "unknown", container, fn), }; engine_containers.set(api, container); return api; } // what ServerWorld.raycast hits in a block: what entities bump into, and fluids up to their surface when it's // looking for them function raycast_shape( world: GameServer["world"], x: number, y: number, z: number, fluids: "none" | "source_only" | "any", ): Shape | undefined { const value = world.get_block_value(x, y, z); const nid = value & ID_MASK; if (nid === AIR) return undefined; const block = EverythingRegistry.get_by_id("blocks", nid); if (!block) return undefined; if (block.fluid) { const level = get_state_value(value, block, "level") ?? 0; if (fluids === "none" || (fluids === "source_only" && level !== 0)) return undefined; return [[0, 0, 0, 1, fluid_height(level, block.fluid.range), 1]]; } // the source in a waterlogged block covers the block, like minecraft's fluid clip if (fluids !== "none" && is_waterlogged(value, block)) return [[0, 0, 0, 1, 1, 1]]; const shape = collision_shape_at(block, value); return shape.length > 0 ? shape : undefined; } function player_api(game: GameServer, player: ServerPlayer): Player { const inventory = container_api(game, `player:${player.id}`, player.inventory); return { get id() { return player.id; }, get name() { return player.name; }, get position() { return { x: player.x, y: player.y, z: player.z }; }, get eye_position() { return { x: player.x, y: player.y + player.eye_height, z: player.z }; }, // the same way the client aims, see ClientLevel.pick get look_direction() { const cos_pitch = Math.cos(player.pitch); return { x: -Math.sin(player.yaw) * cos_pitch, y: Math.sin(player.pitch), z: -Math.cos(player.yaw) * cos_pitch, }; }, get biome() { return game.world.biome_at(Math.floor(player.x), Math.floor(player.z)); }, get season() { return biome_season(this.biome, game.world.time); }, inventory, get selected_slot() { return player.selected_slot; }, get held_item() { const stack = player.held_item; return stack && item_api(stack); }, give_item(id, count = 1, data) { if (!EverythingRegistry.get("items", id)) throw new Error(`unknown item ${id}`); game.give(player, id, count, data); }, exchange_held(result) { const held = player.held_item; if (!held) throw new Error("exchange_held needs something in the hand"); const stack = new_stack(result); held.amount -= 1; if (held.amount <= 0) player.inventory.set_item(player.selected_slot, stack); else game.give_stack(player, stack); }, send_message(text, options) { game.send_chat(player, String(text), options?.overlay === true); }, set_worn(key, items) { if (typeof key !== "string" || key.length === 0) throw new Error('set_worn needs a key, like "mymod:hats"'); if (!Array.isArray(items)) throw new Error("set_worn needs a list of items, [] for none"); if (items.length === 0) player.worn.delete(key); else player.worn.set(key, items.map(new_stack)); }, teleport(x, y, z) { game.teleport(player, x, y, z); }, get health() { return player.health; }, get max_health() { return player.max_health; }, get food() { return player.vitals.food; }, get saturation() { return player.vitals.saturation; }, damage(amount, cause = "script") { if (typeof amount !== "number" || !Number.isFinite(amount)) throw new Error(`damage must be a number`); game.damage_player(player, amount, String(cause)); }, heal(amount) { if (typeof amount !== "number" || !Number.isFinite(amount)) throw new Error(`heal must be a number`); game.heal_player(player, amount); }, feed(nutrition, saturation_modifier) { if (![nutrition, saturation_modifier].every((n) => typeof n === "number" && Number.isFinite(n) && n >= 0)) { throw new Error("feed takes two numbers of 0 or more"); } player.vitals.eat(nutrition, saturation_modifier); }, add_exhaustion(amount) { if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0) { throw new Error("exhaustion must be a number of 0 or more"); } player.vitals.add_exhaustion(amount); }, attribute: (id) => player.attribute(known_attribute(id)), add_modifier(attribute, modifier) { const type = known_attribute(attribute); const { id, amount, operation } = modifier; if (typeof id !== "string" || typeof amount !== "number" || !Number.isFinite(amount)) { throw new Error("a modifier needs a string id and a number amount"); } if (!MODIFIER_OPERATIONS.includes(operation)) throw new Error(`unknown modifier operation ${operation}`); player.attributes.get(type)?.add_modifier({ id, amount, operation }); }, remove_modifier: (attribute, id) => player.attributes.get(known_attribute(attribute))?.remove_modifier(id) ?? false, add_effect(id, duration, options = {}) { const type = known_effect(id); if (!Number.isInteger(duration) || (duration < 1 && duration !== -1)) { throw new Error("an effect's duration is a whole number of ticks, or -1 for forever"); } const amplifier = options.amplifier ?? 0; if (!Number.isInteger(amplifier) || amplifier < 0) { throw new Error("amplifier must be a whole number of 0 or more"); } player.add_effect(new EffectInstance(type, duration, { ...options, amplifier })); }, effect(id) { const effect = player.get_effect(known_effect(id).id); return effect && { amplifier: effect.amplifier, duration: effect.duration }; }, remove_effect: (id) => player.remove_effect(known_effect(id).id), is_swimming: () => player.swimming, is_sneaking: () => player.sneaking, push(x, y, z) { if (![x, y, z].every(Number.isFinite)) throw new Error("a push is three numbers, in blocks a second"); game.push_player(player, x, y, z); }, start_using(ticks) { if (!Number.isInteger(ticks) || (ticks < 1 && ticks !== -1)) { throw new Error("start_using takes a whole number of ticks, or -1 until they let go"); } game.start_using(player, ticks); }, stop_using() { player.using = undefined; }, is_using: () => player.using !== undefined, }; } function known_effect(id: string): EffectType { const type = effect_type(id); if (!type) throw new Error(`unknown effect ${id}`); return type; } function known_attribute(id: string): AttributeType { const type = attribute_type(id); if (!type) throw new Error(`unknown attribute ${id}`); return type; } function living_ref(entity: LivingEntity): LivingRef { return { id: entity.id, get health() { return entity.health; }, get max_health() { return entity.max_health; }, damage(amount, cause = "script") { if (typeof amount !== "number" || !Number.isFinite(amount)) throw new Error(`damage must be a number`); entity.hurt(amount, damage_source(String(cause))); }, heal(amount) { if (typeof amount !== "number" || !Number.isFinite(amount)) throw new Error(`heal must be a number`); entity.heal(amount); }, }; } export function entity_ref(entity: Entity): EntityRef { return { id: entity.id, type: entity.type, get position() { return { x: entity.x, y: entity.y, z: entity.z }; }, get biome() { return entity.level.biome_at(Math.floor(entity.x), Math.floor(entity.z)); }, get season() { return entity.level.season_at(Math.floor(entity.x), Math.floor(entity.z)); }, get removed() { return entity.removed; }, get velocity() { return { x: entity.vx, y: entity.vy, z: entity.vz }; }, get on_ground() { return entity.on_ground; }, teleport(x, y, z) { if (!entity.removed) entity.set_position(x, y, z); }, push(x, y, z) { if (![x, y, z].every(Number.isFinite)) throw new Error("a push is three numbers, in blocks a second"); entity.vx += x; entity.vy += y; entity.vz += z; }, remove() { entity.remove(); }, get_item: () => entity instanceof ItemEntity ? item_copy(entity.item) : undefined, set_item(item) { if (!(entity instanceof ItemEntity)) throw new Error(`${entity.type} isn't an item lying around`); if (entity.removed) return; if (!item || item.count <= 0) entity.remove(); else entity.item = new_stack(item); }, }; }