// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // loads the mods the server lists: downloads their .cubi files, registers their data, then runs their scripts' shared // and client phases. see docs/modding/networking/index.md import { AIR } from "@/common/constants.ts"; import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts"; import type { ClientContext, ClientMenu, Graphics, HudLayer, HudSpace, InventoryOverlay, KeyMappings, MenuScreen, } from "@/common/mod_api/client.ts"; import { check_recipe_types, ModListing, ModLoadError, type Phase, recipe_lookup, RecipeBook, register_mod_data, registrar, run_phase, } from "@/common/mod_loader.ts"; import { blocks_api, shared_context } from "@/common/shared_context.ts"; import { type Mod, read_mod } from "@/common/mod.ts"; import { get_state_value, set_state_value, shared_items_api } from "@/common/utils.ts"; import { BlockRules } from "@/common/block_rules.ts"; import { FluidRules } from "@/common/fluids.ts"; import { fluid_rules, set_fluid_rules } from "./fluid_rules.ts"; import { covers_face, EMPTY_SHAPE, FULL_SHAPE } from "@/common/block_shapes.ts"; import type { SharedWorld } from "@/common/mod_api/shared.ts"; import { tag_api } from "@/common/tags.ts"; import { AIR_ID } from "@/common/protocol.ts"; import type { Client } from "./client.ts"; import { code_url, fetch_verified } from "./handshake.ts"; import { GuiModScreen } from "./gui/gui_mod_screens.ts"; import { item_tooltips } from "./gui/tooltip.ts"; import { clear_hooks, expose_engine } from "@/common/hooks.ts"; import { common_engine } from "@/common/engine_modules.ts"; import { client_engine } from "./engine_modules.ts"; import { block_visuals } from "./rendering/visuals.ts"; import { biome_season } from "@/common/worldgen/biomes.ts"; import { clock, farming_day } from "@/common/time.ts"; import type { LootTableJson } from "@/common/loot.ts"; // each loaded mod's credits file, for the credits screen export const mod_credits: { name: string; version: string; text: string }[] = []; // set once the game is running, mods can't look at it during setup let client: Client | undefined; // what mods draw on inventory screens, see GuiInventoryScreen export const inventory_overlays: { mod: string; overlay: InventoryOverlay }[] = []; // each menu type's screen, see ctx.ui.register_menu_screen export const menu_screens = new Map MenuScreen }>(); // what mods draw over the world, in order, see ctx.hud and client/gui/hud.ts export const hud_layers: { mod: string; id: string; layer: HudLayer }[] = []; // draws every hud layer in order, all raising the same space. one that throws is removed so it doesn't throw every frame export function render_hud_layers(g: Graphics, space: HudSpace) { for (const entry of [...hud_layers]) { try { entry.layer.on_render(g, space); } catch (e) { console.error(`[${entry.mod}] hud layer ${entry.id} threw, so it's removed:`, e); hud_layers.splice(hud_layers.indexOf(entry), 1); } } } const overlay_listeners: { mod: string; fn: (text: string) => void }[] = []; // the server sent an overlay message, see MessageOptions.overlay export function receive_overlay_message(text: string) { for (const { mod, fn } of overlay_listeners) run_mod(mod, "an overlay message listener", () => fn(text)); } // mod channels, see ctx.net: who listens on each channel const net_handlers = new Map void }[]>(); // the server sent a mod message export function receive_mod_message(channel: string, data: unknown) { for (const { mod, handler } of net_handlers.get(channel) ?? []) { try { handler(data); } catch (e) { console.error(`[${mod}] a ${channel} handler threw:`, e); } } } // the world shared rules see on this client: what it shows. what they change is a guess the server corrects const rules_world: SharedWorld = { get_block(x, y, z) { const nid = client?.level.get_block(x, y, z); if (nid === undefined) return undefined; if (nid === AIR) return AIR_ID; return EverythingRegistry.get_by_id("blocks", nid)?.id; }, get_state(x, y, z, name) { const level = client?.level; const info = level && EverythingRegistry.get_by_id("blocks", level.get_block(x, y, z)); if (!info?.states?.some((state) => state.name === name)) return undefined; return get_state_value(level!.get_block_value(x, y, z), info, name); }, set_state(x, y, z, name, value) { const level = client?.level; const info = level && EverythingRegistry.get_by_id("blocks", level.get_block(x, y, z)); if (!info?.states?.some((state) => state.name === name)) return false; const old_value = level!.get_block_value(x, y, z); const new_value = set_state_value(old_value, info, name, value); if (new_value === undefined) return false; if (new_value !== old_value) { level!.add_block({ x, y, z, id: info.id }, new_value >>> 16); predict_neighbors(x, y, z); } return true; }, is_face_sturdy(x, y, z, face) { const shape = client?.level.collision_shape(x, y, z) ?? false; return covers_face(shape === true ? FULL_SHAPE : shape === false ? EMPTY_SHAPE : shape, face); }, biome_at: (x, y, z) => client?.level.biome_at(Math.floor(x), Math.floor(y), Math.floor(z)), season_at(x, y, z) { const biome = this.biome_at(x, y, z); return biome === undefined ? undefined : biome_season(biome, client!.level.time); }, }; // what the mods' shared phases registered, run to guess ahead of the server, see common/block_rules.ts export let block_rules = new BlockRules(run_mod, rules_world.get_block); // whether shared phases are being set up, the only time they can register rules let rules_setup = false; // whether client phases are being set up, the only time they can register visuals, since chunk workers are told // which blocks have them when the level starts let client_setup = false; function run_mod(mod: string, what: string, fn: () => T): T | undefined { try { return fn(); } catch (e) { console.error(`[${mod}] ${what} threw:`, e); return undefined; } } // this client changed the block at x y z ahead of the server, the blocks beside it change with it the way they will // on the server export function predict_neighbors(x: number, y: number, z: number) { block_rules.notify_neighbors(x, y, z); } // the loaded mods' recipes, and their names by id let recipe_book = new RecipeBook(); const mod_names = new Map(); // the name of the mod whose namespace an id is in, or the namespace when no loaded mod has it function mod_name(id: string) { const namespace = id.split(":")[0]; return mod_names.get(namespace) ?? namespace; } export function set_mods_client(game_client: Client) { client = game_client; } // downloads every mod's .cubi and checks it against the hash the server listed. everything a mod runs comes from // the checked bytes, never fetched twice export async function download_mods(listings: ModListing[], base: URL): Promise { return await Promise.all(listings.map(async (listing) => { try { const bytes = await fetch_verified(new URL(listing.file, base), listing.sha256, `${listing.name}`); const mod = read_mod(bytes, `${listing.id}.cubi`); if (mod.manifest.id !== listing.id) throw new Error(`the server listed it as ${listing.id}`); // the confirm screen said whether it has engine access, going by the listing if ((mod.manifest.engine_access ?? false) !== (listing.engine_access ?? false)) { throw new Error("its engine access isn't what the server listed"); } return mod; } catch (e) { throw new ModLoadError(listing.id, (e as Error).message); } })); } // registers the mods' data and runs their scripts' shared and client phases, in the order the server listed them export async function load_client_mods(listings: ModListing[], mods: Mod[]) { for (const [i, mod] of mods.entries()) { if (mod.credits) { mod_credits.push({ name: listings[i].name, version: listings[i].version, text: mod.credits }); } } const recipes = register_mod_data(mods.map((mod) => ({ id: mod.manifest.id, data: mod.data }))); recipe_book = recipes; inventory_overlays.length = 0; hud_layers.length = 0; overlay_listeners.length = 0; item_tooltips.length = 0; menu_screens.clear(); net_handlers.clear(); block_visuals.clear(); mod_names.clear(); for (const listing of listings) mod_names.set(listing.id, listing.name); // for engine access mods. the last server's hooks go first clear_hooks(); expose_engine({ common: common_engine(), client: client_engine() }); // one url for each mod's script, so its phases share one module const urls = mods.map((mod) => mod.script === undefined ? undefined : script_url(mod.script)); const run = async (phase: Phase, context: (i: number) => unknown) => { for (const [i, mod] of mods.entries()) { const url = urls[i]; if (url === undefined) continue; const as = { id: mod.manifest.id, engine_access: mod.manifest.engine_access }; await run_phase(as, url, phase, () => context(i)); } }; // every mod's shared rules first, so client phases can count on any mod's being there block_rules = new BlockRules(run_mod, rules_world.get_block); set_fluid_rules(new FluidRules(run_mod)); rules_setup = true; await run("shared", (i) => shared_context({ id: listings[i].id, version: listings[i].version }, { side: "client", world: rules_world, block_rules, fluid_rules, recipes: () => recipe_book, running: () => rules_setup, })); rules_setup = false; check_recipe_types(recipe_book); client_setup = true; await run("client", (i) => client_context(listings[i])); client_setup = false; } function script_url(code: string) { return code_url(new TextEncoder().encode(code)); } function client_context(listing: ModListing): ClientContext { const mod = listing.id; const not_yet = (name: string, where: string) => new Proxy({}, { get: (_, prop) => () => { throw new Error( `[${mod}] ctx.${name}.${String(prop)} isn't implemented yet (${where}, see docs/modding_plan.md)`, ); }, }); const need_client = () => { if (!client) throw new Error(`[${mod}] the world isn't there yet during setup`); return client; }; const register = registrar(mod, "client", () => client_setup); const known_item = (id: string) => { const item = EverythingRegistry.get("items", id); if (!item) throw new Error(`[${mod}] unknown item ${id}`); return item; }; return { mod: { id: mod, version: listing.version }, ui: { register_menu_screen(type, create) { register.own("menu type", type); if (menu_screens.has(type)) register.fail(`the screen of ${type} is registered twice`); menu_screens.set(type, { mod, create }); }, open(screen) { if (typeof screen?.on_render !== "function") throw new Error(`[${mod}] a screen needs an on_render`); const game = need_client(); game.push_screen(new GuiModScreen(game, mod, screen)); }, close() { need_client().pop_screen(); }, add_inventory_overlay(overlay) { inventory_overlays.push({ mod, overlay }); }, add_item_tooltip(fn) { if (typeof fn !== "function") throw new Error(`[${mod}] add_item_tooltip takes a function`); item_tooltips.push((item, lines) => run_mod(mod, "an item tooltip", () => fn(item, lines))); }, }, hud: { register(id, layer) { register.new_id("hud layer", id, hud_layers.some((other) => other.id === id)); if (typeof layer?.on_render !== "function") throw new Error(`[${mod}] a hud layer needs an on_render`); hud_layers.push({ mod, id, layer }); }, on_overlay_message(fn) { if (typeof fn !== "function") throw new Error(`[${mod}] on_overlay_message takes a function`); overlay_listeners.push({ mod, fn }); }, }, input: not_yet("input", "keybinds") as ClientContext["input"], options: key_mappings(need_client), net: { on(channel, handler) { register.own("channel", channel); const handlers = net_handlers.get(channel) ?? []; handlers.push({ mod, handler: handler as (data: unknown) => void }); net_handlers.set(channel, handlers); }, send(channel, data) { register.own("channel", channel); need_client().connection.send({ type: "mod", channel, data }); }, }, player: { get name() { return need_client().connection.name; }, get position() { const { x, y, z } = need_client().player; return { x, y, z }; }, get biome() { const { x, y, z } = need_client().player; return rules_world.biome_at(x, y, z); }, get season() { const { x, y, z } = need_client().player; return rules_world.season_at(x, y, z); }, is_swimming: () => need_client().player.swimming, is_sneaking: () => need_client().player.holding_sneak, get health() { return need_client().player.health; }, get max_health() { return need_client().player.max_health; }, get food() { return need_client().player.food; }, get saturation() { return need_client().player.saturation; }, get air() { return need_client().player.air; }, is_underwater: () => need_client().player.eyes_in_water, attack_strength: () => need_client().player.attack_strength(), inventory: { get size() { return need_client().player.inventories.inventory.size; }, get(slot) { const item = need_client().player.inventories.inventory.get_item(slot); return item && structuredClone(item.to_data()); }, }, get selected_slot() { return need_client().player.inventories.hotbar_selected; }, }, world: { get_block(x, y, z) { const nid = need_client().level.get_block(x, y, z); if (nid === AIR) return AIR_ID; return EverythingRegistry.get_by_id("blocks", nid)?.id; }, get_client_data: (x, y, z, field) => structuredClone(need_client().level.get_block_data(x, y, z)?.[field]) as never, biome_at: (x, y, z) => rules_world.biome_at(x, y, z), season_at: (x, y, z) => rules_world.season_at(x, y, z), get min_y() { return need_client().level.shape.min_y; }, get max_y() { return need_client().level.shape.max_y; }, get time() { return need_client().level.time; }, get day() { return farming_day(need_client().level.time); }, get hour() { const { hour, minute } = clock(need_client().level.time); return hour + minute / 60; }, }, items: { ...shared_items_api(mod, fluid_rules), mod(id) { known_item(id); return mod_name(id); }, }, blocks: blocks_api(), fluids: { ...fluid_rules.api(), mod(id) { if (!EverythingRegistry.get("fluids", id)) throw new Error(`[${mod}] unknown fluid ${id}`); return mod_name(id); }, }, loot: { table: (id) => structuredClone(EverythingRegistry.get("loot_tables", id)), }, recipes: { list: (type) => structuredClone(type ? recipe_book.all.filter((recipe) => recipe.type === type) : recipe_book.all), ...recipe_lookup(() => recipe_book), }, tags: tag_api(), render: { register_visual(block, create, options) { register.running("visual"); const nid = EverythingRegistry.get_id("blocks", block); if (nid === undefined) throw new Error(`[${mod}] unknown block ${block}`); if (typeof create !== "function") throw new Error(`[${mod}] a visual needs a function that makes it`); const other = block_visuals.get(nid); if (other) register.fail(`${block} already has a visual, from ${other.mod}`); block_visuals.set(nid, { mod, create, replaces_model: options?.replaces_model ?? false }); }, }, log: (...args) => console.log(`[${mod}]`, ...args), }; } // the client's key settings as they are when read, so changing them reaches mods function key_mappings(client: () => Client): KeyMappings { const keys = [ "key_forward", "key_back", "key_left", "key_right", "key_jump", "key_sprint", "key_sneak", "key_inventory", "key_drop", "key_chat", ] as const; const mappings = {} as KeyMappings; for (const key of keys) { Object.defineProperty(mappings, key, { get: () => client().options[key], enumerable: true }); } return Object.freeze(mappings); }