420 lines
15 KiB
TypeScript
420 lines
15 KiB
TypeScript
// 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 client scripts.
|
|
// 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, InventoryOverlay, KeyMappings, MenuScreen } from "@/common/mod_api/client.ts";
|
|
import {
|
|
check_recipe_types,
|
|
ModListing,
|
|
ModLoadError,
|
|
recipe_lookup,
|
|
RecipeBook,
|
|
register_mod_data,
|
|
shared_recipes_api,
|
|
} from "@/common/mod_loader.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 { fluid_exists, FluidRules, same_fluid } from "@/common/fluids.ts";
|
|
import { fluid_rules, set_fluid_rules } from "./fluid_rules.ts";
|
|
import { covers_face, EMPTY_SHAPE, FULL_SHAPE, is_solid } from "@/common/block_shapes.ts";
|
|
import type { SharedContext, 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 { clear_hooks, expose_engine, loading_mod } from "@/common/hooks.ts";
|
|
import { common_engine } from "@/common/engine_modules.ts";
|
|
import { client_engine } from "./engine_modules.ts";
|
|
import { block_visuals } from "./rendering/visuals.ts";
|
|
import { biome_season } from "@/common/worldgen/biomes.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<string, { mod: string; create: (menu: ClientMenu) => MenuScreen }>();
|
|
|
|
// mod channels, see ctx.net: who listens on each channel
|
|
const net_handlers = new Map<string, { mod: string; handler: (data: unknown) => 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<BlockRegistry>("blocks", nid)?.id;
|
|
},
|
|
get_state(x, y, z, name) {
|
|
const level = client?.level;
|
|
const info = level && EverythingRegistry.get_by_id<BlockRegistry>("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<BlockRegistry>("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, z) => client?.level.biome_at(Math.floor(x), Math.floor(z)),
|
|
season_at(x, z) {
|
|
const biome = this.biome_at(x, z);
|
|
return biome === undefined ? undefined : biome_season(biome, client!.level.time);
|
|
},
|
|
};
|
|
|
|
// what the mods' shared scripts 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 scripts are being set up, the only time they can register rules
|
|
let rules_setup = false;
|
|
// whether client scripts 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<T>(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<string, string>();
|
|
|
|
// 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<Mod[]> {
|
|
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 client scripts, 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;
|
|
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() });
|
|
const as_mod = (mod: Mod, fn: () => Promise<void>) =>
|
|
loading_mod(mod.manifest.id, mod.manifest.engine_access ?? false, fn);
|
|
|
|
// every mod's shared rules first, so client scripts can count on any mod's being there
|
|
block_rules = new BlockRules(run_mod, rules_world.get_block);
|
|
set_fluid_rules(new FluidRules(run_mod));
|
|
rules_setup = true;
|
|
for (const [i, mod] of mods.entries()) {
|
|
const code = mod.scripts.shared;
|
|
if (!code) continue;
|
|
await as_mod(mod, async () => {
|
|
const module = await import(script_url(code));
|
|
if (typeof module.setup !== "function") {
|
|
throw new ModLoadError(mod.manifest.id, "the shared script doesn't export a setup function");
|
|
}
|
|
await module.setup(shared_context(listings[i]));
|
|
});
|
|
}
|
|
rules_setup = false;
|
|
check_recipe_types(recipe_book);
|
|
|
|
client_setup = true;
|
|
for (const [i, mod] of mods.entries()) {
|
|
const code = mod.scripts.client;
|
|
if (!code) continue;
|
|
await as_mod(mod, async () => {
|
|
const module = await import(script_url(code));
|
|
if (typeof module.setup !== "function") {
|
|
throw new ModLoadError(mod.manifest.id, "the client script doesn't export a setup function");
|
|
}
|
|
await module.setup(client_context(listings[i]));
|
|
});
|
|
}
|
|
client_setup = false;
|
|
}
|
|
|
|
function script_url(code: string) {
|
|
return code_url(new TextEncoder().encode(code));
|
|
}
|
|
|
|
// ctx.blocks, the same in shared and client scripts
|
|
function blocks_api(mod: string): SharedContext["blocks"] {
|
|
return {
|
|
exists: (id) => EverythingRegistry.get("blocks", id) !== undefined,
|
|
components(id) {
|
|
const block = EverythingRegistry.get<BlockRegistry>("blocks", id);
|
|
if (!block) throw new Error(`[${mod}] unknown block ${id}`);
|
|
return structuredClone(block.components ?? {});
|
|
},
|
|
solid(id) {
|
|
if (id === AIR_ID) return false;
|
|
const block = EverythingRegistry.get<BlockRegistry>("blocks", id);
|
|
if (!block) throw new Error(`[${mod}] unknown block ${id}`);
|
|
return is_solid(block);
|
|
},
|
|
};
|
|
}
|
|
|
|
function shared_context(listing: ModListing): SharedContext {
|
|
const mod = listing.id;
|
|
return {
|
|
mod: { id: mod, version: listing.version },
|
|
side: "client",
|
|
tags: tag_api(),
|
|
blocks: blocks_api(mod),
|
|
items: shared_items_api(mod),
|
|
fluids: {
|
|
exists: fluid_exists,
|
|
same: same_fluid,
|
|
register(id, rules) {
|
|
if (!rules_setup) throw new Error(`[${mod}] rules can only be registered during setup`);
|
|
fluid_rules.register(mod, id, rules);
|
|
},
|
|
},
|
|
recipes: shared_recipes_api(mod, () => recipe_book, () => rules_setup, (message) => {
|
|
throw new Error(`[${mod}] ${message}`);
|
|
}),
|
|
world: rules_world,
|
|
components: {
|
|
register_block(id, rules) {
|
|
if (!id.startsWith(`${mod}:`)) {
|
|
throw new Error(`[${mod}] component ${id} must be in the namespace "${mod}"`);
|
|
}
|
|
if (!rules_setup) throw new Error(`[${mod}] rules can only be registered during setup`);
|
|
block_rules.register(mod, id, rules);
|
|
},
|
|
},
|
|
};
|
|
}
|
|
|
|
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 own = (id: string, what = "channel") => {
|
|
if (!id.startsWith(`${mod}:`)) {
|
|
throw new Error(`[${mod}] ${what} ${id} must be in the namespace "${mod}"`);
|
|
}
|
|
};
|
|
const known_item = (id: string) => {
|
|
const item = EverythingRegistry.get<ItemRegistry>("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) {
|
|
own(type, "menu type");
|
|
if (menu_screens.has(type)) throw new Error(`[${mod}] ${type} already has a screen`);
|
|
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 });
|
|
},
|
|
},
|
|
hud: not_yet("hud", "HUD elements") as ClientContext["hud"],
|
|
input: not_yet("input", "keybinds") as ClientContext["input"],
|
|
options: key_mappings(need_client),
|
|
net: {
|
|
on(channel, handler) {
|
|
own(channel);
|
|
const handlers = net_handlers.get(channel) ?? [];
|
|
handlers.push({ mod, handler: handler as (data: unknown) => void });
|
|
net_handlers.set(channel, handlers);
|
|
},
|
|
send(channel, data) {
|
|
own(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, z } = need_client().player;
|
|
return rules_world.biome_at(x, z);
|
|
},
|
|
get season() {
|
|
const { x, z } = need_client().player;
|
|
return rules_world.season_at(x, z);
|
|
},
|
|
is_swimming: () => need_client().player.swimming,
|
|
is_sneaking: () => need_client().player.holding_sneak,
|
|
},
|
|
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<BlockRegistry>("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, z) => rules_world.biome_at(x, z),
|
|
season_at: (x, z) => rules_world.season_at(x, z),
|
|
get time() {
|
|
return need_client().level.time;
|
|
},
|
|
},
|
|
items: {
|
|
...shared_items_api(mod),
|
|
mod(id) {
|
|
known_item(id);
|
|
return mod_name(id);
|
|
},
|
|
},
|
|
blocks: blocks_api(mod),
|
|
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<LootTableJson>("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) {
|
|
if (!client_setup) throw new Error(`[${mod}] visuals can only be registered during setup`);
|
|
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) throw new Error(`[${mod}] ${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);
|
|
}
|