Files
bworld/common/mod_loader.ts
T

308 lines
12 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// registers mods' data, the same way on the server and on clients
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "./everything_registry.ts";
import {
add_to_block_item,
block_from_json,
BlockJson,
choice_ids,
choice_list,
choice_problems,
EffectJson,
EntityJson,
EntityModelJson,
FluidJson,
grid_recipe_from_json,
GridRecipe,
is_mod_recipe,
item_from_json,
item_problems,
ItemJson,
ModRecipeJson,
OreJson,
RecipeJson,
SpawnJson,
stack_problems,
TagJson,
TagRegistry,
validate_recipe,
} from "./mod_data.ts";
import type { RecipeLookup, RecipeReader, RecipeType, SharedContext } from "./mod_api/shared.ts";
import { resolve_tags, Tags } from "./tags.ts";
import type { LootTableJson } from "./loot.ts";
import { type BiomeJson, register_biome } from "./worldgen/biomes.ts";
import type { BiomeSourceJson, DensityFunctionJson, NoiseJson, NoiseSettingsJson } from "./worldgen/data.ts";
import type { FeatureJson } from "./worldgen/features.ts";
import { register_block_item } from "./utils.ts";
import { find_model, type ModelFileJson, type ModelJson, resolve_models } from "./block_models.ts";
// everything a mod's json files hold, merged into one file by the build (build/mods/<id>/<hash>/data.json)
export interface ModData {
blocks: BlockJson[];
// block models as mods write them, parents not merged in yet. see common/block_models.ts
models: ModelFileJson[];
items: ItemJson[];
recipes: RecipeJson[];
ores: OreJson[];
// natural spawns, see SpawnJson
spawns: SpawnJson[];
entities: EntityJson[];
entity_models: EntityModelJson[];
// status effects, see EffectJson
effects: EffectJson[];
// kinds of fluid, see FluidJson
fluids: FluidJson[];
// tag files, see common/tags.ts
tags: TagJson[];
// see common/loot.ts. missing from mods packed before there were loot tables
loot_tables?: LootTableJson[];
// see common/worldgen/biomes.ts. missing from mods packed before biomes were data
biomes?: BiomeJson[];
// the terrain as data, see common/worldgen/data.ts. server only, players' copies leave them out
noises?: NoiseJson[];
density_functions?: DensityFunctionJson[];
noise_settings?: NoiseSettingsJson[];
biome_sources?: BiomeSourceJson[];
// data features, see common/worldgen/features.ts. server only too
features?: FeatureJson[];
// the mod's settings, its config.json's "config", with the server's changes once the server loads it. server only
// too, see docs/modding/misc/config.md
config?: Record<string, unknown>;
}
// a mod as the server lists it to clients, in load order: the .bmod players download, without its server script
export interface ModListing {
id: string;
name: string;
version: string;
// sha-256 in hex of the .bmod, clients check it before using anything in it
sha256: string;
// where it's served from, relative to the server's root. named by its hash, so it never changes
file: string;
size: number;
// it imports bworld/engine, see docs/modding/misc/engine.md. the confirm screen for other sites says so
engine_access?: boolean;
}
export class RecipeBook {
shaped: GridRecipe[] = [];
// recipes of mods' own types, by type
by_type = new Map<string, ModRecipeJson[]>();
// the types shared scripts registered, and their recipes as parse made them, see SharedContext.recipes.register_type
types = new Map<string, RecipeType<unknown, unknown>>();
parsed = new Map<string, unknown[]>();
// every recipe as its json, in load order, for recipe viewers
all: RecipeJson[] = [];
// each mod's ores, in load order. each mod's are their own pass, see generate_raw_chunk
ores: OreJson[][] = [];
spawns: SpawnJson[] = [];
}
export class ModLoadError extends Error {
constructor(mod: string, message: string) {
super(`${mod}: ${message}`);
this.name = "ModLoadError";
}
}
// whether a block, item, entity or biome is registered, for tags. air isn't a registered block, but tags can hold it
export function is_registered(registry: TagRegistry, id: string): boolean {
return (registry === "blocks" && id === "bworld:air") || EverythingRegistry.get(registry, id) !== undefined;
}
// registers every mod's blocks, items, entities, effects, fluids, tags and recipes, in the order given (dependencies
// first). tags load once every mod's content has, since a tag can hold anything, and recipes after them, since they can
// use tags
export function register_mod_data(mods: { id: string; data: ModData }[]): RecipeBook {
const recipes = new RecipeBook();
for (const { id, data } of mods) {
try {
// parents are this mod's or an earlier one's, which are already registered with theirs merged in
const { models, problems } = resolve_models(
data.models,
(model_id) => find_model(model_id, {}) ?? EverythingRegistry.get<ModelJson>("models", model_id),
);
if (problems.length > 0) {
throw new Error(problems.map(({ id, problem }) => `model ${id}: ${problem}`).join("\n"));
}
for (const model of models) {
EverythingRegistry.register<ModelJson>("models", model.id, model);
}
for (const json of data.blocks) {
const { block, has_item } = block_from_json(json);
EverythingRegistry.register<BlockRegistry>("blocks", block.id, block);
if (has_item) {
register_block_item(block);
}
}
for (const json of data.items) {
if (json.texture !== undefined) {
EverythingRegistry.register<ItemRegistry>("items", json.id, item_from_json(json));
continue;
}
const block_item = EverythingRegistry.get<BlockRegistry>("blocks", json.id) &&
EverythingRegistry.get<ItemRegistry>("items", json.id);
if (!block_item) throw new Error(`item ${json.id} has no texture and isn't a block's item`);
add_to_block_item(json, block_item);
}
for (const model of data.entity_models) {
EverythingRegistry.register<EntityModelJson>("entity_models", model.id, model);
}
for (const json of data.entities) {
EverythingRegistry.register<EntityJson>("entities", json.id, json);
}
for (const json of data.effects) {
EverythingRegistry.register<EffectJson>("effects", json.id, json);
}
for (const json of data.fluids) {
EverythingRegistry.register<FluidJson>("fluids", json.id, json);
}
for (const json of data.loot_tables ?? []) {
EverythingRegistry.register<LootTableJson>("loot_tables", json.id, json);
}
for (const json of data.biomes ?? []) {
register_biome(json);
}
// compiled into a generator once every mod's are in, see common/worldgen/generator.ts
for (const json of data.noises ?? []) EverythingRegistry.register("noises", json.id, json);
for (const json of data.density_functions ?? []) {
EverythingRegistry.register("density_functions", json.id, json);
}
for (const json of data.noise_settings ?? []) EverythingRegistry.register("noise_settings", json.id, json);
for (const json of data.biome_sources ?? []) EverythingRegistry.register("biome_sources", json.id, json);
// compiled with the types worldgen scripts register, see common/worldgen_loader.ts
for (const json of data.features ?? []) EverythingRegistry.register("features", json.id, json);
} catch (e) {
throw new ModLoadError(id, (e as Error).message);
}
}
const { tags, problems } = resolve_tags(
mods.flatMap(({ id, data }) =>
data.tags.map((json) => ({ mod: id, file: `tags/${json.registry}/${json.id}`, json }))
),
is_registered,
);
if (problems.length > 0) throw new ModLoadError(problems[0].mod, `${problems[0].file}: ${problems[0].message}`);
Tags.load(tags);
for (const { id, data } of mods) {
try {
for (const recipe of data.recipes) add_recipe(recipes, recipe);
} catch (e) {
throw new ModLoadError(id, (e as Error).message);
}
if (data.ores.length > 0) recipes.ores.push(data.ores);
recipes.spawns.push(...data.spawns);
}
return recipes;
}
// puts a recipe in the book, from a mod's recipes/ or a shared script. throws when its registered type's parse throws
export function add_recipe(recipes: RecipeBook, recipe: RecipeJson) {
recipes.all.push(recipe);
if (is_mod_recipe(recipe)) {
const list = recipes.by_type.get(recipe.type) ?? [];
recipes.by_type.set(recipe.type, list);
list.push(recipe);
const type = recipes.types.get(recipe.type);
if (type) recipes.parsed.get(recipe.type)!.push(parse_recipe(type, recipe, list.length - 1));
return;
}
recipes.shaped.push(grid_recipe_from_json(recipe));
}
// the index'th recipe of its type, turned into what its type's parse makes of it, or throwing naming it
function parse_recipe(type: RecipeType<unknown, unknown>, json: ModRecipeJson, index: number): unknown {
try {
return type.parse(structuredClone(json), recipe_reader);
} catch (e) {
throw new Error(`${json.type} recipe ${index + 1}: ${(e as Error).message}`);
}
}
// items and tags load before any script sets up, so the ones recipes name can be checked
const recipe_reader: RecipeReader = {
item: (json, field) => checked_item(field, item_problems(json[field]), json[field] as string),
stack(json, field) {
const stack = json[field] as { id: string; count: number } | undefined;
return { id: checked_item(field, stack_problems(stack), stack?.id as string), count: stack!.count };
},
// a tag can be empty, like one of another mod's items that isn't installed, but it has to exist
ingredient(json, field) {
const choice = json[field] as string | string[];
const problems = choice_problems(choice);
if (problems.length > 0) throw new Error(`${field} ${problems[0]}`);
for (const entry of choice_list(choice)) {
if (!entry.startsWith("#")) checked_item(field, [], entry);
else if (!Tags.exists("items", entry)) throw new Error(`${field}: there's no item tag ${entry}`);
}
return choice_ids(choice);
},
};
// the item a field names, once the field has no problems
function checked_item(field: string, problems: string[], id: string): string {
if (problems.length > 0) throw new Error(`${field} ${problems[0]}`);
if (!is_registered("items", id)) throw new Error(`${field}: there's no item ${id}`);
return id;
}
// find and all, for every side's ctx.recipes
export function recipe_lookup(recipes: () => RecipeBook): RecipeLookup {
return {
find<R>(type: string, input: unknown) {
const rules = recipes().types.get(type);
return recipes().parsed.get(type)?.find((recipe) => rules!.matches(recipe, input)) as R | undefined;
},
all: <R>(type: string) => (recipes().parsed.get(type) ?? []) as R[],
};
}
// ctx.recipes for shared scripts, the same on the server and every client: a recipe registered there is in the book
// on every side without being sent, like one from the mod's recipes/. checked like a data file's. fail throws, as the
// side's error for the mod. list reads the book as it is, so a script sees the recipes of the ones before it
export function shared_recipes_api(
mod: string,
recipes: () => RecipeBook,
setting_up: () => boolean,
fail: (message: string) => never,
): SharedContext["recipes"] {
return {
...recipe_lookup(recipes),
register(type, json) {
if (!setting_up()) fail("recipes can only be registered during setup");
const recipe = { ...structuredClone(json), type };
const problems = validate_recipe(recipe);
if (problems.length > 0) fail(`recipe of type ${type}: ${problems.join(", ")}`);
try {
add_recipe(recipes(), recipe as RecipeJson);
} catch (e) {
fail((e as Error).message);
}
},
list: (type) => structuredClone(type ? recipes().all.filter((recipe) => recipe.type === type) : recipes().all),
// the recipes of the type there are so far are parsed now, and the ones registered after as they come
register_type(type, rules) {
if (!setting_up()) fail("recipe types can only be registered during setup");
if (!type.startsWith(`${mod}:`)) fail(`recipe type ${type} must be in the namespace "${mod}"`);
const book = recipes();
if (book.types.has(type)) fail(`recipe type ${type} is already registered`);
const type_rules = rules as RecipeType<unknown, unknown>;
try {
book.parsed.set(
type,
(book.by_type.get(type) ?? []).map((json, i) => parse_recipe(type_rules, json, i)),
);
} catch (e) {
fail((e as Error).message);
}
book.types.set(type, type_rules);
},
};
}