996 lines
39 KiB
TypeScript
996 lines
39 KiB
TypeScript
// 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,
|
|
RENDER_LAYERS,
|
|
type RenderLayer,
|
|
type ToolProperties,
|
|
type WornProperties,
|
|
} from "./everything_registry.ts";
|
|
import { type BlockVariant, MODEL_FACES, type ModelFace } from "./block_models.ts";
|
|
import { expand_items, list_matches } from "./tags.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"] 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;
|
|
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<string, BlockVariant>;
|
|
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; tier?: number };
|
|
drops?: string;
|
|
item?: boolean;
|
|
interactive?: boolean;
|
|
replaceable?: boolean;
|
|
place_on?: string[];
|
|
place_in?: string[];
|
|
states?: BlockStateDefinition[];
|
|
components?: Record<string, unknown>;
|
|
item_display?: { surface: number };
|
|
}
|
|
|
|
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;
|
|
texture: string;
|
|
// data key -> texture, see ItemRegistry.data_textures
|
|
data_textures?: Record<string, string>;
|
|
// tier and speed default to 0 and 2
|
|
tool?: Omit<ToolProperties, "tier" | "speed"> & Partial<ToolProperties>;
|
|
places?: string;
|
|
max_stack?: number;
|
|
food?: FoodProperties;
|
|
// how it looks worn on a player
|
|
worn?: WornProperties;
|
|
name?: string;
|
|
lore?: string;
|
|
components?: Record<string, unknown>;
|
|
}
|
|
|
|
// 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;
|
|
}
|
|
|
|
// 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<string, unknown>;
|
|
}
|
|
|
|
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/<name>.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/<registry>/<namespace>/<path>.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<string, ItemChoice>;
|
|
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.tool_tier) json.mining.tier = block.tool_tier;
|
|
}
|
|
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;
|
|
if (block.item_display) json.item_display = block.item_display;
|
|
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.mining.tier) block.tool_tier = json.mining.tier;
|
|
}
|
|
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;
|
|
if (json.item_display) block.item_display = json.item_display;
|
|
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.food !== undefined) json.food = item.food;
|
|
if (item.worn !== undefined) json.worn = item.worn;
|
|
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 = { 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.food !== undefined) item.food = json.food;
|
|
if (json.worn !== undefined) item.worn = json.worn;
|
|
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<string, ItemChoice> = {};
|
|
// by the choice as json, so equal lists share a letter
|
|
const letters = new Map<string, string>();
|
|
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<RecipeJson, { type: "shaped" }>): 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<string>) {
|
|
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.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");
|
|
} 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.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`);
|
|
}
|
|
}
|
|
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}`)
|
|
);
|
|
}
|
|
|
|
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");
|
|
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.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"');
|
|
}
|
|
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<string>();
|
|
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/<name>.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<string, unknown> {
|
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
}
|