Validators using zod

This commit is contained in:
2026-10-25 12:41:46 -03:00
parent 31ae2973d7
commit 4fad43d9cc
24 changed files with 1242 additions and 1788 deletions
+1 -6
View File
@@ -7,9 +7,7 @@
import { type BlockRegistry, type BlockTextures, liquid_textures } from "./everything_registry.ts";
import { tint_without_biome } from "./worldgen/biome_colors.ts";
import { get_state_value } from "./utils.ts";
export type ModelFace = "top" | "bottom" | "north" | "south" | "west" | "east";
export const MODEL_FACES: ModelFace[] = ["top", "bottom", "north", "south", "west", "east"];
import { type DisplayContext, MODEL_FACES, type ModelFace } from "./mod_data.ts";
export interface ModelFaceJson {
// a texture variable like "#side", or a texture id
@@ -47,9 +45,6 @@ export interface DisplayTransform {
scale?: [number, number, number];
}
// 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];
export type ModelDisplay = Partial<Record<DisplayContext, DisplayTransform>>;
// a model as a mod writes it in models/. it can start from a parent, like minecraft's: it gets the parent's elements
+1 -2
View File
@@ -11,8 +11,6 @@ import {
type EffectJson,
type EntityJson,
type EntityModelJson,
ID_PATTERN,
is_object,
type ItemJson,
type ManifestJson,
type OreJson,
@@ -31,6 +29,7 @@ import {
validate_spawn,
validate_tag,
} from "./mod_data.ts";
import { ID_PATTERN, is_object } from "./schema.ts";
import type { ModData } from "./mod_loader.ts";
import { type LootTableJson, validate_loot_table } from "./loot.ts";
import { type BiomeJson, validate_biome } from "./worldgen/biomes.ts";
+108 -159
View File
@@ -6,9 +6,19 @@
// decide whether a table, pool or entry counts, functions change the items it gives. mods can add their own
// conditions and functions (ctx.loot in server scripts), which are ids in their namespace.
// see docs/modding/resources/loot_tables.md
import * as z from "zod";
import { EverythingRegistry, type ItemRegistry } from "./everything_registry.ts";
import { list_matches, Tags } from "./tags.ts";
import { is_object, TAG_ID_PATTERN } from "./mod_data.ts";
import {
by_kind,
find_problems,
id,
id_or_tag,
json_object,
loot_table_id,
type Problems,
TAG_ID_PATTERN,
} from "./schema.ts";
// a whole number, a random one from min to max, or the number of n tries at chance p that succeed, like minecraft's
// constant, uniform and binomial number providers
@@ -87,17 +97,6 @@ export interface LootEnvironment<C extends BaseLootContext> {
random?: () => number;
}
export const LOOT_CONDITIONS = [
"random_chance",
"match_tool",
"block_state",
"killed_by_player",
"inverted",
"any_of",
"all_of",
] as const;
export const LOOT_FUNCTIONS = ["set_count", "limit_count", "set_data"] as const;
const ENTRY_TYPES = ["item", "tag", "loot_table", "empty"];
// tables in tables in tables: past this it's taken as a loop and gives nothing more
const MAX_DEPTH = 16;
@@ -263,155 +262,105 @@ function apply<C extends BaseLootContext>(
// checking a table's json
type Problems = string[];
const whole = z.int().min(0);
const number_provider: z.ZodType<NumberProvider> = z.union([
whole,
z.object({ min: whole, max: whole }).refine(({ min, max }) => min <= max, {
path: ["max"],
message: "can't be below min",
}),
z.object({ n: whole, p: z.number().min(0).max(1) }),
], "must be a whole number, { min, max } or { n, p }");
const conditions = z.array(z.lazy(() => loot_condition));
// the engine's conditions, by name
const CONDITIONS = new Map<string, z.ZodType>([
["random_chance", z.object({ chance: z.number().min(0).max(1) })],
[
"match_tool",
z.object({ items: z.array(id_or_tag).optional(), tool: z.string().optional(), min_tier: z.int().optional() }),
],
[
"block_state",
z.object({
block: id.optional(),
states: z.record(
z.string(),
z.union(
[z.int(), z.object({ min: z.int().optional(), max: z.int().optional() })],
'must be a number or { min, max }, like { "age": 7 }',
),
),
}),
],
["killed_by_player", z.object({})],
["inverted", z.object({ term: z.lazy(() => loot_condition) })],
["any_of", z.object({ terms: conditions })],
["all_of", z.object({ terms: conditions })],
]);
// any other condition is a mod's own, by its id. the server checks a script registered it when it starts
const loot_condition: z.ZodType<LootCondition> = by_kind(
"condition",
(name) => CONDITIONS.get(name) ?? (name.includes(":") ? json_object : undefined),
`must be one of ${[...CONDITIONS.keys()].join(", ")}, or a mod's own condition's id`,
);
// every function can have conditions
const loot_function_base = z.object({ conditions: conditions.optional() });
// the engine's functions, by name
const FUNCTIONS = new Map<string, z.ZodType>([
["set_count", loot_function_base.extend({ count: number_provider, add: z.boolean().optional() })],
["limit_count", loot_function_base.extend({ min: z.int().optional(), max: z.int().optional() })],
["set_data", loot_function_base.extend({ data: z.unknown() })],
]);
// any other function is a mod's own, like conditions
const loot_function: z.ZodType<LootFunction> = by_kind(
"function",
(name) => FUNCTIONS.get(name) ?? (name.includes(":") ? loot_function_base : undefined),
`must be one of ${[...FUNCTIONS.keys()].join(", ")}, or a mod's own function's id`,
);
const functions = z.array(loot_function);
// every entry can have these
const loot_entry_base = z.object({
weight: z.number().min(0).optional(),
conditions: conditions.optional(),
functions: functions.optional(),
});
const loot_entry: z.ZodType<LootEntry> = z.discriminatedUnion("type", [
loot_entry_base.extend({ type: z.literal("item").optional(), item: id, count: number_provider.optional() }),
loot_entry_base.extend({
type: z.literal("tag"),
tag: z.string('must be a #tag, like "#bworld:logs"').refine((tag) =>
tag.startsWith("#") && TAG_ID_PATTERN.test(tag.slice(1))
),
count: number_provider.optional(),
}),
loot_entry_base.extend({ type: z.literal("loot_table"), table: loot_table_id }),
loot_entry_base.extend({ type: z.literal("empty") }),
]);
const loot_table_schema: z.ZodType<LootTableJson> = z.object({
id: z.string("its file name must be a-z, 0-9 and _, in folders").regex(TAG_ID_PATTERN),
pools: z.array(z.object({
rolls: number_provider.optional(),
conditions: conditions.optional(),
entries: z.array(loot_entry).min(1),
functions: functions.optional(),
})),
conditions: conditions.optional(),
functions: functions.optional(),
});
export function validate_loot_table(json: unknown): Problems {
if (!is_object(json)) return ["loot_table must be an object"];
const problems: Problems = [];
if (typeof json.id !== "string" || !TAG_ID_PATTERN.test(json.id)) {
problems.push("its file name must be a-z, 0-9 and _, in folders");
}
problems.push(...validate_conditions(json.conditions, "conditions"));
problems.push(...validate_functions(json.functions, "functions"));
if (!Array.isArray(json.pools)) return [...problems, "pools must be a list"];
json.pools.forEach((pool, i) => {
const where = `pools[${i}]`;
if (!is_object(pool)) return problems.push(`${where} must be { rolls, entries }`);
if (pool.rolls !== undefined) problems.push(...validate_number(pool.rolls, `${where}.rolls`));
problems.push(...validate_conditions(pool.conditions, `${where}.conditions`));
problems.push(...validate_functions(pool.functions, `${where}.functions`));
if (!Array.isArray(pool.entries) || pool.entries.length === 0) {
return problems.push(`${where}.entries must be a list of entries`);
}
pool.entries.forEach((entry, j) => problems.push(...validate_entry(entry, `${where}.entries[${j}]`)));
});
return problems;
}
function validate_entry(entry: unknown, where: string): Problems {
if (!is_object(entry)) return [`${where} must be { type, item, weight }`];
const problems: Problems = [];
const type = entry.type ?? "item";
if (typeof type !== "string" || !ENTRY_TYPES.includes(type)) {
problems.push(`${where}.type must be one of ${ENTRY_TYPES.join(", ")}`);
}
const field = { item: "item", tag: "tag", loot_table: "table" }[type as string];
if (field && typeof entry[field] !== "string") problems.push(`${where}.${field} is needed for a "${type}" entry`);
if (type === "tag" && typeof entry.tag === "string" && !entry.tag.startsWith("#")) {
problems.push(`${where}.tag must be a #tag, like "#bworld:logs"`);
}
if (entry.count !== undefined) problems.push(...validate_number(entry.count, `${where}.count`));
if (entry.weight !== undefined && (typeof entry.weight !== "number" || entry.weight < 0)) {
problems.push(`${where}.weight must be a number, 0 or more`);
}
problems.push(...validate_conditions(entry.conditions, `${where}.conditions`));
problems.push(...validate_functions(entry.functions, `${where}.functions`));
return problems;
}
export function validate_number(value: unknown, where: string): Problems {
const whole = (n: unknown) => Number.isInteger(n) && (n as number) >= 0;
if (whole(value)) return [];
if (is_object(value) && whole(value.min) && whole(value.max) && (value.max as number) >= (value.min as number)) {
return [];
}
if (
is_object(value) && whole(value.n) && typeof value.p === "number" && value.p >= 0 && value.p <= 1
) return [];
return [`${where} must be a whole number, { min, max } or { n, p }`];
}
function validate_conditions(list: unknown, where: string): Problems {
if (list === undefined) return [];
if (!Array.isArray(list)) return [`${where} must be a list`];
return list.flatMap((condition, i) => validate_condition(condition, `${where}[${i}]`));
}
function validate_condition(condition: unknown, where: string): Problems {
if (!is_object(condition) || typeof condition.condition !== "string") {
return [`${where} must be { "condition": ... }`];
}
const name = condition.condition;
switch (name) {
case "random_chance": {
const chance = condition.chance;
return typeof chance === "number" && chance >= 0 && chance <= 1
? []
: [`${where}.chance must be from 0 to 1`];
}
case "match_tool": {
const problems: Problems = [];
const items = condition.items;
if (items !== undefined && !(Array.isArray(items) && items.every((i) => typeof i === "string"))) {
problems.push(`${where}.items must be a list of item ids and #tags`);
}
if (condition.tool !== undefined && typeof condition.tool !== "string") {
problems.push(`${where}.tool must be a tool type, like "axe"`);
}
if (condition.min_tier !== undefined && !Number.isInteger(condition.min_tier)) {
problems.push(`${where}.min_tier must be a whole number`);
}
return problems;
}
case "block_state": {
const states = condition.states;
const ok = is_object(states) && Object.values(states).every((match) =>
Number.isInteger(match) ||
(is_object(match) && (match.min === undefined || Number.isInteger(match.min)) &&
(match.max === undefined || Number.isInteger(match.max)))
);
return ok ? [] : [`${where}.states must map states to a number or { min, max }, like { "age": 7 }`];
}
case "killed_by_player":
return [];
case "inverted":
return validate_condition(condition.term, `${where}.term`);
case "any_of":
case "all_of":
return Array.isArray(condition.terms)
? condition.terms.flatMap((term, i) => validate_condition(term, `${where}.terms[${i}]`))
: [`${where}.terms must be a list of conditions`];
}
return name.includes(":") ? [] : [
`${where}: ${name} isn't a loot condition. the engine's are ${LOOT_CONDITIONS.join(", ")}, a mod's has its id`,
];
}
function validate_functions(list: unknown, where: string): Problems {
if (list === undefined) return [];
if (!Array.isArray(list)) return [`${where} must be a list`];
return list.flatMap((fn, i) => {
const at = `${where}[${i}]`;
if (!is_object(fn) || typeof fn.function !== "string") return [`${at} must be { "function": ... }`];
const problems = validate_conditions(fn.conditions, `${at}.conditions`);
switch (fn.function) {
case "set_count":
problems.push(...validate_number(fn.count, `${at}.count`));
if (fn.add !== undefined && typeof fn.add !== "boolean") {
problems.push(`${at}.add must be true or false`);
}
break;
case "limit_count":
for (const key of ["min", "max"]) {
if (fn[key] !== undefined && !Number.isInteger(fn[key])) {
problems.push(`${at}.${key} must be a whole number`);
}
}
break;
case "set_data":
if (fn.data === undefined) problems.push(`${at}.data is needed`);
break;
default:
if (!fn.function.includes(":")) {
problems.push(
`${at}: ${fn.function} isn't a loot function. the engine's are ${
LOOT_FUNCTIONS.join(", ")
}, a mod's has its id`,
);
}
}
return problems;
});
return find_problems(loot_table_schema, json);
}
// what a table refers to, for check-mods: items, item #tags, other tables, and mods' conditions and functions
+2 -2
View File
@@ -406,12 +406,12 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
}
for (const { file, json } of mod.noise_settings ?? []) {
const refs = new_refs();
noise_settings_refs(json as unknown as Record<string, unknown>, refs);
noise_settings_refs(json, refs);
check_worldgen("noise settings", file, json.id, refs);
}
for (const { file, json } of mod.biome_sources ?? []) {
const refs = new_refs();
biome_source_refs(json as unknown as Record<string, unknown>, refs);
biome_source_refs(json, refs);
check_worldgen("biome source", file, json.id, refs);
// what its rules look at, in every generator that uses it
const users = all_noise_settings.filter((settings) => settings.biome_source === (json.extends ?? json.id));
+454 -824
View File
File diff suppressed because it is too large Load Diff
+141
View File
@@ -0,0 +1,141 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the pieces mod data's zod schemas are made of, and the problems they find, worded for mod authors. it imports
// nothing else of the game's, so every file can make its schemas with these as it loads, whatever imports it first
import * as z from "zod";
// a list of what's wrong with some json, empty when it's fine
export type Problems = string[];
export const ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+$/;
// 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_]+)*$/;
export const id = z.string('must be an id like "my_mod:thing"').regex(ID_PATTERN);
// an id, or a #tag of them
export const id_or_tag = z.string('must be an id like "my_mod:thing" or a tag like "#my_mod:things"').refine(
(value) => value.startsWith("#") ? TAG_ID_PATTERN.test(value.slice(1)) : ID_PATTERN.test(value),
);
export const loot_table_id = z.string('must be a loot table id, like "my_mod:blocks/thing"').regex(TAG_ID_PATTERN);
// text players see
export const text = z.string().min(1);
export const vec3 = z.tuple([z.number(), z.number(), z.number()], "must be [x, y, z]");
// any json object, for what's only stored, like components
export const json_object = z.record(z.string(), z.unknown());
// json that says what kind of thing it is in one field, like a loot condition's "condition", checked by the schema
// schema_for gives for its kind: the engine's kinds, and mods' own for the rest. no schema is a kind there isn't, which
// unknown says what's wrong with
export function by_kind<T extends Record<string, unknown>>(
field: string,
schema_for: (kind: string) => z.ZodType | undefined,
unknown: string,
): z.ZodType<T> {
const kinded: z.ZodType = z.looseObject({ [field]: z.string() }).superRefine((json, ctx) => {
const schema = schema_for(json[field]);
if (schema) add_problems(ctx, schema, json);
else ctx.addIssue({ code: "custom", path: [field], message: unknown });
});
// the kind's schema checked the rest of T
return kinded as z.ZodType<T>;
}
// checks json with schema as part of a bigger check, like a feature's config by its type. the problems go to ctx, under
// path from where it is
export function add_problems(ctx: z.RefinementCtx, schema: z.ZodType, json: unknown, path: PropertyKey[] = []) {
for (const issue of schema.safeParse(json, { error: describe }).error?.issues ?? []) {
ctx.addIssue({ ...issue, path: [...path, ...issue.path] } as z.core.$ZodRawIssue);
}
}
// what's wrong with json for a schema, each as where it is and what it should be, like "tool.durability must be 1 or
// more". a schema's own message wins over the ones from describe
export function find_problems(schema: z.ZodType, json: unknown): Problems {
const result = schema.safeParse(json, { error: describe });
return result.success ? [] : result.error.issues.flatMap((issue) => issue_problems(issue, []));
}
function issue_problems(issue: z.core.$ZodIssue, outer: PropertyKey[]): Problems {
const path = [...outer, ...issue.path];
if (issue.code === "unrecognized_keys") {
const where = field_name(path);
return issue.keys.map((key) => `${where ? `${where} ` : ""}can't have ${JSON.stringify(key)}`);
}
// a union's options are the kinds of thing the json can be, like a texture id or { variable: texture id }. when
// it's only one of them, that one's problems say more than the union's message
if (issue.code === "invalid_union") {
const fitting = issue.errors.filter((issues) => !issues.every(wrong_kind));
if (fitting.length === 1) return fitting[0].flatMap((inner) => issue_problems(inner, path));
}
const where = field_name(path);
return [where ? `${where} ${issue.message}` : issue.message];
}
// a problem saying json isn't the kind of thing at all: it's the wrong type, none of a union's kinds, or not the
// value a literal like "open_sky" is
function wrong_kind(issue: z.core.$ZodIssue): boolean {
return issue.path.length === 0 &&
(issue.code === "invalid_type" || issue.code === "invalid_union" || issue.code === "invalid_value");
}
// a path into the json as it's written in js, like tool.durability, parts[0].when or variants["age=3"]
function field_name(path: PropertyKey[]): string {
return path.map((key, i) => {
if (typeof key === "number") return `[${key}]`;
const name = String(key);
return /^\w+$/.test(name) ? (i === 0 ? name : `.${name}`) : `[${JSON.stringify(name)}]`;
}).join("");
}
const TYPE_NAMES: Record<string, string> = {
number: "a number",
int: "a whole number",
string: "text",
boolean: "true or false",
array: "a list",
tuple: "a list",
object: "an object",
record: "an object",
};
// zod's messages, in words for mod authors. what isn't here keeps zod's own
const describe: z.core.$ZodErrorMap = (issue) => {
switch (issue.code) {
case "invalid_type":
return issue.input === undefined
? "is required"
: `must be ${TYPE_NAMES[issue.expected] ?? issue.expected}`;
case "too_small":
if (issue.origin === "array" || issue.origin === "string") {
if (issue.minimum === 1) return "can't be empty";
return `must have at least ${issue.minimum} ${issue.origin === "string" ? "characters" : "entries"}`;
}
return issue.inclusive ? `must be ${issue.minimum} or more` : `must be above ${issue.minimum}`;
case "too_big":
if (issue.origin === "array" || issue.origin === "string") {
return `must have at most ${issue.maximum} ${issue.origin === "string" ? "characters" : "entries"}`;
}
return issue.inclusive ? `must be at most ${issue.maximum}` : `must be below ${issue.maximum}`;
case "invalid_value":
return `must be ${or_list(issue.values.map((value) => JSON.stringify(value)))}`;
// a record's key, its schema says what's wrong with it
case "invalid_key":
return issue.issues[0]?.message;
// a discriminated union's field that isn't one of its kinds
case "invalid_union":
if (Array.isArray(issue.options)) {
return `must be ${or_list(issue.options.map((kind) => JSON.stringify(kind)))}`;
}
}
};
// "a", "b" or "c"
function or_list(values: string[]): string {
return values.length < 2 ? values.join("") : `${values.slice(0, -1).join(", ")} or ${values.at(-1)}`;
}
// a json object, not null or an array
export function is_object(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
+36 -56
View File
@@ -3,23 +3,27 @@
// animated textures, like minecraft's .png.mcmeta and in the same format: textures/<name>.json next to
// textures/<name>.png says how to cut the png into frames and how long each one shows. see docs/modding/resources/textures.md
import { is_object } from "./mod_data.ts";
import * as z from "zod";
import { find_problems, type Problems } from "./schema.ts";
export interface TextureJson {
animation?: AnimationJson;
}
export interface AnimationJson {
const animation_schema = z.object({
// ticks each frame shows unless the frame says otherwise, 1 if not given
frametime?: number;
frametime: z.int().min(1).optional(),
// blend each frame into the next a tick at a time instead of switching
interpolate?: boolean;
interpolate: z.boolean().optional(),
// the order to show frames in, by index or { index, time }. every frame in order if not given
frames?: (number | { index: number; time: number })[];
frames: z.array(z.union([z.int().min(0), z.object({ index: z.int().min(0), time: z.int().min(1) })])).min(1)
.optional(),
// a frame's size in pixels. frames are square, as wide as the png is or as tall if that's less, if not given
width?: number;
height?: number;
}
width: z.int().min(1).optional(),
height: z.int().min(1).optional(),
});
export type AnimationJson = z.infer<typeof animation_schema>;
const texture_schema = z.object({ animation: animation_schema.optional() }, 'must be { "animation": { ... } }');
export type TextureJson = z.infer<typeof texture_schema>;
// an animation ready to play
export interface Animation {
@@ -29,52 +33,28 @@ export interface Animation {
frames: { x: number; y: number; time: number }[];
}
// what's wrong with a texture's .json, for the png it goes with
export function validate_texture_json(json: unknown, size: { width: number; height: number }): string[] {
if (!is_object(json)) return [`must be { "animation": { ... } }`];
if (json.animation === undefined) return [];
const animation = json.animation;
if (!is_object(animation)) return ["animation must be an object"];
const problems: string[] = [];
const ticks = (value: unknown) => Number.isInteger(value) && (value as number) >= 1;
if (animation.frametime !== undefined && !ticks(animation.frametime)) {
problems.push("animation.frametime must be a whole number of ticks, at least 1");
}
if (animation.interpolate !== undefined && typeof animation.interpolate !== "boolean") {
problems.push("animation.interpolate must be true or false");
}
for (const key of ["width", "height"] as const) {
if (animation[key] !== undefined && !ticks(animation[key])) {
problems.push(`animation.${key} must be a whole number of pixels, at least 1`);
}
}
if (problems.length > 0) return problems;
const { frame_width, frame_height } = frame_size(animation as AnimationJson, size);
if (size.width % frame_width !== 0 || size.height % frame_height !== 0) {
return [
`the png is ${size.width}×${size.height}, which doesn't split into ${frame_width}×${frame_height} frames`,
];
}
const count = (size.width / frame_width) * (size.height / frame_height);
if (animation.frames !== undefined) {
if (!Array.isArray(animation.frames) || animation.frames.length === 0) {
problems.push("animation.frames must be a list of frames");
} else {
animation.frames.forEach((frame, i) => {
const index = is_object(frame) ? frame.index : frame;
if (!Number.isInteger(index) || index < 0 || index >= count) {
problems.push(`animation.frames[${i}]: the png has frames 0 to ${count - 1}`);
}
if (is_object(frame) && !ticks(frame.time)) {
problems.push(`animation.frames[${i}]: time must be a whole number of ticks, at least 1`);
}
// what's wrong with a texture's .json, for the png it goes with: its frames have to be in it
export function validate_texture_json(json: unknown, size: { width: number; height: number }): Problems {
const fits_png = texture_schema.superRefine(({ animation }, ctx) => {
if (!animation) return;
const { frame_width, frame_height } = frame_size(animation, size);
if (size.width % frame_width !== 0 || size.height % frame_height !== 0) {
return ctx.addIssue({
code: "custom",
message:
`the png is ${size.width}×${size.height}, which doesn't split into ${frame_width}×${frame_height} frames`,
});
}
}
return problems;
const count = (size.width / frame_width) * (size.height / frame_height);
animation.frames?.forEach((frame, i) => {
const index = typeof frame === "number" ? frame : frame.index;
if (index >= count) {
const path = ["animation", "frames", i, ...(typeof frame === "number" ? [] : ["index"])];
ctx.addIssue({ code: "custom", path, message: `isn't one of the png's frames, 0 to ${count - 1}` });
}
});
});
return find_problems(fits_png, json);
}
// the animation in a texture's .json, which validate_texture_json passed. undefined if it isn't animated
+32 -85
View File
@@ -3,8 +3,9 @@
// biomes as data: worldgen/biomes/<name>.json in a mod, see docs/modding/worldgen/biomes.md. which biome a column
// gets is the generator's biome rules (worldgen/biome_source), these say what a biome looks like once it's picked
import * as z from "zod";
import { EverythingRegistry } from "../everything_registry.ts";
import { ID_PATTERN, is_object } from "../mod_data.ts";
import { find_problems, id, type Problems } from "../schema.ts";
import { farming_day } from "../time.ts";
export const SEASONS = ["spring", "summer", "autumn", "winter"] as const;
@@ -12,31 +13,41 @@ export type Season = typeof SEASONS[number];
// how long each season lasts. day 1 to 49 is spring, 50 to 98 summer and so on, a year is 196 days
export const SEASON_DAYS = 49;
// how a biome covers its ground, like minecraft's surface rules. blocks are ids
export interface SurfaceJson {
top: string;
filler: string;
filler_depth: number;
// how a biome covers its ground, like minecraft's surface rules
const surface_schema = z.object({
top: id,
filler: id,
filler_depth: z.int().min(0).max(32),
// the ground's cover under water, filler when not set
underwater_top?: string;
underwater_filler?: string;
underwater_top: id.optional(),
underwater_filler: id.optional(),
// cliffs show bare stone instead of top
bare_cliffs?: boolean;
}
bare_cliffs: z.boolean().optional(),
});
export interface BiomeJson {
id: string;
export type SurfaceJson = z.infer<typeof surface_schema>;
const color = z.string('must be a color like "#79c05a"').regex(/^#[0-9a-fA-F]{6}$/);
const biome_schema = z.object({
id,
// a season it's always in, like winter for snowy biomes. when not set it follows the calendar, see calendar_season
season?: Season;
surface: SurfaceJson;
// "#rrggbb", minecraft's grass, foliage and water colors, which blocks pick with "tint". plains' when not set
colors?: { grass?: string; foliage?: string; water?: string };
season: z.enum(SEASONS).optional(),
surface: surface_schema,
// minecraft's grass, foliage and water colors, which blocks pick with "tint". plains' when not set
colors: z.strictObject({ grass: color.optional(), foliage: color.optional(), water: color.optional() }).optional(),
// how likely each tree cell is to have a tree, and which kinds grow, picked evenly (list one twice to make it
// twice as likely). wood is the logs and leaves a kind grows here when it isn't its own, like big oaks being dark
// oak in the dark forest. the trees feature reads it (bworld's, in its worldgen script), which says what kinds
// and woods there are
trees?: { chance: number; kinds: string[]; wood?: Record<string, string> };
}
// and woods there are, and checks them when it loads
trees: z.object({
chance: z.number().min(0).max(1),
kinds: z.array(z.string()).min(1),
wood: z.record(z.string(), z.string()).optional(),
}).optional(),
});
export type BiomeJson = z.infer<typeof biome_schema>;
// what's registered in "biomes", with the defaults filled in
export interface Biome {
@@ -97,70 +108,6 @@ export function biome_blocks(json: BiomeJson): string[] {
return [top, filler, underwater_top, underwater_filler].filter((id) => id !== undefined);
}
export function validate_biome(json: unknown): string[] {
if (!is_object(json)) return ["biome must be an object"];
const problems: string[] = [];
const id = (value: unknown, field: string) => {
if (!(typeof value === "string" && ID_PATTERN.test(value))) {
problems.push(`${field} must be an id like "my_mod:thing"`);
}
};
id(json.id, "id");
if (json.season !== undefined && !SEASONS.includes(json.season as Season)) {
problems.push(`season must be one of ${SEASONS.join(", ")}`);
}
const surface = json.surface;
if (!is_object(surface)) {
problems.push("surface must be { top, filler, filler_depth }");
} else {
id(surface.top, "surface.top");
id(surface.filler, "surface.filler");
if (surface.underwater_top !== undefined) id(surface.underwater_top, "surface.underwater_top");
if (surface.underwater_filler !== undefined) id(surface.underwater_filler, "surface.underwater_filler");
const depth = surface.filler_depth;
if (!Number.isInteger(depth) || (depth as number) < 0 || (depth as number) > 32) {
problems.push("surface.filler_depth must be a whole number from 0 to 32");
}
if (surface.bare_cliffs !== undefined && typeof surface.bare_cliffs !== "boolean") {
problems.push("surface.bare_cliffs must be true or false");
}
}
if (json.colors !== undefined) {
if (!is_object(json.colors)) {
problems.push("colors must be { grass, foliage, water }");
} else {
for (const [key, value] of Object.entries(json.colors)) {
if (!["grass", "foliage", "water"].includes(key)) problems.push(`colors.${key} isn't a biome color`);
else if (!(typeof value === "string" && /^#[0-9a-fA-F]{6}$/.test(value))) {
problems.push(`colors.${key} must be a color like "#79c05a"`);
}
}
}
}
const trees = json.trees;
if (trees !== undefined) {
if (!is_object(trees)) {
problems.push("trees must be { chance, kinds }");
} else {
if (typeof trees.chance !== "number" || trees.chance < 0 || trees.chance > 1) {
problems.push("trees.chance must be a number from 0 to 1");
}
// which kinds and woods there are is up to the trees feature, bworld's checks them when it loads
if (
!Array.isArray(trees.kinds) || trees.kinds.length === 0 ||
!trees.kinds.every((kind) => typeof kind === "string")
) {
problems.push("trees.kinds must list at least one kind of tree");
}
if (trees.wood !== undefined) {
if (!is_object(trees.wood) || !Object.values(trees.wood).every((wood) => typeof wood === "string")) {
problems.push("trees.wood must be { <kind>: <wood> }");
}
}
}
}
return problems;
export function validate_biome(json: unknown): Problems {
return find_problems(biome_schema, json);
}
+222 -352
View File
@@ -4,7 +4,8 @@
// world generation as data: noises, density functions, noise settings (a generator) and biome sources, see
// docs/modding/worldgen/terrain.md. checked here, compiled by density.ts and generator.ts. the names follow
// minecraft's (density functions, the noise router, surface rules) where the idea is the same
import { ID_PATTERN, is_object, TAG_ID_PATTERN } from "../mod_data.ts";
import * as z from "zod";
import { find_problems, ID_PATTERN, is_object, type Problems, TAG_ID_PATTERN } from "../schema.ts";
// ids of worldgen data can have folders, like "bworld:overworld/erosion"
export const WORLDGEN_ID_PATTERN = TAG_ID_PATTERN;
@@ -142,376 +143,256 @@ export function new_refs(): WorldgenRefs {
return { noises: new Set(), functions: new Set(), blocks: new Set(), biomes: new Set(), biome_sources: new Set() };
}
const ARITHMETIC = ["add", "sub", "mul", "div", "min", "max"];
export const DENSITY_TYPES = [
"constant",
"x",
"y",
"z",
"noise",
...ARITHMETIC,
"abs",
"clamp",
"smoothstep",
"spline",
"range_choice",
"cache_2d",
];
// checking
const worldgen_id = z.string('must be an id like "my_mod:thing" or "my_mod:folder/thing"').regex(WORLDGEN_ID_PATTERN);
const block_id = z.string("must be a block's id").regex(ID_PATTERN);
const biome_id = z.string("must be a biome's id").regex(ID_PATTERN);
const noise_schema: z.ZodType<NoiseJson> = z.object({
id: worldgen_id,
seed_name: z.string().optional(),
wavelength: z.number().positive(),
amplitudes: z.array(z.number()).min(1).refine((amplitudes) => amplitudes.some((a) => a !== 0), "can't all be 0"),
dimensions: z.literal([2, 3]).optional(),
vertical_stretch: z.number().positive().optional(),
quantiles: z.union([
worldgen_id,
z.array(z.number()).min(2).refine((q) => q.every((value, i) => i === 0 || value > q[i - 1]), "must go up"),
], "must be at least 2 numbers going up, or a noise's id").optional(),
}).refine((noise) => noise.vertical_stretch === undefined || noise.dimensions === 3, {
path: ["vertical_stretch"],
message: "is only for 3d noises",
});
const RANGE_KEYS = ["min_inclusive", "min_exclusive", "max_inclusive", "max_exclusive"] as const;
export function validate_noise(json: unknown): string[] {
const problems: string[] = [];
if (!is_object(json)) return ["noise must be an object"];
worldgen_id(json.id, "id", problems);
if (json.seed_name !== undefined && typeof json.seed_name !== "string") problems.push("seed_name must be text");
if (!(typeof json.wavelength === "number" && json.wavelength > 0)) problems.push("wavelength must be above 0");
if (
!Array.isArray(json.amplitudes) || json.amplitudes.length === 0 ||
!json.amplitudes.every((a) => typeof a === "number" && Number.isFinite(a)) ||
json.amplitudes.every((a) => a === 0)
) {
problems.push("amplitudes must be a list of numbers, not all 0");
}
if (json.dimensions !== undefined && json.dimensions !== 2 && json.dimensions !== 3) {
problems.push("dimensions must be 2 or 3");
}
if (json.vertical_stretch !== undefined) {
if (json.dimensions !== 3) problems.push("vertical_stretch is only for 3d noises");
if (!(typeof json.vertical_stretch === "number" && json.vertical_stretch > 0)) {
problems.push("vertical_stretch must be above 0");
// a range's bounds, numbers or (in range_choice) density functions. a range needs at least one
function bounds<T extends z.ZodType>(bound: T) {
return {
min_inclusive: bound.optional(),
min_exclusive: bound.optional(),
max_inclusive: bound.optional(),
max_exclusive: bound.optional(),
};
}
const has_bound = (range: Partial<Record<typeof RANGE_KEYS[number], unknown>>) =>
RANGE_KEYS.some((key) => range[key] !== undefined);
const NEEDS_BOUND = `needs at least one of ${RANGE_KEYS.join(", ")}`;
const range = z.object(bounds(z.number())).refine(has_bound, NEEDS_BOUND);
// a density function, by itself or by its id
const density: z.ZodType<DensityJson> = z.lazy(() =>
z.union(
[z.number(), z.string("must be a density function's id").regex(WORLDGEN_ID_PATTERN), density_object],
'must be a number, a density function\'s id or { "type": ... }',
)
);
const spline: z.ZodType<SplineJson> = z.object({
coordinate: density,
points: z.array(z.object({
location: z.number(),
value: z.union([z.number(), z.lazy(() => spline)], "must be a number or a spline"),
derivative: z.number().optional(),
})).min(1).superRefine((points, ctx) => {
points.forEach((point, i) => {
if (i > 0 && point.location < points[i - 1].location) {
ctx.addIssue({ code: "custom", path: [i, "location"], message: "can't be below the point before's" });
}
});
}),
});
const density_object = z.discriminatedUnion("type", [
z.object({ type: z.literal("constant"), argument: z.number() }),
z.object({ type: z.literal(["x", "y", "z"]) }),
z.object({
type: z.literal("noise"),
noise: z.string("must be a noise's id").regex(WORLDGEN_ID_PATTERN),
even: z.boolean().optional(),
x: density.optional(),
y: density.optional(),
z: density.optional(),
}),
z.object({ type: z.literal(["add", "sub", "mul", "div", "min", "max"]), argument1: density, argument2: density }),
z.object({ type: z.literal(["abs", "cache_2d"]), argument: density }),
z.object({ type: z.literal("clamp"), input: density, min: z.number(), max: z.number() })
.refine(({ min, max }) => min <= max, { path: ["min"], message: "can't be above max" }),
z.object({ type: z.literal("smoothstep"), input: density, from: z.number(), to: z.number() })
.refine(({ from, to }) => from !== to, { path: ["to"], message: "must be different from from" }),
z.object({ type: z.literal("spline"), spline }),
z.object({
type: z.literal("range_choice"),
input: density,
...bounds(density),
when_in_range: density,
when_out_of_range: density,
}).refine(has_bound, NEEDS_BOUND),
]);
const density_function_schema: z.ZodType<DensityFunctionJson> = z.intersection(
z.object({ id: worldgen_id }),
density_object,
);
const surface_rule: z.ZodType<SurfaceRuleJson> = z.lazy(() =>
z.discriminatedUnion("type", [
z.object({ type: z.literal("sequence"), sequence: z.array(surface_rule) }),
z.object({ type: z.literal("condition"), if_true: surface_condition, then_run: surface_rule }),
z.object({ type: z.literal("block"), result_state: z.object({ Name: block_id }) }),
z.object({ type: z.literal("biome_surface"), part: z.enum(BIOME_SURFACE_PARTS) }),
])
);
const surface_condition: z.ZodType<SurfaceConditionJson> = z.lazy(() =>
z.discriminatedUnion("type", [
z.object({ type: z.literal("stone_depth"), offset: z.int() }),
z.object({ type: z.literal(["filler_depth", "surface_underwater", "steep", "bare_cliffs"]) }),
z.object({ type: z.literal("above_preliminary_surface"), offset: z.number().optional() }),
z.object({ type: z.literal("y_at_least"), function: density }),
z.object({ type: z.literal("biome"), biome_is: z.array(biome_id) }),
z.object({ type: z.literal("not"), invert: surface_condition }),
])
);
const cell_height = z.literal([1, 2, 4, 8, 16, 32]);
const noise_settings_schema: z.ZodType<NoiseSettingsJson> = z.object({
id: worldgen_id,
sea_level: z.int().min(0).max(256),
default_block: block_id,
cell_width: z.literal([1, 2, 4, 8, 16]),
terrain: z.object({ density, cell_height }),
caves: z.object({ density, cell_height }),
preliminary_surface: density,
climate: z.record(
z.string("isn't a name a climate value can have: lowercase letters and _, but not surface or steep")
.regex(/^[a-z_]+$/).refine((name) => name !== "surface" && name !== "steep"),
density,
),
steep: z.number().min(0),
biome_source: z.string("must be a biome source's id").regex(WORLDGEN_ID_PATTERN),
fluids: z.array(z.object({
block: block_id,
below: z.int(),
where: z.union([
z.literal("open_sky"),
z.object({ function: density, ...bounds(z.number()) }).refine(has_bound, NEEDS_BOUND),
], 'must be "open_sky" or { "function", <range> }'),
})),
surface_rule,
});
const biome_source_schema: z.ZodType<BiomeSourceJson> = z.object({
id: worldgen_id,
extends: z.string("must be a biome source's id").regex(WORLDGEN_ID_PATTERN).optional(),
rules: z.array(z.object({
id: worldgen_id,
before: worldgen_id.optional(),
after: worldgen_id.optional(),
// steep is true or false, any other name is a range of that climate value
when: z.object({ steep: z.boolean().optional() }).catchall(range).optional(),
biome: biome_id,
})),
}).superRefine((source, ctx) => {
// a rule added to another biome source goes before or after one of its rules
source.rules.forEach((rule, i) => {
const placed = [rule.before, rule.after].filter((id) => id !== undefined).length;
if (source.extends !== undefined && placed !== 1) {
ctx.addIssue({ code: "custom", path: ["rules", i], message: "needs before or after, one of them" });
}
}
const quantiles = json.quantiles;
if (quantiles !== undefined && typeof quantiles !== "string") {
if (
!Array.isArray(quantiles) || quantiles.length < 2 ||
!quantiles.every((q, i) => typeof q === "number" && (i === 0 || q > quantiles[i - 1]))
) {
problems.push("quantiles must be at least 2 numbers going up, or a noise's id");
if (source.extends === undefined && placed > 0) {
ctx.addIssue({
code: "custom",
path: ["rules", i],
message: "can't have before or after, they're for rules added to another biome source with extends",
});
}
} else if (typeof quantiles === "string") {
worldgen_id(quantiles, "quantiles", problems);
}
return problems;
});
});
export function validate_noise(json: unknown): Problems {
return find_problems(noise_schema, json);
}
// the noises a noise file refers to: the one it takes its quantiles from
export function validate_density_function(json: unknown): Problems {
return find_problems(density_function_schema, json);
}
export function validate_noise_settings(json: unknown): Problems {
return find_problems(noise_settings_schema, json);
}
export function validate_biome_source(json: unknown): Problems {
return find_problems(biome_source_schema, json);
}
// what worldgen data that passed its checks refers to
export function noise_refs(json: NoiseJson, refs: WorldgenRefs) {
if (typeof json.quantiles === "string") refs.noises.add(json.quantiles);
}
export function validate_density_function(json: unknown): string[] {
if (!is_object(json)) return ["density_function must be an object"];
const problems: string[] = [];
worldgen_id(json.id, "id", problems);
const { id: _, ...fn } = json;
check_density(fn, "", new_refs(), problems);
return problems;
}
export function density_function_refs(json: DensityFunctionJson, refs: WorldgenRefs) {
const { id: _, ...fn } = json;
check_density(fn, "", refs, []);
density_refs(fn, refs);
}
// checks a density function, adding what it refers to to refs. at is where it is, for messages
export function check_density(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) {
const where = at ? `${at}: ` : "";
if (typeof json === "number") {
if (!Number.isFinite(json)) problems.push(`${where}must be a finite number`);
return;
}
function density_refs(json: DensityJson, refs: WorldgenRefs) {
if (typeof json === "number") return;
if (typeof json === "string") {
if (WORLDGEN_ID_PATTERN.test(json)) refs.functions.add(json);
else problems.push(`${where}"${json}" isn't a density function's id`);
refs.functions.add(json);
return;
}
if (!is_object(json) || typeof json.type !== "string") {
problems.push(`${where}must be a number, a density function's id or { "type": ... }`);
return;
}
const field = (name: string) => check_density(json[name], at ? `${at}.${name}` : name, refs, problems);
const number = (name: string) => {
if (typeof json[name] !== "number" || !Number.isFinite(json[name])) {
problems.push(`${where}${name} must be a number`);
for (const [key, value] of Object.entries(json)) {
if (key === "noise") refs.noises.add(value as string);
else if (key === "spline") spline_refs(value as SplineJson, refs);
// the other fields that are text or objects are density functions, the rest numbers and true or false
else if (key !== "type" && (typeof value === "string" || is_object(value))) {
density_refs(value as DensityJson, refs);
}
};
switch (json.type) {
case "constant":
number("argument");
break;
case "x":
case "y":
case "z":
break;
case "noise":
if (typeof json.noise === "string" && WORLDGEN_ID_PATTERN.test(json.noise)) refs.noises.add(json.noise);
else problems.push(`${where}noise must be a noise's id`);
if (json.even !== undefined && typeof json.even !== "boolean") {
problems.push(`${where}even must be true or false`);
}
for (const axis of ["x", "y", "z"]) if (json[axis] !== undefined) field(axis);
break;
case "abs":
case "cache_2d":
field("argument");
break;
case "clamp":
field("input");
number("min");
number("max");
if ((json.min as number) > (json.max as number)) problems.push(`${where}min is above max`);
break;
case "smoothstep":
field("input");
number("from");
number("to");
if (json.from === json.to) problems.push(`${where}from and to must be different`);
break;
case "spline":
check_spline(json.spline, at ? `${at}.spline` : "spline", refs, problems);
break;
case "range_choice":
field("input");
if (!RANGE_KEYS.some((key) => json[key] !== undefined)) problems.push(`${where}needs at least one bound`);
for (const key of RANGE_KEYS) if (json[key] !== undefined) field(key);
field("when_in_range");
field("when_out_of_range");
break;
default:
if (ARITHMETIC.includes(json.type)) {
field("argument1");
field("argument2");
} else {
problems.push(`${where}type ${json.type} isn't one of ${DENSITY_TYPES.join(", ")}`);
}
}
}
function check_spline(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) {
if (!is_object(json) || !Array.isArray(json.points) || json.points.length === 0) {
problems.push(`${at}: must be { "coordinate": ..., "points": [ ... ] }`);
return;
}
check_density(json.coordinate, `${at}.coordinate`, refs, problems);
let last = -Infinity;
json.points.forEach((point: unknown, i: number) => {
const here = `${at}.points[${i}]`;
if (!is_object(point) || typeof point.location !== "number") {
problems.push(`${here}: must be { "location", "value", "derivative" }`);
return;
}
if (point.location < last) problems.push(`${here}: locations must go up`);
last = point.location;
if (typeof point.value !== "number") check_spline(point.value, `${here}.value`, refs, problems);
if (point.derivative !== undefined && typeof point.derivative !== "number") {
problems.push(`${here}: derivative must be a number`);
}
});
function spline_refs(spline: SplineJson, refs: WorldgenRefs) {
density_refs(spline.coordinate, refs);
for (const point of spline.points) if (typeof point.value !== "number") spline_refs(point.value, refs);
}
export function validate_noise_settings(json: unknown): string[] {
if (!is_object(json)) return ["noise_settings must be an object"];
const problems: string[] = [];
noise_settings_refs(json, new_refs(), problems);
return problems;
export function noise_settings_refs(json: NoiseSettingsJson, refs: WorldgenRefs) {
refs.blocks.add(json.default_block);
const { terrain, caves, preliminary_surface, climate } = json;
for (const fn of [terrain.density, caves.density, preliminary_surface, ...Object.values(climate)]) {
density_refs(fn, refs);
}
refs.biome_sources.add(json.biome_source);
for (const fluid of json.fluids) {
refs.blocks.add(fluid.block);
if (fluid.where !== "open_sky") density_refs(fluid.where.function, refs);
}
surface_rule_refs(json.surface_rule, refs);
}
export function noise_settings_refs(json: Record<string, unknown>, refs: WorldgenRefs, problems: string[] = []) {
worldgen_id(json.id, "id", problems);
const whole = (name: string, min: number, max: number) => {
const value = json[name];
if (!(Number.isInteger(value) && (value as number) >= min && (value as number) <= max)) {
problems.push(`${name} must be a whole number from ${min} to ${max}`);
}
};
whole("sea_level", 0, 256);
block_id(json.default_block, "default_block", refs, problems);
if (![1, 2, 4, 8, 16].includes(json.cell_width as number)) problems.push("cell_width must be 1, 2, 4, 8 or 16");
for (const part of ["terrain", "caves"]) {
const value = json[part];
if (!is_object(value)) {
problems.push(`${part} must be { "density", "cell_height" }`);
continue;
}
check_density(value.density, `${part}.density`, refs, problems);
if (![1, 2, 4, 8, 16, 32].includes(value.cell_height as number)) {
problems.push(`${part}.cell_height must be 1, 2, 4, 8, 16 or 32`);
}
function surface_rule_refs(rule: SurfaceRuleJson, refs: WorldgenRefs) {
if (rule.type === "sequence") { for (const inner of rule.sequence) surface_rule_refs(inner, refs); }
if (rule.type === "condition") {
surface_condition_refs(rule.if_true, refs);
surface_rule_refs(rule.then_run, refs);
}
check_density(json.preliminary_surface, "preliminary_surface", refs, problems);
if (!is_object(json.climate)) {
problems.push("climate must be { <name>: <density function> }");
} else {
for (const [name, value] of Object.entries(json.climate)) {
if (!/^[a-z_]+$/.test(name) || name === "surface" || name === "steep") {
problems.push(`climate.${name}: names are lowercase letters and _, and not surface or steep`);
}
check_density(value, `climate.${name}`, refs, problems);
}
}
if (!(typeof json.steep === "number" && json.steep >= 0)) problems.push("steep must be a number, 0 or more");
if (typeof json.biome_source === "string" && WORLDGEN_ID_PATTERN.test(json.biome_source)) {
refs.biome_sources.add(json.biome_source);
} else {
problems.push("biome_source must be a biome source's id");
}
if (!Array.isArray(json.fluids)) {
problems.push("fluids must be a list");
} else {
json.fluids.forEach((fluid: unknown, i: number) => {
const at = `fluids[${i}]`;
if (!is_object(fluid)) {
problems.push(`${at}: must be { "block", "below", "where" }`);
return;
}
block_id(fluid.block, `${at}.block`, refs, problems);
if (!Number.isInteger(fluid.below)) problems.push(`${at}.below must be a whole number`);
if (fluid.where !== "open_sky") {
if (!is_object(fluid.where)) {
problems.push(`${at}.where must be "open_sky" or { "function", <range> }`);
} else {
check_density(fluid.where.function, `${at}.where.function`, refs, problems);
check_range(fluid.where, `${at}.where`, problems);
}
}
});
}
check_surface_rule(json.surface_rule, "surface_rule", refs, problems);
if (rule.type === "block") refs.blocks.add(rule.result_state.Name);
}
function check_surface_rule(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) {
if (!is_object(json)) {
problems.push(`${at}: must be a rule`);
return;
}
switch (json.type) {
case "sequence":
if (!Array.isArray(json.sequence)) problems.push(`${at}.sequence must be a list of rules`);
else json.sequence.forEach((rule, i) => check_surface_rule(rule, `${at}.sequence[${i}]`, refs, problems));
break;
case "condition":
check_surface_condition(json.if_true, `${at}.if_true`, refs, problems);
check_surface_rule(json.then_run, `${at}.then_run`, refs, problems);
break;
case "block":
if (!is_object(json.result_state)) problems.push(`${at}.result_state must be { "Name": <block> }`);
else block_id(json.result_state.Name, `${at}.result_state.Name`, refs, problems);
break;
case "biome_surface":
if (!BIOME_SURFACE_PARTS.includes(json.part as BiomeSurfacePart)) {
problems.push(`${at}.part must be one of ${BIOME_SURFACE_PARTS.join(", ")}`);
}
break;
default:
problems.push(`${at}: type must be sequence, condition, block or biome_surface`);
}
function surface_condition_refs(condition: SurfaceConditionJson, refs: WorldgenRefs) {
if (condition.type === "y_at_least") density_refs(condition.function, refs);
if (condition.type === "biome") { for (const biome of condition.biome_is) refs.biomes.add(biome); }
if (condition.type === "not") surface_condition_refs(condition.invert, refs);
}
function check_surface_condition(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) {
if (!is_object(json)) {
problems.push(`${at}: must be a condition`);
return;
}
switch (json.type) {
case "stone_depth":
if (!Number.isInteger(json.offset)) problems.push(`${at}.offset must be a whole number`);
break;
case "above_preliminary_surface":
if (json.offset !== undefined && typeof json.offset !== "number") {
problems.push(`${at}.offset must be a number`);
}
break;
case "filler_depth":
case "surface_underwater":
case "steep":
case "bare_cliffs":
break;
case "y_at_least":
check_density(json.function, `${at}.function`, refs, problems);
break;
case "biome":
if (!Array.isArray(json.biome_is) || !json.biome_is.every((b) => typeof b === "string")) {
problems.push(`${at}.biome_is must be a list of biome ids`);
} else {
for (const biome of json.biome_is) refs.biomes.add(biome);
}
break;
case "not":
check_surface_condition(json.invert, `${at}.invert`, refs, problems);
break;
default:
problems.push(
`${at}: type must be stone_depth, filler_depth, above_preliminary_surface, surface_underwater, steep, ` +
`bare_cliffs, y_at_least, biome or not`,
);
}
}
export function validate_biome_source(json: unknown): string[] {
if (!is_object(json)) return ["biome_source must be an object"];
const problems: string[] = [];
biome_source_refs(json, new_refs(), problems);
return problems;
}
export function biome_source_refs(json: Record<string, unknown>, refs: WorldgenRefs, problems: string[] = []) {
worldgen_id(json.id, "id", problems);
if (json.extends !== undefined) {
if (typeof json.extends === "string" && WORLDGEN_ID_PATTERN.test(json.extends)) {
refs.biome_sources.add(json.extends);
} else problems.push("extends must be a biome source's id");
}
if (!Array.isArray(json.rules)) {
problems.push("rules must be a list");
return;
}
json.rules.forEach((rule: unknown, i: number) => {
const at = `rules[${i}]`;
if (!is_object(rule)) {
problems.push(`${at}: must be { "id", "when", "biome" }`);
return;
}
worldgen_id(rule.id, `${at}.id`, problems);
const placed = [rule.before, rule.after].filter((id) => id !== undefined);
if (json.extends !== undefined && placed.length !== 1) {
problems.push(`${at}: a rule added to another biome source needs before or after, one of them`);
}
if (json.extends === undefined && placed.length > 0) {
problems.push(`${at}: before and after are for rules added to another biome source, with extends`);
}
for (const id of placed) worldgen_id(id, `${at}.before/after`, problems);
if (typeof rule.biome === "string" && ID_PATTERN.test(rule.biome)) refs.biomes.add(rule.biome);
else problems.push(`${at}.biome must be a biome's id`);
if (rule.when !== undefined) {
if (!is_object(rule.when)) {
problems.push(`${at}.when must be { <climate value>: <range>, "steep": true or false }`);
} else {
for (const [name, condition] of Object.entries(rule.when)) {
if (name === "steep") {
if (typeof condition !== "boolean") problems.push(`${at}.when.steep must be true or false`);
} else {
check_range(condition, `${at}.when.${name}`, problems);
}
}
}
}
});
}
// a range of numbers, with at least one bound
function check_range(json: unknown, at: string, problems: string[]) {
if (!is_object(json)) {
problems.push(`${at} must be a range like { "min_inclusive": 0 }`);
return;
}
let bounds = 0;
for (const key of RANGE_KEYS) {
if (json[key] === undefined) continue;
bounds++;
if (typeof json[key] !== "number") problems.push(`${at}.${key} must be a number`);
}
if (bounds === 0) problems.push(`${at} needs at least one of ${RANGE_KEYS.join(", ")}`);
export function biome_source_refs(json: BiomeSourceJson, refs: WorldgenRefs) {
if (json.extends !== undefined) refs.biome_sources.add(json.extends);
for (const rule of json.rules) refs.biomes.add(rule.biome);
}
// a test of whether a value is in the range, with only the bounds it has: value >= min, value < max
@@ -529,14 +410,3 @@ export function range_test(range: RangeJson): (value: number) => boolean {
}
return (value) => tests.every((test) => test(value));
}
function worldgen_id(value: unknown, field: string, problems: string[]) {
if (!(typeof value === "string" && WORLDGEN_ID_PATTERN.test(value))) {
problems.push(`${field} must be an id like "my_mod:thing" or "my_mod:folder/thing"`);
}
}
function block_id(value: unknown, field: string, refs: WorldgenRefs, problems: string[]) {
if (typeof value === "string" && ID_PATTERN.test(value)) refs.blocks.add(value);
else problems.push(`${field} must be a block's id`);
}
+147 -206
View File
@@ -7,7 +7,18 @@
import { EverythingRegistry } from "../everything_registry.ts";
import type { BlockRegistry } from "../everything_registry.ts";
import { CHUNK_HEIGHT, CHUNK_SIZE } from "../constants.ts";
import { ID_PATTERN, is_object, TAG_ID_PATTERN } from "../mod_data.ts";
import * as z from "zod";
import {
add_problems,
by_kind,
find_problems,
id_or_tag,
ID_PATTERN,
is_object,
json_object,
type Problems,
TAG_ID_PATTERN,
} from "../schema.ts";
import { list_matches } from "../tags.ts";
import { can_stand_on } from "../utils.ts";
import { AIR_ID } from "../protocol.ts";
@@ -66,56 +77,108 @@ export interface FeatureRefs {
custom: Set<string>;
}
export function validate_feature(json: unknown): string[] {
const problems: string[] = [];
feature_refs(json, { blocks: new Set(), biomes: new Set(), custom: new Set() }, problems);
return problems;
// a built in name, with its namespace or without, see builtin_name
const builtin = (...names: string[]) => z.literal(names.flatMap((name) => [name, `minecraft:${name}`]));
const block_id = z.string("must be a block's id").regex(ID_PATTERN);
const biome_id = z.string("must be a biome's id").regex(ID_PATTERN);
// a block, see state_id
const block_state_schema = z.union(
[block_id, z.object({ state: z.object({ Name: block_id }) }), z.object({ Name: block_id })],
'must be a block\'s id or { "type": "simple_state_provider", "state": { "Name": ... } }',
);
// a whole number, see int_provider
const int_provider_schema: z.ZodType = z.lazy(() =>
z.union([
z.int(),
z.discriminatedUnion("type", [
z.object({ type: builtin("constant"), value: z.int() }),
z.object({ type: builtin("uniform"), min_inclusive: z.int(), max_inclusive: z.int() }).refine(
({ min_inclusive, max_inclusive }) => min_inclusive <= max_inclusive,
{ path: ["min_inclusive"], message: "can't be above max_inclusive" },
),
z.object({
type: builtin("weighted_list"),
distribution: z.array(z.object({ data: int_provider_schema, weight: z.int().min(1) })).min(1),
}),
], "must be constant, uniform or weighted_list"),
], 'must be a whole number or { "type": "uniform", ... }')
);
// a y, see anchor
const anchor_schema = z.union([
z.strictObject({ absolute: z.int() }),
z.strictObject({ above_bottom: z.int() }),
z.strictObject({ below_top: z.int() }),
], 'must be one of { "absolute": y }, { "above_bottom": n } or { "below_top": n }');
// see height_provider
const height_schema = z.union([
anchor_schema,
z.discriminatedUnion("type", [
z.object({ type: builtin("constant"), value: anchor_schema }),
z.object({ type: builtin("uniform"), min_inclusive: anchor_schema, max_inclusive: anchor_schema }),
], "must be constant or uniform"),
], 'must be a height, like { "absolute": 10 } or { "type": "uniform", ... }');
// see block_predicate. offset moves where it looks
const predicate_base = z.object({
offset: z.tuple([z.int(), z.int(), z.int()], "must be [x, y, z], whole numbers").optional(),
});
const block_predicate_schema: z.ZodType = z.lazy(() =>
z.discriminatedUnion("type", [
predicate_base.extend({
type: builtin("matching_blocks"),
blocks: z.union([id_or_tag, z.array(id_or_tag)], "must be a block, a #tag, or a list of them"),
}),
predicate_base.extend({ type: builtin("solid", "replaceable", "true") }),
predicate_base.extend({ type: builtin("would_survive"), state: block_state_schema }),
predicate_base.extend({ type: builtin("not"), predicate: block_predicate_schema }),
predicate_base.extend({ type: builtin("all_of", "any_of"), predicates: z.array(block_predicate_schema) }),
], "must be matching_blocks, solid, replaceable, would_survive, not, all_of, any_of or true")
);
// a mod's own modifier is checked by the worldgen script that registers it
const placement_modifier = by_kind<PlacementJson>("type", (type) => {
const name = builtin_name(type);
if (name === undefined) return json_object;
return Object.hasOwn(MODIFIERS, name) ? MODIFIERS[name].schema : undefined;
}, "isn't a built in placement modifier");
const feature_schema: z.ZodType<FeatureJson> = z.object({
id: z.string('must be an id like "my_mod:thing" or "my_mod:folder/thing"').regex(TAG_ID_PATTERN),
type: z.string(),
config: json_object.optional(),
placement: z.array(placement_modifier).optional(),
biomes: z.union([biome_id, z.array(biome_id)], "must be a biome's id or a list of them").optional(),
step: z.enum(FEATURE_STEPS).optional(),
}).superRefine((feature, ctx) => {
// a built in type's config. a mod's own type is checked by the worldgen script that registers it, like modifiers
const name = builtin_name(feature.type);
if (name === undefined) return;
if (!Object.hasOwn(FEATURE_TYPES, name)) {
return ctx.addIssue({ code: "custom", path: ["type"], message: `${feature.type} isn't built in` });
}
add_problems(ctx, FEATURE_TYPES[name].schema, feature.config ?? {}, ["config"]);
});
export function validate_feature(json: unknown): Problems {
return find_problems(feature_schema, json);
}
export function feature_refs(json: unknown, refs: FeatureRefs, problems: string[] = []) {
if (!is_object(json)) {
problems.push("feature must be an object");
return;
}
if (!(typeof json.id === "string" && TAG_ID_PATTERN.test(json.id))) {
problems.push(`id must be an id like "my_mod:thing" or "my_mod:folder/thing"`);
}
if (json.step !== undefined && !FEATURE_STEPS.includes(json.step as FeatureStep)) {
problems.push(`step must be one of ${FEATURE_STEPS.join(", ")}`);
}
if (json.biomes !== undefined) {
const biomes = typeof json.biomes === "string" ? [json.biomes] : json.biomes;
if (!Array.isArray(biomes) || !biomes.every((b) => typeof b === "string" && ID_PATTERN.test(b))) {
problems.push("biomes must be a biome's id or a list of them");
} else {
for (const biome of biomes) refs.biomes.add(biome);
}
}
if (json.config !== undefined && !is_object(json.config)) problems.push("config must be an object");
if (typeof json.type !== "string") {
problems.push("type must be a feature type");
} else {
const name = builtin_name(json.type);
if (name === undefined) refs.custom.add(json.type);
else if (!(name in FEATURE_TYPES)) problems.push(`type ${json.type} isn't built in`);
else FEATURE_TYPES[name].check((json.config ?? {}) as Record<string, unknown>, "config", refs, problems);
}
if (json.placement !== undefined) {
if (!Array.isArray(json.placement)) {
problems.push("placement must be a list of placement modifiers");
return;
}
json.placement.forEach((modifier: unknown, i: number) => {
const at = `placement[${i}]`;
if (!is_object(modifier) || typeof modifier.type !== "string") {
problems.push(`${at}: must be { "type": ... }`);
return;
}
const name = builtin_name(modifier.type);
if (name === undefined) refs.custom.add(modifier.type);
else if (!(name in MODIFIERS)) problems.push(`${at}: ${modifier.type} isn't a built in placement modifier`);
else MODIFIERS[name].check(modifier, at, refs, problems);
});
// what a feature that passed its checks uses
export function feature_refs(json: FeatureJson, refs: FeatureRefs) {
for (const biome of [json.biomes ?? []].flat()) refs.biomes.add(biome);
const type = builtin_name(json.type);
if (type === undefined) refs.custom.add(json.type);
else FEATURE_TYPES[type].refs?.(json.config ?? {}, refs);
for (const modifier of json.placement ?? []) {
const name = builtin_name(modifier.type);
if (name === undefined) refs.custom.add(modifier.type);
else MODIFIERS[name].refs?.(modifier, refs);
}
}
@@ -183,15 +246,19 @@ export function compile_feature(
// built in feature types
interface Builtin<T> {
check(json: Record<string, unknown>, at: string, refs: FeatureRefs, problems: string[]): void;
// its json: a feature type's config, or the placement modifier
schema: z.ZodType;
// what it uses, when it uses something
refs?(json: Record<string, unknown>, refs: FeatureRefs): void;
compile(json: Record<string, unknown>): T;
}
const FEATURE_TYPES: Record<string, Builtin<(chunk: FeatureChunk, origin: Position) => boolean>> = {
// one block, where it can stand
simple_block: {
check(json, at, refs, problems) {
check_state(json.to_place, `${at}.to_place`, refs, problems);
schema: z.object({ to_place: block_state_schema }),
refs(json, refs) {
refs.blocks.add(state_id(json.to_place));
},
compile(json) {
const id = state_id(json.to_place);
@@ -204,29 +271,15 @@ const FEATURE_TYPES: Record<string, Builtin<(chunk: FeatureChunk, origin: Positi
},
// layers of blocks stacked up (or down) from the origin, cut short where allowed_placement doesn't hold
block_column: {
check(json, at, refs, problems) {
if (!Array.isArray(json.layers) || json.layers.length === 0) {
problems.push(`${at}.layers must be a list of { "height", "provider" }`);
} else {
json.layers.forEach((layer: unknown, i: number) => {
const here = `${at}.layers[${i}]`;
if (!is_object(layer)) {
problems.push(`${here} must be { "height", "provider" }`);
return;
}
check_int(layer.height, `${here}.height`, problems);
check_state(layer.provider, `${here}.provider`, refs, problems);
});
}
if (json.direction !== undefined && json.direction !== "up" && json.direction !== "down") {
problems.push(`${at}.direction must be "up" or "down"`);
}
if (json.allowed_placement !== undefined) {
check_predicate(json.allowed_placement, `${at}.allowed_placement`, refs, problems);
}
if (json.prioritize_tip !== undefined && typeof json.prioritize_tip !== "boolean") {
problems.push(`${at}.prioritize_tip must be true or false`);
}
schema: z.object({
layers: z.array(z.object({ height: int_provider_schema, provider: block_state_schema })).min(1),
direction: z.enum(["up", "down"]).optional(),
allowed_placement: block_predicate_schema.optional(),
prioritize_tip: z.boolean().optional(),
}),
refs(json, refs) {
for (const layer of json.layers as { provider: unknown }[]) refs.blocks.add(state_id(layer.provider));
if (json.allowed_placement !== undefined) predicate_refs(json.allowed_placement, refs);
},
compile(json) {
const layers = (json.layers as { height: unknown; provider: unknown }[]).map((layer) => ({
@@ -259,14 +312,12 @@ const FEATURE_TYPES: Record<string, Builtin<(chunk: FeatureChunk, origin: Positi
type Modifier = (chunk: FeatureChunk, positions: Position[]) => Position[];
const HEIGHTMAPS = ["WORLD_SURFACE_WG", "WORLD_SURFACE", "MOTION_BLOCKING", "OCEAN_FLOOR_WG", "OCEAN_FLOOR"];
const HEIGHTMAPS = ["WORLD_SURFACE_WG", "WORLD_SURFACE", "MOTION_BLOCKING", "OCEAN_FLOOR_WG", "OCEAN_FLOOR"] as const;
const MODIFIERS: Record<string, Builtin<Modifier>> = {
// each position becomes count of them
count: {
check(json, at, _refs, problems) {
check_int(json.count, `${at}.count`, problems);
},
schema: z.object({ count: int_provider_schema }),
compile(json) {
const count = int_provider(json.count);
return (chunk, positions) =>
@@ -275,11 +326,7 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
},
// one in chance positions are kept
rarity_filter: {
check(json, at, _refs, problems) {
if (!(Number.isInteger(json.chance) && (json.chance as number) >= 1)) {
problems.push(`${at}.chance must be a whole number, 1 or more`);
}
},
schema: z.object({ chance: z.int().min(1) }),
compile(json) {
const chance = json.chance as number;
return (chunk, positions) => positions.filter(() => chunk.rng.next() < 1 / chance);
@@ -287,7 +334,7 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
},
// somewhere random in the chunk, across
in_square: {
check() {},
schema: z.object({}),
compile() {
return (chunk, positions) =>
positions.map((p) => {
@@ -299,10 +346,7 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
},
// moved by up to xz_spread across and y_spread up or down
random_offset: {
check(json, at, _refs, problems) {
check_int(json.xz_spread ?? 0, `${at}.xz_spread`, problems);
check_int(json.y_spread ?? 0, `${at}.y_spread`, problems);
},
schema: z.object({ xz_spread: int_provider_schema.optional(), y_spread: int_provider_schema.optional() }),
compile(json) {
const xz = int_provider(json.xz_spread ?? 0);
const y = int_provider(json.y_spread ?? 0);
@@ -312,9 +356,7 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
},
// at a height
height_range: {
check(json, at, _refs, problems) {
check_height(json.height, `${at}.height`, problems);
},
schema: z.object({ height: height_schema }),
compile(json) {
const height = height_provider(json.height);
return (chunk, positions) => positions.map((p) => ({ x: p.x, y: height(chunk), z: p.z }));
@@ -323,11 +365,7 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
// on top of the column: WORLD_SURFACE on its highest block, OCEAN_FLOOR on its highest that isn't a liquid.
// positions outside the chunk are dropped
heightmap: {
check(json, at, _refs, problems) {
if (!HEIGHTMAPS.includes(json.heightmap as string)) {
problems.push(`${at}.heightmap must be one of ${HEIGHTMAPS.join(", ")}`);
}
},
schema: z.object({ heightmap: z.enum(HEIGHTMAPS) }),
compile(json) {
const floor = String(json.heightmap).startsWith("OCEAN_FLOOR");
return (chunk, positions) =>
@@ -341,8 +379,9 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
},
// where a block predicate holds
block_predicate_filter: {
check(json, at, refs, problems) {
check_predicate(json.predicate, `${at}.predicate`, refs, problems);
schema: z.object({ predicate: block_predicate_schema }),
refs(json, refs) {
predicate_refs(json.predicate, refs);
},
compile(json) {
const predicate = block_predicate(json.predicate);
@@ -359,44 +398,22 @@ function counts_for_heightmap(id: string | undefined, floor: boolean) {
// block predicates, like minecraft's
type Predicate = (chunk: FeatureChunk, x: number, y: number, z: number) => boolean;
const PREDICATES = ["matching_blocks", "solid", "replaceable", "would_survive", "not", "all_of", "any_of", "true"];
function check_predicate(json: unknown, at: string, refs: FeatureRefs, problems: string[]) {
if (!is_object(json) || typeof json.type !== "string") {
problems.push(`${at} must be a block predicate, { "type": ... }`);
return;
}
const name = builtin_name(json.type);
if (name === undefined || !PREDICATES.includes(name)) {
problems.push(`${at}: ${json.type} isn't one of ${PREDICATES.join(", ")}`);
return;
}
if (
json.offset !== undefined &&
!(Array.isArray(json.offset) && json.offset.length === 3 && json.offset.every(Number.isInteger))
) {
problems.push(`${at}.offset must be [x, y, z], whole numbers`);
}
switch (name) {
case "matching_blocks": {
const blocks = typeof json.blocks === "string" ? [json.blocks] : json.blocks;
if (!Array.isArray(blocks) || !blocks.every((b) => typeof b === "string")) {
problems.push(`${at}.blocks must be a block, a #tag, or a list of them`);
} else {
for (const block of blocks) refs.blocks.add(block);
}
// the blocks a predicate tests for
function predicate_refs(json: unknown, refs: FeatureRefs) {
const predicate = json as Record<string, unknown>;
switch (builtin_name(predicate.type as string)) {
case "matching_blocks":
for (const block of [predicate.blocks].flat()) refs.blocks.add(block as string);
break;
}
case "would_survive":
check_state(json.state, `${at}.state`, refs, problems);
refs.blocks.add(state_id(predicate.state));
break;
case "not":
check_predicate(json.predicate, `${at}.predicate`, refs, problems);
predicate_refs(predicate.predicate, refs);
break;
case "all_of":
case "any_of":
if (!Array.isArray(json.predicates)) problems.push(`${at}.predicates must be a list`);
else json.predicates.forEach((p, i) => check_predicate(p, `${at}.predicates[${i}]`, refs, problems));
for (const inner of predicate.predicates as unknown[]) predicate_refs(inner, refs);
}
}
@@ -456,18 +473,6 @@ function inside(chunk: FeatureChunk, x: number, z: number) {
// block states: a block's id, or minecraft's { "type": "simple_state_provider", "state": { "Name": id } }
function check_state(json: unknown, at: string, refs: FeatureRefs, problems: string[]) {
const id = typeof json === "string"
? json
: is_object(json) && is_object(json.state)
? json.state.Name
: is_object(json)
? json.Name
: undefined;
if (typeof id === "string" && ID_PATTERN.test(id)) refs.blocks.add(id);
else problems.push(`${at} must be a block's id or { "type": "simple_state_provider", "state": { "Name": ... } }`);
}
function state_id(json: unknown): string {
if (typeof json === "string") return json;
const object = json as Record<string, unknown>;
@@ -479,41 +484,6 @@ function state_id(json: unknown): string {
type IntProvider = (chunk: FeatureChunk) => number;
function check_int(json: unknown, at: string, problems: string[]) {
if (Number.isInteger(json)) return;
if (!is_object(json)) {
problems.push(`${at} must be a whole number or { "type": "uniform", ... }`);
return;
}
switch (builtin_name(String(json.type))) {
case "constant":
if (!Number.isInteger(json.value)) problems.push(`${at}.value must be a whole number`);
break;
case "uniform":
if (!Number.isInteger(json.min_inclusive) || !Number.isInteger(json.max_inclusive)) {
problems.push(`${at} needs whole numbers min_inclusive and max_inclusive`);
} else if ((json.min_inclusive as number) > (json.max_inclusive as number)) {
problems.push(`${at}: min_inclusive is above max_inclusive`);
}
break;
case "weighted_list":
if (!Array.isArray(json.distribution) || json.distribution.length === 0) {
problems.push(`${at}.distribution must be a list of { "data", "weight" }`);
} else {
json.distribution.forEach((entry: unknown, i: number) => {
if (!is_object(entry) || !(Number.isInteger(entry.weight) && (entry.weight as number) > 0)) {
problems.push(`${at}.distribution[${i}] needs a whole number weight above 0`);
} else {
check_int(entry.data, `${at}.distribution[${i}].data`, problems);
}
});
}
break;
default:
problems.push(`${at}.type must be constant, uniform or weighted_list`);
}
}
function int_provider(json: unknown): IntProvider {
if (typeof json === "number") return () => json;
const object = json as Record<string, unknown>;
@@ -548,35 +518,6 @@ function int_provider(json: unknown): IntProvider {
// heights: an anchor ({ "absolute" }, { "above_bottom" } or { "below_top" }), { "type": "constant", "value": anchor }
// or { "type": "uniform", "min_inclusive": anchor, "max_inclusive": anchor }
function check_height(json: unknown, at: string, problems: string[]) {
if (!is_object(json)) {
problems.push(`${at} must be a height, like { "absolute": 10 } or { "type": "uniform", ... }`);
return;
}
if (json.type === undefined) return check_anchor(json, at, problems);
switch (builtin_name(String(json.type))) {
case "constant":
check_anchor(json.value, `${at}.value`, problems);
break;
case "uniform":
check_anchor(json.min_inclusive, `${at}.min_inclusive`, problems);
check_anchor(json.max_inclusive, `${at}.max_inclusive`, problems);
break;
default:
problems.push(`${at}.type must be constant or uniform`);
}
}
function check_anchor(json: unknown, at: string, problems: string[]) {
const keys = ["absolute", "above_bottom", "below_top"];
if (
!is_object(json) || Object.keys(json).length !== 1 || !keys.includes(Object.keys(json)[0]) ||
!Number.isInteger(Object.values(json)[0])
) {
problems.push(`${at} must be one of { "absolute": y }, { "above_bottom": n } or { "below_top": n }`);
}
}
function anchor(json: unknown): number {
const object = json as Record<string, number>;
if (object.absolute !== undefined) return object.absolute;
+2 -1
View File
@@ -38,7 +38,8 @@
"@std/path": "jsr:@std/path@^1.0.0",
"fflate": "npm:fflate@^0.8.2",
"gl-matrix": "npm:gl-matrix@^3.4.4",
"marked": "npm:marked@^17.0.3"
"marked": "npm:marked@^17.0.3",
"zod": "jsr:@zod/zod@^4.6.7"
},
"desktop": {
"app": { "name": "bworld", "identifier": "com.bworld.game" },
Generated
+16 -1
View File
@@ -15,11 +15,13 @@
"jsr:@std/http@^1.0.23": "1.0.24",
"jsr:@std/internal@^1.0.10": "1.0.12",
"jsr:@std/internal@^1.0.12": "1.0.12",
"jsr:@std/internal@^1.0.14": "1.0.14",
"jsr:@std/media-types@^1.1.0": "1.1.0",
"jsr:@std/net@^1.0.6": "1.0.6",
"jsr:@std/path@1": "1.1.4",
"jsr:@std/path@1": "1.1.6",
"jsr:@std/path@^1.1.4": "1.1.4",
"jsr:@std/streams@^1.0.17": "1.1.2",
"jsr:@zod/zod@^4.6.7": "4.6.7",
"npm:fflate@~0.8.2": "0.8.3",
"npm:gl-matrix@^3.4.4": "3.4.4",
"npm:marked@^17.0.3": "17.0.3"
@@ -79,6 +81,9 @@
"@std/internal@1.0.12": {
"integrity": "972a634fd5bc34b242024402972cd5143eac68d8dffaca5eaa4dba30ce17b027"
},
"@std/internal@1.0.14": {
"integrity": "291516b3d4c35024d6ffbc0a9df5bf4c64116e05b50012cf846710152d2ffdf7"
},
"@std/media-types@1.1.0": {
"integrity": "c9d093f0c05c3512932b330e3cc1fe1d627b301db33a4c2c2185c02471d6eaa4"
},
@@ -91,8 +96,17 @@
"jsr:@std/internal@^1.0.12"
]
},
"@std/path@1.1.6": {
"integrity": "c68485c2a4dfbb5ae3cc74fae4e8c4e5d874cf8a8ed12927917235c758b46cbe",
"dependencies": [
"jsr:@std/internal@^1.0.14"
]
},
"@std/streams@1.1.2": {
"integrity": "0249bf9b78a999f57032ca4d8e7ccaa57579090242640b35ddc948fbb745d3af"
},
"@zod/zod@4.6.7": {
"integrity": "6706868ce1e1907362e1bf008e298e482723345f0ba4125c43e5b9fd7960b186"
}
},
"npm": {
@@ -119,6 +133,7 @@
"jsr:@std/fs@^1.0.23",
"jsr:@std/http@^1.0.23",
"jsr:@std/path@1",
"jsr:@zod/zod@^4.6.7",
"npm:fflate@~0.8.2",
"npm:gl-matrix@^3.4.4",
"npm:marked@^17.0.3"
+5 -3
View File
@@ -7,7 +7,8 @@ import { join } from "@std/path";
import { type Bmod, BMOD_EXTENSION, client_copy, read_bmod, write_bmod } from "$/common/bmod.ts";
import { check_references, load_order, type LoadedMod } from "$/common/mod_check.ts";
import type { ModListing } from "$/common/mod_loader.ts";
import { FORMAT_VERSION, is_object } from "$/common/mod_data.ts";
import { data_file, FORMAT_VERSION } from "$/common/mod_data.ts";
import { is_object, json_object } from "$/common/schema.ts";
import { sha256 } from "$/common/utils.ts";
export interface ServerMod {
@@ -118,11 +119,12 @@ function change_config(bmod: Bmod, config_dir: string, problems: string[]) {
problems.push(`${file}: isn't valid json: ${(e as Error).message}`);
return;
}
if (!is_object(json) || json.format_version !== FORMAT_VERSION || !is_object(json.config)) {
const config_file = data_file("config", json_object).safeParse(json);
if (!config_file.success) {
problems.push(`${file}: must be { "format_version": ${FORMAT_VERSION}, "config": { ... } }`);
return;
}
const changed = apply_config(bmod.data.config ?? {}, json.config);
const changed = apply_config(bmod.data.config ?? {}, config_file.data.config as Record<string, unknown>);
problems.push(...changed.problems.map((problem) => `${file}: ${problem}`));
bmod.data.config = changed.config;
}
+2 -2
View File
@@ -6,7 +6,7 @@ import { assert, assertEquals, assertRejects, assertStringIncludes, assertThrows
import { zipSync } from "fflate";
import { ATLAS_BORDER, atlas_layout, extrude_borders } from "$/client/atlas.ts";
import { MAX_TEXTURE_SIZE } from "$/common/constants.ts";
import { read_bmod, write_bmod } from "$/common/bmod.ts";
import { type Bmod, read_bmod, write_bmod } from "$/common/bmod.ts";
import { load_and_check } from "$/tools/check_mods.ts";
import { pack_mod } from "$/tools/pack_mod.ts";
import { create_mod } from "$/tools/new_mod.ts";
@@ -417,7 +417,7 @@ Deno.test({
// write_bmod without anything optional still makes a file read_bmod takes
Deno.test("a mod with only data packs and reads", () => {
const bmod = {
const bmod: Bmod = {
manifest: { format_version: 1, id: "tiny", name: "Tiny", version: "1.0.0" },
data: {
blocks: [],
+6 -6
View File
@@ -61,16 +61,16 @@ Deno.test("a liquid's still texture is its top and bottom, the flowing one its s
Deno.test("check-mods catches liquids that can't work", () => {
assertEquals(validate_block(OIL), []);
const problems = (json: Record<string, unknown>) => validate_block({ ...OIL, ...json });
assertEquals(problems({ liquid: { range: 8 } }), ["liquid.range must be a whole number from 1 to 7"]);
assertEquals(problems({ liquid: { range: 8 } }), ["liquid.range must be at most 7"]);
assertEquals(problems({ liquid: true }), ["liquid must be { range, ticks, renewable }, or {}"]);
assertEquals(problems({ liquid: { ticks: 0 } }), ["liquid.ticks must be a whole number of 1 or more"]);
assertEquals(problems({ liquid: { speed: 2 } }), ["liquid.speed isn't a liquid property"]);
assertEquals(problems({ liquid: { ticks: 0 } }), ["liquid.ticks must be 1 or more"]);
assertEquals(problems({ liquid: { speed: 2 } }), ['liquid can\'t have "speed"']);
assertEquals(problems({ textures: { top: "a:b" } }), [
"a liquid's textures must be a texture id or { still, flowing }",
"textures must be a texture id or { still, flowing } for a liquid",
]);
assertEquals(problems({ model: "engine:cross" }), ["a liquid can't have model, the engine draws it"]);
assertEquals(problems({ model: "engine:cross" }), ["model isn't for liquids, the engine draws them"]);
assertEquals(problems({ states: [{ name: "level", bits: 2, default: 0 }] }), [
'a liquid gets a "level" state of its own',
`states can't have "level", a liquid gets that state of its own`,
]);
});
+12 -11
View File
@@ -26,23 +26,24 @@ Deno.test("a bedrock geo.json becomes an entity model with only what the engine
// per face uvs and parents that come later aren't supported
const per_face = { origin: [0, 0, 0], size: [1, 1, 1], uv: { north: { uv: [0, 0], uv_size: [1, 1] } } };
const bad = entity_model_from_geo({
"minecraft:geometry": [{
description: { texture_width: 16, texture_height: 16 },
bones: [{ name: "leg", parent: "body", cubes: [per_face] }, { name: "body" }],
}],
}, "a:b");
assertEquals(bad.model, undefined);
assert(bad.problems.some((p) => p.includes("parent body must be a bone before it")), String(bad.problems));
assert(bad.problems.some((p) => p.includes("per face uvs aren't supported")), String(bad.problems));
const geo_problems = (bones: unknown[]) => {
const geometry = { description: { texture_width: 16, texture_height: 16 }, bones };
const { model, problems } = entity_model_from_geo({ "minecraft:geometry": [geometry] }, "a:b");
assertEquals(model, undefined);
return problems;
};
const late_parent = geo_problems([{ name: "leg", parent: "body" }, { name: "body" }]);
assert(late_parent.some((p) => p.includes("parent body must be a bone before it")), String(late_parent));
const per_face_problems = geo_problems([{ name: "leg", cubes: [per_face] }]);
assert(per_face_problems.some((p) => p.includes("per face uvs aren't supported")), String(per_face_problems));
assertEquals(entity_model_from_geo({ format_version: "1.12.0" }, "a:b").model, undefined);
});
Deno.test("an entity needs a texture and a size", () => {
assertEquals(validate_entity({ id: "a:b", model: "a:b", texture: "a:b", width: 0.5, height: 1 }), []);
assertEquals(validate_entity({ id: "a:b", model: "a:b", texture: "a:b", width: 0, height: 1, max_health: -1 }), [
"width must be a number of blocks above 0, at most 16",
"max_health must be a number, 0 or more",
"width must be above 0",
"max_health must be 0 or more",
]);
});
+3 -3
View File
@@ -142,10 +142,10 @@ Deno.test("check-mods finds broken mods", async () => {
has(report.errors, "block broken:x is also defined by broken, broken");
has(report.errors, "items/bad.json: isn't valid json");
has(report.errors, "model broken:no_such_model doesn't exist");
has(report.errors, `"size=1" must be a state of this block`);
has(report.errors, `variants["size=1"] names size, which isn't one of this block's states`);
has(report.errors, "elements[0].from must be [x, y, z]");
has(report.errors, `elements[0].faces: "up" isn't one of`);
has(report.errors, `pattern uses "B" but key doesn't define it`);
has(report.errors, `elements[0].faces can't have "up"`);
has(report.errors, `key needs "B", which pattern uses`);
has(report.errors, "textures/huge.png: is");
has(report.errors, "scripts don't typecheck");
has(report.errors, `depends on "missing_mod", which isn't installed`);
+1 -1
View File
@@ -34,8 +34,8 @@ Deno.test("a model gets its parent's display transform for each place it doesn't
assertEquals(models[1].display, { gui: { scale: [2, 2, 2] }, ground: { scale: [0.25, 0.25, 0.25] } });
assertEquals(validate_model({ id: "a:base", display: models[1].display }), []);
assertEquals(validate_model({ id: "a:base", display: { head: {}, gui: { scale: 2 } } }), [
'display: "head" isn\'t one of gui, firstperson_righthand, ground, fixed',
"display.gui.scale must be [x, y, z]",
'display can\'t have "head"',
]);
});
+4 -4
View File
@@ -6,7 +6,7 @@ import { assert, assertEquals, assertThrows } from "@std/assert";
import { Container, ItemStack } from "$/common/inventory.ts";
import { CRAFTING_RESULT_SLOT } from "$/common/protocol.ts";
import { type BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
import type { TagJson } from "$/common/mod_data.ts";
import type { ManifestJson, TagJson } from "$/common/mod_data.ts";
import { resolve_tags, tag_api, type TagSource } from "$/common/tags.ts";
import { can_stand_on } from "$/common/utils.ts";
import { read_bmod, write_bmod } from "$/common/bmod.ts";
@@ -192,10 +192,10 @@ Deno.test("check-mods finds broken tags and tags nobody defines", async () => {
const has = (list: string[], text: string) =>
assert(list.some((e) => e.includes(text)), `expected "${text}" in\n${list.join("\n")}`);
has(report.errors, "tags/items/maple/broken.json: #maple:broken needs maple:no_such_item, which doesn't exist");
has(report.errors, `tags/items/maple/bad.json: values must be an id like "my_mod:thing"`);
has(report.errors, `tags/items/maple/bad.json: values[0] must be an id like "my_mod:thing"`);
has(report.errors, "tags/items/maple/bad.json: replace must be true or false");
has(report.errors, "tags/items/misplaced.json: tag files go in tags/<registry>/<namespace>/");
has(report.errors, "tags/fluids/maple/sap.json: registry must be one of blocks, items, entities");
has(report.errors, `tags/fluids/maple/sap.json: registry must be "blocks", "items", "entities"`);
has(report.errors, "recipes/uses_missing_tag.json: item tag #maple:nothing_here doesn't exist");
has(report.warnings, `uses #farmersdelight:knives but doesn't list "farmersdelight" in dependencies`);
// the shared namespace and optional entries need no dependency
@@ -217,7 +217,7 @@ Deno.test("tags survive packing into a .bmod", () => {
effects: [],
tags: [tag],
};
const manifest = { format_version: 1, id: "x", name: "X", version: "1.0.0" };
const manifest: ManifestJson = { format_version: 1, id: "x", name: "X", version: "1.0.0" };
const bmod = read_bmod(write_bmod({ manifest, data, scripts: {}, textures: new Map() }), "x.bmod");
assertEquals(bmod.data.tags, [tag]);
});
+39 -52
View File
@@ -3,11 +3,12 @@
// deno task check-mods
// validates every mod in mods/: manifests, data files, textures, references between them, and typechecks scripts
import * as z from "zod";
import {
data_file,
entity_model_from_geo,
FORMAT_VERSION,
is_object,
OreJson,
type OreJson,
type SpawnJson,
type TagJson,
validate_block,
@@ -21,6 +22,7 @@ import {
validate_spawn,
validate_tag,
} from "$/common/mod_data.ts";
import { json_object } from "$/common/schema.ts";
import { check_references, load_order, type LoadedMod, type ModReport } from "$/common/mod_check.ts";
import { png_size, texture_size_problem } from "$/common/bmod.ts";
import { type TextureJson, validate_texture_json } from "$/common/texture_animation.ts";
@@ -139,6 +141,18 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
error(`manifest.json: credits ${credits} doesn't exist`);
}
// what a data file holds, under key next to its format_version. example is what that looks like, for the error
const read_data = <T extends z.ZodType>(path: string, key: string, contents: T, example: string) => {
const json = read_json(`${dir}/${path}`, (m) => error(`${path}: ${m}`));
if (json === undefined) return undefined;
const file = data_file(key, contents).safeParse(json);
if (!file.success) {
error(`${path}: must be { "format_version": ${FORMAT_VERSION}, "${key}": ${example} }`);
return undefined;
}
return file.data[key] as z.infer<T>;
};
const load_data = <T>(
folder: string,
key: string,
@@ -148,15 +162,11 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
// models/<name>.geo.json are entity models, not block ones
for (const file of walk(`${dir}/${folder}`, ".json").filter((file) => !file.endsWith(".geo.json"))) {
const path = `${folder}/${file}`;
const wrapper = read_json(`${dir}/${path}`, (m) => error(`${path}: ${m}`));
if (wrapper === undefined) continue;
if (!is_object(wrapper) || wrapper.format_version !== FORMAT_VERSION || !(key in wrapper)) {
error(`${path}: must be { "format_version": ${FORMAT_VERSION}, "${key}": { ... } }`);
continue;
}
const problems = validate(wrapper[key]);
const json = read_data(path, key, json_object, "{ ... }");
if (json === undefined) continue;
const problems = validate(json);
for (const problem of problems) error(`${path}: ${problem}`);
if (problems.length === 0) into.push({ file: path, json: wrapper[key] as T });
if (problems.length === 0) into.push({ file: path, json: json as T });
}
};
load_data("blocks", "block", validate_block, mod.blocks);
@@ -187,18 +197,14 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
// tags/<registry>/<namespace>/<path>.json is the tag <namespace>:<path>, in any namespace: tags are shared
for (const file of walk(`${dir}/tags`, ".json")) {
const path = `tags/${file}`;
const wrapper = read_json(`${dir}/${path}`, (m) => error(`${path}: ${m}`));
if (wrapper === undefined) continue;
const [registry, namespace, ...rest] = file.replace(/\.json$/, "").split("/");
if (rest.length === 0) {
error(`${path}: tag files go in tags/<registry>/<namespace>/, like tags/items/${id}/things.json`);
continue;
}
if (!is_object(wrapper) || wrapper.format_version !== FORMAT_VERSION || !is_object(wrapper.tag)) {
error(`${path}: must be { "format_version": ${FORMAT_VERSION}, "tag": { "values": [ ... ] } }`);
continue;
}
const json = { ...wrapper.tag, registry, id: `${namespace}:${rest.join("/")}` };
const tag = read_data(path, "tag", json_object, '{ "values": [ ... ] }');
if (tag === undefined) continue;
const json = { ...tag, registry, id: `${namespace}:${rest.join("/")}` };
const problems = validate_tag(json);
for (const problem of problems) error(`${path}: ${problem}`);
if (problems.length === 0) mod.tags.push({ file: path, json: json as TagJson });
@@ -207,53 +213,34 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
// loot_tables/<path>.json is the loot table <mod id>:<path>, like minecraft's
for (const file of walk(`${dir}/loot_tables`, ".json")) {
const path = `loot_tables/${file}`;
const wrapper = read_json(`${dir}/${path}`, (m) => error(`${path}: ${m}`));
if (wrapper === undefined) continue;
if (!is_object(wrapper) || wrapper.format_version !== FORMAT_VERSION || !is_object(wrapper.loot_table)) {
error(`${path}: must be { "format_version": ${FORMAT_VERSION}, "loot_table": { "pools": [ ... ] } }`);
continue;
}
const json = { ...wrapper.loot_table, id: `${id}:${file.replace(/\.json$/, "")}` };
const loot_table = read_data(path, "loot_table", json_object, '{ "pools": [ ... ] }');
if (loot_table === undefined) continue;
const json = { ...loot_table, id: `${id}:${file.replace(/\.json$/, "")}` };
const problems = validate_loot_table(json);
for (const problem of problems) error(`${path}: ${problem}`);
if (problems.length === 0) mod.loot_tables.push({ file: path, json: json as LootTableJson });
}
if (exists(`${dir}/worldgen/ores.json`)) {
const ores = read_json(`${dir}/worldgen/ores.json`, (m) => error(`worldgen/ores.json: ${m}`));
if (!is_object(ores) || ores.format_version !== FORMAT_VERSION || !Array.isArray(ores.ores)) {
error(`worldgen/ores.json: must be { "format_version": ${FORMAT_VERSION}, "ores": [ ... ] }`);
} else {
ores.ores.forEach((ore, i) => {
const problems = validate_ore(ore);
for (const problem of problems) error(`worldgen/ores.json: ore ${i}: ${problem}`);
if (problems.length === 0) mod.ores.push({ file: "worldgen/ores.json", json: ore as OreJson });
});
}
const ores = read_data("worldgen/ores.json", "ores", z.array(z.unknown()), "[ ... ]") ?? [];
ores.forEach((ore, i) => {
const problems = validate_ore(ore);
for (const problem of problems) error(`worldgen/ores.json: ore ${i}: ${problem}`);
if (problems.length === 0) mod.ores.push({ file: "worldgen/ores.json", json: ore as OreJson });
});
}
if (exists(`${dir}/worldgen/spawns.json`)) {
const spawns = read_json(`${dir}/worldgen/spawns.json`, (m) => error(`worldgen/spawns.json: ${m}`));
if (!is_object(spawns) || spawns.format_version !== FORMAT_VERSION || !Array.isArray(spawns.spawns)) {
error(`worldgen/spawns.json: must be { "format_version": ${FORMAT_VERSION}, "spawns": [ ... ] }`);
} else {
spawns.spawns.forEach((spawn, i) => {
const problems = validate_spawn(spawn);
for (const problem of problems) error(`worldgen/spawns.json: spawn ${i}: ${problem}`);
if (problems.length === 0) {
mod.spawns.push({ file: "worldgen/spawns.json", json: spawn as SpawnJson });
}
});
}
const spawns = read_data("worldgen/spawns.json", "spawns", z.array(z.unknown()), "[ ... ]") ?? [];
spawns.forEach((spawn, i) => {
const problems = validate_spawn(spawn);
for (const problem of problems) error(`worldgen/spawns.json: spawn ${i}: ${problem}`);
if (problems.length === 0) mod.spawns.push({ file: "worldgen/spawns.json", json: spawn as SpawnJson });
});
}
if (exists(`${dir}/config.json`)) {
const config = read_json(`${dir}/config.json`, (m) => error(`config.json: ${m}`));
if (!is_object(config) || config.format_version !== FORMAT_VERSION || !is_object(config.config)) {
error(`config.json: must be { "format_version": ${FORMAT_VERSION}, "config": { ... } }`);
} else {
mod.config = config.config;
}
mod.config = read_data("config.json", "config", json_object, "{ ... }");
}
// a mod only registers ids in its own namespace
+2 -9
View File
@@ -5,15 +5,8 @@
// bottom instead of up and down, ids lose their folders, a parent keeps being a parent (bworld merges them when it
// loads, see resolve_models), and what bworld has no use for (blockbench's names, display transforms for places bworld
// doesn't show items, like third person) is left out
import {
DISPLAY_CONTEXTS,
type ModelDisplay,
type ModelElementJson,
type ModelFace,
type ModelFaceJson,
type ModelFileJson,
} from "$/common/block_models.ts";
import { FORMAT_VERSION } from "$/common/mod_data.ts";
import type { ModelDisplay, ModelElementJson, ModelFaceJson, ModelFileJson } from "$/common/block_models.ts";
import { DISPLAY_CONTEXTS, FORMAT_VERSION, type ModelFace } from "$/common/mod_data.ts";
import { join } from "@std/path";
import {
DEFAULT_REMAPS,
+2 -1
View File
@@ -4,7 +4,8 @@
// where things are in a java mod's resources, and what they're called in bworld. a resource location like
// "create:block/cogwheel" (or "block/stone", which is minecraft's) becomes the id "create:block_cogwheel": bworld ids
// have no folders, so the path's folders are joined with _, the same way check_mods names textures in subfolders
import { ID_PATTERN, type TagRegistry } from "$/common/mod_data.ts";
import type { TagRegistry } from "$/common/mod_data.ts";
import { ID_PATTERN } from "$/common/schema.ts";
import { registered_ids } from "$/common/mod_check.ts";
import { load_and_check } from "$/tools/check_mods.ts";
import { dirname, relative, resolve, SEPARATOR } from "@std/path";
+2 -1
View File
@@ -5,7 +5,8 @@
// format is the same: values, replace and remove, with { id, required: false } for entries that can be missing. tag ids
// keep their folders, since bworld's can have them too
import { join } from "@std/path";
import { FORMAT_VERSION, TAG_ID_PATTERN, type TagRegistry } from "$/common/mod_data.ts";
import { FORMAT_VERSION, type TagRegistry } from "$/common/mod_data.ts";
import { TAG_ID_PATTERN } from "$/common/schema.ts";
import {
DEFAULT_REMAPS,
empty_report,
+2 -1
View File
@@ -12,7 +12,8 @@
// the parts lock their textures to the world (uvlock), so every piece shows the part of the texture under it, the
// texture's line running north to south or its line running east to west, and it lines up from one wire to the next
import { model_shape } from "$/common/block_shapes.ts";
import type { ModelElementJson, ModelFace } from "$/common/block_models.ts";
import type { ModelElementJson } from "$/common/block_models.ts";
import type { ModelFace } from "$/common/mod_data.ts";
import type { Face } from "$/common/mod_api/shared.ts";
import { can_cover, ways_out } from "$/mods/bworld/scripts/verdigris/joins.ts";
import { DIRECTIONS, FACE_OFFSETS, FACES } from "$/mods/bworld/scripts/verdigris/sides.ts";