Files
bworld/common/mod_api/client.ts
T
2026-11-14 00:29:34 -03:00

399 lines
17 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// what client scripts get, see docs/modding/gui/index.md
import type {
FluidApi,
FluidVariant,
Id,
ItemStack,
KeyCode,
ModInfo,
Position,
RecipeLookup,
Season,
TagApi,
} from "./shared.ts";
import type { LootTableJson } from "../loot.ts";
export type {
FluidApi,
FluidStack,
FluidVariant,
Id,
ItemStack,
KeyCode,
ModInfo,
Position,
Season,
TagApi,
TagRegistry,
} from "./shared.ts";
export interface ClientContext {
mod: ModInfo;
ui: ClientUi;
hud: HudRegistry;
input: { bind(id: Id, default_key: KeyCode, on_press: () => void): void };
// the player's settings, read only, like minecraft's Options. a screen closes on key_inventory like the inventory,
// the way jei's recipes screen checks options.keyInventory
options: KeyMappings;
net: ClientNet;
// is_swimming: lying flat in water in the 0.8 tall box, like minecraft's isSwimming. is_sneaking: holding the sneak
// key, like isShiftKeyDown. biome and season are where their feet are, undefined until that chunk loads
player: {
readonly name: string;
readonly position: Readonly<Position>;
readonly biome: Id | undefined;
readonly season: Season | undefined;
is_swimming(): boolean;
is_sneaking(): boolean;
// health and hunger as the server last sent them, like the server's Player. air is out of 20 like food, 2 a
// bubble
readonly health: number;
readonly max_health: number;
readonly food: number;
readonly saturation: number;
readonly air: number;
// their eyes are in water, like minecraft's isUnderWater
is_underwater(): boolean;
// how far the attack cooldown is, 0 right after attacking and 1 when it's done, like getAttackStrengthScale
attack_strength(): number;
// their 36 slots, hotbar is 0-8, as the server last synced them. copies
readonly inventory: { readonly size: number; get(slot: number): ItemStack | undefined };
readonly selected_slot: number;
};
// read only, what this client sees
world: {
get_block(x: number, y: number, z: number): Id | undefined;
// a field of the block's client data, what server scripts set with BlockRef.set_client_data, a copy.
// undefined when it isn't set or the chunk isn't loaded
get_client_data<T>(x: number, y: number, z: number, field: string): T | undefined;
// the biome at a block and its season, like the server's. undefined when the chunk isn't loaded
biome_at(x: number, y: number, z: number): Id | undefined;
season_at(x: number, y: number, z: number): Season | undefined;
// the dimension's blocks go from min_y up to max_y - 1
readonly min_y: number;
readonly max_y: number;
// ticks since 06:00 of day 1, see ServerWorld.time. day and hour are like ServerWorld's
readonly time: number;
readonly day: number;
readonly hour: number;
};
// every item any mod registered, in load order
items: {
ids(): Id[];
exists(id: Id): boolean;
// what players see, like "Cooked Rice"
name(id: Id): string;
// the mod that registered it
mod(id: Id): string;
// the components its json lists and their params, a copy, like the server's ctx.items.components. for showing
// what a component means, like when a fish can be caught
components(id: Id): Record<Id, unknown>;
// what one sells for with this data, or undefined if it can't be sold, like the server's ctx.items.sell_value
sell_value(id: Id, data?: unknown): number | undefined;
};
// every block any mod registered
blocks: {
exists(id: Id): boolean;
// the components its json lists and their params, a copy, like the server's ctx.blocks.components. for showing
// what a component does, like what a crab pot catches
components(id: Id): Record<Id, unknown>;
// whether it's solid like stone, like the server's ctx.blocks.solid
solid(id: Id): boolean;
};
// every fluid, named and colored by its rules, see docs/modding/resources/fluids.md
fluids: FluidApi & {
// the mod that registered it, like ctx.items.mod
mod(id: Id): string;
};
// the mods' loot table files (see docs/modding/resources/loot_tables.md), to show what they give. tables server
// scripts make with ctx.loot.register_table aren't here
loot: {
// the table's json, a copy, or undefined when no mod has a file for it
table(id: Id): LootTableJson | undefined;
};
// every recipe as its json (see docs/modding/resources/recipes.md), including mods' own types, in load order. copies.
// find and all read the recipes of types shared scripts registered
recipes: {
// deno-lint-ignore no-explicit-any
list(type?: Id): any[];
} & RecipeLookup;
// every mod's block, item and entity tags
tags: TagApi;
// blocks drawn with code, like a shaft that turns, see docs/modding/blocks/visuals.md
render: ClientRender;
log(...args: unknown[]): void;
}
export interface ClientRender {
// every block of this id gets a visual from create while its chunk is shown, like a block entity renderer or
// flywheel's visuals. only during setup, and one per block. replaces_model leaves the block's model out of the
// terrain, for a visual that draws all of it
register_visual(
block: Id,
create: (block: VisualBlock, instances: Instances) => Visual,
options?: { replaces_model?: boolean },
): void;
}
// the block a visual draws
export interface VisualBlock {
readonly id: Id;
readonly x: number;
readonly y: number;
readonly z: number;
// they stay the same for the visual's life, it's made again when they change
readonly states: Readonly<Record<string, number>>;
// a field of its client data now, a copy, see BlockRef.set_client_data in cubi/server
get_client_data<T>(field: string): T | undefined;
}
export interface Visual {
// a field of its block's client data changed
update?(): void;
// before each frame its chunk is in view, for what moves on the cpu, like a crank slowing down. time is in ticks
// with the part of the next one, the same time rotating instances turn by
on_frame?(time: number): void;
// it's going, with its block, with its chunk, or because its states changed. its instances go with it
on_delete?(): void;
}
// a model from models/ by id, turned like a block variant: x then y, in steps of 90 degrees
export type ModelRef = Id | { model: Id; x?: number; y?: number };
// what a visual draws: models lit by the block's light. without a model, the block's own, the way its states draw it
export interface Instances {
// placed by a matrix, set again whenever it moves
transformed(model?: ModelRef): TransformedInstance;
// turning at a steady speed worked out from the time, so it never needs anything per frame
rotating(model?: ModelRef): RotatingInstance;
// one of an item, whatever the stack's count: the size it's drawn on the ground, with its middle at the middle of
// the block, placed by a matrix like a transformed model. like a block entity renderer drawing an item
item(stack: ItemStack): TransformedInstance;
// a box of a fluid, its texture tinted in its color, see FluidInstance. it shows what's behind it
fluid(fluid: FluidVariant): FluidInstance;
}
export interface Instance {
// stops drawing it for good
delete(): void;
}
export interface TransformedInstance extends Instance {
// a 4x4 matrix in column major order, like gl-matrix's mat4, from the model's space (0 to 1 across the block) to
// the block's, where 0 0 0 is its corner. where the block is when not set
set_transform(matrix: ArrayLike<number>): void;
}
// nothing is drawn until set_box is called
export interface FluidInstance extends Instance {
// from one corner to the other, in pixels like a model's elements: 0 to 16 across the block, past it for a box that
// reaches into the blocks around, like a tank's. the texture is cut to fit, never stretched
set_box(from: [number, number, number], to: [number, number, number]): void;
}
export interface RotatingInstance extends Instance {
// turns around axis through the middle of the block, counterclockwise seen from the axis's positive end when rpm
// is positive, at time * rpm * 0.3 + offset degrees. still when not set
set_rotation(axis: "x" | "y" | "z", rpm: number, offset?: number): void;
}
// the keys the player has bound, like the key mappings in minecraft's Options
export interface KeyMappings {
readonly key_forward: KeyCode;
readonly key_back: KeyCode;
readonly key_left: KeyCode;
readonly key_right: KeyCode;
readonly key_jump: KeyCode;
readonly key_sprint: KeyCode;
readonly key_sneak: KeyCode;
readonly key_inventory: KeyCode;
readonly key_drop: KeyCode;
readonly key_chat: KeyCode;
}
// a screen with no menu, only on this client, like neoforge's Screen. see docs/modding/gui/index.md
export interface Screen {
// when it opens, and whenever the window changes size. in gui pixels
on_init?(width: number, height: number): void;
// 20 times a second
on_tick?(): void;
on_render(g: Graphics): void;
// true when not set
should_close_on_escape?(): boolean;
// the player closed it, with escape
on_close?(): void;
// it's gone for any reason, including another screen replacing it
on_removed?(): void;
}
// the client side of a menu the server opened, see docs/modding/inventories/menus.md
export interface ClientMenu {
readonly type: Id;
readonly title: string;
// what the server's build function set, sent once
readonly open_data: unknown;
// the server's latest values of its add_data numbers
readonly data: Readonly<Record<string, number>>;
// what's in one of its slots, by menu slot index, as the server last synced it. a copy
item(slot: number): ItemStack | undefined;
// like clickMenuButton, the server's on_button decides what it does
click_button(id: number): void;
close(): void;
}
// draws a menu, like neoforge's AbstractContainerScreen. the engine puts it in the middle of the window, and draws
// the menu's slots, the item on the cursor and item tooltips. g's 0, 0 is the screen's top left
export interface MenuScreen {
// in gui pixels, like imageWidth and imageHeight
width: number;
height: number;
// under the slots
on_render_background?(g: Graphics): void;
// over the slots
on_render_labels?(g: Graphics): void;
// 20 times a second, like containerTick
on_tick?(): void;
// darkens the world behind it, true when not set. false draws it right over the world, like stardew valley's
// fishing minigame
dim_background?: boolean;
// mods' inventory overlays, like the recipe viewer's item list, show on it. true when not set
inventory_overlays?: boolean;
}
export type Color = [number, number, number, number];
// a line of a tooltip, see Graphics.tooltip and ClientUi.add_item_tooltip
export interface TooltipLine {
text: string;
color?: Color;
// a texture drawn before the text, as tall as the line
icon?: Id;
// lower comes first, TOOLTIP_PRIORITY.default when not set. lines with the same priority keep the order they were
// added in: the game's first, then mods' in load order. only item tooltips are sorted
priority?: number;
}
// where the game's own lines of an item's tooltip go, so a mod's can go between them
export const TOOLTIP_PRIORITY = {
name: 0,
fluid: 100,
food: 200,
default: 500,
lore: 1000,
// g.item_tooltip's extra lines
extra: 2000,
} as const;
// immediate mode drawing, like the debug ui, styled with the gui sprites (assets/sprites/gui.png). everything is in
// gui pixels, like neoforge's: 18 of them are a slot
export interface Graphics {
readonly width: number;
readonly height: number;
readonly mouse: { x: number; y: number; down: boolean; pressed: boolean; right_pressed: boolean };
rect(x: number, y: number, w: number, h: number, color?: Color): void;
panel(x: number, y: number, w: number, h: number): void;
// how tall a line of text is at scale 1, the game's text size
readonly text_height: number;
// shadow draws it again under, a bit down and right in dark grey, so it reads over the world, like drawString's
text(text: string, x: number, y: number, options?: { scale?: number; color?: Color; shadow?: boolean }): void;
measure_text(text: string, scale?: number): number;
// part is the part of the texture to draw, [u, v, width, height] from 0 to 1, like a progress bar's filled part
texture(id: Id, x: number, y: number, w: number, h: number, part?: [number, number, number, number]): void;
// a progress bar: filled (0 to 1) of full drawn over empty, from the left, or from the bottom going "up"
progress(
empty: Id,
full: Id,
x: number,
y: number,
w: number,
h: number,
filled: number,
direction?: "right" | "up",
): void;
// one of the engine's gui sprites (assets/sprites/gui.png), like "cubi:heart_full", at its size unless given one.
// like neoforge's blitSprite. color multiplies it, like a shadow drawn in see through black
sprite(id: Id, x: number, y: number, options?: { width?: number; height?: number; color?: Color }): void;
// an item at a slot's top left. a stack draws like a slot does, with its count and its data, like a worn tool's
// durability bar
item(item: Id | ItemStack, x: number, y: number, count?: number): void;
// a fluid as a slot shows it, its texture in its color, at a slot's top left like item. filled (0 to 1, 1 when not
// set) is how much of the slot it fills from the bottom up, like amount / capacity for a machine's tank
fluid(fluid: FluidVariant, x: number, y: number, filled?: number): void;
clip(x: number, y: number, w: number, h: number, draw: () => void): void;
button(label: string, x: number, y: number, w: number, h: number): boolean;
text_input(id: string, x: number, y: number, w: number): string;
slider(id: string, x: number, y: number, w: number, min: number, max: number): number;
// false while a text input has the keyboard
key_pressed(key: KeyCode): boolean;
// shown next to the mouse over everything else, the last one this frame wins. white unless a line says
tooltip(lines: (string | TooltipLine)[], x: number, y: number): void;
// an item's tooltip as slots show it (its name, food, lore, mods' lines), with extra lines, grey unless they say.
// they go under everything unless they have a priority
item_tooltip(id: Id, x: number, y: number, extra?: (string | TooltipLine)[]): void;
// the click was used, so nothing under it (like slots) gets it
consume_click(): void;
// the screen underneath ignores the mouse over this area this frame, for something drawn over it
block_mouse(x: number, y: number, w: number, h: number): void;
}
// drawn on every menu's screen (the player's inventory, chests, furnaces...), over it, like just enough items' item
// list. it gets the screen's box to lay itself out around
export interface InventoryOverlay {
on_render(g: Graphics, screen: InventoryScreenView): void;
// the screen closed for any reason, like the player closing their inventory
on_close?(): void;
}
export interface InventoryScreenView {
// the open menu's type, like "bworld:furnace". undefined on the player's own inventory
readonly menu_type: Id | undefined;
readonly x: number;
readonly y: number;
readonly width: number;
readonly height: number;
// what's in the slot under the mouse
readonly hovered_item: ItemStack | undefined;
}
export interface ClientUi {
// the screen for a menu type of this mod, like RegisterMenuScreensEvent. called each time one opens
register_menu_screen(type: Id, create: (menu: ClientMenu) => MenuScreen): void;
// a screen that doesn't involve the server, like a settings page, over whatever's open
open(screen: Screen): void;
// closes the screen on top
close(): void;
add_inventory_overlay(overlay: InventoryOverlay): void;
// adds to every item's tooltip, like neoforge's ItemTooltipEvent. lines has the game's lines and earlier mods'. push
// to it, and the lines are sorted by priority once every function has run
add_item_tooltip(fn: (item: ItemStack, lines: TooltipLine[]) => void): void;
}
// what's drawn over the world while playing, under screens, like neoforge's gui layers. see docs/modding/gui/hud.md
export interface HudRegistry {
// a layer, drawn every frame in the order they're registered, mods in load order, like RegisterGuiLayersEvent's
// registerAboveAll. only during setup. one that throws is removed, with the error in the console
register(id: Id, layer: HudLayer): void;
// a server script sent an overlay message (MessageOptions.overlay), for a layer to show
on_overlay_message(fn: (text: string) => void): void;
}
export interface HudLayer {
on_render(g: Graphics, hud: HudSpace): void;
}
// how far up from the bottom of the window the hud reaches on the left and right, in gui pixels, like neoforge's
// leftHeight and rightHeight. both start at 0 each frame. a layer drawing along the bottom, like a row of hearts, draws
// above them and raises them, so the next one goes on top. chat goes above the higher one
export interface HudSpace {
left_height: number;
right_height: number;
}
export interface ClientNet {
on<T = unknown>(channel: Id, handler: (data: T) => void): void;
send(channel: Id, data: unknown): void;
}