Files
2026-11-22 16:09:11 -03:00

1033 lines
50 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// what server phases get, see docs/modding/
import type {
EventSignal,
Face,
FluidApi,
FluidStack,
FluidVariant,
Id,
ItemStack,
ModInfo,
PlayOptions,
Position,
RecipeLookup,
Season,
TagApi,
} from "./shared.ts";
import type { ArgumentType, CommandNode } from "../commands.ts";
import type { LootTableJson } from "../loot.ts";
import type { Schematic } from "../schematic.ts";
export type { ArgumentType, CommandContext, CommandNode, Suggestion } from "../commands.ts";
export type { Schematic, SchematicBlock, SchematicEntity, SchematicPaletteEntry } from "../schematic.ts";
export type {
EventSignal,
Face,
FluidApi,
FluidStack,
FluidVariant,
Id,
ItemStack,
ModInfo,
PlayOptions,
Position,
Season,
TagApi,
TagRegistry,
} from "./shared.ts";
export interface ServerContext {
mod: ModInfo;
// the mod's settings: its config.json's "config", with the server's changes from config/<mod id>.json. the same
// for the whole time the server runs. see docs/modding/misc/config.md
// deno-lint-ignore no-explicit-any
readonly config: any;
components: ComponentRegistry; // only during setup
commands: CommandRegistry; // only during setup
// mob behaviors, see docs/modding/entities/index.md. register_behavior only during setup
entities: EntityApi;
events: { before: ServerBeforeEvents; after: ServerAfterEvents };
system: System;
world: ServerWorld;
players: PlayerList;
containers: ContainerApi;
schematics: SchematicApi;
items: ItemApi;
blocks: BlockApi;
// every fluid, named and colored by its rules, and fluid handlers, see docs/modding/resources/fluids.md
fluids: ServerFluidApi;
recipes: RecipeApi;
tags: TagApi;
loot: LootApi;
menus: MenuRegistry;
ui: ServerUi;
net: ServerNet;
storage: ModStorage;
// sounds from the mods' sounds.json, played on players' clients, see docs/modding/resources/sounds.md
sounds: ServerSounds;
log(...args: unknown[]): void;
}
// one-off sounds. what lasts, like a machine's hum, is a client phase's to play, see ClientSounds in cubi/client
export interface ServerSounds {
// once at x y z, for every player within its range. except leaves out a player whose own client already played it,
// like the one whose click a client phase answered with a sound. throws for a sound no mod defines
play(sound: Id, x: number, y: number, z: number, options?: PlayOptions & { except?: Player }): void;
exists(sound: Id): boolean;
}
// components
export interface BlockRef {
readonly id: Id;
readonly x: number;
readonly y: number;
readonly z: number;
// the biome at the block and that biome's season, see ServerWorld.biome_at
readonly biome: Id;
readonly season: Season;
// tile data, any json value. saved with the world, never sent to clients
// deno-lint-ignore no-explicit-any
data: any;
// the part of its data clients see too, like how fast a shaft turns, by field. each is any json value, saved with
// the world, sent to players with the block's chunk and again when it's set to something else, so a field that
// changes often doesn't resend the rest. undefined removes a field, and they all go with the block. "item" is the
// item a block with item_display shows, see set_block_item. get returns a copy
get_client_data<T>(field: string): T | undefined;
set_client_data(field: string, value: unknown): void;
// turns on_tick and on_second off for this block, or back on, like a machine with nothing to do. it stays off until
// it's turned on again, saved with the world, and goes with the block
set_ticking(ticking: boolean): void;
// ctx.sounds.play at its middle
play_sound(sound: Id, options?: PlayOptions): void;
}
// P is the component's params from the block json
// deno-lint-ignore no-explicit-any
export interface BlockComponent<P = any> {
on_create?(block: BlockRef, params: P): void;
on_break?(block: BlockRef, params: P, player: Player | undefined): void;
on_click?(block: BlockRef, params: P, player: Player): void;
// return true if it did something, so no block gets placed
on_interact?(block: BlockRef, params: P, player: Player): boolean;
// the player turned the mouse wheel while looking at it, for a block whose json has "scrollable": true, like a
// setting turned up and down. the wheel doesn't change their hotbar slot then
on_scroll?(block: BlockRef, params: P, player: Player, scroll: BlockScroll): void;
on_tick?(block: BlockRef, params: P, dt: number): void;
on_second?(block: BlockRef, params: P, dt: number): void;
// every morning at 06:00, for every block with data in the world, near a player or not. day is ServerWorld.day
on_new_day?(block: BlockRef, params: P, day: number): void;
// a block on one of its 6 sides was placed, broken or changed its states, like neoforge's neighborChanged. after
// the shared rules' on_neighbor_change, so it sees what they changed, and can do what rules can't: read tile data,
// change other blocks. neighbor is where, and what's there now
on_neighbor_change?(block: BlockRef, params: P, neighbor: { readonly id: Id } & Position): void;
// its own states changed without it being replaced, by set_state or a rule, like a clutch another mod powers.
// before is what they were. it runs right away, before the blocks beside it hear of the change
on_state_change?(block: BlockRef, params: P, before: Readonly<Record<string, number>>): void;
// the tick ServerWorld.schedule_tick asked for came, like neoforge's tick from scheduleTick
on_scheduled_tick?(block: BlockRef, params: P): void;
// an entity is standing on it, every tick the entity moves, like minecraft's updateEntityAfterFallOn: an item
// dropped into a basin going in. items lying still move every tick too
on_entity_stand?(block: BlockRef, params: P, entity: EntityRef): void;
// an entity's box is in it, every tick the entity moves, like neoforge's entityInside: a block that kills or slows
// what walks into it. players' after each move their client sends. any block, whatever its shape, so one that
// cares where in it the entity is checks the entity's position
on_entity_inside?(block: BlockRef, params: P, entity: EntityRef): void;
// what pipes, buckets and other blocks put fluid in and take it out by, reached from face, or from no side in
// particular when it's undefined, like neoforge's Capabilities.FluidHandler.BLOCK. undefined when it has none
// there. see ServerFluidApi.block_handler
fluid_handler?(block: BlockRef, params: P, face: Face | undefined): FluidHandler | undefined;
// its tile data the way it's kept outside the world, in a schematic, like neoforge's
// BlockEntity.saveWithoutMetadata: what lives elsewhere written in, like its container's items in place of the
// container's id. any json value. the first of its components that returns something other than undefined gives
// it, and a block without any keeps its data as it is
export_data?(block: BlockRef, params: P): unknown;
// placing and neighbor rules are in shared phases, see BlockRules in cubi/shared
}
// deno-lint-ignore no-explicit-any
export interface ItemComponent<P = any> {
on_create?(item: ItemStack, params: P): void;
get_lore?(item: ItemStack, params: P): string;
// right clicked while holding it, at nothing or at the block in target, like minecraft's use and useOn
on_use?(item: ItemStack, params: P, player: Player, target: UseTarget | undefined): void;
// using it over time, see Player.start_using. every tick while they do, ticks counting from 1, like onUseTick
on_use_tick?(item: ItemStack, params: P, player: Player, ticks: number): void;
// they let go of use before it finished, like a bow being shot, after using it for ticks. like releaseUsing
on_release_using?(item: ItemStack, params: P, player: Player, ticks: number): void;
// they used it for as long as start_using said, like food being eaten. like finishUsingItem
on_finish_using?(item: ItemStack, params: P, player: Player): void;
}
// the block an item was used on, the face that was clicked, and where on the block (0 to 1 on each axis)
export interface UseTarget {
readonly block: BlockRef;
readonly face: Face;
readonly hit: readonly [number, number, number];
}
// P is the component's params from the effect json. see docs/modding/entities/effects.md
// deno-lint-ignore no-explicit-any
export interface EffectComponent<P = any> {
// whether on_tick runs this tick, like neoforge's shouldApplyEffectTickThisTick. ticks is what's left of the
// effect, or how long it's been on for ones that last forever. every tick when not set
should_tick?(ticks: number, amplifier: number, params: P): boolean;
// like neoforge's applyEffectTick. returning false takes the effect off. instant effects run it once, when added
on_tick?(entity: LivingRef, amplifier: number, params: P): boolean | void;
}
// a player or a mob, what effects work on
export interface LivingRef {
readonly id: string;
readonly health: number;
readonly max_health: number;
// ticks of air left under water, max_air when full. it drowns 20 ticks after reaching 0. setting it over max_air
// sets max_air
air: number;
readonly max_air: number;
// the one it has of that type, like Player.effect
effect(id: Id): { readonly amplifier: number; readonly duration: number } | undefined;
// cause is for events and the death message, like "magic"
damage(amount: number, cause?: string): void;
heal(amount: number): void;
// its stats, like Player's: "cubi:movement_speed", "cubi:attack_damage"... a mob's modifiers are saved with it
attribute(id: Id): number;
// replaces one with the same id on that attribute
add_modifier(attribute: Id, modifier: AttributeModifier): void;
// whether it had it
remove_modifier(attribute: Id, id: string): boolean;
}
export interface ComponentRegistry {
register_block<P>(id: Id, component: BlockComponent<P>): void;
register_item<P>(id: Id, component: ItemComponent<P>): void;
register_effect<P>(id: Id, component: EffectComponent<P>): void;
}
// mob behaviors, like neoforge's Mob.registerGoals: an entity whose json has "behavior": "my_mod:thing" gets its goals
// from the function registered under that id
export interface EntityApi {
// runs once for each mob with this behavior, before its first thought. what the mob has to remember goes in the
// function's closures, one set per mob. only during setup
register_behavior(id: Id, behavior: (mob: MobRef, goals: MobGoals) => void): void;
// the engine's own goals, to add next to a mod's
readonly goals: BuiltinGoals;
}
// the controls a goal needs while it runs. a goal only starts once every flag it has is free, or held by a less
// important goal that can be interrupted, which then stops. "target" is for goals that pick who the mob is after
export type GoalFlag = "move" | "look" | "jump" | "target";
// something a mob does, like minecraft's Goal. every tick, running goals that can't continue stop, then goals that
// can start do, most important first, then every running goal ticks
export interface ScriptGoal {
flags?: GoalFlag[];
// whether it wants to start
can_use(): boolean;
// whether it wants to keep going, can_use when not given
can_continue_to_use?(): boolean;
// whether a more important goal can take its flags, true when not given
is_interruptable?(): boolean;
start?(): void;
stop?(): void;
tick?(): void;
}
// what a behavior adds its goals to. a lower priority number is more important
export interface MobGoals {
// what it does
add(priority: number, goal: ScriptGoal | BuiltinGoal): void;
// who it goes after, like minecraft's targetSelector. these set mob.target
add_target(priority: number, goal: ScriptGoal | BuiltinGoal): void;
}
// one of the engine's goals, made by BuiltinGoals and built for the mob when it's added
export interface BuiltinGoal {
readonly kind: string;
}
// the goals animal and monster behaviors are made of. speeds multiply the mob's movement_speed
export interface BuiltinGoals {
// swims up in water so it doesn't drown
float(): BuiltinGoal;
// wanders to a random spot within range every interval ticks or so
random_stroll(options?: { speed?: number; interval?: number; range?: number }): BuiltinGoal;
// runs around after being hurt or while burning
panic(options?: { speed?: number }): BuiltinGoal;
// looks at a player within range for a couple of seconds, with probability each tick
look_at_player(options?: { range?: number; probability?: number }): BuiltinGoal;
random_look_around(): BuiltinGoal;
// walks to its target and hits it with its attack_damage, at most once every interval ticks
melee_attack(options?: { speed?: number; interval?: number }): BuiltinGoal;
// target goals: whoever hurt it last, and the nearest player within its follow range
hurt_by_target(): BuiltinGoal;
nearest_attackable_player(): BuiltinGoal;
}
// a mob, the way its behavior's goals see it. each mob has one, so a target can be compared with ===
export interface MobRef extends LivingRef {
readonly type: Id;
readonly position: Readonly<Position>;
// where it sees from and which way it looks, a vector 1 long, like Player's
readonly eye_position: Readonly<Position>;
readonly look_direction: Readonly<Position>;
// in blocks a second
readonly velocity: Readonly<Position>;
readonly on_ground: boolean;
readonly in_water: boolean;
// who it's after, set by target goals or by a script. undefined once they die or leave
target: Player | MobRef | undefined;
// who hurt it last
readonly last_attacker: Player | MobRef | undefined;
// a number from 0 to 1, from the mob's own random, which tests replace
random(): number;
// finds a way to x y z around what's in between and walks it, see PATHFINDING.md. when the whole way isn't there it
// walks as close as it can get. false when it can't get any closer, or when it searched in vain less than a second
// ago, keeping the way it had. speed multiplies its movement_speed
move_to(x: number, y: number, z: number, speed?: number): boolean;
// stops walking its way
stop(): void;
// whether it's still on its way
readonly moving: boolean;
// a solid block in its way that its way goes through, tagged #cubi:mobs_path_through, which it's pressed against.
// it waits there for as long as the block is solid and in its way, instead of giving up
readonly blocked_by: { readonly x: number; readonly y: number; readonly z: number; readonly id: Id } | undefined;
// turns its head, and its body after it, toward a point. it stops after a couple of ticks, so a goal that keeps
// looking at something calls this every tick
look_at(x: number, y: number, z: number): void;
// this tick: jumps if it's on the ground, swims up if it's in water
jump(): void;
// swings its arm and hits target with its attack_damage, wherever target is
attack(target: Player | MobRef): void;
// what clients see of its state, like BlockRef's: what its animator reads (see register_entity_animator in
// cubi/client). each field is any json value, saved with it, and sent to clients when it changes. undefined
// removes one
get_client_data<T>(field: string): T | undefined;
set_client_data(field: string, value: unknown): void;
// a sound following it, like EntityRef.play_sound
play_sound(sound: Id, options?: PlayOptions): void;
}
// commands, brigadier's way like neoforge's: see common/commands.ts and docs/modding/misc/commands.md
// who ran a command
export interface CommandSource {
readonly player: Player;
// answers them in chat
send_message(text: string): void;
}
// the simple way: the words after the name, split on spaces
export interface Command {
description: string;
usage: string;
run(args: string[], player: Player): void;
}
export interface CommandRegistry {
// a tree of literal() and argument() nodes, like neoforge's dispatcher.register(literal("heal").then(...))
register(node: CommandNode<CommandSource>): void;
register(name: string, command: Command): void;
literal(name: string): CommandNode<CommandSource>;
argument<T>(name: string, type: ArgumentType<T, CommandSource>): CommandNode<CommandSource>;
// argument types. they parse their text and suggest what could go there as players type
types: {
integer(min?: number, max?: number): ArgumentType<number, CommandSource>;
number(min?: number, max?: number): ArgumentType<number, CommandSource>;
boolean(): ArgumentType<boolean, CommandSource>;
word(): ArgumentType<string, CommandSource>;
greedy_string(): ArgumentType<string, CommandSource>;
// a json value, the rest of the line like greedy_string
json(): ArgumentType<unknown, CommandSource>;
choice<T extends string>(options: readonly T[]): ArgumentType<T, CommandSource>;
// an item, block or fluid id. without a namespace, whichever has that name
item(): ArgumentType<Id, CommandSource>;
block(): ArgumentType<Id, CommandSource>;
fluid(): ArgumentType<Id, CommandSource>;
// an online player's name
player(): ArgumentType<Player, CommandSource>;
};
}
// events
export interface Cancelable {
cancel: boolean;
}
export interface BlockBreakEvent {
readonly player: Player;
readonly block: BlockRef;
readonly item: ItemStack | undefined;
}
export interface BlockPlaceEvent {
readonly player: Player;
readonly block: { readonly id: Id } & Position;
readonly face: Face;
// where on the clicked block the player clicked, 0 to 1 on each axis
readonly hit: readonly [number, number, number];
readonly item: ItemStack | undefined;
}
export interface BlockInteractEvent {
readonly player: Player;
readonly block: BlockRef;
readonly item: ItemStack | undefined;
}
// a right click on an entity, like neoforge's PlayerInteractEvent.EntityInteract
export interface EntityInteractEvent {
readonly player: Player;
readonly entity: EntityRef;
readonly item: ItemStack | undefined;
}
// a player or a mob being hurt, like neoforge's LivingIncomingDamageEvent
export interface EntityDamageEvent {
readonly entity: LivingRef;
// set when a player is hurt
readonly player: Player | undefined;
// before events can change it
amount: number;
// what hurt it: "fall", "void", "starve", "mob_attack", or what a mod passed to damage
readonly cause: string;
// like falling out of the world. even invulnerable entities are hurt
readonly bypasses_invulnerability: boolean;
}
export interface PlayerDeathEvent {
readonly player: Player;
readonly cause: string;
}
export interface ChatSendEvent {
readonly player: Player;
message: string;
}
export interface ServerBeforeEvents {
block_break: EventSignal<BlockBreakEvent & Cancelable>;
block_place: EventSignal<BlockPlaceEvent & Cancelable>;
block_interact: EventSignal<BlockInteractEvent & Cancelable>;
// handlers do what the click does, and cancel it so the held item isn't used too
entity_interact: EventSignal<EntityInteractEvent & Cancelable>;
chat_send: EventSignal<ChatSendEvent & Cancelable>;
entity_damage: EventSignal<EntityDamageEvent & Cancelable>;
}
export interface ServerAfterEvents {
block_break: EventSignal<BlockBreakEvent>;
block_place: EventSignal<BlockPlaceEvent>;
block_interact: EventSignal<BlockInteractEvent>;
chat_send: EventSignal<Readonly<ChatSendEvent>>;
player_join: EventSignal<{ readonly player: Player }>;
player_leave: EventSignal<{ readonly player: Player }>;
// it was hurt, after before handlers had their say. amount is what it took
entity_damage: EventSignal<Readonly<EntityDamageEvent>>;
// they drop what they carried and respawn right after
player_death: EventSignal<PlayerDeathEvent>;
server_start: EventSignal<Record<never, never>>;
tick: EventSignal<{ readonly dt: number }>;
// 06:00, after every block's on_new_day
new_day: EventSignal<{ readonly day: number }>;
}
// world and players
export interface ServerWorld {
// generates the chunk if it never was, which takes a while, see is_loaded
get_block(x: number, y: number, z: number): Id | undefined;
// runs on_break / on_create, synced to everyone. states are the ones it's placed with, the rest keep their defaults,
// like minecraft's setBlock with a block state: a shaft turned into an encased one keeps its axis
set_block(x: number, y: number, z: number, id: Id, states?: Record<string, number>): boolean;
// every block between two corners, both included, set to id like set_block, like a schematic all at once: they all
// change before any of them hears of it. parts above or below the world are left out. says how many it changed
fill(from: Position, to: Position, id: Id): number;
// like breaking it by hand without a tool: on_break, then its drops, which it returns (copies). undefined when there
// was nothing to break. see BreakOptions for machines breaking it
break_block(x: number, y: number, z: number, options?: BreakOptions): ItemStack[] | undefined;
// cracks on the block, 0 to 1 of the way to breaking, shown to everyone who sees it, like minecraft's
// destroyBlockProgress: a drill getting through it. undefined takes them off, and so does the block changing
set_break_progress(x: number, y: number, z: number, progress: number | undefined): void;
get_state(x: number, y: number, z: number, name: string): number | undefined;
// update_neighbors false changes the state without telling the blocks around it, for a script that tells them
// itself, like a wire telling each block beside its whole length once. on_state_change still runs
set_state(x: number, y: number, z: number, name: string, value: number, options?: SetStateOptions): boolean;
// tells the block at x y z that the one at from changed, running its rules' and components' on_neighbor_change,
// like neoforge's neighborChanged. for a block whose effect on others changed without it changing, or for blocks
// it reaches that aren't beside it. it hears once the change going on is done, like the blocks beside one do
neighbor_changed(x: number, y: number, z: number, from: Position): void;
// runs the block's components' on_scheduled_tick in delay ticks (at least 1), if the same kind of block is still
// there, like neoforge's scheduleTick. one per block: scheduling while one waits does nothing. of those due on the
// same tick, lower priority (-8 to 7, 0 when not given) runs first, then the order they were scheduled in. saved
// with the world. they only run within 6 chunks of a player, the rest wait until one comes near
schedule_tick(x: number, y: number, z: number, delay: number, priority?: number): void;
has_scheduled_tick(x: number, y: number, z: number): boolean;
// whether the block's side is a full square things can attach to, like minecraft's isFaceSturdy: its collision
// shape covers the whole face. false for air, plants, water and the sides of a slab
is_face_sturdy(x: number, y: number, z: number, face: Face): boolean;
get_block_data<T>(x: number, y: number, z: number): T | undefined;
// the block the way its components' handlers get it, for changing another block's data or client data, like
// minecraft's getBlockEntity. undefined for air
get_block_ref(x: number, y: number, z: number): BlockRef | undefined;
// BlockRef.set_ticking for a block, for waking one from somewhere else, like a machine getting something to work on
set_block_ticking(x: number, y: number, z: number, ticking: boolean): void;
// the item a block with item_display shows on top of it, like a block entity renderer: its "item" client data, see
// BlockRef.set_client_data. undefined shows nothing. it goes away with the block, without dropping
set_block_item(x: number, y: number, z: number, item: ItemStack | undefined): void;
// a copy
get_block_item(x: number, y: number, z: number): ItemStack | undefined;
// pops an item out of the block at x y z, like a broken block's drops
drop_item(x: number, y: number, z: number, item: ItemStack): void;
// an item lying still at x y z, which players can pick up after half a second, like a new minecraft ItemEntity
spawn_item(x: number, y: number, z: number, item: ItemStack): EntityRef;
// the entities whose boxes touch the box between two corners, like minecraft's getEntitiesOfClass. only ones of type
// when given, like "cubi:item" for items lying around. players aren't among them, they're in ctx.players
entities_in(from: Position, to: Position, type?: Id): EntityRef[];
// uses item on face of the block at x y z the way a player holding it would, like a deployer: the block's
// on_interact, or the item's on_use, or placing it. a player that isn't anyone does it, standing in the block in
// front of that face and looking at it, like neoforge's FakePlayer. returns what it's holding after (what's left of
// item, or what it turned into) and anything else it was given, like a bucket filled from a stack of them
use_item_on(item: ItemStack, x: number, y: number, z: number, face: Face): {
item: ItemStack | undefined;
given: ItemStack[];
};
// an entity from entities/ with its feet at x y z. throws for kinds that don't exist
spawn_entity(id: Id, x: number, y: number, z: number): EntityRef;
// the first block on the line from one point to another, like minecraft's Level.clip. it hits what entities bump
// into, so it goes through plants and other blocks without collision. undefined when nothing is in the way
raycast(from: Position, to: Position, options?: RaycastOptions): RaycastHit | undefined;
// which way the fluid at x y z flows, a vector 1 long, or 0 0 0 where it's still or there's none, like minecraft's
// FluidState.getFlow: toward lower cells of it beside it, and down where it falls. for what it pushes, like a wheel
fluid_flow(x: number, y: number, z: number): Position;
// whether the chunk the column is in was ever generated, so reading its blocks generates nothing. for code that
// reaches far, like a walk along something long, which can stop at the rest: nobody has built anything there
is_loaded(x: number, z: number): boolean;
// the biome at a block, like "bworld:plains", and that biome's season, like neoforge's level.getBiome(pos). one per
// block across and every 4 blocks up, see docs/modding/worldgen/biomes.md. in chunks that aren't loaded it's what
// generation makes there, which takes a while the first time
biome_at(x: number, y: number, z: number): Id;
season_at(x: number, y: number, z: number): Season;
// the dimension's blocks go from min_y up to max_y - 1. outside them get_block is air and nothing can be placed
readonly min_y: number;
readonly max_y: number;
readonly seed: string;
// ticks since 06:00 of day 1. a day is 36000 ticks (06:00 to 18:00), a night 12000
readonly time: number;
// days since the world started, going up at 06:00 each morning: 0 on the first day
readonly day: number;
// the time on a 24 hour clock, in hours: 14.5 is 14:30. hours go by faster at night, see common/time.ts
readonly hour: number;
set_time(time: number): void;
}
// the mouse wheel turned at a block, see BlockComponent.on_scroll
export interface BlockScroll {
// how many notches, more than 0 turned up and less than 0 down
readonly amount: number;
readonly face: Face;
// where on the block they look, 0 to 1 on each axis, like BlockInteraction's
readonly hit: readonly [number, number, number];
}
export interface MessageOptions {
// shows it above their hotbar for a moment instead of in chat, like neoforge's overlay messages. for something
// that changes as they do it, like a setting they're scrolling through
overlay?: boolean;
}
export interface SetStateOptions {
// true when not given
update_neighbors?: boolean;
}
// how a machine breaks a block, see ServerWorld.break_block
export interface BreakOptions {
// it drops what it would for the right tool, though nothing holds one, like create's drills and saws
harvest?: boolean;
// the drops are only returned, not dropped, for a machine to put somewhere, like a saw onto a belt
collect?: boolean;
}
export interface RaycastOptions {
// like minecraft's ClipContext.Fluid: "none" (the default) goes through fluids, "source_only" hits their sources
// and goes through where they flow, "any" hits all of them. a fluid is hit at its surface
fluids?: "none" | "source_only" | "any";
}
export interface RaycastHit {
// the block it hit, and where that is
readonly id: Id;
readonly x: number;
readonly y: number;
readonly z: number;
// the side it went in by
readonly face: Face;
// the exact point it hit
readonly position: Readonly<Position>;
}
// an entity in the world. once it's removed, by a script or anything else, it stays removed and moving it does nothing
export interface EntityRef {
readonly id: string;
readonly type: Id;
readonly position: Readonly<Position>;
// the biome where its feet are and that biome's season
readonly biome: Id;
readonly season: Season;
readonly removed: boolean;
// how fast it's moving, in blocks a second
readonly velocity: Readonly<Position>;
// standing or lying on something, like an item that's landed, like minecraft's onGround
readonly on_ground: boolean;
teleport(x: number, y: number, z: number): void;
// adds to how fast it's moving, in blocks a second, like minecraft's Entity.push: a fan blowing it along
push(x: number, y: number, z: number): void;
remove(): void;
// like neoforge's Entity.kill: a player or a mob dies, even when invulnerable, and anything else is removed. cause
// is for events and the death message, like LivingRef.damage's. mods' entity_damage can still cancel it
kill(cause?: string): void;
// what an item lying around is, or what an object holds, a copy. undefined for every other kind of entity
get_item(): ItemStack | undefined;
// changes what an item lying around is, like ItemEntity.setItem, undefined or a count of 0 removing it. or what an
// object holds, undefined or a count of 0 leaving it holding nothing. throws for every other kind of entity
set_item(item: ItemStack | undefined): void;
// a sound following it, once, for every player who sees it and is within its range
play_sound(sound: Id, options?: PlayOptions): void;
}
export interface Player {
readonly id: string;
readonly name: string;
readonly position: Readonly<Position>;
// where they see from, lower while swimming, and which way they look as a vector 1 long. for aiming, like
// ctx.world.raycast(player.eye_position, ...)
readonly eye_position: Readonly<Position>;
readonly look_direction: Readonly<Position>;
// the biome where their feet are and that biome's season
readonly biome: Id;
readonly season: Season;
readonly inventory: Container; // 36 slots, hotbar is 0-8
readonly selected_slot: number;
readonly held_item: ItemStack | undefined;
// what doesn't fit in the inventory drops at their feet
give_item(id: Id, count?: number, data?: unknown): void;
// one of the held item becomes result, like an empty bucket filling: straight into the hand when it was the last
// one, into the inventory (or at their feet) when there are more
exchange_held(result: ItemStack): void;
send_message(text: string, options?: MessageOptions): void;
// items drawn on them, under a key so each mod keeps its own list, like "bworld:curios". replaces what that key
// had, [] clears it. only items whose json has worn show. not saved: set it again when they join
set_worn(key: string, items: ItemStack[]): void;
teleport(x: number, y: number, z: number): void;
// health and hunger, like minecraft: 20 each, saturation is never above hunger. max_health is the
// cubi:max_health attribute
readonly health: number;
readonly max_health: number;
readonly food: number;
readonly saturation: number;
// cause is for events and the death message, like "fall"
damage(amount: number, cause?: string): void;
heal(amount: number): void;
// like eating: nutrition in hunger points, saturation_modifier like minecraft's (bread's is 0.6)
feed(nutrition: number, saturation_modifier: number): void;
// tires them out: 4 costs a point of saturation, or of hunger once it's gone
add_exhaustion(amount: number): void;
// their stats, like minecraft's attributes: "cubi:attack_damage", "cubi:attack_speed", "cubi:max_health"...
// see docs/modding/entities/players.md. modifiers aren't saved, they're gone when the player leaves
attribute(id: Id): number;
// replaces one with the same id on that attribute
add_modifier(attribute: Id, modifier: AttributeModifier): void;
// whether it had it
remove_modifier(attribute: Id, id: string): boolean;
// status effects, any mod's, like the base game's "bworld:regeneration". duration in ticks, -1 for forever.
// adding one they have merges them like minecraft: the stronger wins, and a weaker longer one waits under it
add_effect(id: Id, duration: number, options?: EffectOptions): void;
// the one they have of that type, undefined when they don't
effect(id: Id): { readonly amplifier: number; readonly duration: number } | undefined;
// whether they had it
remove_effect(id: Id): boolean;
// lying flat in water in the 0.8 tall box, like minecraft's isSwimming. their client says when
is_swimming(): boolean;
// holding the sneak key, flying or not, like minecraft's isShiftKeyDown. their client says when
is_sneaking(): boolean;
// adds to how fast they're moving, in blocks a second, like minecraft's Entity.push: a fan blowing them along. their
// client moves them, so it's sent there and added to theirs
push(x: number, y: number, z: number): void;
// keeps using the held item while they hold use, like minecraft's startUsingItem: its components' on_use_tick runs
// every tick, then on_finish_using after ticks, or on_release_using if they let go first. -1 uses it until they let
// go, like a bow. it slows them down like sneaking. for an on_use to call. switching away from it stops it
start_using(ticks: number): void;
// a sound only they hear, as it is wherever they are, like one in a menu. ctx.sounds.play for one others near
// them hear too
play_sound(sound: Id, options?: PlayOptions): void;
// stops using it without on_release_using or on_finish_using, like stopUsingItem
stop_using(): void;
is_using(): boolean;
}
export interface EffectOptions {
amplifier?: number; // level minus 1: 1 is regeneration II
ambient?: boolean; // fainter particles, like from a beacon
show_particles?: boolean;
show_icon?: boolean;
}
// like minecraft's: the base, plus every add_value, plus that times each add_multiplied_base, then times 1 + each
// add_multiplied_total
export interface AttributeModifier {
id: string;
amount: number;
operation: "add_value" | "add_multiplied_base" | "add_multiplied_total";
}
export interface PlayerList {
all(): Player[];
get(id: string): Player | undefined;
by_name(name: string): Player | undefined;
}
export interface System {
run_timeout(fn: () => void, ticks: number): number;
run_interval(fn: () => void, ticks: number): number;
clear_run(handle: number): void;
readonly current_tick: number;
}
// small key value store per mod, saved with the world
export interface ModStorage {
get<T>(key: string): T | undefined;
set(key: string, value: unknown): void; // json values only
delete(key: string): void;
}
// containers and recipes
export interface Container {
readonly id: string;
readonly size: number;
get(slot: number): ItemStack | undefined;
set(slot: number, item: ItemStack | undefined): void;
add(item: ItemStack): ItemStack | undefined; // returns what didn't fit
on_change(fn: (slot: number) => void): () => void;
}
export interface ContainerApi {
create(size: number): Container; // saved with the world
get(id: string): Container | undefined;
delete(id: string): void;
}
// see docs/modding/misc/schematics.md
export interface SchematicApi {
// the blocks between two corners, both of them in it, with their tile data (see BlockComponent.export_data) and
// the entities whose feet are in that box, written to a .cbsm file the host keeps in a temporary directory, like
// create's schematic and quill. resolves to where the file is. throws for a box of more than 1048576 blocks (2^20)
export(from: Position, to: Position): Promise<string>;
// adds a schematic for place, by an id in this mod's namespace, while the server phase runs. it's checked here:
// every state and entity in it has to be registered. blocks that aren't are left out, with a warning
register(id: Id, schematic: Schematic): void;
// a copy of a registered schematic, a file's or one a script registered, with its id, like neoforge's
// StructureTemplateManager.get. undefined for an id nothing registered. for reading what's in it before placing it,
// like where a room's doorways are
get(id: Id): Schematic | undefined;
// every registered schematic's id, the files' and the ones scripts registered, in the order they were registered
ids(): Id[];
// puts a registered schematic in the world, all of it at once, replacing what was there, air too. replaced blocks
// get their on_break. blocks it has data for get that data as it is, the rest their on_create, then everything
// placed tells the blocks beside it. its entities come with new uuids. throws for an id nothing registered, or a
// placement that isn't one, before changing anything
place(id: Id, placement: SchematicPlacement): void;
}
export interface SchematicPlacement {
// where the schematic's lowest corner goes, before it's turned
position: Position;
// the block it turns and mirrors around, from its lowest corner. 0 0 0 by default
position_pivot?: Position;
// clockwise seen from above. turns positions, a state named facing and entities' yaw, see
// docs/modding/misc/schematics.md
rotation?: 0 | 90 | 180 | 270;
// the axis that gets flipped, before it's turned
mirror?: "x" | "z";
}
export interface ItemApi {
exists(id: Id): boolean;
// every item, in load order
ids(): Id[];
// how many fit in one slot, with this data: a full fluid container's can be fewer
max_stack(id: Id, data?: unknown): number;
// how much a fluid container holds when full, in mB, or undefined for an item that isn't one. see
// docs/modding/resources/fluids.md
fluid_capacity(id: Id): number | undefined;
// the tool type it is, like "pickaxe" or "shovel", from the item's "tool"
tool(id: Id): string | undefined;
// takes durability off a tool, kept in its data's damage, like ItemStack.hurtAndBreak. true when that used it up.
// does nothing to items that aren't tools
damage(item: ItemStack, amount: number): boolean;
// what one of it sells for with this data, or undefined if it can't be sold: the item's "base_sell_value", and a full
// fluid container's fluid on top, rounded up. see docs/modding/resources/fluids.md
sell_value(id: Id, data?: unknown): number | undefined;
// the components its json lists and their params, a copy. a mod can read params of its components this way
// without a stack, like the curios slots do for bworld:curio_modifiers
components(id: Id): Record<Id, unknown>;
}
export interface BlockApi {
exists(id: Id): boolean;
// how long breaking it by hand takes without a tool, in seconds, from the block's mining. Infinity for one that
// can't be broken. for machines that break blocks, like a drill
toughness(id: Id): number;
// the components its json lists and their params, a copy, like ItemApi.components. air has none
components(id: Id): Record<Id, unknown>;
// whether it's solid like stone: drawn in the solid layer, and a whole block to bump into in every state. glass,
// leaves, slabs and chests aren't. what passes signals on, and what wire turns corners around. false for air
solid(id: Id): boolean;
}
// fluid handlers, like neoforge's IFluidHandler: tanks others can fill and drain without knowing how a block or an
// item keeps what's in them. see docs/modding/resources/fluids.md
// whether fill and drain do it, or only say what they would, like neoforge's FluidAction
export type FluidAction = "execute" | "simulate";
export interface FluidHandler {
// how many tanks it has, like getTanks
tanks(): number;
// what's in a tank, undefined when it's empty, like getFluidInTank. not to be changed
fluid_in_tank(tank: number): FluidStack | undefined;
// how much a tank holds in mB, like getTankCapacity
tank_capacity(tank: number): number;
// whether a tank can hold the fluid at all, full or not, like isFluidValid
is_fluid_valid(tank: number, fluid: FluidVariant): boolean;
// puts in what of stack fits, returning how much that is, like fill
fill(stack: FluidStack, action: FluidAction): number;
// takes out up to stack's amount of its fluid, or up to a number of mB of whatever it gives first, returning what
// came out, undefined for nothing, like neoforge's two drains
drain(what: FluidStack | number, action: FluidAction): FluidStack | undefined;
}
// a fluid container's, see ServerFluidApi.item_handler. like IFluidHandlerItem
export interface FluidHandlerItem extends FluidHandler {
// one of the container, as filling and draining left it, like getContainer
readonly container: ItemStack;
}
// tanks kept by a script, see ServerFluidApi.tank_handler
export interface TankHandlerOptions {
// how many tanks, and how much each holds in mB
tanks: number;
capacity: number;
// what's in them, without empty ones, read every time the handler is used, so it's never out of date
get(): readonly FluidStack[];
// what's in them after an executed fill or drain changed it, without empty ones, to be kept for get
set(tanks: FluidStack[]): void;
}
// ctx.fluids in server phases: FluidApi, and fluid handlers
export interface ServerFluidApi extends FluidApi {
// the handler of the block at x y z reached from face, from the first of its components with one, like
// level.getCapability(Capabilities.FluidHandler.BLOCK, pos, side). undefined for a block without one there
block_handler(x: number, y: number, z: number, face?: Face): FluidHandler | undefined;
// the handler of one of a stack of fluid containers, undefined for an item that isn't one, like
// Capabilities.FluidHandler.ITEM. it holds a single fluid, full or empty, so it only fills with its whole capacity
// and drains all of it, like neoforge's FluidBucketWrapper. it changes container, not stack
item_handler(stack: ItemStack): FluidHandlerItem | undefined;
// a handler for tanks a script keeps, like neoforge's FluidTank: each holds one fluid, and there's never two of the
// same fluid. a fluid goes into the tank that has it, or else an empty one, and a number of mB drains from the
// first one
tank_handler(options: TankHandlerOptions): FluidHandler;
// pours up to max mB from one handler into the other, what the second takes of what the first gives, returning what
// moved, undefined for nothing, like FluidUtil.tryFluidTransfer
transfer(from: FluidHandler, to: FluidHandler, max: number): FluidStack | undefined;
// the fluid container the player holds filled from handler, or else emptied into it, the held one becoming what
// it's turned into, like FluidUtil.interactWithFluidHandler. returns whether any fluid moved, false when they don't
// hold a fluid container
interact(player: Player, handler: FluidHandler): boolean;
}
// find and all read the recipes of types shared phases registered
export interface RecipeApi extends RecipeLookup {
// every recipe of a mod's own type, like "bworld:cooking", as its json. copies, in load order
// deno-lint-ignore no-explicit-any
list(type: Id): any[];
}
// loot tables, see docs/modding/resources/loot_tables.md
// what's happening when a table is rolled. its built in conditions read block, tool and killed_by_player, mods'
// conditions and functions get all of it
export interface LootContext {
// where it happens, like the broken block or the fishing hook
position?: Position;
// the block being broken. its states are read from the world when not given
block?: { id: Id; x: number; y: number; z: number; states?: Record<string, number> };
// what it's done with, like the tool breaking the block or the fishing rod
tool?: ItemStack;
// who did it: broke the block, fished, killed the mob
player?: Player;
// the mob that died
entity?: EntityRef;
// a player killed it, for the "killed_by_player" condition
killed_by_player?: boolean;
}
// a condition's or function's json, with its "condition" or "function" id and whatever params it has
// deno-lint-ignore no-explicit-any
export type LootParams = Record<string, any>;
export interface LootApi {
exists(id: Id): boolean;
// what rolling the table gives, stacks split to fit a slot. throws for a table that doesn't exist
roll(id: Id, context?: LootContext): ItemStack[];
// rolls the table into the container's empty slots, at random like minecraft's chests. returns what didn't fit
fill(container: Container, id: Id, context?: LootContext): ItemStack[];
// a condition tables can use by its id, in the mod's namespace. only during setup
register_condition(id: Id, condition: (params: LootParams, context: LootContext) => boolean): void;
// a function tables can use by its id: the item changed, or undefined to take it away. only during setup
register_function(
id: Id,
fn: (item: ItemStack, params: LootParams, context: LootContext) => ItemStack | undefined,
): void;
// changes what a table gives every time it's rolled, or every table's with "*", like neoforge's global loot
// modifiers. return the new items, or change the list. only during setup
modify(table: Id | "*", fn: (items: ItemStack[], context: LootContext, table: Id) => ItemStack[] | void): void;
// a table made by the script instead of a file, like the base game's fishing table built from its fish. the json
// is what a file's "loot_table" is, the id is in the mod's namespace. only during setup
register_table(id: Id, table: Omit<LootTableJson, "id">): void;
}
// forms, not built yet: menus whose screens the engine provides, see docs/modding_plan.md
export interface ActionForm {
title: string;
body?: string;
buttons: { text: string; icon?: Id }[];
}
export interface MessageForm {
title: string;
body: string;
buttons: [string, string];
}
export type FormField =
| { type: "toggle"; label: string; default?: boolean }
| { type: "slider"; label: string; min: number; max: number; step?: number; default?: number }
| { type: "dropdown"; label: string; options: string[]; default?: number }
| { type: "text"; label: string; placeholder?: string; default?: string; max_length?: number };
export interface ModalForm {
title: string;
fields: FormField[];
}
export type FormResult<T> = ({ canceled: true } & Partial<T>) | ({ canceled: false } & T);
// menus, like neoforge's: the server side of a gui, see docs/modding/inventories/menus.md
export interface SlotOptions {
// gui pixels from the screen's top left to the slot's 18 pixel frame
x: number;
y: number;
// what can be put in, checked on the server
filter?: (item: ItemStack) => boolean;
// can only be taken from, all at once, like the furnace result
output_only?: boolean;
// runs when a player takes from an output_only slot, before they get it. false stops them taking it
on_take?: (item: ItemStack) => boolean;
// a texture drawn in the slot while it's empty, like minecraft's armor slots
icon?: Id;
// the most it holds, when that's less than a stack, like minecraft's Slot.getMaxStackSize
max_count?: number;
}
export interface FluidSlotOptions {
// gui pixels from the screen's top left to the slot's 18 pixel frame
x: number;
y: number;
// fluid containers only fill from it, like a machine's output
output_only?: boolean;
}
// what a menu type's build function gets, like neoforge's server menu constructor
export interface MenuBuilder {
title: string;
// sent to the client once when it opens, any json up to 16 KB, like IContainerFactory's extra data
open_data: unknown;
// a slot of a container from ctx.containers, or of player.inventory. returns its menu slot index
add_slot(container: Container, slot: number, options: SlotOptions): number;
// a tank of handler, like modern industrialization's fluid slots: the screen draws its fluid in an 18 pixel frame,
// with the amount in its tooltip, and clicking it with a fluid container on the cursor fills that from the tank, or
// else empties it in through the handler. returns its index among the menu's fluid slots
add_fluid_slot(handler: FluidHandler, tank: number, options: FluidSlotOptions): number;
// the player's 36 slots, like addStandardInventorySlots: the rest of the inventory in 3 rows from x and y, the
// hotbar 58 pixels under them. added in inventory order, so inventory slot i is the returned index plus i
add_player_inventory(x: number, y: number): number;
// a number the screen shows, like DataSlot: read every tick and sent when it changes
add_data(name: string, get: () => number): void;
// checked every tick, false closes it
still_valid(check: (player: Player) => boolean): void;
// closes it when the player is over 8 blocks from the block, or it's been broken or replaced
still_valid_near(block: BlockRef): void;
// a button the client pressed, like clickMenuButton. any number can come, check it
on_button(fn: (player: Player, id: number) => void): void;
// shift clicks: the menu slot indexes the stack in this one tries, in order. the default rule when not set
quick_move(fn: (player: Player, index: number) => number[]): void;
on_tick(fn: () => void): void;
// when it closes for any reason: the player closed it, left, opened another, or it was closed
on_close(fn: () => void): void;
}
export interface MenuHandle {
readonly player: Player;
readonly open: boolean;
close(): void;
on_close(fn: () => void): void;
}
export interface MenuType<Args> {
readonly id: Id;
// like openMenu: builds a menu for the player with these args and opens it, closing whatever they had open
open(player: Player, args: Args): MenuHandle;
}
// the player's own inventory menu, see MenuRegistry.extend_player_menu
export interface PlayerMenuBuilder {
// x and y are from the inventory screen's top left, and can be outside it, like left of it with a negative x. the
// engine draws a panel behind slots outside its own. returns the menu slot index, from 46 on
add_slot(container: Container, slot: number, options: SlotOptions): number;
}
export interface MenuRegistry {
// adds slots to every player's own inventory menu, always there while they play, like the curios slots next to the
// inventory. build runs when each player joins. only during setup
extend_player_menu(build: (menu: PlayerMenuBuilder, player: Player) => void): void;
// like registering a MenuType. the client phase gives it a screen with ctx.ui.register_menu_screen
register<Args = undefined>(
id: Id,
build: (menu: MenuBuilder, args: Args, player: Player) => void,
): MenuType<Args>;
}
export interface ServerUi {
message_form(player: Player, form: MessageForm): Promise<FormResult<{ selection: 0 | 1 }>>;
action_form(player: Player, form: ActionForm): Promise<FormResult<{ selection: number }>>;
modal_form(player: Player, form: ModalForm): Promise<FormResult<{ values: (boolean | number | string)[] }>>;
}
// mod channels
export interface ServerNet {
on<T = unknown>(channel: Id, handler: (player: Player, data: T) => void): void;
send(player: Player, channel: Id, data: unknown): void;
broadcast(channel: Id, data: unknown): void;
}