956 lines
38 KiB
TypeScript
956 lines
38 KiB
TypeScript
// 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 * as z from "zod";
|
|
import { is_tint_color, type TintColor } from "./worldgen/biome_colors.ts";
|
|
import {
|
|
type BlockRegistry,
|
|
type BlockStateDefinition,
|
|
FLUID_DEFAULTS,
|
|
FLUID_LEVEL,
|
|
type FluidContainerProperties,
|
|
type FluidProperties,
|
|
type FoodProperties,
|
|
type ItemLayer,
|
|
type ItemRegistry,
|
|
MAX_FLUID_RANGE,
|
|
RENDER_LAYERS,
|
|
type RenderLayer,
|
|
type ToolProperties,
|
|
WATERLOGGED,
|
|
type WornProperties,
|
|
} from "./everything_registry.ts";
|
|
import type { BlockPart, BlockVariant, ModelFileJson } from "./block_models.ts";
|
|
import { expand_items, list_matches } from "./tags.ts";
|
|
import { GAME_VERSION } from "./constants.ts";
|
|
import {
|
|
by_kind,
|
|
color,
|
|
find_problems,
|
|
id,
|
|
id_or_tag,
|
|
ID_PATTERN,
|
|
is_object,
|
|
json_object,
|
|
loot_table_id,
|
|
type Problems,
|
|
TAG_ID_PATTERN,
|
|
text,
|
|
vec3,
|
|
} from "./schema.ts";
|
|
|
|
export const FORMAT_VERSION = 1;
|
|
export const NAMESPACE_PATTERN = /^[a-z0-9_]{1,32}$/;
|
|
export const RESERVED_NAMESPACES = ["bworld", "engine"];
|
|
// 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];
|
|
|
|
// a data file, with what it holds under key next to the format it's in, like { "format_version": 1, "block": { ... } }
|
|
export function data_file(key: string, contents: z.ZodType) {
|
|
return z.object({ format_version: z.literal(FORMAT_VERSION), [key]: contents });
|
|
}
|
|
|
|
type BlockTextures = BlockRegistry["textures"];
|
|
|
|
// the pieces the formats here are made of, past the ones in schema.ts
|
|
|
|
// how far a model turns
|
|
const right_angle = z.literal([0, 90, 180, 270]);
|
|
|
|
// what a block's tint draws its textures in, see TintColor
|
|
const tint_color = z.custom<TintColor>(is_tint_color, 'must be "grass", "foliage", "water" or a color like "#80a755"');
|
|
|
|
// a texture id, or texture variables mapped to ids
|
|
const textures = z.union([id, z.record(z.string(), id)], "must be a texture id or { variable: texture id }");
|
|
const stack = z.object({ id, count: z.int().min(1) });
|
|
|
|
// the manifest of the mod in the folder folder_name, which is its id
|
|
const manifest_schema = (folder_name: string) =>
|
|
z.object({
|
|
format_version: z.literal(FORMAT_VERSION),
|
|
id: z.string("must be 1-32 characters of a-z, 0-9 and _").regex(NAMESPACE_PATTERN)
|
|
.refine((id) => id === folder_name, `must match the folder name "${folder_name}"`),
|
|
name: text,
|
|
description: z.string().optional(),
|
|
version: z.string("must be semver, like 1.0.0").regex(/^\d+\.\d+\.\d+/),
|
|
authors: z.array(z.string()).optional(),
|
|
game_version: z.string().optional(),
|
|
// imports bworld/engine to reach into the engine and hook its methods. needs game_version within one minor version
|
|
engine_access: z.boolean().optional(),
|
|
dependencies: z.array(z.object({ id: z.string(), version: z.string() })).optional(),
|
|
scripts: z.strictObject({
|
|
server: z.string().optional(),
|
|
client: z.string().optional(),
|
|
worldgen: z.string().optional(),
|
|
shared: z.string().optional(),
|
|
}).optional(),
|
|
credits: z.string().optional(),
|
|
}).superRefine((manifest, ctx) => {
|
|
const problem = manifest.engine_access ? engine_version_problem(manifest.game_version) : undefined;
|
|
if (problem) ctx.addIssue({ code: "custom", message: problem });
|
|
});
|
|
|
|
export type ManifestJson = z.infer<ReturnType<typeof manifest_schema>>;
|
|
|
|
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;
|
|
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;
|
|
scrollable?: boolean;
|
|
replaceable?: boolean;
|
|
place_on?: string[];
|
|
place_in?: string[];
|
|
states?: BlockStateDefinition[];
|
|
components?: Record<string, unknown>;
|
|
item_display?: { surface: number };
|
|
// makes it a fluid, see FluidProperties. range is 7 when not set
|
|
fluid?: Partial<FluidProperties>;
|
|
// what it drops when broken, see common/loot.ts. drops is the shorthand for one of an item
|
|
loot_table?: string;
|
|
// the fluid it can hold, see BlockRegistry.waterloggable
|
|
waterloggable?: string;
|
|
// only placed into a source of it, see BlockRegistry.waterlogged_only
|
|
waterlogged_only?: boolean;
|
|
}
|
|
|
|
// 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 boxes(top: number) {
|
|
const pixel = z.number().min(0).max(16);
|
|
const height = z.number().min(0).max(top);
|
|
const box = z.tuple([pixel, height, pixel, pixel, height, pixel], "must be a box, [x1, y1, z1, x2, y2, z2]")
|
|
.refine(([x1, y1, z1, x2, y2, z2]) => x1 <= x2 && y1 <= y2 && z1 <= z2, "can't end before it starts");
|
|
return z.array(box, "must be a list of boxes in pixels, like [[0, 0, 0, 16, 8, 16]]").min(1);
|
|
}
|
|
|
|
const shape = boxes(16);
|
|
// what entities bump into can be taller than the block, like a fence
|
|
const collision_shape = boxes(24);
|
|
|
|
const variant = z.object({
|
|
model: id.optional(),
|
|
textures: textures.optional(),
|
|
x: right_angle.optional(),
|
|
y: right_angle.optional(),
|
|
uvlock: z.boolean().optional(),
|
|
shape: shape.optional(),
|
|
collision_shape: collision_shape.optional(),
|
|
});
|
|
|
|
const part = variant.extend({ when: z.string().optional(), model: id });
|
|
|
|
// a whole number of light, from none to full
|
|
const light = z.int().min(0).max(15);
|
|
|
|
const block_fields = z.object({
|
|
id,
|
|
name: text.optional(),
|
|
textures,
|
|
model: id.optional(),
|
|
// keys are conditions on the block's states, like "age=3"
|
|
variants: z.record(z.string(), variant).optional(),
|
|
render_layer: z.enum(RENDER_LAYERS).optional(),
|
|
cull_same: z.boolean().optional(),
|
|
tint: z.object({
|
|
color: tint_color,
|
|
// texture variables, like ["top"]
|
|
textures: z.array(z.string()).optional(),
|
|
}).optional(),
|
|
light_emission: light.optional(),
|
|
light_opacity: light.optional(),
|
|
transparent: z.boolean().optional(),
|
|
alpha: z.number().min(0).max(1).optional(),
|
|
collision: z.boolean().optional(),
|
|
shape: shape.optional(),
|
|
collision_shape: collision_shape.optional(),
|
|
parts: z.array(part).min(1).optional(),
|
|
item_model: id.optional(),
|
|
// toughness is in seconds
|
|
mining: z.object({
|
|
toughness: z.number().min(0),
|
|
tool: z.string().optional(),
|
|
requires_tool: z.boolean().optional(),
|
|
tier: z.int().min(0).optional(),
|
|
}).optional(),
|
|
drops: id.optional(),
|
|
item: z.boolean().optional(),
|
|
interactive: z.boolean().optional(),
|
|
scrollable: z.boolean().optional(),
|
|
replaceable: z.boolean().optional(),
|
|
place_on: z.array(id_or_tag).min(1).optional(),
|
|
place_in: z.array(id_or_tag).min(1).optional(),
|
|
states: z.array(z.object({ name: z.string(), bits: z.int().min(1), default: z.int().min(0) })).optional(),
|
|
components: json_object.optional(),
|
|
// the height in pixels items lie on
|
|
item_display: z.object({ surface: z.number().min(0).max(16) }).optional(),
|
|
fluid: z.strictObject({
|
|
range: z.int().min(1).max(MAX_FLUID_RANGE).optional(),
|
|
ticks: z.int().min(1).optional(),
|
|
renewable: z.boolean().optional(),
|
|
}, "must be { range, ticks, renewable }, or {}").optional(),
|
|
loot_table: loot_table_id.optional(),
|
|
waterloggable: id.optional(),
|
|
waterlogged_only: z.boolean().optional(),
|
|
});
|
|
|
|
const block_schema: z.ZodType<BlockJson> = block_fields.superRefine(check_block);
|
|
|
|
// what a fluid's and a plain cube's textures can be, past being ids
|
|
const fluid_textures = z.union([z.string(), z.strictObject({ still: z.string(), flowing: z.string().optional() })]);
|
|
const cube_textures = z.union([
|
|
z.string(),
|
|
z.object({ top: z.string(), bottom: z.string(), side: z.string() }),
|
|
z.object({ front: z.string(), side: z.string() }),
|
|
]);
|
|
|
|
// what a block's fields mean for each other
|
|
function check_block(block: z.infer<typeof block_fields>, ctx: z.RefinementCtx) {
|
|
const problem = (path: PropertyKey[], message: string) => ctx.addIssue({ code: "custom", path, message });
|
|
const states = block.states ?? [];
|
|
const names = new Set(states.map((state) => state.name));
|
|
|
|
// a condition like "age=3,facing=1" on the block's states, for a variant or a part
|
|
const check_condition = (path: PropertyKey[], condition: string) => {
|
|
for (const term of condition === "" ? [] : condition.split(",")) {
|
|
const [name, value] = term.split("=").map((side) => side.trim());
|
|
if (!names.has(name)) problem(path, `names ${name}, which isn't one of this block's states`);
|
|
else if (!/^\d+$/.test(value ?? "")) problem(path, `must give ${name} a number, like ${name}=1`);
|
|
}
|
|
};
|
|
for (const condition of Object.keys(block.variants ?? {})) check_condition(["variants", condition], condition);
|
|
block.parts?.forEach((part, i) => {
|
|
if (part.when !== undefined) check_condition(["parts", i, "when"], part.when);
|
|
});
|
|
|
|
if (block.fluid) {
|
|
// a fluid is drawn by the engine, so it has no model of its own, and its level is a state it gets
|
|
if (!fluid_textures.safeParse(block.textures).success) {
|
|
problem(["textures"], "must be a texture id or { still, flowing } for a fluid");
|
|
}
|
|
for (const key of ["model", "variants", "parts", "shape", "collision_shape", "item_model"] as const) {
|
|
if (block[key] !== undefined) problem([key], "isn't for fluids, the engine draws them");
|
|
}
|
|
if (names.has(FLUID_LEVEL.name)) {
|
|
problem(["states"], `can't have "${FLUID_LEVEL.name}", a fluid gets that state of its own`);
|
|
}
|
|
if (block.waterloggable !== undefined) problem(["waterloggable"], "isn't for fluids");
|
|
} else if (block.parts === undefined && (block.model ?? "engine:cube") === "engine:cube") {
|
|
if (!cube_textures.safeParse(block.textures).success) {
|
|
problem(["textures"], "must be a texture id, { top, bottom, side } or { front, side }");
|
|
}
|
|
}
|
|
|
|
if (block.waterloggable !== undefined && names.has(WATERLOGGED.name)) {
|
|
problem(["states"], `can't have "${WATERLOGGED.name}", a waterloggable block gets that state of its own`);
|
|
}
|
|
if (block.waterlogged_only && block.waterloggable === undefined) {
|
|
problem(["waterlogged_only"], "needs waterloggable, the fluid it's placed into");
|
|
}
|
|
// a block's states fit in 16 bits, with the one it gets for being a fluid or waterloggable
|
|
const added = block.fluid ? FLUID_LEVEL : block.waterloggable !== undefined ? WATERLOGGED : undefined;
|
|
const bits = states.reduce((sum, state) => sum + state.bits, added?.bits ?? 0);
|
|
if (bits > 16) problem(["states"], `use ${bits} bits${added ? ` with ${added.name}` : ""}, the most is 16`);
|
|
if (block.drops !== undefined && block.loot_table !== undefined) {
|
|
problem(["drops"], "can't be set with loot_table, drops is the shorthand for a loot table of one item");
|
|
}
|
|
}
|
|
|
|
// the names block models' json uses, see block_models.ts. they live here because the schemas below need them as this
|
|
// file loads, and block_models.ts imports this file (through utils.ts and biome_colors.ts) before its own are set
|
|
|
|
export type ModelFace = "top" | "bottom" | "north" | "south" | "west" | "east";
|
|
export const MODEL_FACES: ModelFace[] = ["top", "bottom", "north", "south", "west", "east"];
|
|
// where items are shown: in slots, held in first person, dropped, and on blocks with item_display
|
|
export const DISPLAY_CONTEXTS = ["gui", "firstperson_righthand", "ground", "fixed"] as const;
|
|
export type DisplayContext = typeof DISPLAY_CONTEXTS[number];
|
|
|
|
const model_face = z.object({
|
|
texture: z.string(),
|
|
uv: z.tuple([z.number(), z.number(), z.number(), z.number()], "must be [u1, v1, u2, v2] in pixels").optional(),
|
|
rotation: right_angle.optional(),
|
|
cullface: z.enum(MODEL_FACES).optional(),
|
|
});
|
|
|
|
const model_element = z.object({
|
|
from: vec3,
|
|
to: vec3,
|
|
rotation: z.object({
|
|
origin: vec3,
|
|
axis: z.enum(["x", "y", "z"]),
|
|
angle: z.number().min(-180).max(180),
|
|
rescale: z.boolean().optional(),
|
|
}).optional(),
|
|
shade: z.boolean().optional(),
|
|
faces: z.partialRecord(z.enum(MODEL_FACES), model_face),
|
|
});
|
|
|
|
const display_transform = z.strictObject({
|
|
rotation: vec3.optional(),
|
|
translation: vec3.optional(),
|
|
scale: vec3.optional(),
|
|
});
|
|
|
|
const model_schema: z.ZodType<ModelFileJson> = z.object({
|
|
id,
|
|
parent: id.optional(),
|
|
textures: z.record(
|
|
z.string(),
|
|
z.union([z.string().startsWith("#"), id], 'must be a texture id, or a variable like "#side"'),
|
|
).optional(),
|
|
elements: z.array(model_element).optional(),
|
|
display: z.partialRecord(z.enum(DISPLAY_CONTEXTS), display_transform).optional(),
|
|
}).refine(
|
|
// a model can leave its elements to its parent, or be one that only gives defaults to its children
|
|
(model) => model.elements || model.parent || model.textures || model.display,
|
|
"a model needs elements, a parent, or textures or display for models that use it as theirs",
|
|
);
|
|
|
|
const ore_schema = z.object({
|
|
id,
|
|
replaces: id,
|
|
min_y: z.number(),
|
|
max_y: z.number(),
|
|
scale: z.number(),
|
|
threshold: z.number(),
|
|
}).refine((ore) => ore.min_y <= ore.max_y, { path: ["min_y"], message: "can't be above max_y" });
|
|
|
|
export type OreJson = z.infer<typeof ore_schema>;
|
|
|
|
// 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
|
|
const spawn_schema = z.object({
|
|
entity: id,
|
|
// how often it's picked over the other spawns where both can spawn
|
|
weight: z.int().min(0),
|
|
// how many spawn together
|
|
min_count: z.int().min(1),
|
|
max_count: z.int().min(1),
|
|
// only in these biomes, every biome when not set
|
|
biomes: z.array(id).optional(),
|
|
// 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: z.number().positive().max(1).optional(),
|
|
}).refine((spawn) => spawn.min_count <= spawn.max_count, { path: ["min_count"], message: "can't be above max_count" });
|
|
|
|
export type SpawnJson = z.infer<typeof spawn_schema>;
|
|
|
|
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<string, string>;
|
|
// see ItemRegistry.model
|
|
model?: string;
|
|
// tier and speed default to 0 and 2
|
|
tool?: Omit<ToolProperties, "tier" | "speed"> & Partial<ToolProperties>;
|
|
places?: string;
|
|
max_stack?: number;
|
|
base_sell_value?: number;
|
|
food?: FoodProperties;
|
|
// how it looks worn on a player
|
|
worn?: WornProperties;
|
|
// see ItemRegistry.targets_fluids
|
|
targets_fluids?: boolean;
|
|
fluid_container?: FluidContainerProperties;
|
|
layers?: ItemLayer[];
|
|
name?: string;
|
|
lore?: string;
|
|
components?: Record<string, unknown>;
|
|
}
|
|
|
|
const item_schema: z.ZodType<ItemJson> = z.object({
|
|
id,
|
|
texture: id.optional(),
|
|
data_textures: z.record(z.string(), id).optional(),
|
|
model: id.optional(),
|
|
tool: z.object({
|
|
type: z.string(),
|
|
durability: z.int().min(1),
|
|
tier: z.int().min(0).optional(),
|
|
speed: z.number().positive().optional(),
|
|
}).optional(),
|
|
places: id.optional(),
|
|
max_stack: z.int().min(1).optional(),
|
|
base_sell_value: z.int().min(0).optional(),
|
|
food: z.object({
|
|
nutrition: z.int().min(0),
|
|
saturation_modifier: z.number().min(0),
|
|
always_edible: z.boolean().optional(),
|
|
returns: id.optional(),
|
|
}).optional(),
|
|
// an entity model and a texture
|
|
worn: z.strictObject({
|
|
model: id,
|
|
texture: id,
|
|
slim_model: id.optional(),
|
|
slim_texture: id.optional(),
|
|
}, "must be { model, texture }, an entity model and a texture").optional(),
|
|
targets_fluids: z.boolean().optional(),
|
|
fluid_container: z.strictObject({
|
|
capacity: z.int().min(1),
|
|
full_max_stack: z.int().min(1).optional(),
|
|
}).optional(),
|
|
layers: z.array(z.strictObject({
|
|
texture: id,
|
|
tint: z.custom<ItemLayer["tint"]>(
|
|
(value) => value === "fluid" || is_tint_color(value),
|
|
'must be "fluid", "grass", "foliage", "water" or a color like "#80a755"',
|
|
).optional(),
|
|
})).optional(),
|
|
name: text.optional(),
|
|
lore: text.optional(),
|
|
components: json_object.optional(),
|
|
});
|
|
|
|
// a kind of entity, drawn with an entity model and one texture, or without a model as its texture facing the camera
|
|
const entity_schema = z.object({
|
|
id,
|
|
// an entity model, see EntityModelJson
|
|
model: id.optional(),
|
|
texture: id,
|
|
// "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: z.enum(["animal", "monster", "scripted"]).optional(),
|
|
// its collision box in blocks, width is for both x and z
|
|
width: z.number().positive().max(16),
|
|
height: z.number().positive().max(16),
|
|
max_health: z.number().min(0).optional(),
|
|
// minecraft's per tick speed, 0.25 for most animals
|
|
movement_speed: z.number().min(0).optional(),
|
|
// what its hits do, for monsters. 2 when not set, like minecraft's
|
|
attack_damage: z.number().min(0).optional(),
|
|
// protection from physical and from arcane damage, not used yet
|
|
physical_shielding: z.number().min(0).optional(),
|
|
arcane_shielding: z.number().min(0).optional(),
|
|
// what it drops when it dies, see common/loot.ts
|
|
loot_table: loot_table_id.optional(),
|
|
});
|
|
|
|
export type EntityJson = z.infer<typeof entity_schema>;
|
|
|
|
// like minecraft's MobEffectCategory, "neutral" when not set
|
|
const effect_category = z.enum(["beneficial", "harmful", "neutral"]);
|
|
export type EffectCategory = z.infer<typeof effect_category>;
|
|
|
|
// a status effect, like neoforge's MobEffect. what it does over time comes from components scripts register, see
|
|
// docs/modding/entities/effects.md
|
|
const effect_schema = z.object({
|
|
id,
|
|
category: effect_category.optional(),
|
|
// happens once when added instead of lasting, like instant health. its components' on_tick runs once
|
|
instant: z.boolean().optional(),
|
|
// a texture, shown at the top of the inventory screen while the player has it
|
|
icon: id.optional(),
|
|
// attribute modifiers while it's on, for level 1. each level adds that much again, like minecraft's speed
|
|
modifiers: z.array(z.object({
|
|
attribute: id,
|
|
amount: z.number(),
|
|
operation: z.enum(["add_value", "add_multiplied_base", "add_multiplied_total"]),
|
|
})).optional(),
|
|
components: json_object.optional(),
|
|
});
|
|
|
|
export type EffectJson = z.infer<typeof effect_schema>;
|
|
|
|
// a kind of fluid, like neoforge's FluidType: what it is apart from any block, container or amount. a block flows in
|
|
// the world with its own "fluid" field, which is another thing
|
|
const fluid_schema = z.object({
|
|
id,
|
|
// what players see, from the id when not set like an item's
|
|
name: text.optional(),
|
|
// for whatever shows it, like a layer tinted "fluid" on a full container
|
|
color,
|
|
});
|
|
|
|
export type FluidJson = z.infer<typeof fluid_schema>;
|
|
|
|
// a box from origin to origin + size, textured like minecraft's box uv: see the renderer's FACES
|
|
const entity_cube = z.object({
|
|
origin: vec3,
|
|
size: vec3,
|
|
uv: z.tuple([z.number(), z.number()], "must be [u, v], per face uvs aren't supported"),
|
|
// grows the box this many pixels each way without moving its texture
|
|
inflate: z.number().optional(),
|
|
});
|
|
|
|
export type EntityCubeJson = z.infer<typeof entity_cube>;
|
|
|
|
const entity_bone = z.object({
|
|
name: z.string(),
|
|
parent: z.string().optional(),
|
|
// what it turns around
|
|
pivot: vec3,
|
|
// degrees around x, y then z
|
|
rotation: vec3.optional(),
|
|
cubes: z.array(entity_cube),
|
|
});
|
|
|
|
export type EntityBoneJson = z.infer<typeof entity_bone>;
|
|
|
|
// 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
|
|
const entity_model_schema = z.object({
|
|
id,
|
|
// the size its uvs are laid out for, the texture is stretched to it
|
|
texture_width: z.int().min(1),
|
|
texture_height: z.int().min(1),
|
|
// parents come before their children
|
|
bones: z.array(entity_bone).superRefine((bones, ctx) => {
|
|
const names = new Set<string>();
|
|
bones.forEach((bone, i) => {
|
|
const problem = (message: string) => ctx.addIssue({ code: "custom", path: [i], message });
|
|
if (names.has(bone.name)) problem(`there are two bones named ${bone.name}`);
|
|
if (bone.parent !== undefined && !names.has(bone.parent)) {
|
|
problem(`parent ${bone.parent} must be a bone before it`);
|
|
}
|
|
names.add(bone.name);
|
|
});
|
|
}),
|
|
});
|
|
|
|
export type EntityModelJson = z.infer<typeof entity_model_schema>;
|
|
|
|
// something in a tag file's values or remove: an id, a "#tag", or either with whether it must exist. a plain one must
|
|
const tag_entry = z.union(
|
|
[id_or_tag, z.object({ id: id_or_tag, required: z.boolean().optional() })],
|
|
'must be an id, a "#tag", or { id, required }',
|
|
);
|
|
|
|
export type TagEntryJson = z.infer<typeof tag_entry>;
|
|
|
|
// 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
|
|
const tag_schema = z.object({
|
|
registry: z.enum(TAG_REGISTRIES),
|
|
id: z.string('must be a tag id like "my_mod:things" or "c:ingots/iron"').regex(TAG_ID_PATTERN),
|
|
values: z.array(tag_entry),
|
|
// drops what mods before this one put in the tag
|
|
replace: z.boolean().optional(),
|
|
// takes these out again, if they're in it
|
|
remove: z.array(tag_entry).optional(),
|
|
});
|
|
|
|
export type TagJson = z.infer<typeof tag_schema>;
|
|
|
|
// 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
|
|
const item_choice = z.union([id_or_tag, z.array(id_or_tag).min(1)], 'must be an item id, a "#tag", or a list of them');
|
|
|
|
export type ItemChoice = z.infer<typeof item_choice>;
|
|
|
|
// 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);
|
|
}
|
|
|
|
const shaped_recipe = z.object({
|
|
type: z.literal("shaped"),
|
|
// up to 3 by 3, a space is an empty slot
|
|
pattern: z.array(z.string().min(1).max(3)).min(1).max(3),
|
|
key: z.record(z.string(), item_choice),
|
|
result: stack,
|
|
}).superRefine((recipe, ctx) => {
|
|
for (const letter of new Set(recipe.pattern.join("").replaceAll(" ", ""))) {
|
|
if (!(letter in recipe.key)) {
|
|
ctx.addIssue({ code: "custom", path: ["key"], message: `needs "${letter}", which pattern uses` });
|
|
}
|
|
}
|
|
});
|
|
|
|
// cook_time and burn_time are in ticks
|
|
const furnace_recipe = z.object({
|
|
type: z.literal("furnace"),
|
|
input: item_choice,
|
|
output: stack,
|
|
cook_time: z.int().min(1),
|
|
});
|
|
|
|
const fuel_recipe = z.object({ type: z.literal("fuel"), item: item_choice, burn_time: z.int().min(1) });
|
|
|
|
// upgrades a tool at a smithing table, with some of a material and maybe one more item
|
|
const smithing_recipe = z.object({
|
|
type: z.literal("smithing"),
|
|
tool: id,
|
|
material: stack,
|
|
addition: id.optional(),
|
|
result: id,
|
|
});
|
|
|
|
export interface ModRecipeJson {
|
|
type: `${string}:${string}`;
|
|
[field: string]: unknown;
|
|
}
|
|
|
|
export type RecipeJson =
|
|
| z.infer<typeof shaped_recipe>
|
|
| z.infer<typeof furnace_recipe>
|
|
| z.infer<typeof fuel_recipe>
|
|
| z.infer<typeof smithing_recipe>
|
|
| ModRecipeJson;
|
|
|
|
const engine_recipes = new Map<string, z.ZodType>([
|
|
["shaped", shaped_recipe],
|
|
["furnace", furnace_recipe],
|
|
["fuel", fuel_recipe],
|
|
["smithing", smithing_recipe],
|
|
]);
|
|
|
|
// a mod's own types, like "farmersdelight:cooking" for its cooking pot, are only stored by the engine. the mod's server
|
|
// script reads them with ctx.recipes.list and checks them
|
|
const recipe_schema = by_kind(
|
|
"type",
|
|
(type) => engine_recipes.get(type) ?? (ID_PATTERN.test(type) ? json_object : undefined),
|
|
'must be "shaped", "furnace", "fuel", "smithing" or a mod\'s own type like "farmersdelight:cooking"',
|
|
);
|
|
|
|
// 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;
|
|
// fluids are without collision and replaceable unless they say otherwise
|
|
if (block.has_collision === !!block.fluid) 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.scrollable) json.scrollable = true;
|
|
if (!!block.replaceable !== !!block.fluid) 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 fluid's level state and a waterloggable block's waterlogged state are its own, added when it loads
|
|
const added = block.fluid || 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.fluid) {
|
|
// only what isn't the default
|
|
const fluid = block.fluid;
|
|
json.fluid = Object.fromEntries(
|
|
Object.entries(fluid).filter(([key, value]) => FLUID_DEFAULTS[key as keyof FluidProperties] !== 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.fluid,
|
|
};
|
|
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.scrollable) block.scrollable = true;
|
|
if (json.replaceable ?? json.fluid) 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.fluid) {
|
|
block.fluid = { ...FLUID_DEFAULTS, ...json.fluid };
|
|
// last, so the block's own states keep their bits
|
|
block.states = [...block.states ?? [], { ...FLUID_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.model !== undefined) json.model = item.model;
|
|
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_fluids !== undefined) json.targets_fluids = item.targets_fluids;
|
|
if (item.fluid_container !== undefined) json.fluid_container = item.fluid_container;
|
|
if (item.layers !== undefined) json.layers = item.layers;
|
|
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<ItemRegistry> {
|
|
const item: Partial<ItemRegistry> = {};
|
|
if (json.data_textures !== undefined) item.data_textures = json.data_textures;
|
|
if (json.model !== undefined) item.model = json.model;
|
|
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_fluids !== undefined) item.targets_fluids = json.targets_fluids;
|
|
if (json.fluid_container !== undefined) item.fluid_container = json.fluid_container;
|
|
if (json.layers !== undefined) item.layers = json.layers;
|
|
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, see find_problems
|
|
|
|
export function validate_manifest(json: unknown, folder_name: string): Problems {
|
|
return find_problems(manifest_schema(folder_name), json);
|
|
}
|
|
|
|
// 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 {
|
|
return find_problems(block_schema, json);
|
|
}
|
|
|
|
export function validate_model(json: unknown): Problems {
|
|
return find_problems(model_schema, json);
|
|
}
|
|
|
|
export function validate_item(json: unknown): Problems {
|
|
return find_problems(item_schema, json);
|
|
}
|
|
|
|
export function validate_recipe(json: unknown): Problems {
|
|
return find_problems(recipe_schema, json);
|
|
}
|
|
|
|
export function validate_ore(json: unknown): Problems {
|
|
return find_problems(ore_schema, json);
|
|
}
|
|
|
|
export function validate_spawn(json: unknown): Problems {
|
|
return find_problems(spawn_schema, json);
|
|
}
|
|
|
|
export function validate_entity(json: unknown): Problems {
|
|
return find_problems(entity_schema, json);
|
|
}
|
|
|
|
export function validate_effect(json: unknown): Problems {
|
|
return find_problems(effect_schema, json);
|
|
}
|
|
|
|
export function validate_fluid(json: unknown): Problems {
|
|
return find_problems(fluid_schema, json);
|
|
}
|
|
|
|
export function validate_entity_model(json: unknown): Problems {
|
|
return find_problems(entity_model_schema, json);
|
|
}
|
|
|
|
// 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 };
|
|
}
|
|
|
|
// a tag file's contents, with the registry and id its path gives it
|
|
export function validate_tag(json: unknown): Problems {
|
|
return find_problems(tag_schema, json);
|
|
}
|