// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // the json formats from docs/modding/, 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, LIQUID_DEFAULTS, LIQUID_LEVEL, type LiquidProperties, MAX_LIQUID_RANGE, RENDER_LAYERS, type RenderLayer, type ToolProperties, WATERLOGGED, type WornProperties, } from "./everything_registry.ts"; import { type BlockPart, type BlockVariant, MODEL_FACES, type ModelFace } from "./block_models.ts"; import { expand_items, list_matches } from "./tags.ts"; import { GAME_VERSION } from "./constants.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"]; // a tag's id may have folders, like c:ingots/iron. see docs/modding/resources/tags.md export const TAG_ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+(\/[a-z0-9_]+)*$/; // the namespace for tags every mod shares, like neoforge's. no mod owns it export const SHARED_TAG_NAMESPACE = "c"; export const TAG_REGISTRIES = ["blocks", "items", "entities", "biomes"] as const; export type TagRegistry = typeof TAG_REGISTRIES[number]; type BlockTextures = BlockRegistry["textures"]; export interface ManifestJson { format_version: number; id: string; name: string; description?: string; version: string; authors?: string[]; game_version?: string; // imports bworld/engine to reach into the engine and hook its methods. needs game_version within one minor version engine_access?: boolean; dependencies?: { id: string; version: string }[]; scripts?: { server?: string; client?: string; worldgen?: string; shared?: 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; shape?: number[][]; collision_shape?: number[][]; parts?: BlockPart[]; item_model?: string; mining?: { toughness: number; tool?: string; requires_tool?: boolean; tier?: number }; drops?: string; item?: boolean; interactive?: boolean; replaceable?: boolean; place_on?: string[]; place_in?: string[]; states?: BlockStateDefinition[]; components?: Record; item_display?: { surface: number }; // makes it a liquid, see LiquidProperties. range is 7 when not set liquid?: Partial; // what it drops when broken, see common/loot.ts. drops is the shorthand for one of an item loot_table?: string; // the liquid it can hold, see BlockRegistry.waterloggable waterloggable?: string; // only placed into a source of it, see BlockRegistry.waterlogged_only waterlogged_only?: boolean; } export interface OreJson { id: string; replaces: string; min_y: number; max_y: number; scale: number; threshold: number; } // mobs that spawn on their own, like neoforge's add_spawns biome modifier and undergarden's biome spawners. only // monsters for now: in the dark near players, like minecraft's NaturalSpawner export interface SpawnJson { entity: string; // how often it's picked over the other spawns where both can spawn weight: number; // how many spawn together min_count: number; max_count: number; // only in these biomes, every biome when not set biomes?: string[]; // the chance each spawn that passed every other check goes ahead, like undergarden's 1 in 10 for its rotspawn. 1 // when not set chance?: number; } export interface ItemJson { id: string; // without one it isn't a new item, it fills in the item of the mod's block with this id, see add_to_block_item texture?: string; // data key -> texture, see ItemRegistry.data_textures data_textures?: Record; // tier and speed default to 0 and 2 tool?: Omit & Partial; places?: string; max_stack?: number; base_sell_value?: number; food?: FoodProperties; // how it looks worn on a player worn?: WornProperties; // see ItemRegistry.targets_liquids targets_liquids?: boolean; name?: string; lore?: string; components?: Record; } // a kind of entity, drawn with an entity model and one texture, or without a model as its texture facing the camera export interface EntityJson { id: string; // an entity model, see EntityModelJson model?: string; texture: string; // "animal" (the default) wanders around, panics when hurt and looks at players. "monster" goes after players it // sees and whoever hurts it, and despawns far from players, like minecraft's zombies. "scripted" stays where // scripts put it: no gravity, ai or health, and it isn't saved with the world, like the fishing hook behavior?: "animal" | "monster" | "scripted"; // its collision box in blocks, width is for both x and z width: number; height: number; max_health?: number; // minecraft's per tick speed, 0.25 for most animals movement_speed?: number; // what its hits do, for monsters. 2 when not set, like minecraft's attack_damage?: number; // protection from physical and from arcane damage, not used yet physical_shielding?: number; arcane_shielding?: number; // what it drops when it dies, see common/loot.ts loot_table?: string; } // a status effect, like neoforge's MobEffect. what it does over time comes from components scripts register, see // docs/modding/entities/effects.md export interface EffectJson { id: string; // like minecraft's MobEffectCategory, "neutral" when not set category?: EffectCategory; // happens once when added instead of lasting, like instant health. its components' on_tick runs once instant?: boolean; // a texture, shown at the top of the inventory screen while the player has it icon?: string; // attribute modifiers while it's on, for level 1. each level adds that much again, like minecraft's speed modifiers?: { attribute: string; amount: number; operation: EffectModifierOperation }[]; components?: Record; } export type EffectCategory = "beneficial" | "harmful" | "neutral"; export type EffectModifierOperation = "add_value" | "add_multiplied_base" | "add_multiplied_total"; type Vec3 = [number, number, number]; // a bedrock entity model (models/.geo.json) with only what the engine uses. positions and sizes are in // texture pixels, 16 to a block, and the model faces -z with its feet at 0 export interface EntityModelJson { id: string; // the size its uvs are laid out for, the texture is stretched to it texture_width: number; texture_height: number; // parents come before their children bones: EntityBoneJson[]; } export interface EntityBoneJson { name: string; parent?: string; // what it turns around pivot: Vec3; // degrees around x, y then z rotation?: Vec3; cubes: EntityCubeJson[]; } // a box from origin to origin + size, textured like minecraft's box uv: see the renderer's FACES export interface EntityCubeJson { origin: Vec3; size: Vec3; uv: [number, number]; // grows the box this many pixels each way without moving its texture inflate?: number; } // something in a tag file's values or remove: an id, a "#tag", or either with whether it must exist. a plain one must export type TagEntryJson = string | { id: string; required?: boolean }; // a tag file, tags///.json, with the registry and id its path gives it. like neoforge's, // every mod's file for the same tag is merged, in load order export interface TagJson { registry: TagRegistry; id: string; values: TagEntryJson[]; // drops what mods before this one put in the tag replace?: boolean; // takes these out again, if they're in it remove?: TagEntryJson[]; } // an item a recipe takes: its id, a "#tag" of items, or a list of those any of which fits, like every kind of planks export type ItemChoice = string | string[]; // the ids and #tags a choice lists, without looking inside the tags export function choice_list(choice: ItemChoice): string[] { return typeof choice === "string" ? [choice] : choice; } // every item that fits a choice, with its tags' items, once each. the tags must be loaded export function choice_ids(choice: ItemChoice): string[] { return expand_items(choice_list(choice)); } export function choice_matches(choice: ItemChoice, id: string): boolean { return list_matches("items", choice_list(choice), id); } 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; // liquids are without collision and replaceable unless they say otherwise if (block.has_collision === !!block.liquid) json.collision = block.has_collision; if (block.shape !== undefined) json.shape = block.shape; if (block.collision_shape !== undefined) json.collision_shape = block.collision_shape; if (block.parts !== undefined) json.parts = block.parts; if (block.item_model !== undefined) json.item_model = block.item_model; 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.tool_tier) json.mining.tier = block.tool_tier; } if (block.drop_table !== undefined) json.drops = block.drop_table; if (block.loot_table !== undefined) json.loot_table = block.loot_table; if (!has_item) json.item = false; if (block.interactive) json.interactive = true; if (!!block.replaceable !== !!block.liquid) json.replaceable = !!block.replaceable; if (block.place_on) json.place_on = block.place_on; if (block.place_in) json.place_in = block.place_in; // a liquid's level state and a waterloggable block's waterlogged state are its own, added when it loads const added = block.liquid || block.waterloggable; const states = added ? block.states?.slice(0, -1) : block.states; if (states && (states.length > 0 || !added)) json.states = states; if (block.waterloggable) json.waterloggable = block.waterloggable; if (block.waterlogged_only) json.waterlogged_only = true; if (block.components) json.components = block.components; if (block.item_display) json.item_display = block.item_display; if (block.liquid) { // only what isn't the default const liquid = block.liquid; json.liquid = Object.fromEntries( Object.entries(liquid).filter(([key, value]) => LIQUID_DEFAULTS[key as keyof LiquidProperties] !== value), ); } 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 ?? !json.liquid, }; if (json.name !== undefined) block.name = json.name; if (json.model !== undefined) block.model = json.model; if (json.variants !== undefined) block.variants = json.variants; if (json.shape !== undefined) block.shape = json.shape; if (json.collision_shape !== undefined) block.collision_shape = json.collision_shape; if (json.parts !== undefined) block.parts = json.parts; if (json.item_model !== undefined) block.item_model = json.item_model; 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.mining.tier) block.tool_tier = json.mining.tier; } if (json.drops !== undefined) block.drop_table = json.drops; if (json.loot_table !== undefined) block.loot_table = json.loot_table; if (json.interactive) block.interactive = true; if (json.replaceable ?? json.liquid) 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; if (json.item_display) block.item_display = json.item_display; if (json.liquid) { block.liquid = { ...LIQUID_DEFAULTS, ...json.liquid }; // last, so the block's own states keep their bits block.states = [...block.states ?? [], { ...LIQUID_LEVEL }]; } if (json.waterlogged_only) block.waterlogged_only = true; if (json.waterloggable) { block.waterloggable = json.waterloggable; // last too, see WATERLOGGED block.states = [...block.states ?? [], { ...WATERLOGGED }]; } 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 !== undefined) json.tool = item.tool; if (item.block_id !== undefined) json.places = item.block_id; if (item.max_stack !== undefined) json.max_stack = item.max_stack; if (item.base_sell_value !== undefined) json.base_sell_value = item.base_sell_value; if (item.food !== undefined) json.food = item.food; if (item.worn !== undefined) json.worn = item.worn; if (item.targets_liquids !== undefined) json.targets_liquids = item.targets_liquids; 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 { if (json.texture === undefined) throw new Error(`${json.id} has no texture and isn't a block's item`); return { texture_id: json.texture, ...item_fields(json) }; } // an item json without a texture: what it sets replaces what the block's item has, the rest stays export function add_to_block_item(json: ItemJson, item: ItemRegistry) { Object.assign(item, item_fields(json)); } // everything but the texture function item_fields(json: ItemJson): Partial { const item: Partial = {}; if (json.data_textures !== undefined) item.data_textures = json.data_textures; if (json.tool !== undefined) item.tool = { tier: 0, speed: 2, ...json.tool }; if (json.places !== undefined) item.block_id = json.places; if (json.max_stack !== undefined) item.max_stack = json.max_stack; if (json.base_sell_value !== undefined) item.base_sell_value = json.base_sell_value; if (json.food !== undefined) item.food = json.food; if (json.worn !== undefined) item.worn = json.worn; if (json.targets_liquids !== undefined) item.targets_liquids = json.targets_liquids; 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_list(choice)[0].replace("#", ""), 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].split("/").at(-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.engine_access !== undefined && typeof json.engine_access !== "boolean") { problems.push("engine_access must be true or false"); } if (json.engine_access === true) { const problem = engine_version_problem(json.game_version); if (problem) problems.push(problem); } 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", "shared"].includes(side)) { problems.push(`unknown script "${side}"`); } if (typeof path !== "string") problems.push(`scripts.${side} must be a path`); } } } return problems; } // engine access isn't a stable api: a mod using it names one minor version of the game, like "~0.4.0" or "0.4.2", and // loading it on another is an error. game is the version it's loading on export function engine_version_problem(range: unknown, game = GAME_VERSION): string | undefined { const [major, minor, patch] = game.split(".").map(Number); const match = typeof range === "string" ? range.match(/^(~?)(\d+)\.(\d+)\.(\d+)$/) : null; if (!match) { return `engine_access needs game_version to be one minor version, like "~${major}.${minor}.0"`; } const [, tilde, m, n, p] = match; const fits = Number(m) === major && Number(n) === minor && (tilde ? Number(p) <= patch : Number(p) === patch); if (!fits) return `uses engine_access for game_version ${range}, this is the game's ${game}`; } 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.parts === undefined && (json.model === undefined || json.model === "engine:cube"); const textures = json.textures; if (json.liquid !== undefined) { problems.push(...validate_liquid(json)); } else 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, shape }`); 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`)); } for (const axis of ["x", "y"]) { if (variant[axis] !== undefined && ![0, 90, 180, 270].includes(variant[axis] as number)) { problems.push(`${where}.${axis} must be 0, 90, 180 or 270`); } } if (variant.shape !== undefined) problems.push(...validate_shape(variant.shape, `${where}.shape`)); if (variant.collision_shape !== undefined) { problems.push(...validate_shape(variant.collision_shape, `${where}.collision_shape`, 24)); } } } } if (json.shape !== undefined) problems.push(...validate_shape(json.shape, "shape")); if (json.collision_shape !== undefined) { problems.push(...validate_shape(json.collision_shape, "collision_shape", 24)); } if (json.item_model !== undefined) problems.push(...validate_id(json.item_model, "item_model")); if (json.parts !== undefined) { if (!Array.isArray(json.parts) || json.parts.length === 0) { problems.push("parts must be a list of { when, model, y }"); } else { const names = new Set(Array.isArray(json.states) ? json.states.map((s) => is_object(s) ? s.name : "") : []); json.parts.forEach((part, i) => { const where = `parts[${i}]`; if (!is_object(part)) { problems.push(`${where} must be { when, model, y }`); return; } problems.push(...validate_id(part.model, `${where}.model`)); if (part.when !== undefined) { const parts = typeof part.when === "string" ? part.when.split(",") : [undefined]; for (const condition of part.when === "" ? [] : parts) { const [name, value] = (condition ?? "").split("=").map((p) => p.trim()); if (!names.has(name) || !/^\d+$/.test(value ?? "")) { problems.push( `${where}.when: "${condition}" must be a state of this block and a number, like north=1`, ); } } } if (part.textures !== undefined) { problems.push(...validate_textures(part.textures, `${where}.textures`)); } for (const axis of ["x", "y"]) { if (part[axis] !== undefined && ![0, 90, 180, 270].includes(part[axis] as number)) { problems.push(`${where}.${axis} must be 0, 90, 180 or 270`); } } if (part.shape !== undefined) problems.push(...validate_shape(part.shape, `${where}.shape`)); if (part.collision_shape !== undefined) { problems.push(...validate_shape(part.collision_shape, `${where}.collision_shape`, 24)); } }); } } 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", "water" 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"); } else if (json.mining.tier !== undefined && !is_whole(json.mining.tier)) { problems.push("mining.tier must be a whole number of 0 or more"); } } if (json.drops !== undefined) problems.push(...validate_id(json.drops, "drops")); if (json.loot_table !== undefined) { if (!(typeof json.loot_table === "string" && TAG_ID_PATTERN.test(json.loot_table))) { problems.push('loot_table must be a loot table id, like "my_mod:blocks/thing"'); } if (json.drops !== undefined) problems.push("drops and loot_table can't both be set, drops is one item"); } if (json.item_display !== undefined) { const surface = is_object(json.item_display) ? json.item_display.surface : undefined; if (typeof surface !== "number" || surface < 0 || surface > 16) { problems.push("item_display.surface must be the height in pixels items lie on, from 0 to 16"); } } 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 or #tags`); } else { for (const id of list) problems.push(...validate_id_or_tag(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`); if (json.waterloggable !== undefined && bits + WATERLOGGED.bits > 16) { problems.push(`its states and waterlogged use more than 16 bits`); } } } if (json.waterloggable !== undefined) { problems.push(...validate_id(json.waterloggable, "waterloggable")); if (json.liquid !== undefined) problems.push("a liquid can't be waterloggable"); const states = Array.isArray(json.states) ? json.states : []; if (states.some((state) => is_object(state) && state.name === WATERLOGGED.name)) { problems.push(`a waterloggable block gets a "${WATERLOGGED.name}" state of its own`); } } if (json.waterlogged_only !== undefined) { if (typeof json.waterlogged_only !== "boolean") problems.push("waterlogged_only must be true or false"); else if (json.waterlogged_only && json.waterloggable === undefined) { problems.push("waterlogged_only needs waterloggable, the liquid it's placed into"); } } return problems; } // a liquid is drawn by the engine, so it has no model of its own, and its level is a state it gets function validate_liquid(json: Record): Problems { const problems: Problems = []; const liquid = json.liquid; if (!is_object(liquid)) return ["liquid must be { range, ticks, renewable }, or {}"]; for (const key of Object.keys(liquid)) { if (!(key in LIQUID_DEFAULTS)) problems.push(`liquid.${key} isn't a liquid property`); } if (liquid.ticks !== undefined && (!Number.isInteger(liquid.ticks) || (liquid.ticks as number) < 1)) { problems.push("liquid.ticks must be a whole number of 1 or more"); } if (liquid.renewable !== undefined && typeof liquid.renewable !== "boolean") { problems.push("liquid.renewable must be true or false"); } const range = liquid.range; if ( range !== undefined && (!Number.isInteger(range) || (range as number) < 1 || (range as number) > MAX_LIQUID_RANGE) ) { problems.push(`liquid.range must be a whole number from 1 to ${MAX_LIQUID_RANGE}`); } const textures = json.textures; const texture_ok = typeof textures === "string" || (is_object(textures) && typeof textures.still === "string" && (textures.flowing === undefined || typeof textures.flowing === "string") && Object.keys(textures).every((key) => key === "still" || key === "flowing")); if (!texture_ok) problems.push("a liquid's textures must be a texture id or { still, flowing }"); for (const key of ["model", "variants", "parts", "shape", "collision_shape", "item_model"]) { if (json[key] !== undefined) problems.push(`a liquid can't have ${key}, the engine draws it`); } const states = Array.isArray(json.states) ? json.states : []; if (states.some((state) => is_object(state) && state.name === LIQUID_LEVEL.name)) { problems.push(`a liquid gets a "${LIQUID_LEVEL.name}" state of its own`); } const bits = states.reduce((sum, s) => sum + (is_object(s) && typeof s.bits === "number" ? s.bits : 0), 0); if (bits + LIQUID_LEVEL.bits > 16) problems.push(`its states and its level use more than 16 bits`); return problems; } // boxes in pixels: [[x1, y1, z1, x2, y2, z2], ...], each corner from 0 to 16 (y to top) and the second past the first function validate_shape(shape: unknown, where: string, top = 16): Problems { const is_box = (box: unknown) => Array.isArray(box) && box.length === 6 && box.every((v, i) => typeof v === "number" && v >= 0 && v <= (i % 3 === 1 ? top : 16)) && box[0] <= box[3] && box[1] <= box[4] && box[2] <= box[5]; if (!Array.isArray(shape) || shape.length === 0 || !shape.every(is_box)) { const most = top === 16 ? "" : `, up to ${top} high`; return [`${where} must be a list of boxes in pixels${most}, like [[0, 0, 0, 16, 8, 16]]`]; } return []; } 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.parent !== undefined) problems.push(...validate_id(json.parent, "parent")); if (json.textures !== undefined) problems.push(...validate_textures(json.textures, "textures", true)); // a model can leave its elements to its parent, or be one that only gives texture defaults to its children if (json.elements === undefined) { if (json.parent === undefined && json.textures === undefined) { problems.push("a model needs elements, a parent, or textures for models that use it as theirs"); } return problems; } if (!Array.isArray(json.elements)) { 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) || typeof rotation.angle !== "number" || Math.abs(rotation.angle) > 180 || !Array.isArray(rotation.origin) ) { problems.push( `${where}.rotation must be { origin, axis: x, y or z, angle: degrees from -180 to 180 }`, ); } } 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}`) ); } function is_whole(value: unknown): value is number { return Number.isInteger(value) && (value as number) >= 0; } export function validate_item(json: unknown): Problems { if (!is_object(json)) return ["item must be an object"]; const problems = validate_id(json.id, "id"); if (json.texture !== undefined) 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.base_sell_value !== undefined && !is_whole(json.base_sell_value)) { problems.push("base_sell_value must be a whole number of 0 or more"); } if (json.targets_liquids !== undefined && typeof json.targets_liquids !== "boolean") { problems.push("targets_liquids must be true or false"); } if (json.tool !== undefined) { const tool = json.tool; if (!is_object(tool) || typeof tool.type !== "string") { problems.push('tool must be { type, durability }, like "pickaxe"'); } else { if (!is_whole(tool.durability) || tool.durability < 1) { problems.push("tool.durability must be a positive whole number"); } if (tool.tier !== undefined && !is_whole(tool.tier)) { problems.push("tool.tier must be a whole number of 0 or more"); } if (tool.speed !== undefined && (typeof tool.speed !== "number" || tool.speed <= 0)) { problems.push("tool.speed must be a positive 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")); } } if (json.worn !== undefined) { const worn = json.worn; if (!is_object(worn)) { problems.push("worn must be { model, texture }, an entity model and a texture"); } else { problems.push(...validate_id(worn.model, "worn.model"), ...validate_id(worn.texture, "worn.texture")); for (const field of ["slim_model", "slim_texture"]) { if (worn[field] !== undefined) problems.push(...validate_id(worn[field], `worn.${field}`)); } for (const field of Object.keys(worn)) { if (!["model", "texture", "slim_model", "slim_texture"].includes(field)) { problems.push(`worn.${field} isn't a field of worn`); } } } } 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; } export function validate_spawn(json: unknown): Problems { if (!is_object(json)) return ["spawn must be an object"]; const problems = validate_id(json.entity, "entity"); for (const key of ["weight", "min_count", "max_count"]) { if (!Number.isInteger(json[key]) || (json[key] as number) < (key === "weight" ? 0 : 1)) { problems.push( key === "weight" ? "weight must be a whole number, 0 or more" : `${key} must be a whole number, 1 or more`, ); } } if (typeof json.min_count === "number" && typeof json.max_count === "number" && json.min_count > json.max_count) { problems.push("min_count must not be above max_count"); } if (json.biomes !== undefined) { if (!Array.isArray(json.biomes)) problems.push("biomes must be a list of biome ids"); else json.biomes.forEach((biome, i) => problems.push(...validate_id(biome, `biomes[${i}]`))); } if (json.chance !== undefined && (typeof json.chance !== "number" || !(json.chance > 0 && json.chance <= 1))) { problems.push("chance must be a number above 0, at most 1"); } return problems; } export function validate_entity(json: unknown): Problems { if (!is_object(json)) return ["entity must be an object"]; const problems = [ ...validate_id(json.id, "id"), ...(json.model === undefined ? [] : validate_id(json.model, "model")), ...validate_id(json.texture, "texture"), ]; if (json.behavior !== undefined && !["animal", "monster", "scripted"].includes(json.behavior as string)) { problems.push('behavior must be "animal", "monster" or "scripted"'); } if ( json.loot_table !== undefined && !(typeof json.loot_table === "string" && TAG_ID_PATTERN.test(json.loot_table)) ) { problems.push('loot_table must be a loot table id, like "my_mod:entities/thing"'); } for (const key of ["width", "height"]) { if (typeof json[key] !== "number" || json[key] <= 0 || json[key] > 16) { problems.push(`${key} must be a number of blocks above 0, at most 16`); } } for (const key of ["max_health", "movement_speed", "attack_damage", "physical_shielding", "arcane_shielding"]) { if (json[key] !== undefined && (typeof json[key] !== "number" || json[key] < 0)) { problems.push(`${key} must be a number, 0 or more`); } } return problems; } export function validate_effect(json: unknown): Problems { if (!is_object(json)) return ["effect must be an object"]; const problems = validate_id(json.id, "id"); if (json.category !== undefined && !["beneficial", "harmful", "neutral"].includes(json.category as string)) { problems.push('category must be "beneficial", "harmful" or "neutral"'); } if (json.instant !== undefined && typeof json.instant !== "boolean") problems.push("instant must be true or false"); if (json.icon !== undefined) problems.push(...validate_id(json.icon, "icon")); if (json.modifiers !== undefined) { if (!Array.isArray(json.modifiers)) { problems.push("modifiers must be a list"); } else { json.modifiers.forEach((modifier, i) => { const field = `modifiers[${i}]`; if (!is_object(modifier)) { problems.push(`${field} must be { attribute, amount, operation }`); return; } problems.push(...validate_id(modifier.attribute, `${field}.attribute`)); if (typeof modifier.amount !== "number" || !Number.isFinite(modifier.amount)) { problems.push(`${field}.amount must be a number`); } if ( !["add_value", "add_multiplied_base", "add_multiplied_total"].includes(modifier.operation as string) ) { problems.push( `${field}.operation must be "add_value", "add_multiplied_base" or "add_multiplied_total"`, ); } }); } } if (json.components !== undefined && !is_object(json.components)) problems.push("components must be an object"); return problems; } export function validate_entity_model(json: unknown): Problems { if (!is_object(json)) return ["entity model must be an object"]; const problems = validate_id(json.id, "id"); for (const key of ["texture_width", "texture_height"]) { if (!Number.isInteger(json[key]) || (json[key] as number) < 1) problems.push(`${key} must be a whole number`); } if (!Array.isArray(json.bones)) return [...problems, "bones must be a list"]; const names = new Set(); json.bones.forEach((bone, i) => { const field = `bones[${i}]`; if (!is_object(bone) || typeof bone.name !== "string") { problems.push(`${field} must be { name, pivot, cubes }`); return; } if (names.has(bone.name)) problems.push(`${field}: there are two bones named ${bone.name}`); if (bone.parent !== undefined && !names.has(bone.parent as string)) { problems.push(`${field}: parent ${bone.parent} must be a bone before it`); } names.add(bone.name); problems.push(...validate_vec3(bone.pivot, `${field}.pivot`)); if (bone.rotation !== undefined) problems.push(...validate_vec3(bone.rotation, `${field}.rotation`)); if (!Array.isArray(bone.cubes)) { problems.push(`${field}.cubes must be a list`); return; } bone.cubes.forEach((cube, j) => { const cube_field = `${field}.cubes[${j}]`; if (!is_object(cube)) { problems.push(`${cube_field} must be { origin, size, uv }`); return; } problems.push(...validate_vec3(cube.origin, `${cube_field}.origin`)); problems.push(...validate_vec3(cube.size, `${cube_field}.size`)); if (!Array.isArray(cube.uv) || cube.uv.length !== 2 || !cube.uv.every((n) => typeof n === "number")) { problems.push(`${cube_field}.uv must be [u, v], per face uvs aren't supported`); } if (cube.inflate !== undefined && typeof cube.inflate !== "number") { problems.push(`${cube_field}.inflate must be a number`); } }); }); return problems; } // a models/.geo.json, as blockbench exports it for bedrock, to an EntityModelJson. its first geometry is used export function entity_model_from_geo(json: unknown, id: string): { model?: EntityModelJson; problems: Problems } { const geometry = is_object(json) && Array.isArray(json["minecraft:geometry"]) ? json["minecraft:geometry"][0] : undefined; if (!is_object(geometry) || !is_object(geometry.description)) { return { problems: ['must be a bedrock model: { "minecraft:geometry": [{ "description": ..., "bones": [...] }] }'], }; } const bones = Array.isArray(geometry.bones) ? geometry.bones : []; const model = { id, texture_width: geometry.description.texture_width, texture_height: geometry.description.texture_height, bones: bones.map((bone) => { if (!is_object(bone)) return bone; const { name, parent, pivot, rotation } = bone; const cubes = Array.isArray(bone.cubes) ? bone.cubes : []; return { name, ...(parent === undefined ? {} : { parent }), pivot: pivot ?? [0, 0, 0], ...(rotation === undefined ? {} : { rotation }), cubes: cubes.map((cube) => { if (!is_object(cube)) return cube; const { origin, size, uv, inflate } = cube; return { origin, size, uv, ...(inflate === undefined ? {} : { inflate }) }; }), }; }), }; const problems = validate_entity_model(model); return problems.length === 0 ? { model: model as EntityModelJson, problems } : { problems }; } function validate_vec3(value: unknown, field: string): Problems { return Array.isArray(value) && value.length === 3 && value.every((n) => typeof n === "number") ? [] : [`${field} must be [x, y, z]`]; } // an item id or #tag, or a list of them any of which fits function validate_choice(value: unknown, field: string): Problems { if (!Array.isArray(value)) return validate_id_or_tag(value, field); if (value.length === 0) return [`${field} must list at least one item`]; return value.flatMap((id) => validate_id_or_tag(id, field)); } function validate_id_or_tag(value: unknown, field: string): Problems { if (typeof value === "string" && value.startsWith("#")) { return TAG_ID_PATTERN.test(value.slice(1)) ? [] : [`${field} must be a tag like "#my_mod:things"`]; } return validate_id(value, field); } // a tag file's contents, with the registry and id its path gives it export function validate_tag(json: unknown): Problems { if (!is_object(json)) return ["tag must be an object"]; const problems: Problems = []; if (!TAG_REGISTRIES.includes(json.registry as TagRegistry)) { problems.push(`registry must be one of ${TAG_REGISTRIES.join(", ")}`); } if (typeof json.id !== "string" || !TAG_ID_PATTERN.test(json.id)) { problems.push('id must be a tag id like "my_mod:things" or "c:ingots/iron"'); } if (json.replace !== undefined && typeof json.replace !== "boolean") problems.push("replace must be true or false"); for (const key of ["values", "remove"]) { const list = json[key]; if (list === undefined && key === "remove") continue; if (!Array.isArray(list)) { problems.push(`${key} must be a list of ids and #tags`); continue; } for (const entry of list) { if (is_object(entry)) { problems.push(...validate_id_or_tag(entry.id, `${key}[].id`)); if (entry.required !== undefined && typeof entry.required !== "boolean") { problems.push(`${key}[].required must be true or false`); } } else { problems.push(...validate_id_or_tag(entry, key)); } } } return problems; } // 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); }