From b329a61d968da1cd28fd9b0e0449275a684448a1 Mon Sep 17 00:00:00 2001 From: Paula Date: Sun, 1 Nov 2026 21:00:44 -0300 Subject: [PATCH] Every recipe type registered from shared scripts --- client/mods.ts | 6 +- common/fluids.ts | 6 +- common/mod_api/shared.ts | 20 ++-- common/mod_data.ts | 2 +- common/mod_loader.ts | 64 +++++++---- docs/modding/resources/fluids.md | 3 + docs/modding/resources/recipes.md | 60 ++++------- docs/modding_plan.md | 2 +- mods/bworld/scripts/client.ts | 4 +- mods/bworld/scripts/cooking.ts | 124 +--------------------- mods/bworld/scripts/cooking_recipes.ts | 85 +++++++++++++++ mods/bworld/scripts/fermenting.ts | 31 ++---- mods/bworld/scripts/juicing.ts | 63 +++-------- mods/bworld/scripts/server.ts | 18 ++-- mods/bworld/scripts/shared.ts | 4 + mods/bworld/scripts/smelting.ts | 17 ++- mods/bworld/scripts/smithing.ts | 8 +- mods/bworld/scripts/stonecutting.ts | 46 +++----- mods/create/scripts/recipes/processing.ts | 31 +++--- mods/create/scripts/server.ts | 27 ++--- mods/create/scripts/shared.ts | 5 + server/game/mod_runtime.ts | 7 +- tests/create/recipes_test.ts | 14 ++- tests/helpers.ts | 2 +- tests/script_recipes_test.ts | 56 ++++++++-- 25 files changed, 334 insertions(+), 371 deletions(-) create mode 100644 mods/bworld/scripts/cooking_recipes.ts diff --git a/client/mods.ts b/client/mods.ts index 5786ee6..4a49ede 100644 --- a/client/mods.ts +++ b/client/mods.ts @@ -7,6 +7,7 @@ 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, @@ -17,7 +18,7 @@ import { import { type Bmod, read_bmod } from "$/common/bmod.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_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"; @@ -192,6 +193,7 @@ export async function load_client_mods(listings: ModListing[], bmods: Bmod[]) { }); } rules_setup = false; + check_recipe_types(recipe_book); client_setup = true; for (const [i, bmod] of bmods.entries()) { @@ -239,6 +241,8 @@ function shared_context(listing: ModListing): SharedContext { 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); diff --git a/common/fluids.ts b/common/fluids.ts index 91808c2..f08d0c8 100644 --- a/common/fluids.ts +++ b/common/fluids.ts @@ -48,7 +48,7 @@ export class FluidRules { api(): FluidApi { return { ids: () => EverythingRegistry.entries("fluids").map(([id]) => id), - exists: (id) => EverythingRegistry.get("fluids", id) !== undefined, + exists: fluid_exists, name: (fluid) => this.name(fluid), color: (fluid) => this.color(fluid), same: same_fluid, @@ -68,6 +68,10 @@ export class FluidRules { } } +export function fluid_exists(id: string): boolean { + return EverythingRegistry.get("fluids", id) !== undefined; +} + // whether they're one fluid, see FluidApi.same export function same_fluid(a: FluidVariant, b: FluidVariant): boolean { return a.id === b.id && same_data(a.data, b.data); diff --git a/common/mod_api/shared.ts b/common/mod_api/shared.ts index d6dc1f8..9faf528 100644 --- a/common/mod_api/shared.ts +++ b/common/mod_api/shared.ts @@ -67,13 +67,17 @@ export interface RecipeType { matches(recipe: R, input: I): boolean; } -// reads a field of a recipe's json for RecipeType.parse, checked like the engine's own recipes' fields. throws naming -// the field when it isn't one, or its item isn't registered +// reads a value from a recipe's json for RecipeType.parse, checked like the engine's own recipes' fields. name is where +// it is, like "result" or "ingredients[0]", for the error thrown when it isn't one, or what it names isn't registered export interface RecipeReader { - item(json: Record, field: string): Id; - stack(json: Record, field: string): { id: Id; count: number }; + item(value: unknown, name: string): Id; + stack(value: unknown, name: string): { id: Id; count: number }; // an item, a #tag or a list of them, any of which fits, as every item that does, like the engine's shaped keys - ingredient(json: Record, field: string): Id[]; + ingredient(value: unknown, name: string): Id[]; + // { fluid, amount } in mB + fluid_stack(value: unknown, name: string): FluidStack; + // a whole number, at least 1, like a time in ticks + positive_int(value: unknown, name: string): number; } // the recipes of registered types, as their parse made them, in load order. not to be changed @@ -156,7 +160,8 @@ export interface SharedContext { // what one sells for, from its "base_sell_value", or undefined if it can't be sold sell_value(id: Id): number | undefined; }; - readonly fluids: { + // every fluid any mod defines, like the server's and clients' ctx.fluids, without what rules decide + readonly fluids: Pick & { // the rules of one of the mod's fluids, which the server and every client name and color it by register(id: Id, rules: FluidRules): void; }; @@ -172,7 +177,8 @@ export interface SharedContext { // deno-lint-ignore no-explicit-any list(type?: string): any[]; // a recipe type of the mod's own, in its namespace, only during setup: its recipes, from files and register, - // are parsed by it then, and find and all read them from there on every side. see RecipeType + // are parsed by it then, and find and all read them from there on every side. a recipe of a type no mod + // registers stops its mod loading once every shared script has set up. see RecipeType register_type(type: Id, rules: RecipeType): void; } & RecipeLookup; readonly components: { diff --git a/common/mod_data.ts b/common/mod_data.ts index 3df6bf8..46ddc12 100644 --- a/common/mod_data.ts +++ b/common/mod_data.ts @@ -605,7 +605,7 @@ const engine_recipes = new Map([ ]); // a mod's own types, like "bworld:cooking" for its cooking pot, are only stored by the engine. the mod parses them, -// with ctx.recipes.register_type, or reads them with ctx.recipes.list and checks them +// with ctx.recipes.register_type const recipe_schema = by_kind( "type", (type) => engine_recipes.get(type) ?? (ID_PATTERN.test(type) ? json_object : undefined), diff --git a/common/mod_loader.ts b/common/mod_loader.ts index 5929b58..7557829 100644 --- a/common/mod_loader.ts +++ b/common/mod_loader.ts @@ -29,7 +29,8 @@ import { TagRegistry, validate_recipe, } from "./mod_data.ts"; -import type { RecipeLookup, RecipeReader, RecipeType, SharedContext } from "./mod_api/shared.ts"; +import type { FluidStack, RecipeLookup, RecipeReader, RecipeType, SharedContext } from "./mod_api/shared.ts"; +import { fluid_exists } from "./fluids.ts"; import { resolve_tags, Tags } from "./tags.ts"; import type { LootTableJson } from "./loot.ts"; import { type BiomeJson, register_biome } from "./worldgen/biomes.ts"; @@ -88,8 +89,9 @@ export interface ModListing { export class RecipeBook { shaped: GridRecipe[] = []; - // recipes of mods' own types, by type + // recipes of mods' own types, by type, and the mod with the first one of each, for the error when nothing registers it by_type = new Map(); + first_used_by = new Map(); // the types shared scripts registered, and their recipes as parse made them, see SharedContext.recipes.register_type types = new Map>(); parsed = new Map(); @@ -191,7 +193,7 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe for (const { id, data } of mods) { try { - for (const recipe of data.recipes) add_recipe(recipes, recipe); + for (const recipe of data.recipes) add_recipe(recipes, recipe, id); } catch (e) { throw new ModLoadError(id, (e as Error).message); } @@ -202,12 +204,13 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe 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) { +// puts mod's recipe in the book, from its recipes/ or its shared script. throws when its registered type's parse throws +export function add_recipe(recipes: RecipeBook, recipe: RecipeJson, mod: string) { recipes.all.push(recipe); if (is_mod_recipe(recipe)) { const list = recipes.by_type.get(recipe.type) ?? []; recipes.by_type.set(recipe.type, list); + if (!recipes.first_used_by.has(recipe.type)) recipes.first_used_by.set(recipe.type, mod); 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)); @@ -225,33 +228,56 @@ function parse_recipe(type: RecipeType, json: ModRecipeJson, i } } -// items and tags load before any script sets up, so the ones recipes name can be checked +// items, fluids 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 }; + item: (value, name) => checked_item(name, item_problems(value), value as string), + stack(value, name) { + const stack = value as { id: string; count: number } | undefined; + return { id: checked_item(name, 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[]; + ingredient(value, name) { + const choice = value as string | string[]; const problems = choice_problems(choice); - if (problems.length > 0) throw new Error(`${field} ${problems[0]}`); + if (problems.length > 0) throw new Error(`${name} ${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}`); + if (!entry.startsWith("#")) checked_item(name, [], entry); + else if (!Tags.exists("items", entry)) throw new Error(`${name}: there's no item tag ${entry}`); } return choice_ids(choice); }, + fluid_stack(value, name) { + const stack = value as Partial | undefined; + const id = stack?.fluid?.id; + if (typeof id !== "string") throw new Error(`${name} must be { fluid: { id, data }, amount }`); + if (!fluid_exists(id)) throw new Error(`${name}: there's no fluid ${id}`); + return { fluid: stack!.fluid!, amount: recipe_reader.positive_int(stack!.amount, `${name} amount`) }; + }, + positive_int(value, name) { + if (!Number.isInteger(value) || (value as number) < 1) { + throw new Error(`${name} must be a whole number, at least 1`); + } + return value as number; + }, }; // 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}`); +function checked_item(name: string, problems: string[], id: string): string { + if (problems.length > 0) throw new Error(`${name} ${problems[0]}`); + if (!is_registered("items", id)) throw new Error(`${name}: there's no item ${id}`); return id; } +// once every shared script has set up: a recipe of a type no mod registered, which nothing would read, is an error +// for the first mod with one, like a misspelled type +export function check_recipe_types(recipes: RecipeBook) { + for (const [type, mod] of recipes.first_used_by) { + if (!recipes.types.has(type)) { + throw new ModLoadError(mod, `it has ${type} recipes, but no mod registers that type`); + } + } +} + // find and all, for every side's ctx.recipes export function recipe_lookup(recipes: () => RecipeBook): RecipeLookup { return { @@ -280,7 +306,7 @@ export function shared_recipes_api( const problems = validate_recipe(recipe); if (problems.length > 0) fail(`recipe of type ${type}: ${problems.join(", ")}`); try { - add_recipe(recipes(), recipe as RecipeJson); + add_recipe(recipes(), recipe as RecipeJson, mod); } catch (e) { fail((e as Error).message); } diff --git a/docs/modding/resources/fluids.md b/docs/modding/resources/fluids.md index 68fcde7..2214613 100644 --- a/docs/modding/resources/fluids.md +++ b/docs/modding/resources/fluids.md @@ -109,6 +109,9 @@ ctx.fluids.same(birch, { id: "copper_tools:syrup" }); // false, the data is diff there as plain `copper_tools:syrup`. Client scripts also have `ctx.fluids.mod(id)`, the name of the mod that added it, like `ctx.items.mod`. +Shared scripts have `ctx.fluids.exists` and `ctx.fluids.same` too, which don't depend on rules, like a +[recipe type](recipes.md#custom-recipe-types) that's found by a fluid. + ## Containers An item with `fluid_container` holds one fluid, full or empty, like a bucket or a bottle: diff --git a/docs/modding/resources/recipes.md b/docs/modding/resources/recipes.md index 8eeafd0..bf947f7 100644 --- a/docs/modding/resources/recipes.md +++ b/docs/modding/resources/recipes.md @@ -74,8 +74,7 @@ recipes with the same tool, material and addition are an error. ## Stonecutting: `bworld:stonecutting` -For the stonecutter, which cuts one item into another. It's the base game's own type, so `mods/bworld` checks these -recipes when the server starts rather than the engine: +For the stonecutter, which cuts one item into another. It's the base game's own type, registered by its shared script: ```json { @@ -96,7 +95,7 @@ uses up one of the input. For the juicer, which presses an item into a fluid. The base game registers one from its [shared script](#recipes-from-scripts) for every item with [`bworld:juiceable`](../items/food.md#juice), making the juice named after it, so most mods never write one. A file can add one for anything else, or make something other than -juice. It's checked when the server starts, like stonecutting: +juice: ```json { @@ -118,7 +117,7 @@ makes. The juicer uses the first recipe that takes the item. A fluid that ferments into another over time, like juice into wine. The base game registers one from its [shared script](#recipes-from-scripts) for every [juice](../items/food.md#juice), into wine from the same item. A file -can add one for anything else. It's checked when the server starts, like juicing: +can add one for anything else: ```json { @@ -179,9 +178,9 @@ export function setup(ctx: SharedContext) { ctx.recipes.register_type("bworld:smithing", { // the json checked and turned into what matches and the machine use parse: (json, read) => ({ - tool: read.item(json, "tool"), - material: read.stack(json, "material"), - result: read.item(json, "result"), + tool: read.item(json.tool, "tool"), + material: read.stack(json.material, "material"), + result: read.item(json.result, "result"), }), // whether what's in the machine makes the recipe matches: (recipe, input) => @@ -193,10 +192,16 @@ export function setup(ctx: SharedContext) { `parse` runs once for every recipe of the type, from files and from [scripts](#recipes-from-scripts), in load order, on the server and every client. Throwing stops the mod loading with an error naming the recipe, so a broken one is caught -when the server starts rather than when someone uses the machine. `read.item(json, field)` and `read.stack(json, field)` -check a field the way the engine's own types are checked, an item id or `{ id, count }` of an item that exists, and -throw naming the field. `read.ingredient(json, field)` reads a [choice](#choices) of items, an item, a `#tag` or a list -of them, as every item that fits. Its tags have to exist, but can be empty. +when the server starts rather than when someone uses the machine. `read` checks a value the way the engine's own types +are checked, throwing with the name it's given, like `"result"` or `"ingredients[0]"`: + +| Reader | Reads | +| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| `read.item(value, name)` | An item id, of an item that exists. | +| `read.stack(value, name)` | `{ id, count }` of an item that exists. | +| `read.ingredient(value, name)` | A [choice](#choices): an item, a `#tag` or a list of them, as every item that fits. Its tags have to exist, but can be empty. | +| `read.fluid_stack(value, name)` | `{ fluid: { id, data }, amount }` of a fluid that exists, in mB. | +| `read.positive_int(value, name)` | A whole number, at least 1, like a time in ticks. | Then server, client and shared scripts look recipes up by what's in the machine, like NeoForge's `RecipeManager.getRecipeFor`: @@ -210,36 +215,11 @@ ctx.recipes.all("bworld:smithing"); // every one, in load order them, not copies, so they aren't to be changed. A type can only be registered during `setup`, in the mod's own namespace. Other mods can add recipes of your type too, as long as they depend on your mod. -Types that aren't registered, like `bworld:cooking` for now, are read as JSON instead: +A recipe of a type no mod registers, like a misspelled one, stops the first mod with one from loading once every shared +script has set up, since nothing would ever read it. -```json -{ - "format_version": 1, - "recipe": { - "type": "bworld:cooking", - "ingredients": ["bworld:cabbage", ["bworld:carrot", "bworld:potato", "bworld:onion"]], - "result": { "id": "bworld:cabbage_rolls", "count": 1 }, - "cook_time": 100 - } -} -``` - -The mod's server script reads them in `setup` and checks their fields itself: - -```ts -const recipes = ctx.recipes.list("bworld:cooking").map((json, i) => { - if (!Array.isArray(json.ingredients) || json.ingredients.length > 6) { - throw new Error(`cooking recipe ${i + 1}: ingredients must be 1 to 6 items`); - } - // ...check the rest, and turn it into whatever the machine needs. expand turns #tags into their items - return { ingredients: json.ingredients.map((choice) => ctx.tags.expand(choice)) }; -}); -``` - -Throwing in `setup` stops the server from starting with the error, like a broken recipe of a registered type does. - -`list` returns copies, in load order. Client scripts can read every recipe with `ctx.recipes.list(type?)`, which is how -the recipe viewer shows mods' own types. +`ctx.recipes.list(type?)` gives recipes as their JSON instead, copies in load order. It's how the recipe viewer shows +every mod's types, and how a shared script makes recipes from another type's, see below. ## Recipes From Scripts diff --git a/docs/modding_plan.md b/docs/modding_plan.md index b9c9f1b..93b2c7c 100644 --- a/docs/modding_plan.md +++ b/docs/modding_plan.md @@ -121,7 +121,7 @@ interface RecipeRegistry { they can't accidentally register different things. - `register_type` would let `check-mods` and the loader validate mods' own recipe types, instead of each mod checking its recipes in `setup`. `shaped` becomes short for `bworld:shaped`. Shared scripts can now register types with - `ctx.recipes.register_type`, and `bworld:smithing`, `bworld:smelting` and `bworld:fuel` are. + `ctx.recipes.register_type`, and every one of the base game's and create's are. ### The Freeze and the Registry Hash diff --git a/mods/bworld/scripts/client.ts b/mods/bworld/scripts/client.ts index dd29a41..3a67407 100644 --- a/mods/bworld/scripts/client.ts +++ b/mods/bworld/scripts/client.ts @@ -19,7 +19,7 @@ import type { } from "bworld/client"; import { MINIGAMES } from "./minigames/mod.ts"; import { JUICER_CAPACITY, JUICER_PRESSES } from "./shared.ts"; -import { stonecutting_options, stonecutting_recipes } from "./stonecutting.ts"; +import { STONECUTTING, stonecutting_options, type StonecuttingRecipe } from "./stonecutting.ts"; const WIDTH = 176; // like minecraft's 176x166 container screens @@ -185,7 +185,7 @@ const SCROLLER_OFF_COLOR: Color = [0.78, 0.78, 0.78, 1]; const SELECTED_COLOR: Color = [1, 1, 1, 0.45]; function stonecutter_screen(ctx: ClientContext, menu: ClientMenu): MenuScreen { - const recipes = stonecutting_recipes(ctx); + const recipes = ctx.recipes.all(STONECUTTING); // the first row shown, and whether the scroller is being dragged let row = 0; let dragging = false; diff --git a/mods/bworld/scripts/cooking.ts b/mods/bworld/scripts/cooking.ts index f029e1b..7bc3064 100644 --- a/mods/bworld/scripts/cooking.ts +++ b/mods/bworld/scripts/cooking.ts @@ -7,6 +7,7 @@ // CuttingBoardBlockEntity, holds a stack of anything and cuts it one at a time with the right tool import type { BlockRef, Container, ItemStack, ServerContext } from "bworld/server"; +import { COOKING, type CookingRecipe, CUTTING, type CuttingRecipe, INGREDIENT_SLOTS } from "./cooking_recipes.ts"; // stove @@ -56,30 +57,16 @@ export function register_stove(ctx: ServerContext) { // cooking pot // slots 0-5 are the ingredients, 6 the meal waiting to be served, 7 containers for it, 8 the served meal -const INGREDIENT_SLOTS = 6; const MEAL_SLOT = 6; const CONTAINER_SLOT = 7; const OUTPUT_SLOT = 8; const POT_SIZE = 9; -// ticks, for recipes that don't say -const DEFAULT_COOK_TIME = 200; - // what's under the pot that heats it, and the state that has to be 1 for it to, like minecraft's heat_sources tag const HEAT_SOURCES: Record = { "bworld:furnace": "lit", "bworld:stove": "lit", }; -// a bworld:cooking recipe: the ingredients in any slots. in the json each is an item id or #tag, or a list of -// those any of which will do. here each is every item that will do -interface CookingRecipe { - ingredients: string[][]; - result: { id: string; count: number }; - // what the meal is served in, like a bowl. without it the meal comes out as soon as it's cooked - container?: string; - cook_time: number; -} - interface PotData { container: string; // ticks, counting up to cook_time_total @@ -89,81 +76,18 @@ interface PotData { meal_container: string; } -// an ingredient: an item, or a #tag of items any of which will do -function item_or_tag(ctx: ServerContext, where: string, id: unknown) { - if (typeof id === "string" && id.startsWith("#")) { - if (!ctx.tags.exists("items", id)) throw new Error(`${where}: there's no item tag ${id}`); - } else if (typeof id !== "string" || !ctx.items.exists(id)) { - throw new Error(`${where}: there's no item ${id}`); - } -} - -// checked when the server starts, so a broken recipe is a load error naming it -function load_recipes(ctx: ServerContext): CookingRecipe[] { - return ctx.recipes.list("bworld:cooking").map((json, i) => { - const where = `bworld:cooking recipe ${i + 1} (${json.result?.id ?? "no result"})`; - const item = (id: unknown) => { - if (typeof id !== "string" || !ctx.items.exists(id)) throw new Error(`${where}: there's no item ${id}`); - return id; - }; - const ingredients = json.ingredients; - if (!Array.isArray(ingredients) || ingredients.length < 1 || ingredients.length > INGREDIENT_SLOTS) { - throw new Error(`${where}: ingredients must be 1 to ${INGREDIENT_SLOTS} items`); - } - for (const ingredient of ingredients) { - if (Array.isArray(ingredient)) { - if (ingredient.length === 0) throw new Error(`${where}: an ingredient's list of items is empty`); - ingredient.forEach((id) => item_or_tag(ctx, where, id)); - } else { - item_or_tag(ctx, where, ingredient); - } - } - item(json.result?.id); - if (!Number.isInteger(json.result.count) || json.result.count < 1) { - throw new Error(`${where}: result.count must be a positive whole number`); - } - if (json.container !== undefined) item(json.container); - const cook_time = json.cook_time ?? DEFAULT_COOK_TIME; - if (!Number.isInteger(cook_time) || cook_time < 1) { - throw new Error(`${where}: cook_time must be positive ticks`); - } - return { - ingredients: ingredients.map((ingredient: string | string[]) => ctx.tags.expand(ingredient)), - result: json.result, - container: json.container, - cook_time, - }; - }); -} - // the recipe whose ingredients are exactly what's in the ingredient slots, one item from each, in any order -function find_recipe(recipes: CookingRecipe[], container: Container): CookingRecipe | undefined { +function find_recipe(ctx: ServerContext, container: Container): CookingRecipe | undefined { const items: string[] = []; for (let slot = 0; slot < INGREDIENT_SLOTS; slot++) { const item = container.get(slot); if (item) items.push(item.id); } if (items.length === 0) return undefined; - return recipes.find((recipe) => recipe.ingredients.length === items.length && matches(recipe.ingredients, items)); -} - -// pairs every ingredient with a different item, trying each way round, like a shapeless recipe -function matches(ingredients: string[][], items: string[], used = new Set()): boolean { - if (ingredients.length === 0) return true; - const [first, ...rest] = ingredients; - const fits = (id: string) => first.includes(id); - for (let i = 0; i < items.length; i++) { - if (used.has(i) || !fits(items[i])) continue; - used.add(i); - if (matches(rest, items, used)) return true; - used.delete(i); - } - return false; + return ctx.recipes.find(COOKING, items); } export function register_cooking_pot(ctx: ServerContext) { - const recipes = load_recipes(ctx); - const pot_data = (block: BlockRef): PotData => { const existing = block.data?.container && ctx.containers.get(block.data.container); const container = existing || ctx.containers.create(POT_SIZE); @@ -277,7 +201,7 @@ export function register_cooking_pot(ctx: ServerContext) { const data = pot_data(block); const container = ctx.containers.get(data.container)!; const heated = is_heated(block); - const recipe = heated ? find_recipe(recipes, container) : undefined; + const recipe = heated ? find_recipe(ctx, container) : undefined; if (recipe && can_cook(container, recipe)) { data.cook_time_total = recipe.cook_time; @@ -297,47 +221,9 @@ export function register_cooking_pot(ctx: ServerContext) { // cutting board -// a bworld:cutting recipe, like the java mod's: one ingredient (an item, or a list any of which will do), the -// tool type that cuts it, and everything one of it is cut into -interface CuttingRecipe { - ingredient: string[]; - tool: string; - result: { id: string; count: number }[]; -} - -// checked when the server starts, like the cooking pot's -function load_cutting_recipes(ctx: ServerContext): CuttingRecipe[] { - return ctx.recipes.list("bworld:cutting").map((json, i) => { - const where = `bworld:cutting recipe ${i + 1} (${json.ingredients?.[0] ?? "no ingredient"})`; - const item = (id: unknown) => { - if (typeof id !== "string" || !ctx.items.exists(id)) throw new Error(`${where}: there's no item ${id}`); - return id; - }; - if (!Array.isArray(json.ingredients) || json.ingredients.length !== 1) { - throw new Error(`${where}: ingredients must be one item, or one list of items any of which will do`); - } - const choice = [json.ingredients[0]].flat(); - if (choice.length === 0) throw new Error(`${where}: the ingredient's list of items is empty`); - choice.forEach((id) => item_or_tag(ctx, where, id)); - const ingredient = ctx.tags.expand(choice); - if (typeof json.tool !== "string") throw new Error(`${where}: tool must be a tool type, like "knife"`); - if (!Array.isArray(json.result) || json.result.length === 0) { - throw new Error(`${where}: result must be a list of { id, count }`); - } - for (const result of json.result) { - item(result?.id); - if (!Number.isInteger(result.count) || result.count < 1) { - throw new Error(`${where}: every result's count must be a positive whole number`); - } - } - return { ingredient, tool: json.tool, result: json.result }; - }); -} - // like the java mod's CuttingBoardBlock and CuttingBoardBlockEntity. what's on the board is the item it shows // (set_block_item), so the client draws it, like its CuttingBoardRenderer export function register_cutting_board(ctx: ServerContext) { - const recipes = load_cutting_recipes(ctx); const on_board = (block: BlockRef) => ctx.world.get_block_item(block.x, block.y, block.z); const set_on_board = (block: BlockRef, item: ItemStack | undefined) => ctx.world.set_block_item(block.x, block.y, block.z, item); @@ -369,7 +255,7 @@ export function register_cutting_board(ctx: ServerContext) { } // anything else is a tool for cutting one of what's on it, like processStoredItemUsingTool - const recipe = item && recipes.find((recipe) => recipe.ingredient.includes(item.id)); + const recipe = item && ctx.recipes.find(CUTTING, item.id); if (item && recipe && ctx.items.tool(held.id) === recipe.tool) { for (const result of recipe.result) ctx.world.drop_item(block.x, block.y, block.z, { ...result }); set_on_board(block, item.count > 1 ? { ...item, count: item.count - 1 } : undefined); diff --git a/mods/bworld/scripts/cooking_recipes.ts b/mods/bworld/scripts/cooking_recipes.ts new file mode 100644 index 0000000..acffc52 --- /dev/null +++ b/mods/bworld/scripts/cooking_recipes.ts @@ -0,0 +1,85 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// the kitchen's recipe types, registered by the shared script: what the cooking pot cooks, found by the items in its +// ingredient slots, and what the cutting board cuts, found by the item on it. see cooking.ts +import type { SharedContext } from "bworld/shared"; + +export const COOKING = "bworld:cooking"; +export const CUTTING = "bworld:cutting"; + +// how many ingredients the pot holds +export const INGREDIENT_SLOTS = 6; +// ticks, for recipes that don't say +const DEFAULT_COOK_TIME = 200; + +// a bworld:cooking recipe: the ingredients in any slots. in the json each is an item id or #tag, or a list of +// those any of which will do. here each is every item that will do +export interface CookingRecipe { + ingredients: string[][]; + result: { id: string; count: number }; + // what the meal is served in, like a bowl. without it the meal comes out as soon as it's cooked + container?: string; + cook_time: number; +} + +// a bworld:cutting recipe, like the java mod's: one ingredient (an item, or a list any of which will do), the +// tool type that cuts it, and everything one of it is cut into +export interface CuttingRecipe { + ingredient: string[]; + tool: string; + result: { id: string; count: number }[]; +} + +export function register_cooking_recipes(ctx: SharedContext) { + // found by the ids of what's in the ingredient slots + ctx.recipes.register_type(COOKING, { + parse(json, read) { + const ingredients = json.ingredients; + if (!Array.isArray(ingredients) || ingredients.length < 1 || ingredients.length > INGREDIENT_SLOTS) { + throw new Error(`ingredients must be 1 to ${INGREDIENT_SLOTS} items`); + } + const recipe: CookingRecipe = { + ingredients: ingredients.map((choice, i) => read.ingredient(choice, `ingredients[${i}]`)), + result: read.stack(json.result, "result"), + cook_time: json.cook_time === undefined + ? DEFAULT_COOK_TIME + : read.positive_int(json.cook_time, "cook_time"), + }; + if (json.container !== undefined) recipe.container = read.item(json.container, "container"); + return recipe; + }, + matches: (recipe, items) => recipe.ingredients.length === items.length && pairs_up(recipe.ingredients, items), + }); + + ctx.recipes.register_type(CUTTING, { + parse(json, read) { + if (!Array.isArray(json.ingredients) || json.ingredients.length !== 1) { + throw new Error("ingredients must be one item, or one list of items any of which will do"); + } + if (typeof json.tool !== "string") throw new Error(`tool must be a tool type, like "knife"`); + if (!Array.isArray(json.result) || json.result.length === 0) { + throw new Error("result must be a list of { id, count }"); + } + return { + ingredient: read.ingredient(json.ingredients[0], "ingredients[0]"), + tool: json.tool, + result: json.result.map((result: unknown, i: number) => read.stack(result, `result[${i}]`)), + }; + }, + matches: (recipe, id) => recipe.ingredient.includes(id), + }); +} + +// pairs every ingredient with a different item, trying each way round, like a shapeless recipe +function pairs_up(ingredients: string[][], items: string[], used = new Set()): boolean { + if (ingredients.length === 0) return true; + const [first, ...rest] = ingredients; + for (let i = 0; i < items.length; i++) { + if (used.has(i) || !first.includes(items[i])) continue; + used.add(i); + if (pairs_up(rest, items, used)) return true; + used.delete(i); + } + return false; +} diff --git a/mods/bworld/scripts/fermenting.ts b/mods/bworld/scripts/fermenting.ts index 6c5a329..533045d 100644 --- a/mods/bworld/scripts/fermenting.ts +++ b/mods/bworld/scripts/fermenting.ts @@ -3,9 +3,8 @@ // fermentable recipes: a fluid that ferments into another over a number of ticks, like juice into wine in the keg. the // shared script registers one for every juice, and mods can add more like any recipe, as files or from their shared -// scripts -import type { FluidStack, SharedContext } from "bworld/shared"; -import { fluid_stack, type RecipeReader } from "./juicing.ts"; +// scripts. they're found by the fluid that ferments +import type { FluidStack, FluidVariant, SharedContext } from "bworld/shared"; import type { JuiceableParams } from "./shared.ts"; export const FERMENTABLE = "bworld:fermentable"; @@ -22,6 +21,14 @@ export interface FermentableRecipe { // a recipe for every juice, the one each juiceable item makes, fermenting it into wine from the same fruit export function register_fermenting(ctx: SharedContext) { + ctx.recipes.register_type(FERMENTABLE, { + parse: (json, read) => ({ + input: read.fluid_stack(json.input, "input"), + output: read.fluid_stack(json.output, "output"), + ticks: read.positive_int(json.ticks, "ticks"), + }), + matches: (recipe, fluid) => ctx.fluids.same(recipe.input.fluid, fluid), + }); for (const id of ctx.items.ids()) { if (!(ctx.items.components(id)["bworld:juiceable"] as JuiceableParams | undefined)) continue; ctx.recipes.register(FERMENTABLE, { @@ -31,21 +38,3 @@ export function register_fermenting(ctx: SharedContext) { }); } } - -// every fermentable recipe, in load order. a broken one throws, which stops the server from starting -export function fermentable_recipes(ctx: RecipeReader): FermentableRecipe[] { - return ctx.recipes.list(FERMENTABLE).map((json, i) => { - const where = `${FERMENTABLE} recipe ${i + 1}`; - const input = fluid_stack(ctx, json.input); - const output = fluid_stack(ctx, json.output); - if (!input || !output) { - throw new Error( - `${where}: input and output must each be a { fluid, amount } of a fluid that exists, in mB`, - ); - } - if (!Number.isInteger(json.ticks) || json.ticks < 1) { - throw new Error(`${where}: ticks must be a whole number of ticks, at least 1`); - } - return { input, output, ticks: json.ticks }; - }); -} diff --git a/mods/bworld/scripts/juicing.ts b/mods/bworld/scripts/juicing.ts index d5713aa..e287e61 100644 --- a/mods/bworld/scripts/juicing.ts +++ b/mods/bworld/scripts/juicing.ts @@ -3,9 +3,9 @@ // juicing recipes: what the juicer presses an item into. the shared script registers one for every item with // bworld:juiceable, its own juice, and mods can add more like any recipe, as files or from their shared scripts. -// whatever makes juice reads them, like the juicer. with create installed, each is also a create:compacting recipe, -// so its press can make juice in a basin -import type { FluidStack, SharedContext, TagApi } from "bworld/shared"; +// whatever makes juice finds them by the item, like the juicer. with create installed, each is also a create:compacting +// recipe, so its press can make juice in a basin +import type { FluidStack, SharedContext } from "bworld/shared"; import type { JuiceableParams } from "./shared.ts"; export const JUICING = "bworld:juicing"; @@ -19,6 +19,18 @@ export interface JuicingRecipe { // a recipe for every juiceable item, pressing one into the juice named after it, as much as its component says export function register_juicing(ctx: SharedContext) { + ctx.recipes.register_type(JUICING, { + parse(json, read) { + if (!Array.isArray(json.fluid_results) || json.fluid_results.length !== 1) { + throw new Error("fluid_results must be one { fluid, amount }"); + } + return { + input: read.ingredient(json.input, "input"), + juice: read.fluid_stack(json.fluid_results[0], "fluid_results[0]"), + }; + }, + matches: (recipe, id) => recipe.input.includes(id), + }); for (const id of ctx.items.ids()) { const params = ctx.items.components(id)["bworld:juiceable"] as JuiceableParams | undefined; if (!params) continue; @@ -41,48 +53,3 @@ function register_compacting(ctx: SharedContext) { }); } } - -// what reading them needs, which server scripts have -export interface RecipeReader { - // deno-lint-ignore no-explicit-any - recipes: { list(type: string): any[] }; - tags: TagApi; - items: { exists(id: string): boolean }; - fluids: { exists(id: string): boolean }; -} - -// every juicing recipe, in load order. a broken one throws, which stops the server from starting -export function juicing_recipes(ctx: RecipeReader): JuicingRecipe[] { - return ctx.recipes.list(JUICING).map((json, i) => { - const where = `${JUICING} recipe ${i + 1}`; - const choice: unknown = json.input; - const entries = typeof choice === "string" ? [choice] : Array.isArray(choice) ? choice : []; - const exists = (entry: unknown) => - typeof entry === "string" && - (entry.startsWith("#") ? ctx.tags.exists("items", entry.slice(1)) : ctx.items.exists(entry)); - if (entries.length === 0 || !entries.every(exists)) { - throw new Error(`${where}: input must be an item, a #tag or a list of them, and they must exist`); - } - const results: unknown = json.fluid_results; - const juice = Array.isArray(results) && results.length === 1 ? fluid_stack(ctx, results[0]) : undefined; - if (!juice) { - throw new Error(`${where}: fluid_results must be one { fluid, amount } of a fluid that exists, in mB`); - } - return { input: ctx.tags.expand(choice as string | string[]), juice }; - }); -} - -// a recipe's { fluid, amount } of a fluid that exists and a whole number of mB, undefined when it isn't one -export function fluid_stack(ctx: RecipeReader, json: unknown): FluidStack | undefined { - const stack = json as Partial | undefined; - const id = stack?.fluid?.id; - if (typeof id !== "string" || !ctx.fluids.exists(id) || !Number.isInteger(stack!.amount) || stack!.amount! < 1) { - return undefined; - } - return { fluid: stack!.fluid!, amount: stack!.amount! }; -} - -// the first recipe that presses id, undefined when none does -export function juicing_for(recipes: JuicingRecipe[], id: string): JuicingRecipe | undefined { - return recipes.find((recipe) => recipe.input.includes(id)); -} diff --git a/mods/bworld/scripts/server.ts b/mods/bworld/scripts/server.ts index a21447d..0e33e54 100644 --- a/mods/bworld/scripts/server.ts +++ b/mods/bworld/scripts/server.ts @@ -6,13 +6,13 @@ import type { BlockRef, Container, FluidHandler, FluidStack, Player, Season, Ser import { register_curios } from "./curios.ts"; import { register_effects } from "./effects.ts"; import { register_fishing } from "./fishing.ts"; -import { stonecutting_options, stonecutting_recipes } from "./stonecutting.ts"; +import { STONECUTTING, stonecutting_options, type StonecuttingRecipe } from "./stonecutting.ts"; import { SMITHING, type SmithingRecipe } from "./smithing.ts"; import { FUEL, type FuelRecipe, SMELTING, type SmeltingRecipe } from "./smelting.ts"; import { register_verdigris } from "./verdigris/server.ts"; import { type JuiceableParams, JUICER_CAPACITY, JUICER_PRESSES } from "./shared.ts"; -import { juicing_for, juicing_recipes } from "./juicing.ts"; -import { fermentable_recipes } from "./fermenting.ts"; +import { JUICING, type JuicingRecipe } from "./juicing.ts"; +import { FERMENTABLE, type FermentableRecipe } from "./fermenting.ts"; import { register_cooking_pot, register_cutting_board, register_stove } from "./cooking.ts"; export function setup(ctx: ServerContext) { @@ -502,7 +502,7 @@ const STONECUTTER_INPUT = 0; const STONECUTTER_RESULT = 1; function register_stonecutter(ctx: ServerContext) { - const recipes = stonecutting_recipes(ctx); + const recipes = ctx.recipes.all(STONECUTTING); const menu_type = ctx.menus.register("bworld:stonecutter", (menu, block, player) => { const container = ctx.containers.create(2); @@ -872,8 +872,6 @@ interface JuicerData { function register_juicer(ctx: ServerContext) { // what juice is made from and how it looks, read by the juicing recipes and the juice's rules in shared.ts ctx.components.register_item("bworld:juiceable", {}); - // checked now, so a broken recipe stops the server rather than the juicer later - const recipes = juicing_recipes(ctx); const show = (block: BlockRef, container: Container) => { const item = container.get(0); const data = item?.data !== undefined && { data: item.data }; @@ -897,7 +895,7 @@ function register_juicer(ctx: ServerContext) { const held = player.held_item; const container = block_container(ctx, block, 1); const data = block.data as JuicerData; - if (held && juicing_for(recipes, held.id)) { + if (held && ctx.recipes.find(JUICING, held.id)) { held.count = container.add(held)?.count ?? 0; show(block, container); // true even when none fit, so the fruit isn't eaten instead @@ -909,7 +907,7 @@ function register_juicer(ctx: ServerContext) { if (held || !player.is_sneaking()) return false; const item = container.get(0); - const recipe = item && juicing_for(recipes, item.id); + const recipe = item && ctx.recipes.find(JUICING, item.id); if (!item || !recipe) return false; const juice = tank(block); if (juice.fill(recipe.juice, "simulate") < recipe.juice.amount) return false; @@ -951,11 +949,9 @@ interface KegData { type KegTank = "input" | "output"; function register_keg(ctx: ServerContext) { - // checked now, so a broken recipe stops the server rather than the keg later - const recipes = fermentable_recipes(ctx); const recipe_for = (block: BlockRef) => { const fluid = (block.data as KegData | undefined)?.input?.fluid; - return fluid && recipes.find((recipe) => ctx.fluids.same(recipe.input.fluid, fluid)); + return fluid && ctx.recipes.find(FERMENTABLE, fluid); }; const tank = (block: BlockRef, which: KegTank) => ctx.fluids.tank_handler({ diff --git a/mods/bworld/scripts/shared.ts b/mods/bworld/scripts/shared.ts index dcb5642..177f68c 100644 --- a/mods/bworld/scripts/shared.ts +++ b/mods/bworld/scripts/shared.ts @@ -6,10 +6,12 @@ // or a door open the moment they click it. and the rules of juice and wine, which name and color them by the item // they're from, and the recipes that make them. and the base game's recipe types import type { SharedBlock, SharedContext } from "bworld/shared"; +import { register_cooking_recipes } from "./cooking_recipes.ts"; import { register_fermenting } from "./fermenting.ts"; import { register_juicing } from "./juicing.ts"; import { register_smelting } from "./smelting.ts"; import { register_smithing } from "./smithing.ts"; +import { register_stonecutting } from "./stonecutting.ts"; import { register_verdigris_rules } from "./verdigris/shared.ts"; export function setup(ctx: SharedContext) { @@ -22,6 +24,8 @@ export function setup(ctx: SharedContext) { register_fermenting(ctx); register_smithing(ctx); register_smelting(ctx); + register_stonecutting(ctx); + register_cooking_recipes(ctx); } // the sides a fence connects on, and the face of the block there it connects to diff --git a/mods/bworld/scripts/smelting.ts b/mods/bworld/scripts/smelting.ts index 666edd2..cd07c38 100644 --- a/mods/bworld/scripts/smelting.ts +++ b/mods/bworld/scripts/smelting.ts @@ -23,20 +23,14 @@ export interface FuelRecipe { } export function register_smelting(ctx: SharedContext) { - // deno-lint-ignore no-explicit-any - const ticks = (json: any, field: string): number => { - if (!Number.isInteger(json[field]) || json[field] < 1) throw new Error(`${field} must be at least 1 tick`); - return json[field]; - }; - // two recipes for one item would leave one that can never be made const smelted = new Set(); ctx.recipes.register_type(SMELTING, { parse(json, read) { const recipe = { - input: read.ingredient(json, "input"), - output: read.stack(json, "output"), - cook_time: ticks(json, "cook_time"), + input: read.ingredient(json.input, "input"), + output: read.stack(json.output, "output"), + cook_time: read.positive_int(json.cook_time, "cook_time"), }; for (const id of recipe.input) { if (smelted.has(id)) throw new Error(`there's already one for ${id}`); @@ -52,7 +46,10 @@ export function register_smelting(ctx: SharedContext) { const burning = new Map(); ctx.recipes.register_type(FUEL, { parse(json, read) { - const recipe = { items: read.ingredient(json, "item"), burn_time: ticks(json, "burn_time") }; + const recipe = { + items: read.ingredient(json.item, "item"), + burn_time: read.positive_int(json.burn_time, "burn_time"), + }; for (const id of recipe.items) { const earlier = burning.get(id); if (earlier) earlier.items = earlier.items.filter((other) => other !== id); diff --git a/mods/bworld/scripts/smithing.ts b/mods/bworld/scripts/smithing.ts index 0562aa7..fe9887d 100644 --- a/mods/bworld/scripts/smithing.ts +++ b/mods/bworld/scripts/smithing.ts @@ -27,11 +27,11 @@ export function register_smithing(ctx: SharedContext) { ctx.recipes.register_type(SMITHING, { parse(json, read) { const recipe: SmithingRecipe = { - tool: read.item(json, "tool"), - material: read.stack(json, "material"), - result: read.item(json, "result"), + tool: read.item(json.tool, "tool"), + material: read.stack(json.material, "material"), + result: read.item(json.result, "result"), }; - if (json.addition !== undefined) recipe.addition = read.item(json, "addition"); + if (json.addition !== undefined) recipe.addition = read.item(json.addition, "addition"); const inputs = `${recipe.tool} ${recipe.material.id} ${recipe.addition}`; if (seen.has(inputs)) throw new Error(`there's already one for ${recipe.tool} with ${recipe.material.id}`); seen.add(inputs); diff --git a/mods/bworld/scripts/stonecutting.ts b/mods/bworld/scripts/stonecutting.ts index 0b4ca04..7a81131 100644 --- a/mods/bworld/scripts/stonecutting.ts +++ b/mods/bworld/scripts/stonecutting.ts @@ -1,10 +1,10 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// stonecutting recipes: the stonecutter cuts one item into another, picked from every recipe that takes it. the -// server's menu and the client's screen both list them from here, in the same order, so a button's number means the -// same recipe to both -import type { TagApi } from "bworld/shared"; +// stonecutting recipes: the stonecutter cuts one item into another, picked from every recipe that takes it. the type is +// registered by the shared script, so the server's menu and the client's screen both list them from ctx.recipes.all, in +// the same order, so a button's number means the same recipe to both +import type { SharedContext } from "bworld/shared"; export const STONECUTTING = "bworld:stonecutting"; @@ -14,36 +14,20 @@ export interface StonecuttingRecipe { output: { id: string; count: number }; } -// what reading them needs, which server and client scripts both have -interface RecipeReader { - // deno-lint-ignore no-explicit-any - recipes: { list(type: string): any[] }; - tags: TagApi; - items: { exists(id: string): boolean }; -} - -// every stonecutting recipe, in load order. a broken one throws, which stops the server from starting -export function stonecutting_recipes(ctx: RecipeReader): StonecuttingRecipe[] { - return ctx.recipes.list(STONECUTTING).map((json, i) => { - const where = `${STONECUTTING} recipe ${i + 1}`; - // a tag can be empty, like one of another mod's items that isn't installed - const choice: unknown = json.input; - const entries = typeof choice === "string" ? [choice] : Array.isArray(choice) ? choice : []; - const exists = (entry: unknown) => - typeof entry === "string" && - (entry.startsWith("#") ? ctx.tags.exists("items", entry.slice(1)) : ctx.items.exists(entry)); - if (entries.length === 0 || !entries.every(exists)) { - throw new Error(`${where}: input must be an item, a #tag or a list of them, and they must exist`); - } - const { id, count } = json.output ?? {}; - if (typeof id !== "string" || !ctx.items.exists(id) || !Number.isInteger(count) || count < 1) { - throw new Error(`${where}: output must be { id, count } of an item that exists`); - } - return { input: ctx.tags.expand(choice as string | string[]), output: { id, count } }; +export function register_stonecutting(ctx: SharedContext) { + ctx.recipes.register_type(STONECUTTING, { + parse: (json, read) => ({ + input: read.ingredient(json.input, "input"), + output: read.stack(json.output, "output"), + }), + matches: (recipe, id) => recipe.input.includes(id), }); } // what an item can be cut into, in the order the stonecutter shows them -export function stonecutting_options(recipes: StonecuttingRecipe[], id: string | undefined): StonecuttingRecipe[] { +export function stonecutting_options( + recipes: readonly StonecuttingRecipe[], + id: string | undefined, +): StonecuttingRecipe[] { return id === undefined ? [] : recipes.filter((recipe) => recipe.input.includes(id)); } diff --git a/mods/create/scripts/recipes/processing.ts b/mods/create/scripts/recipes/processing.ts index 2af6a88..bff9645 100644 --- a/mods/create/scripts/recipes/processing.ts +++ b/mods/create/scripts/recipes/processing.ts @@ -2,9 +2,10 @@ // SPDX-License-Identifier: AGPL-3.0-or-later // create's processing recipes, the shape its machines' recipe types share, like ProcessingRecipe: item choices in, and -// stacks out, each with a chance, and for the types that can, fluids out as { fluid, amount }. read and checked when the server starts, so a broken one stops it there instead of -// in a machine. no ctx, tests give what it needs -import type { FluidStack, Id } from "bworld/shared"; +// stacks out, each with a chance, and for the types that can, fluids out as { fluid, amount }. the shared script +// registers each type, so a broken recipe stops the mod loading instead of a machine later. no ctx, tests give what it +// needs +import type { FluidStack, Id, RecipeType } from "bworld/shared"; // how many ingredients, item results and fluid results a type takes at most, like getMaxInputCount, // getMaxOutputCount and getMaxFluidOutputCount @@ -42,14 +43,17 @@ export interface RecipeLookup { fluid_exists(id: Id): boolean; } -// every recipe of type, from their json, or an error saying what's wrong with each broken one -export function processing_recipes(jsons: unknown[], type: ProcessingType, lookup: RecipeLookup): ProcessingRecipe[] { - const parsed = jsons.map((json) => parse_processing(json, type, lookup)); - const problems = parsed.flatMap((recipe, i) => - "problems" in recipe ? [`${type.id} recipe ${JSON.stringify(jsons[i])}: ${recipe.problems.join("; ")}`] : [] - ); - if (problems.length > 0) throw new Error(problems.join("\n")); - return parsed as ProcessingRecipe[]; +// the recipe type for ctx.recipes.register_type, saying everything wrong with a broken recipe. it's found by the item +// it takes first, like a machine's getRecipe +export function processing_type(type: ProcessingType, lookup: RecipeLookup): RecipeType { + return { + parse(json) { + const parsed = parse_processing(json, type, lookup); + if ("problems" in parsed) throw new Error(parsed.problems.join("; ")); + return parsed; + }, + matches: (recipe, item) => recipe.ingredients[0]?.includes(item) ?? false, + }; } // one recipe, or what's wrong with it, like ProcessingRecipe.validate @@ -120,11 +124,6 @@ export function parse_processing( return problems.length > 0 ? { problems } : { ingredients, results, fluid_results }; } -// the first recipe that takes the item, like a machine's getRecipe -export function processing_for(recipes: ProcessingRecipe[], item: Id): ProcessingRecipe | undefined { - return recipes.find((recipe) => recipe.ingredients[0]?.includes(item)); -} - // what one go of a recipe makes: each result, with each of its count kept by its chance, like rollResults export function roll_results(recipe: ProcessingRecipe, random = Math.random): { id: Id; count: number }[] { return recipe.results.flatMap(({ id, count, chance }) => { diff --git a/mods/create/scripts/server.ts b/mods/create/scripts/server.ts index 5dd03dc..ebb07d6 100644 --- a/mods/create/scripts/server.ts +++ b/mods/create/scripts/server.ts @@ -19,14 +19,7 @@ import { } from "./kinetics/connections.ts"; import { flow_score, motor_step } from "./kinetics/generators.ts"; import { handle_added, handle_removed, type KineticWorld, update_generated } from "./kinetics/spreading.ts"; -import { - COMPACTING, - PRESSING, - processing_for, - processing_recipes, - type ProcessingRecipe, - roll_results, -} from "./recipes/processing.ts"; +import { COMPACTING, PRESSING, type ProcessingRecipe, roll_results } from "./recipes/processing.ts"; import { CYCLE, cycle_rate, PRESS_AT, type PressShown, SCAN_TICKS } from "./processing/press.ts"; import { apply_basin_recipe, @@ -90,16 +83,9 @@ export function setup(ctx: ServerContext) { const config: Config = ctx.config; const world = kinetic_world(ctx, config); - // checked now, so a broken recipe stops the server rather than a press later - const lookup = { - expand: (choice: Id | Id[]) => ctx.tags.expand(choice), - item_exists: (id: Id) => ctx.items.exists(id), - fluid_exists: (id: Id) => ctx.fluids.exists(id), - }; - const pressing = processing_recipes(ctx.recipes.list(PRESSING.id), PRESSING, lookup); // the ones that take more ingredients first, so a recipe isn't beaten by one that takes part of what it does, like // BasinOperatingBlockEntity.getMatchingRecipes - const compacting = processing_recipes(ctx.recipes.list(COMPACTING.id), COMPACTING, lookup) + const compacting = [...ctx.recipes.all(COMPACTING.id)] .sort((a, b) => b.ingredients.length - a.ingredients.length); ctx.components.register_block("create:kinetic", { @@ -209,7 +195,7 @@ export function setup(ctx: ServerContext) { on_second: update_flow, }); - register_press(ctx, pressing, compacting); + register_press(ctx, compacting); register_basin(ctx); } @@ -280,7 +266,8 @@ function set_basin(block: BlockRef, contents: Partial) { // lone item turns into what it's pressed into, and from a stack one at a time is, landing beside the rest. with a // basin two blocks under it, it presses into that instead, making a compacting recipe in it each time, like // MechanicalPressBlockEntity as a BasinOperatingBlockEntity. it only ticks while it turns -function register_press(ctx: ServerContext, recipes: ProcessingRecipe[], compacting: ProcessingRecipe[]) { +function register_press(ctx: ServerContext, compacting: ProcessingRecipe[]) { + const pressing_for = (item: Id) => ctx.recipes.find(PRESSING.id, item); // the basin two blocks under it, with a block between for the head to come down through, like // BasinOperatingBlockEntity.getBasin const basin_under = (block: BlockRef) => { @@ -308,11 +295,11 @@ function register_press(ctx: ServerContext, recipes: ProcessingRecipe[], compact { x: block.x + inset, y: block.y - 1 + inset, z: block.z + inset }, { x: block.x + 1 - inset, y: block.y - inset, z: block.z + 1 - inset }, "bworld:item", - ).filter((item) => item.on_ground && processing_for(recipes, item.get_item()!.id)); + ).filter((item) => item.on_ground && pressing_for(item.get_item()!.id)); const press = (item: EntityRef) => { const stack = item.get_item()!; - const results = roll_results(processing_for(recipes, stack.id)!); + const results = roll_results(pressing_for(stack.id)!); const { x, y, z } = item.position; if (stack.count === 1) { const [first, ...rest] = results; diff --git a/mods/create/scripts/shared.ts b/mods/create/scripts/shared.ts index a5fe96b..f24e287 100644 --- a/mods/create/scripts/shared.ts +++ b/mods/create/scripts/shared.ts @@ -5,6 +5,7 @@ // placed against, and chain drives join into lines import type { BlockPlacement, Face, Id, SharedContext } from "bworld/shared"; import { chain_update, type ChainState } from "./kinetics/chains.ts"; +import { COMPACTING, PRESSING, processing_type } from "./recipes/processing.ts"; import { AXES, type Axis, @@ -20,6 +21,10 @@ import { } from "./kinetics/connections.ts"; export function setup(ctx: SharedContext) { + const lookup = { expand: ctx.tags.expand, item_exists: ctx.items.exists, fluid_exists: ctx.fluids.exists }; + ctx.recipes.register_type(PRESSING.id, processing_type(PRESSING, lookup)); + ctx.recipes.register_type(COMPACTING.id, processing_type(COMPACTING, lookup)); + // what turns at x y z, undefined when nothing does const kinetic_at = (x: number, y: number, z: number): KineticShape | undefined => { const id = ctx.world.get_block(x, y, z); diff --git a/server/game/mod_runtime.ts b/server/game/mod_runtime.ts index 2fe86e1..6461ae5 100644 --- a/server/game/mod_runtime.ts +++ b/server/game/mod_runtime.ts @@ -24,7 +24,7 @@ import { AIR, CHUNK_SIZE, faces, ID_MASK } from "$/common/constants.ts"; import { physics } from "$/common/physics.ts"; import { clock } from "$/common/time.ts"; import { BlockRules } from "$/common/block_rules.ts"; -import { FluidRules } from "$/common/fluids.ts"; +import { fluid_exists, FluidRules, same_fluid } from "$/common/fluids.ts"; import { interact, item_handler, tank_handler, transfer, use_container } from "./fluid_handlers.ts"; import type { SharedContext } from "$/common/mod_api/shared.ts"; import { tag_api } from "$/common/tags.ts"; @@ -57,7 +57,7 @@ import type { ServerContext, SlotOptions, } from "$/common/mod_api/server.ts"; -import { ModLoadError, recipe_lookup, shared_recipes_api } from "$/common/mod_loader.ts"; +import { check_recipe_types, ModLoadError, recipe_lookup, shared_recipes_api } from "$/common/mod_loader.ts"; import { argument, block as block_argument, @@ -278,6 +278,7 @@ export class ModRuntime { for (const { mod, version, url, engine_access, config } of scripts) { await loading_mod(mod, engine_access, () => this.#load_shared_script(mod, version, url, config)); } + check_recipe_types(game.recipes); } finally { this.#shared_setup = false; } @@ -298,6 +299,8 @@ export class ModRuntime { blocks, items: shared_items_api(mod), fluids: { + exists: fluid_exists, + same: same_fluid, register: (id, rules) => { if (!this.#setting_up) throw new ModLoadError(mod, "rules can only be registered during setup"); this.fluid_rules.register(mod, id, rules); diff --git a/tests/create/recipes_test.ts b/tests/create/recipes_test.ts index e7204ca..6d01501 100644 --- a/tests/create/recipes_test.ts +++ b/tests/create/recipes_test.ts @@ -1,16 +1,19 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// create's recipe types: read and checked when the server starts, and shown by the recipe viewer +// create's recipe types: read and checked when the mod loads, and shown by the recipe viewer import { assert, assertEquals, assertThrows } from "@std/assert"; import { EverythingRegistry } from "$/common/everything_registry.ts"; import { tag_api } from "$/common/tags.ts"; import type { ClientContext } from "$/common/mod_api/client.ts"; +import type { RecipeReader } from "$/common/mod_api/shared.ts"; +import { recipe_lookup } from "$/common/mod_loader.ts"; import { COMPACTING, parse_processing, PRESSING, - processing_recipes, + processing_type, + type ProcessingRecipe, } from "$/mods/create/scripts/recipes/processing.ts"; import { inputs, outputs } from "$/mods/recipe_viewer/scripts/recipes.ts"; import { RecipeIndex } from "$/mods/recipe_viewer/scripts/recipes_screen.ts"; @@ -24,7 +27,7 @@ const lookup = () => ({ Deno.test("create's pressing recipes are read with every item each ingredient stands for", async () => { const { game } = await test_game("mods"); - const recipes = processing_recipes(game.recipes.by_type.get(PRESSING.id) ?? [], PRESSING, lookup()); + const recipes = recipe_lookup(() => game.recipes).all(PRESSING.id); const sheet = recipes.find((recipe) => recipe.results[0].id === "create:iron_sheet"); assert(sheet, "iron is pressed into sheets"); assert(sheet.ingredients[0].includes("bworld:iron_ingot")); @@ -50,9 +53,10 @@ Deno.test("a pressing recipe that a press couldn't make says what's wrong with i assertEquals(problems({ ingredients: ["bworld:iron_ingot"], results: [sheet], processing_time: 100 }).length, 1); assertEquals(problems({ results: [sheet] }).length, 1); - // the server doesn't start with one, and says which + // the mod doesn't load with one, and says what's wrong + const type = processing_type(PRESSING, lookup()); assertThrows( - () => processing_recipes([{ ingredients: ["bworld:no_such_ingot"], results: [sheet] }], PRESSING, lookup()), + () => type.parse({ ingredients: ["bworld:no_such_ingot"], results: [sheet] }, {} as RecipeReader), Error, "bworld:no_such_ingot", ); diff --git a/tests/helpers.ts b/tests/helpers.ts index ccc8d50..c587e3b 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -261,7 +261,7 @@ export function client_of(game: GameServer, area: Area) { }, items: shared_items_api("bworld"), // only its blocks are looked at here - fluids: { register() {} }, + fluids: { exists: () => false, same: () => false, register() {} }, recipes: { register() {}, list: () => [], register_type() {}, find: () => undefined, all: () => [] }, world, components: { register_block: (id, block_rules) => rules.register("bworld", id, block_rules) }, diff --git a/tests/script_recipes_test.ts b/tests/script_recipes_test.ts index 5b1000e..488ee46 100644 --- a/tests/script_recipes_test.ts +++ b/tests/script_recipes_test.ts @@ -8,11 +8,13 @@ import { EverythingRegistry } from "$/common/everything_registry.ts"; import type { ModListing } from "$/common/mod_loader.ts"; import { read_bmod } from "$/common/bmod.ts"; import { load_client_mods } from "$/client/mods.ts"; +import { load_order } from "$/common/mod_check.ts"; import { load_and_check } from "$/tools/check_mods.ts"; import { pack_mod } from "$/tools/pack_mod.ts"; import { copy_dir, test_game } from "./helpers.ts"; -// sifts into what its component says, and a shaped recipe made in code +// sifts into what its component says, and a shaped recipe made in code. then sifting and washing as testrecipes' own +// types, found by the item put in const SHARED = ` import type { SharedContext } from "bworld/shared"; export function setup(ctx: SharedContext) { @@ -21,6 +23,12 @@ const SHARED = ` if (sifts) ctx.recipes.register("testrecipes:sifting", { input: id, result: { id: sifts.into, count: 1 } }); } ctx.recipes.register("shaped", { pattern: ["#"], key: { "#": "testrecipes:gravel" }, result: { id: "testrecipes:flint", count: 2 } }); + for (const type of ["testrecipes:sifting", "testrecipes:washing"]) { + ctx.recipes.register_type(type, { + parse: (json, read) => ({ input: read.item(json.input, "input"), result: read.stack(json.result, "result") }), + matches: (recipe, input) => recipe.input === input, + }); + } SHARED_EXTRA } `; @@ -101,14 +109,9 @@ Deno.test("recipes a shared script registers are on the server and clients, for assertEquals(seen.testrecipes_client, SIFTING); }); -// sifting as a type of testrecipes' own, matched by the item put in, and a recipe registered after it -const SIFTING_TYPE = ` - ctx.recipes.register_type("testrecipes:sifting", { - parse: (json, read) => ({ input: read.item(json, "input"), result: read.stack(json, "result") }), - matches: (recipe, input) => recipe.input === input, - }); - ctx.recipes.register("testrecipes:sifting", { input: "testrecipes:sand", result: { id: "testrecipes:gravel", count: 1 } }); -`; +// a sifting recipe registered after the type +const SAND_AFTER = + `ctx.recipes.register("testrecipes:sifting", { input: "testrecipes:sand", result: { id: "testrecipes:gravel", count: 1 } });`; const SAND_FILE = { "sand.json": { @@ -119,7 +122,7 @@ const SAND_FILE = { }; Deno.test("a recipe type parses its recipes, and find gives the first one an input makes, on every side", async () => { - const dir = recipe_mod(SIFTING_TYPE, SAND_FILE); + const dir = recipe_mod(SAND_AFTER, SAND_FILE); await test_game(dir); await load_client(dir); for (const side of ["server", "client"]) { @@ -135,7 +138,7 @@ Deno.test("a recipe type parses its recipes, and find gives the first one an inp }); Deno.test("a recipe its type can't parse stops the mod loading, naming it", async () => { - const dir = recipe_mod(SIFTING_TYPE, { + const dir = recipe_mod("", { "sand.json": { type: "testrecipes:sifting", input: "testrecipes:nothing", @@ -150,6 +153,22 @@ Deno.test("a recipe its type can't parse stops the mod loading, naming it", asyn Deno.removeSync(dir, { recursive: true }); }); +Deno.test("a recipe of a type no mod registers stops its mod loading, like a misspelled one", async () => { + const dir = recipe_mod("", { + "sand.json": { + type: "testrecipes:sieving", + input: "testrecipes:sand", + result: { id: "testrecipes:flint", count: 1 }, + }, + }); + await assertRejects( + () => test_game(dir), + Error, + "testrecipes: it has testrecipes:sieving recipes, but no mod registers that type", + ); + Deno.removeSync(dir, { recursive: true }); +}); + Deno.test("a mod can only register recipe types in its own namespace", async () => { const dir = recipe_mod( `ctx.recipes.register_type("bworld:sifting", { parse: (json) => json, matches: () => true });`, @@ -201,3 +220,18 @@ Deno.test("recipes can only be registered while shared scripts set up", async () Deno.removeSync(dir, { recursive: true }); } }); + +Deno.test("every mod's recipe types are registered on a client too, so it loads them", async () => { + const mods = load_order(load_and_check("mods")); + const bmods = await Promise.all(mods.map(async (mod) => read_bmod(await pack_mod(mod), `${mod.id}.bmod`))); + const listings = mods.map((mod): ModListing => ({ + id: mod.id, + name: mod.id, + version: "1.0.0", + sha256: "", + file: "", + size: 0, + })); + EverythingRegistry.clear(); + await load_client_mods(listings, bmods); +});