// the json formats from MODS.md, and converting them to and from the engine's registry entries. // the mod loader uses the from_json direction, tests use both to check nothing is lost import { is_tint_color, type TintColor } from "./worldgen/biome_colors.ts"; import { type BlockRegistry, type BlockStateDefinition, type FoodProperties, type ItemRegistry, RENDER_LAYERS, type RenderLayer, } from "./everything_registry.ts"; import { type BlockVariant, MODEL_FACES, type ModelFace } from "./block_models.ts"; export const FORMAT_VERSION = 1; export const ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+$/; export const NAMESPACE_PATTERN = /^[a-z0-9_]{1,32}$/; export const RESERVED_NAMESPACES = ["bworld", "engine"]; type BlockTextures = BlockRegistry["textures"]; export interface ManifestJson { format_version: number; id: string; name: string; description?: string; version: string; authors?: string[]; game_version?: string; dependencies?: { id: string; version: string }[]; scripts?: { server?: string; client?: string; worldgen?: string }; credits?: string; } export interface BlockJson { id: string; name?: string; textures: BlockTextures; model?: string; variants?: Record; render_layer?: RenderLayer; cull_same?: boolean; tint?: { color: TintColor; textures?: string[] }; light_emission?: number; light_opacity?: number; // replaced by render_layer, true means translucent transparent?: boolean; alpha?: number; collision?: boolean; mining?: { toughness: number; tool?: string; requires_tool?: boolean }; drops?: string; item?: boolean; interactive?: boolean; replaceable?: boolean; place_on?: string[]; place_in?: string[]; states?: BlockStateDefinition[]; components?: Record; } export interface OreJson { id: string; replaces: string; min_y: number; max_y: number; scale: number; threshold: number; } export interface ItemJson { id: string; texture: string; // data key -> texture, see ItemRegistry.data_textures data_textures?: Record; tool?: string; places?: string; max_stack?: number; food?: FoodProperties; name?: string; lore?: string; components?: Record; } // an item a recipe takes: its id, or a list of ids any of which fits, like every kind of planks export type ItemChoice = string | string[]; export function choice_ids(choice: ItemChoice): string[] { return typeof choice === "string" ? [choice] : choice; } export type RecipeJson = | { type: "shaped"; pattern: string[]; key: Record; result: { id: string; count: number }; } | { type: "furnace"; input: ItemChoice; output: { id: string; count: number }; cook_time: number } | { type: "fuel"; item: ItemChoice; burn_time: number } // upgrades a tool at a smithing table, with some of a material and maybe one more item | { type: "smithing"; tool: string; material: { id: string; count: number }; addition?: string; result: string; } // a mod's own recipe type, like "farmersdelight:cooking" for its cooking pot. the engine only stores these, the mod's // server script reads them with ctx.recipes.list and checks the rest | ModRecipeJson; export interface ModRecipeJson { type: `${string}:${string}`; [field: string]: unknown; } // a recipe type a mod made up, as opposed to the engine's shaped, furnace, fuel and smithing export function is_mod_recipe(recipe: RecipeJson): recipe is ModRecipeJson { return recipe.type.includes(":"); } // the crafting grid's format, see server/game/crafting.ts export interface GridRecipe { width: number; height: number; pattern: (ItemChoice | undefined)[]; result: { id: string; count: number }; } // blocks export function block_to_json(block: BlockRegistry, has_item: boolean): BlockJson { const json: BlockJson = { id: block.id, textures: block.textures }; if (block.name !== undefined) json.name = block.name; if (block.model !== undefined) json.model = block.model; if (block.variants !== undefined) json.variants = block.variants; if (block.render_layer && block.render_layer !== "solid") json.render_layer = block.render_layer; if (block.cull_same !== undefined) json.cull_same = block.cull_same; if (block.tint !== undefined) json.tint = block.tint; if (block.light_emission !== undefined) json.light_emission = block.light_emission; if (block.light_opacity !== undefined) json.light_opacity = block.light_opacity; if (block.alpha !== undefined) json.alpha = block.alpha; if (!block.has_collision) json.collision = false; if (block.toughness !== undefined) { json.mining = { toughness: block.toughness }; if (block.tool_to_break !== undefined) json.mining.tool = block.tool_to_break; if (block.requires_tool) json.mining.requires_tool = true; } if (block.drop_table !== undefined) json.drops = block.drop_table; if (!has_item) json.item = false; if (block.interactive) json.interactive = true; if (block.replaceable) json.replaceable = true; if (block.place_on) json.place_on = block.place_on; if (block.place_in) json.place_in = block.place_in; if (block.states) json.states = block.states; if (block.components) json.components = block.components; return json; } export function block_from_json(json: BlockJson): { block: BlockRegistry; has_item: boolean } { const block: BlockRegistry = { id: json.id, textures: json.textures, has_collision: json.collision ?? true, }; if (json.name !== undefined) block.name = json.name; if (json.model !== undefined) block.model = json.model; if (json.variants !== undefined) block.variants = json.variants; const render_layer = json.render_layer ?? (json.transparent ? "translucent" : undefined); if (render_layer && render_layer !== "solid") block.render_layer = render_layer; if (json.cull_same !== undefined) block.cull_same = json.cull_same; if (json.tint !== undefined) block.tint = json.tint; if (json.light_emission !== undefined) block.light_emission = json.light_emission; if (json.light_opacity !== undefined) block.light_opacity = json.light_opacity; if (json.alpha !== undefined) block.alpha = json.alpha; if (json.mining) { block.toughness = json.mining.toughness; block.requires_tool = json.mining.requires_tool ?? false; if (json.mining.tool !== undefined) block.tool_to_break = json.mining.tool; } if (json.drops !== undefined) block.drop_table = json.drops; if (json.interactive) block.interactive = true; if (json.replaceable) block.replaceable = true; if (json.place_on) block.place_on = json.place_on; if (json.place_in) block.place_in = json.place_in; if (json.states) block.states = json.states; if (json.components) block.components = json.components; return { block, has_item: json.item ?? true }; } // items that aren't the item form of a block export function item_to_json(id: string, item: ItemRegistry): ItemJson { if (typeof item.texture_id !== "string") { throw new Error(`${id} picks its texture with a function, which json can't hold`); } const json: ItemJson = { id, texture: item.texture_id }; if (item.data_textures !== undefined) json.data_textures = item.data_textures; if (item.tool_type !== undefined) json.tool = item.tool_type; if (item.block_id !== undefined) json.places = item.block_id; if (item.max_stack !== undefined) json.max_stack = item.max_stack; if (item.food !== undefined) json.food = item.food; if (item.name !== undefined) json.name = item.name; if (item.lore !== undefined) json.lore = item.lore; if (item.components) json.components = item.components; return json; } export function item_from_json(json: ItemJson): ItemRegistry { const item: ItemRegistry = { texture_id: json.texture }; if (json.data_textures !== undefined) item.data_textures = json.data_textures; if (json.tool !== undefined) item.tool_type = json.tool; if (json.places !== undefined) item.block_id = json.places; if (json.max_stack !== undefined) item.max_stack = json.max_stack; if (json.food !== undefined) item.food = json.food; if (json.name !== undefined) item.name = json.name; if (json.lore !== undefined) item.lore = json.lore; if (json.components) item.components = json.components; return item; } // shaped recipes <-> the grid format export function grid_recipe_to_json(recipe: GridRecipe): RecipeJson { const key: Record = {}; // by the choice as json, so equal lists share a letter const letters = new Map(); for (const choice of recipe.pattern) { if (choice === undefined || letters.has(JSON.stringify(choice))) continue; const letter = pick_letter(choice_ids(choice)[0], new Set(letters.values())); letters.set(JSON.stringify(choice), letter); key[letter] = choice; } const pattern: string[] = []; for (let y = 0; y < recipe.height; y++) { let row = ""; for (let x = 0; x < recipe.width; x++) { const choice = recipe.pattern[y * recipe.width + x]; row += choice === undefined ? " " : letters.get(JSON.stringify(choice)); } pattern.push(row); } return { type: "shaped", pattern, key, result: recipe.result }; } export function grid_recipe_from_json(json: Extract): GridRecipe { const height = json.pattern.length; const width = Math.max(...json.pattern.map((row) => row.length)); const pattern: (ItemChoice | undefined)[] = []; for (const row of json.pattern) { for (let x = 0; x < width; x++) { const letter = row[x] ?? " "; pattern.push(letter === " " ? undefined : json.key[letter]); } } return { width, height, pattern, result: json.result }; } // a readable letter for an item in a pattern: its first letter if free, like P for planks function pick_letter(id: string, taken: Set) { const name = id.split(":")[1].toUpperCase(); for (const letter of [...name, ..."ABCDEFGHIJKLMNOPQRSTUVWXYZ"]) { if (/[A-Z]/.test(letter) && !taken.has(letter)) { return letter; } } throw new Error(`Ran out of letters for ${id}`); } // validation. every function returns a list of problems, empty when it's fine type Problems = string[]; export function validate_manifest(json: unknown, folder_name: string): Problems { const problems: Problems = []; if (!is_object(json)) return ["manifest.json must be an object"]; if (json.format_version !== FORMAT_VERSION) { problems.push(`format_version must be ${FORMAT_VERSION}`); } if (typeof json.id !== "string" || !NAMESPACE_PATTERN.test(json.id)) { problems.push("id must be 1-32 characters of a-z, 0-9 and _"); } else if (json.id !== folder_name) { problems.push(`id "${json.id}" must match the folder name "${folder_name}"`); } if (typeof json.name !== "string" || json.name.length === 0) problems.push("name is required"); if (typeof json.version !== "string" || !/^\d+\.\d+\.\d+/.test(json.version)) { problems.push("version must be semver, like 1.0.0"); } if (json.dependencies !== undefined) { if (!Array.isArray(json.dependencies)) { problems.push("dependencies must be a list"); } else { for (const dep of json.dependencies) { if (!is_object(dep) || typeof dep.id !== "string" || typeof dep.version !== "string") { problems.push("each dependency needs an id and a version range"); } } } } if (json.scripts !== undefined) { if (!is_object(json.scripts)) { problems.push("scripts must be an object"); } else { for (const [side, path] of Object.entries(json.scripts)) { if (!["server", "client", "worldgen"].includes(side)) problems.push(`unknown script "${side}"`); if (typeof path !== "string") problems.push(`scripts.${side} must be a path`); } } } return problems; } export function validate_block(json: unknown): Problems { if (!is_object(json)) return ["block must be an object"]; const problems = validate_id(json.id, "id"); if (json.model !== undefined) problems.push(...validate_id(json.model, "model")); const is_cube = json.model === undefined || json.model === "engine:cube"; const textures = json.textures; if (is_cube) { const texture_ok = typeof textures === "string" || (is_object(textures) && (["top", "bottom", "side"].every((k) => typeof textures[k] === "string") || ["front", "side"].every((k) => typeof textures[k] === "string"))); if (!texture_ok) problems.push("textures must be a texture id, { top, bottom, side } or { front, side }"); } else { problems.push(...validate_textures(textures, "textures")); } if (json.variants !== undefined) { if (!is_object(json.variants)) { problems.push('variants must map conditions like "age=3" to { model, textures, y }'); } else { const names = new Set(Array.isArray(json.states) ? json.states.map((s) => is_object(s) ? s.name : "") : []); for (const [condition, variant] of Object.entries(json.variants)) { const where = `variants["${condition}"]`; for (const part of condition === "" ? [] : condition.split(",")) { const [name, value] = part.split("=").map((p) => p.trim()); if (!names.has(name) || !/^\d+$/.test(value ?? "")) { problems.push(`${where}: "${part}" must be a state of this block and a number, like age=3`); } } if (!is_object(variant)) { problems.push(`${where} must be { model, textures, y }`); continue; } if (variant.model !== undefined) problems.push(...validate_id(variant.model, `${where}.model`)); if (variant.textures !== undefined) { problems.push(...validate_textures(variant.textures, `${where}.textures`)); } if (variant.y !== undefined && ![0, 90, 180, 270].includes(variant.y as number)) { problems.push(`${where}.y must be 0, 90, 180 or 270`); } } } } if (json.render_layer !== undefined && !RENDER_LAYERS.includes(json.render_layer as RenderLayer)) { problems.push(`render_layer must be one of ${RENDER_LAYERS.join(", ")}`); } for (const key of ["light_emission", "light_opacity"]) { const value = json[key]; if (value !== undefined && (!Number.isInteger(value) || (value as number) < 0 || (value as number) > 15)) { problems.push(`${key} must be a whole number from 0 to 15`); } } problems.push(...validate_text(json.name, "name")); for (const key of ["cull_same", "transparent", "collision", "item", "interactive", "replaceable"]) { if (json[key] !== undefined && typeof json[key] !== "boolean") problems.push(`${key} must be true or false`); } if (json.tint !== undefined) { const tint = json.tint; if (!is_object(tint) || !is_tint_color(tint.color)) { problems.push('tint.color must be "grass", "foliage" or a color like "#80a755"'); } else if ( tint.textures !== undefined && !(Array.isArray(tint.textures) && tint.textures.every((name) => typeof name === "string")) ) { problems.push('tint.textures must be a list of texture variables, like ["top"]'); } } if (json.alpha !== undefined && (typeof json.alpha !== "number" || json.alpha < 0 || json.alpha > 1)) { problems.push("alpha must be between 0 and 1"); } if (json.mining !== undefined) { if (!is_object(json.mining) || typeof json.mining.toughness !== "number" || json.mining.toughness < 0) { problems.push("mining.toughness must be a number of seconds"); } } if (json.drops !== undefined) problems.push(...validate_id(json.drops, "drops")); for (const key of ["place_on", "place_in"]) { const list = json[key]; if (list === undefined) continue; if (!Array.isArray(list) || list.length === 0) { problems.push(`${key} must be a list of block ids`); } else { for (const id of list) problems.push(...validate_id(id, key)); } } if (json.states !== undefined) { const states = json.states; if (!Array.isArray(states)) { problems.push("states must be a list"); } else { const bits = states.reduce((sum, s) => sum + (is_object(s) && typeof s.bits === "number" ? s.bits : 0), 0); if (bits > 16) problems.push(`states use ${bits} bits, the most is 16`); } } return problems; } export function validate_model(json: unknown): Problems { if (!is_object(json)) return ["model must be an object"]; const problems = validate_id(json.id, "id"); if (json.textures !== undefined) problems.push(...validate_textures(json.textures, "textures", true)); if (!Array.isArray(json.elements) || json.elements.length === 0) { problems.push("elements must be a list of boxes"); return problems; } json.elements.forEach((element, i) => { const where = `elements[${i}]`; if (!is_object(element)) { problems.push(`${where} must be { from, to, faces }`); return; } for (const key of ["from", "to"]) { const point = element[key]; if (!Array.isArray(point) || point.length !== 3 || !point.every((v) => typeof v === "number")) { problems.push(`${where}.${key} must be [x, y, z] in pixels`); } } const rotation = element.rotation; if (rotation !== undefined) { if ( !is_object(rotation) || !["x", "y", "z"].includes(rotation.axis as string) || ![-45, -22.5, 0, 22.5, 45].includes(rotation.angle as number) || !Array.isArray(rotation.origin) ) { problems.push( `${where}.rotation must be { origin, axis: x, y or z, angle: -45, -22.5, 0, 22.5 or 45 }`, ); } } if (element.shade !== undefined && typeof element.shade !== "boolean") { problems.push(`${where}.shade must be true or false`); } if (!is_object(element.faces)) { problems.push(`${where}.faces must map sides to { texture }`); return; } for (const [side, face] of Object.entries(element.faces)) { if (!MODEL_FACES.includes(side as ModelFace)) { problems.push(`${where}.faces: "${side}" isn't one of ${MODEL_FACES.join(", ")}`); } if (!is_object(face) || typeof face.texture !== "string") { problems.push(`${where}.faces.${side} needs a texture, like "#side"`); continue; } if (face.uv !== undefined && (!Array.isArray(face.uv) || face.uv.length !== 4)) { problems.push(`${where}.faces.${side}.uv must be [u1, v1, u2, v2] in pixels`); } if (face.rotation !== undefined && ![0, 90, 180, 270].includes(face.rotation as number)) { problems.push(`${where}.faces.${side}.rotation must be 0, 90, 180 or 270`); } if (face.cullface !== undefined && !MODEL_FACES.includes(face.cullface as ModelFace)) { problems.push(`${where}.faces.${side}.cullface isn't one of ${MODEL_FACES.join(", ")}`); } } }); return problems; } // a texture id, or texture variables mapped to ids. a model's own defaults may also point at variables ("#side") function validate_textures(value: unknown, field: string, allow_variables = false): Problems { if (typeof value === "string") return validate_id(value, field); if (!is_object(value)) return [`${field} must be a texture id or { variable: texture id }`]; return Object.entries(value).flatMap(([name, id]) => allow_variables && typeof id === "string" && id.startsWith("#") ? [] : validate_id(id, `${field}.${name}`) ); } export function validate_item(json: unknown): Problems { if (!is_object(json)) return ["item must be an object"]; const problems = validate_id(json.id, "id"); problems.push(...validate_id(json.texture, "texture")); if (json.data_textures !== undefined) { if (!is_object(json.data_textures)) problems.push("data_textures must be { data key: texture id }"); else { for (const [key, id] of Object.entries(json.data_textures)) { problems.push(...validate_id(id, `data_textures.${key}`)); } } } if (json.places !== undefined) problems.push(...validate_id(json.places, "places")); problems.push(...validate_text(json.name, "name"), ...validate_text(json.lore, "lore")); if (json.max_stack !== undefined && (!Number.isInteger(json.max_stack) || (json.max_stack as number) < 1)) { problems.push("max_stack must be a positive whole number"); } if (json.food !== undefined) { const food = json.food; if ( !is_object(food) || !Number.isInteger(food.nutrition) || (food.nutrition as number) < 0 || typeof food.saturation_modifier !== "number" || food.saturation_modifier < 0 ) { problems.push("food must be { nutrition, saturation_modifier }, nutrition a whole number"); } else { if (food.always_edible !== undefined && typeof food.always_edible !== "boolean") { problems.push("food.always_edible must be true or false"); } if (food.returns !== undefined) problems.push(...validate_id(food.returns, "food.returns")); } } return problems; } export function validate_recipe(json: unknown): Problems { if (!is_object(json)) return ["recipe must be an object"]; const problems: Problems = []; switch (json.type) { case "shaped": { const pattern = json.pattern; if ( !Array.isArray(pattern) || pattern.length < 1 || pattern.length > 3 || !pattern.every((row) => typeof row === "string" && row.length >= 1 && row.length <= 3) ) { problems.push("pattern must be 1-3 rows of 1-3 characters"); } else if (is_object(json.key)) { for (const letter of pattern.join("").replaceAll(" ", "")) { if (!(letter in json.key)) problems.push(`pattern uses "${letter}" but key doesn't define it`); } } if (!is_object(json.key)) { problems.push("key must map letters to item ids, or lists of them"); } else { for (const choice of Object.values(json.key)) problems.push(...validate_choice(choice, "key")); } problems.push(...validate_stack(json.result, "result")); break; } case "furnace": problems.push(...validate_choice(json.input, "input"), ...validate_stack(json.output, "output")); if (!Number.isInteger(json.cook_time) || (json.cook_time as number) < 1) { problems.push("cook_time must be a positive number of ticks"); } break; case "fuel": problems.push(...validate_choice(json.item, "item")); if (!Number.isInteger(json.burn_time) || (json.burn_time as number) < 1) { problems.push("burn_time must be a positive number of ticks"); } break; case "smithing": problems.push( ...validate_id(json.tool, "tool"), ...validate_stack(json.material, "material"), ...validate_id(json.result, "result"), ); if (json.addition !== undefined) problems.push(...validate_id(json.addition, "addition")); break; default: if (typeof json.type !== "string" || !json.type.includes(":")) { problems.push( 'type must be "shaped", "furnace", "fuel", "smithing" or a mod\'s own type like "farmersdelight:cooking"', ); } else { problems.push(...validate_id(json.type, "type")); } } return problems; } export function validate_ore(json: unknown): Problems { if (!is_object(json)) return ["ore must be an object"]; const problems = [...validate_id(json.id, "id"), ...validate_id(json.replaces, "replaces")]; for (const key of ["min_y", "max_y", "scale", "threshold"]) { if (typeof json[key] !== "number") problems.push(`${key} must be a number`); } if (typeof json.min_y === "number" && typeof json.max_y === "number" && json.min_y > json.max_y) { problems.push("min_y must not be above max_y"); } return problems; } // an item id, or a list of them any of which fits function validate_choice(value: unknown, field: string): Problems { if (!Array.isArray(value)) return validate_id(value, field); if (value.length === 0) return [`${field} must list at least one item`]; return value.flatMap((id) => validate_id(id, field)); } // optional text players see function validate_text(value: unknown, field: string): Problems { return value === undefined || (typeof value === "string" && value.length > 0) ? [] : [`${field} must be text`]; } function validate_id(value: unknown, field: string): Problems { return typeof value === "string" && ID_PATTERN.test(value) ? [] : [`${field} must be an id like "my_mod:thing"`]; } function validate_stack(value: unknown, field: string): Problems { if (!is_object(value)) return [`${field} must be { id, count }`]; const problems = validate_id(value.id, `${field}.id`); if (!Number.isInteger(value.count) || (value.count as number) < 1) { problems.push(`${field}.count must be a positive whole number`); } return problems; } function is_object(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); }