Implement tags !

This commit is contained in:
2026-09-30 13:41:29 -03:00
parent dc70ada7c4
commit 342b45d593
51 changed files with 978 additions and 219 deletions
+1
View File
@@ -60,6 +60,7 @@ deno task build && deno task server # packs the mods and starts a se
- [Textures](docs/modding/resources/textures.md)
- [Block Models](docs/modding/resources/models.md)
- [Recipes](docs/modding/resources/recipes.md): crafting, smelting, smithing and your own recipe types
- [Tags](docs/modding/resources/tags.md): lists of blocks, items or entities that every mod can add to
**Everything else**
+2
View File
@@ -6,6 +6,7 @@ import type { ClientContext, InventoryOverlay } from "$/common/mod_api/client.ts
import { ModListing, ModLoadError, RecipeBook, register_mod_data } from "$/common/mod_loader.ts";
import { type Bmod, read_bmod } from "$/common/bmod.ts";
import { display_name } from "$/common/utils.ts";
import { tag_api } from "$/common/tags.ts";
import { AIR_ID } from "$/common/protocol.ts";
import type { Client } from "./client.ts";
import { code_url, fetch_verified } from "./handshake.ts";
@@ -139,6 +140,7 @@ function client_context(listing: ModListing): ClientContext {
list: (type) =>
structuredClone(type ? recipe_book.all.filter((recipe) => recipe.type === type) : recipe_book.all),
},
tags: tag_api(),
log: (...args) => console.log(`[${mod}]`, ...args),
};
}
+4 -1
View File
@@ -12,6 +12,7 @@ import {
type ManifestJson,
type OreJson,
type RecipeJson,
type TagJson,
validate_block,
validate_entity,
validate_entity_model,
@@ -20,6 +21,7 @@ import {
validate_model,
validate_ore,
validate_recipe,
validate_tag,
} from "./mod_data.ts";
import type { ModData } from "./mod_loader.ts";
@@ -53,7 +55,7 @@ export class BmodError extends Error {
// the zip's layout:
// manifest.json the mod's manifest, with "scripts" and "credits" pointing into the zip
// data.json every block, model, item, recipe, ore, entity and entity model
// data.json every block, model, item, recipe, ore, entity, entity model and tag
// scripts/<side>.js
// textures/<name>.png the texture <mod id>:<name>
// credits.md
@@ -144,6 +146,7 @@ export function read_bmod(bytes: Uint8Array, file: string): Bmod {
validate_entity_model,
problems,
) as EntityModelJson[],
tags: checked(raw_data.tags, "tags", validate_tag, problems) as TagJson[],
};
// a mod only registers ids in its own namespace
for (const { id } of [...data.blocks, ...data.models, ...data.items, ...data.entities, ...data.entity_models]) {
+4 -3
View File
@@ -135,10 +135,11 @@ export interface BlockRegistry {
interactive?: boolean;
// placing a block into it replaces it, like water
replaceable?: boolean;
// the blocks it can stand on, like crops on farmland. it can't be placed elsewhere, and breaks when the block
// under it becomes something else. anything when not set
// the blocks (ids or #tags) it can stand on, like crops on farmland. it can't be placed elsewhere, and breaks when
// the block under it becomes something else. anything when not set
place_on?: string[];
// the blocks it can be placed into, replacing them, like rice into water. air and replaceable blocks when not set
// the blocks (ids or #tags) it can be placed into, replacing them, like rice into water. air and replaceable blocks
// when not set
place_in?: string[];
// custom components from mods and their params, the server runs them
components?: Record<string, unknown>;
+4 -2
View File
@@ -1,7 +1,7 @@
// what client scripts get, see docs/modding/gui/index.md
import type { Id, ItemStack, KeyCode, ModInfo, Position } from "./shared.ts";
import type { Id, ItemStack, KeyCode, ModInfo, Position, TagApi } from "./shared.ts";
export type { Id, ItemStack, KeyCode, ModInfo, Position } from "./shared.ts";
export type { Id, ItemStack, KeyCode, ModInfo, Position, TagApi, TagRegistry } from "./shared.ts";
export interface ClientContext {
mod: ModInfo;
@@ -30,6 +30,8 @@ export interface ClientContext {
// deno-lint-ignore no-explicit-any
list(type?: Id): any[];
};
// every mod's block, item and entity tags
tags: TagApi;
log(...args: unknown[]): void;
}
+3 -2
View File
@@ -1,10 +1,10 @@
// what server scripts get, see docs/modding/
import type { EventSignal, Face, Id, ItemStack, ModInfo, Position } from "./shared.ts";
import type { EventSignal, Face, Id, ItemStack, ModInfo, Position, TagApi } from "./shared.ts";
import type { ArgumentType, CommandNode } from "../commands.ts";
export type { ArgumentType, CommandContext, CommandNode, Suggestion } from "../commands.ts";
export type { EventSignal, Face, Id, ItemStack, ModInfo, Position } from "./shared.ts";
export type { EventSignal, Face, Id, ItemStack, ModInfo, Position, TagApi, TagRegistry } from "./shared.ts";
export interface ServerContext {
mod: ModInfo;
@@ -17,6 +17,7 @@ export interface ServerContext {
containers: ContainerApi;
items: ItemApi;
recipes: RecipeApi;
tags: TagApi;
ui: ServerUi;
net: ServerNet;
storage: ModStorage;
+17
View File
@@ -10,6 +10,23 @@ export interface ItemStack {
data?: unknown;
}
// the registries tags are for, see docs/modding/resources/tags.md
export type TagRegistry = "blocks" | "items" | "entities";
// every mod's tags, the same on the server and every client. tags can be written with or without their #
export interface TagApi {
// whether any mod defines the tag and it loaded
exists(registry: TagRegistry, tag: Id): boolean;
// whether id is in the tag, like has("items", "bworld:planks", "bworld:birch_planks"). false for a tag nobody defines
has(registry: TagRegistry, tag: Id, id: Id): boolean;
// every id in the tag, including its tags' ids, in the order they were added. empty for a tag nobody defines
get(registry: TagRegistry, tag: Id): Id[];
// every tag id is in
of(registry: TagRegistry, id: Id): Id[];
// the items a recipe's item choice stands for, once each: an item id or "#tag", or a list of those
expand(choice: Id | Id[]): Id[];
}
export interface ModInfo {
readonly id: string;
readonly version: string;
+57 -7
View File
@@ -2,14 +2,18 @@
// and the server (on .bmod files) all use it
import {
type BlockJson,
choice_ids,
choice_list,
type EntityJson,
type EntityModelJson,
type ItemJson,
type OreJson,
type RecipeJson,
SHARED_TAG_NAMESPACE,
type TagJson,
type TagRegistry,
} from "./mod_data.ts";
import { BUILTIN_MODELS, type ModelJson } from "./block_models.ts";
import { resolve_tags } from "./tags.ts";
export interface ModReport {
id: string;
@@ -29,6 +33,7 @@ export interface LoadedMod {
ores: { file: string; json: OreJson }[];
entities: { file: string; json: EntityJson }[];
entity_models: { file: string; json: EntityModelJson }[];
tags: { file: string; json: TagJson }[];
textures: string[];
// absolute paths by texture id
texture_files: Map<string, string>;
@@ -68,6 +73,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
const model_owners = new Map<string, string[]>();
const entity_owners = new Map<string, string[]>();
const entity_model_owners = new Map<string, string[]>();
const tag_owners = new Map<TagRegistry, Set<string>>();
const add = (map: Map<string, string[]>, id: string, mod: string) => map.set(id, [...(map.get(id) ?? []), mod]);
const textures = new Set<string>(engine_textures);
@@ -81,6 +87,10 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
for (const { json } of mod.models) add(model_owners, json.id, mod.id);
for (const { json } of mod.entities) add(entity_owners, json.id, mod.id);
for (const { json } of mod.entity_models) add(entity_model_owners, json.id, mod.id);
for (const { json } of mod.tags) {
if (!tag_owners.has(json.registry)) tag_owners.set(json.registry, new Set());
tag_owners.get(json.registry)!.add(json.id);
}
for (const texture of mod.textures) textures.add(texture);
}
@@ -95,12 +105,24 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
if (!mod_ids.has(dep)) errors.push(`manifest.json: depends on "${dep}", which isn't installed`);
}
const uses = (file: string, id: string, what: "block" | "item" | "texture" | "model" | "entity model") => {
const namespace = id.split(":")[0];
// the shared tag namespace belongs to no mod, so using it needs no dependency
const check_namespace = (file: string, id: string) => {
const tag = id.startsWith("#");
const namespace = id.replace("#", "").split(":")[0];
if (tag && namespace === SHARED_TAG_NAMESPACE) return;
if (namespace !== mod.id && namespace !== "engine" && !dependencies.has(namespace)) {
warnings.push(`${file}: uses ${id} but doesn't list "${namespace}" in dependencies`);
}
if (what === "model") {
};
// block and item ids can be #tags, like in recipes and place_on
const uses = (file: string, id: string, what: "block" | "item" | "texture" | "model" | "entity model") => {
check_namespace(file, id);
if (id.startsWith("#") && (what === "block" || what === "item")) {
if (!tag_owners.get(what === "block" ? "blocks" : "items")?.has(id.slice(1))) {
errors.push(`${file}: ${what} tag ${id} doesn't exist`);
}
} else if (what === "model") {
if (!BUILTIN_MODELS[id] && !model_owners.has(id)) errors.push(`${file}: model ${id} doesn't exist`);
} else if (what === "entity model") {
if (!entity_model_owners.has(id)) errors.push(`${file}: entity model ${id} doesn't exist`);
@@ -152,15 +174,15 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
for (const { file, json } of mod.recipes) {
switch (json.type) {
case "shaped":
for (const id of Object.values(json.key).flatMap(choice_ids)) uses(file, id, "item");
for (const id of Object.values(json.key).flatMap(choice_list)) uses(file, id, "item");
uses(file, json.result.id, "item");
break;
case "furnace":
for (const id of choice_ids(json.input)) uses(file, id, "item");
for (const id of choice_list(json.input)) uses(file, id, "item");
uses(file, json.output.id, "item");
break;
case "fuel":
for (const id of choice_ids(json.item)) uses(file, id, "item");
for (const id of choice_list(json.item)) uses(file, id, "item");
break;
case "smithing":
uses(file, json.tool, "item");
@@ -186,5 +208,33 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
errors.push(`${file}: entity model ${json.id} is defined more than once`);
}
}
// whether what a tag holds exists is up to resolve_tags below, since entries can be optional
for (const { file, json } of mod.tags) {
check_namespace(file, `#${json.id}`);
for (const entry of json.values) {
if (typeof entry === "string" || entry.required !== false) {
check_namespace(file, typeof entry === "string" ? entry : entry.id);
}
}
}
}
// tags merge in load order. when there's no order, mods depending on each other in a circle is its own error
let ordered = mods;
try {
ordered = load_order(mods);
} catch {
// checked by the caller
}
const owners: Record<TagRegistry, Map<string, string[]>> = {
blocks: block_owners,
items: item_owners,
entities: entity_owners,
};
const { problems } = resolve_tags(
ordered.flatMap((mod) => mod.tags.map(({ file, json }) => ({ mod: mod.id, file, json }))),
(registry, id) => (registry === "blocks" && id === "bworld:air") || owners[registry].has(id),
);
const by_id = new Map(mods.map((mod) => [mod.id, mod]));
for (const { mod, file, message } of problems) by_id.get(mod)!.report.errors.push(`${file}: ${message}`);
}
+80 -9
View File
@@ -11,11 +11,18 @@ import {
type ToolProperties,
} from "./everything_registry.ts";
import { type BlockVariant, MODEL_FACES, type ModelFace } from "./block_models.ts";
import { expand_items, list_matches } from "./tags.ts";
export const FORMAT_VERSION = 1;
export const ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+$/;
export const NAMESPACE_PATTERN = /^[a-z0-9_]{1,32}$/;
export const RESERVED_NAMESPACES = ["bworld", "engine"];
// a tag's id may have folders, like c:ingots/iron. see docs/modding/resources/tags.md
export const TAG_ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+(\/[a-z0-9_]+)*$/;
// the namespace for tags every mod shares, like neoforge's and fabric's. no mod owns it
export const SHARED_TAG_NAMESPACE = "c";
export const TAG_REGISTRIES = ["blocks", "items", "entities"] as const;
export type TagRegistry = typeof TAG_REGISTRIES[number];
type BlockTextures = BlockRegistry["textures"];
@@ -135,13 +142,38 @@ export interface EntityCubeJson {
inflate?: number;
}
// an item a recipe takes: its id, or a list of ids any of which fits, like every kind of planks
// something in a tag file's values or remove: an id, a "#tag", or either with whether it must exist. a plain one must
export type TagEntryJson = string | { id: string; required?: boolean };
// a tag file, tags/<registry>/<namespace>/<path>.json, with the registry and id its path gives it. like neoforge's,
// every mod's file for the same tag is merged, in load order
export interface TagJson {
registry: TagRegistry;
id: string;
values: TagEntryJson[];
// drops what mods before this one put in the tag
replace?: boolean;
// takes these out again, if they're in it
remove?: TagEntryJson[];
}
// an item a recipe takes: its id, a "#tag" of items, or a list of those any of which fits, like every kind of planks
export type ItemChoice = string | string[];
export function choice_ids(choice: ItemChoice): string[] {
// the ids and #tags a choice lists, without looking inside the tags
export function choice_list(choice: ItemChoice): string[] {
return typeof choice === "string" ? [choice] : choice;
}
// every item that fits a choice, with its tags' items, once each. the tags must be loaded
export function choice_ids(choice: ItemChoice): string[] {
return expand_items(choice_list(choice));
}
export function choice_matches(choice: ItemChoice, id: string): boolean {
return list_matches("items", choice_list(choice), id);
}
export type RecipeJson =
| {
type: "shaped";
@@ -285,7 +317,7 @@ export function grid_recipe_to_json(recipe: GridRecipe): RecipeJson {
const letters = new Map<string, string>();
for (const choice of recipe.pattern) {
if (choice === undefined || letters.has(JSON.stringify(choice))) continue;
const letter = pick_letter(choice_ids(choice)[0], new Set(letters.values()));
const letter = pick_letter(choice_list(choice)[0].replace("#", ""), new Set(letters.values()));
letters.set(JSON.stringify(choice), letter);
key[letter] = choice;
}
@@ -318,7 +350,7 @@ export function grid_recipe_from_json(json: Extract<RecipeJson, { type: "shaped"
// a readable letter for an item in a pattern: its first letter if free, like P for planks
function pick_letter(id: string, taken: Set<string>) {
const name = id.split(":")[1].toUpperCase();
const name = id.split(":")[1].split("/").at(-1)!.toUpperCase();
for (const letter of [...name, ..."ABCDEFGHIJKLMNOPQRSTUVWXYZ"]) {
if (/[A-Z]/.test(letter) && !taken.has(letter)) {
return letter;
@@ -458,9 +490,9 @@ export function validate_block(json: unknown): Problems {
const list = json[key];
if (list === undefined) continue;
if (!Array.isArray(list) || list.length === 0) {
problems.push(`${key} must be a list of block ids`);
problems.push(`${key} must be a list of block ids or #tags`);
} else {
for (const id of list) problems.push(...validate_id(id, key));
for (const id of list) problems.push(...validate_id_or_tag(id, key));
}
}
if (json.states !== undefined) {
@@ -775,11 +807,50 @@ function validate_vec3(value: unknown, field: string): Problems {
: [`${field} must be [x, y, z]`];
}
// an item id, or a list of them any of which fits
// an item id or #tag, or a list of them any of which fits
function validate_choice(value: unknown, field: string): Problems {
if (!Array.isArray(value)) return validate_id(value, field);
if (!Array.isArray(value)) return validate_id_or_tag(value, field);
if (value.length === 0) return [`${field} must list at least one item`];
return value.flatMap((id) => validate_id(id, field));
return value.flatMap((id) => validate_id_or_tag(id, field));
}
function validate_id_or_tag(value: unknown, field: string): Problems {
if (typeof value === "string" && value.startsWith("#")) {
return TAG_ID_PATTERN.test(value.slice(1)) ? [] : [`${field} must be a tag like "#my_mod:things"`];
}
return validate_id(value, field);
}
// a tag file's contents, with the registry and id its path gives it
export function validate_tag(json: unknown): Problems {
if (!is_object(json)) return ["tag must be an object"];
const problems: Problems = [];
if (!TAG_REGISTRIES.includes(json.registry as TagRegistry)) {
problems.push(`registry must be one of ${TAG_REGISTRIES.join(", ")}`);
}
if (typeof json.id !== "string" || !TAG_ID_PATTERN.test(json.id)) {
problems.push('id must be a tag id like "my_mod:things" or "c:ingots/iron"');
}
if (json.replace !== undefined && typeof json.replace !== "boolean") problems.push("replace must be true or false");
for (const key of ["values", "remove"]) {
const list = json[key];
if (list === undefined && key === "remove") continue;
if (!Array.isArray(list)) {
problems.push(`${key} must be a list of ids and #tags`);
continue;
}
for (const entry of list) {
if (is_object(entry)) {
problems.push(...validate_id_or_tag(entry.id, `${key}[].id`));
if (entry.required !== undefined && typeof entry.required !== "boolean") {
problems.push(`${key}[].required must be true or false`);
}
} else {
problems.push(...validate_id_or_tag(entry, key));
}
}
}
return problems;
}
// optional text players see
+27 -5
View File
@@ -14,7 +14,10 @@ import {
ModRecipeJson,
OreJson,
RecipeJson,
TagJson,
TagRegistry,
} from "./mod_data.ts";
import { resolve_tags, Tags } from "./tags.ts";
import { register_block_item } from "./utils.ts";
import type { ModelJson } from "./block_models.ts";
@@ -28,6 +31,8 @@ export interface ModData {
ores: OreJson[];
entities: EntityJson[];
entity_models: EntityModelJson[];
// tag files, see common/tags.ts
tags: TagJson[];
}
// a mod as the server lists it to clients, in load order: the .bmod players download, without its server script
@@ -61,14 +66,17 @@ export class ModLoadError extends Error {
}
}
// registers every mod's blocks, items, entities and recipes, in the order given (dependencies first)
// whether a block, item or entity is registered, for tags. air isn't a registered block, but tags can hold it
export function is_registered(registry: TagRegistry, id: string): boolean {
return (registry === "blocks" && id === "bworld:air") || EverythingRegistry.get(registry, id) !== undefined;
}
// registers every mod's blocks, items, entities, tags and recipes, in the order given (dependencies first). tags load
// once every mod's content has, since a tag can hold anything, and recipes after them, since they can use tags
export function register_mod_data(mods: { id: string; data: ModData }[]): RecipeBook {
const recipes = new RecipeBook();
for (const { id, data } of mods) {
const fail = (message: string): never => {
throw new ModLoadError(id, message);
};
try {
for (const model of data.models) {
EverythingRegistry.register<ModelJson>("models", model.id, model);
@@ -90,9 +98,23 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
EverythingRegistry.register<EntityJson>("entities", json.id, json);
}
} catch (e) {
fail((e as Error).message);
throw new ModLoadError(id, (e as Error).message);
}
}
const { tags, problems } = resolve_tags(
mods.flatMap(({ id, data }) =>
data.tags.map((json) => ({ mod: id, file: `tags/${json.registry}/${json.id}`, json }))
),
is_registered,
);
if (problems.length > 0) throw new ModLoadError(problems[0].mod, `${problems[0].file}: ${problems[0].message}`);
Tags.load(tags);
for (const { id, data } of mods) {
const fail = (message: string): never => {
throw new ModLoadError(id, message);
};
for (const recipe of data.recipes) {
recipes.all.push(recipe);
if (is_mod_recipe(recipe)) {
+196
View File
@@ -0,0 +1,196 @@
// tags: named lists of blocks, items or entities that mods add to, like neoforge's. see docs/modding/resources/tags.md.
// resolve_tags works them out from every mod's tag files, the same way on the server, clients and in check-mods
import type { TagEntryJson, TagJson, TagRegistry } from "./mod_data.ts";
import type { TagApi } from "./mod_api/shared.ts";
export interface TagSource {
mod: string;
// where the tag came from, for problems
file: string;
json: TagJson;
}
export interface TagProblem {
mod: string;
file: string;
message: string;
}
// ids by tag id, by registry. each list in the order its ids were added
export type ResolvedTags = Map<TagRegistry, Map<string, string[]>>;
interface Entry {
id: string;
tag: boolean;
required: boolean;
remove: boolean;
source: TagSource;
}
function parse_entry(json: TagEntryJson, remove: boolean, source: TagSource): Entry {
const raw = typeof json === "string" ? json : json.id;
const tag = raw.startsWith("#");
// like neoforge, what's removed never has to exist
const required = !remove && (typeof json === "string" || json.required !== false);
return { id: tag ? raw.slice(1) : raw, tag, required, remove, source };
}
// merges the tag files, sources in load order, and resolves the tags inside tags. like neoforge, a later file with
// replace drops the entries before it, and values and removes apply in order, so a later mod can add back what an
// earlier one removed. a tag with a required entry that doesn't exist, or that contains itself, doesn't load and is a
// problem. exists says whether a block, item or entity is registered
export function resolve_tags(
sources: TagSource[],
exists: (registry: TagRegistry, id: string) => boolean,
): { tags: ResolvedTags; problems: TagProblem[] } {
const entries = new Map<TagRegistry, Map<string, Entry[]>>();
for (const source of sources) {
const { registry, id, values, replace, remove } = source.json;
if (!entries.has(registry)) entries.set(registry, new Map());
const by_tag = entries.get(registry)!;
const list = replace ? [] : by_tag.get(id) ?? [];
list.push(...values.map((json) => parse_entry(json, false, source)));
list.push(...(remove ?? []).map((json) => parse_entry(json, true, source)));
by_tag.set(id, list);
}
const problems: TagProblem[] = [];
const problem = (entry: Entry, message: string) =>
problems.push({ mod: entry.source.mod, file: entry.source.file, message });
const tags: ResolvedTags = new Map();
for (const [registry, by_tag] of entries) {
// undefined while resolving, null once it failed
const resolved = new Map<string, Set<string> | null | undefined>();
const resolve = (id: string, path: string[]): Set<string> | null => {
const done = resolved.get(id);
if (done !== undefined) return done;
resolved.set(id, undefined);
const ids = new Set<string>();
let failed = false;
for (const entry of by_tag.get(id)!) {
const apply = (member: string) => entry.remove ? ids.delete(member) : ids.add(member);
if (!entry.tag) {
if (exists(registry, entry.id)) apply(entry.id);
else if (entry.required) {
problem(entry, `#${id} needs ${entry.id}, which doesn't exist`);
failed = true;
}
continue;
}
if (!by_tag.has(entry.id)) {
if (entry.required) {
problem(entry, `#${id} needs #${entry.id}, which no mod defines`);
failed = true;
}
continue;
}
if (resolved.has(entry.id) && resolved.get(entry.id) === undefined) {
const start = path.indexOf(entry.id);
const circle = [...(start === -1 ? [] : path.slice(start)), id, entry.id].map((t) => `#${t}`);
problem(entry, `tags contain each other in a circle: ${circle.join(" -> ")}`);
failed = true;
continue;
}
const inner = resolve(entry.id, [...path, id]);
// what went wrong inside is its own problem
if (inner === null) {
if (!entry.remove) failed = true;
continue;
}
for (const member of inner) apply(member);
}
const result = failed ? null : ids;
resolved.set(id, result);
return result;
};
const out = new Map<string, string[]>();
for (const id of by_tag.keys()) {
const ids = resolve(id, []);
if (ids) out.set(id, [...ids]);
}
tags.set(registry, out);
}
return { tags, problems };
}
// the loaded mods' tags, set by register_mod_data in common/mod_loader.ts
export class Tags {
static #tags: ResolvedTags = new Map();
static #sets = new Map<TagRegistry, Map<string, Set<string>>>();
// tags by member, made the first time something asks
static #of: Map<TagRegistry, Map<string, string[]>> | undefined;
static load(tags: ResolvedTags) {
this.#tags = tags;
this.#sets = new Map(
[...tags].map((
[registry, by_tag],
) => [registry, new Map([...by_tag].map(([id, ids]) => [id, new Set(ids)]))]),
);
this.#of = undefined;
}
// whether a tag loaded. with or without its #
static exists(registry: TagRegistry, tag: string): boolean {
return this.#tags.get(registry)?.has(strip(tag)) ?? false;
}
// false when the tag doesn't exist
static has(registry: TagRegistry, tag: string, id: string): boolean {
return this.#sets.get(registry)?.get(strip(tag))?.has(id) ?? false;
}
// empty when the tag doesn't exist
static get(registry: TagRegistry, tag: string): string[] {
return this.#tags.get(registry)?.get(strip(tag)) ?? [];
}
// every tag id is in, in the order the tags were first defined
static of(registry: TagRegistry, id: string): string[] {
if (!this.#of) {
this.#of = new Map();
for (const [reg, by_tag] of this.#tags) {
const by_member = new Map<string, string[]>();
for (const [tag, ids] of by_tag) {
for (const member of ids) by_member.set(member, [...(by_member.get(member) ?? []), tag]);
}
this.#of.set(reg, by_member);
}
}
return this.#of.get(registry)?.get(id) ?? [];
}
}
function strip(tag: string) {
return tag.startsWith("#") ? tag.slice(1) : tag;
}
// whether id is one of a list of ids and #tags, like a recipe's choice or a block's place_on
export function list_matches(registry: TagRegistry, list: readonly string[], id: string): boolean {
return list.some((entry) => entry.startsWith("#") ? Tags.has(registry, entry, id) : entry === id);
}
// every item a list of item ids and #tags stands for, once each
export function expand_items(list: readonly string[]): string[] {
return [...new Set(list.flatMap((id) => id.startsWith("#") ? Tags.get("items", id) : [id]))];
}
// ctx.tags for server and client scripts. everything it returns is a copy
export function tag_api(): TagApi {
const registry = (name: string): TagRegistry => {
if (name !== "blocks" && name !== "items" && name !== "entities") {
throw new Error(`tags are for "blocks", "items" or "entities", not ${JSON.stringify(name)}`);
}
return name;
};
return {
exists: (reg, tag) => Tags.exists(registry(reg), tag),
has: (reg, tag, id) => Tags.has(registry(reg), tag, id),
get: (reg, tag) => [...Tags.get(registry(reg), tag)],
of: (reg, id) => [...Tags.of(registry(reg), id)],
expand: (choice) => expand_items([choice].flat()),
};
}
+3 -2
View File
@@ -2,6 +2,7 @@ import { ID_MASK, STATE_SHIFT } from "./constants.ts";
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "./everything_registry.ts";
import { block_item_texture, cube_face_texture } from "./block_models.ts";
import type { ItemStack } from "./inventory.ts";
import { list_matches } from "./tags.ts";
export function point_inside_rec(
point_x: number,
@@ -134,7 +135,7 @@ function compile_block_states(block_info: BlockRegistry) {
// whether a block can be at a spot with below under it, see place_on
export function can_stand_on(block: BlockRegistry | undefined, below: string): boolean {
return !block?.place_on || block.place_on.includes(below);
return !block?.place_on || list_matches("blocks", block.place_on, below);
}
// where a block placed by clicking a face of another goes: into the clicked block when it can be replaced (like water),
@@ -158,7 +159,7 @@ export function can_place(
if (!block) return false;
const into = current?.id ?? "bworld:air";
const replaceable = !current || current.replaceable === true;
const in_ok = block.place_in ? block.place_in.includes(into) : replaceable;
const in_ok = block.place_in ? list_matches("blocks", block.place_in, into) : replaceable;
return in_ok && can_stand_on(block, below);
}
+16 -16
View File
@@ -49,22 +49,22 @@ there will be holes in the world behind them.
### Behavior
| Field | Default | Meaning |
| ---------------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `collision` | `true` | Whether entities bump into it. Plants and water set `false`. |
| `mining.toughness` | unbreakable | Seconds to break by hand. Without `mining`, a block can't be broken. |
| `mining.tool` | none | The [tool type](../items/tools.md) that breaks it faster, like `pickaxe`, `axe` or `shovel`. |
| `mining.requires_tool` | `false` | Only drops when broken with `mining.tool`. |
| `mining.tier` | `0` | With `requires_tool`, the lowest tool tier it drops for. Iron ore is `1`, so a wood pickaxe gets nothing. |
| `drops` | nothing | The item id it drops when broken. |
| `item` | `true` | Also register an item that places it, with the same id. |
| `interactive` | `false` | Right clicking it does something, like opening a screen, so clients don't guess that it places a block. |
| `replaceable` | `false` | Placing a block into it replaces it, like water. |
| `place_in` | see meaning | Block ids it can be placed into, replacing them, like `["bworld:water"]` for rice. Air and `replaceable` blocks when not set. |
| `place_on` | anywhere | Block ids it can stand on, like `["bworld:hoed_dirt"]` for crops. See [below](#placement). |
| `states` | none | Named [state](states.md) bits, like a crop's age. |
| `components` | none | [Components](components.md) and their parameters. |
| `item_display` | none | Shows an item on top of it, see [Tile Data](tiledata.md#showing-an-item). |
| Field | Default | Meaning |
| ---------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `collision` | `true` | Whether entities bump into it. Plants and water set `false`. |
| `mining.toughness` | unbreakable | Seconds to break by hand. Without `mining`, a block can't be broken. |
| `mining.tool` | none | The [tool type](../items/tools.md) that breaks it faster, like `pickaxe`, `axe` or `shovel`. |
| `mining.requires_tool` | `false` | Only drops when broken with `mining.tool`. |
| `mining.tier` | `0` | With `requires_tool`, the lowest tool tier it drops for. Iron ore is `1`, so a wood pickaxe gets nothing. |
| `drops` | nothing | The item id it drops when broken. |
| `item` | `true` | Also register an item that places it, with the same id. |
| `interactive` | `false` | Right clicking it does something, like opening a screen, so clients don't guess that it places a block. |
| `replaceable` | `false` | Placing a block into it replaces it, like water. |
| `place_in` | see meaning | Block ids or [tags](../resources/tags.md) it can be placed into, replacing them, like `["bworld:water"]` for rice. Air and `replaceable` blocks when not set. |
| `place_on` | anywhere | Block ids or [tags](../resources/tags.md) it can stand on, like `["bworld:hoed_dirt"]` for crops or `["#bworld:logs"]`. See [below](#placement). |
| `states` | none | Named [state](states.md) bits, like a crop's age. |
| `components` | none | [Components](components.md) and their parameters. |
| `item_display` | none | Shows an item on top of it, see [Tile Data](tiledata.md#showing-an-item). |
A block's definition goes to every player, since clients need it to draw the block, time breaking and collide with it.
It can't hold functions.
+5 -2
View File
@@ -20,6 +20,9 @@ Two namespaces are reserved:
`bworld:air` is the one exception: it's the engine's empty block, but keeps that id because every save has it.
[Tags](../resources/tags.md) aren't registered like this: they're lists that every mod can add to, their ids can have
folders (`c:ingots/iron`), and the `c` namespace is shared by every mod.
The same id can name different kinds of thing. A block registers an item with the same id unless it sets
`"item": false`, and its texture is often named the same too.
@@ -29,8 +32,8 @@ The server and every client load mods the same way, in the same order:
1. **Order.** Dependencies come before the mods that need them, and otherwise mods load alphabetically. Mods that depend
on each other in a circle are an error. The server sends its order to clients, and they follow it.
2. **Data**, one mod at a time: its block models, blocks (and their items), items, entity models, entities, then recipes
and ores.
2. **Data**, one mod at a time: its block models, blocks (and their items), items, entity models and entities. Then
every mod's [tags](../resources/tags.md), merged in load order, then each mod's recipes and ores, which can use tags.
3. **Scripts.** Server scripts' `setup` runs on the server, and client scripts' on each client. Worldgen scripts'
`setup` runs on the server before it makes chunks.
+3 -2
View File
@@ -17,6 +17,7 @@ mods/
models/*.geo.json # entity models
entities/*.json
recipes/*.json
tags/<registry>/<namespace>/*.json # tags, see resources/tags.md
worldgen/ores.json
textures/*.png
scripts/
@@ -34,8 +35,8 @@ Data folders can have subfolders. Every data file holds one definition, wrapped
}
```
The key is `block`, `item`, `model`, `entity` or `recipe`, depending on the folder. File names don't matter, the `id`
inside does.
The key is `block`, `item`, `model`, `entity`, `recipe` or `tag`, depending on the folder. File names don't matter, the
`id` inside does, except for [tags](../resources/tags.md), whose id is their path.
## `manifest.json`
+12 -4
View File
@@ -68,15 +68,23 @@ recipes with the same tool, material and addition are an error.
## Choices
Anywhere a recipe takes an item (`key` values, `input`, `item`), a list of ids means any of them fits:
Anywhere a recipe takes an item (`key` values, `input`, `item`), an item [tag](tags.md) means anything in it fits, and
so does a list of ids and tags:
```json
"key": { "P": ["bworld:planks", "bworld:birch_planks", "bworld:spruce_planks"] }
"key": { "P": "#bworld:planks" }
```
```json
"item": ["bworld:coal", "#bworld:logs"]
```
In the crafting grid, each slot can hold a different one of them, so a stick can be made from oak and birch planks
together. The recipe viewer takes turns showing them.
Use a tag rather than listing ids when other mods might have more of the same thing: a mod that adds planks to
`#bworld:planks` makes them work in every recipe that takes it.
## Custom Recipe Types
Any `type` with a namespace is a mod's own, like `farmersdelight:cooking` for the cooking pot. The engine only stores
@@ -101,8 +109,8 @@ const recipes = ctx.recipes.list("farmersdelight:cooking").map((json, i) => {
if (!Array.isArray(json.ingredients) || json.ingredients.length > 6) {
throw new Error(`cooking recipe ${i + 1}: ingredients must be 1 to 6 items`);
}
// ...check the rest, and turn it into whatever the machine needs
return json;
// ...check the rest, and turn it into whatever the machine needs. expand turns #tags into their items
return { ingredients: json.ingredients.map((choice) => ctx.tags.expand(choice)) };
});
```
+108
View File
@@ -0,0 +1,108 @@
# Tags
A tag is a named list of blocks, items or entities, like every kind of planks. Recipes and blocks can use a tag anywhere
they take an id, and any mod can add to any tag, so a mod's planks can make sticks just by adding them to
`#bworld:planks`. Tags work like [NeoForge's](https://docs.neoforged.net/docs/resources/server/tags).
A tag's id starts with `#` where it's used, so `#bworld:planks` is the tag and `bworld:planks` is the oak planks item.
## Tag Files
Tags are data in a mod's `tags/` folder, at `tags/<registry>/<namespace>/<path>.json`:
```
tags/
items/
bworld/planks.json # the item tag #bworld:planks
c/ingots/copper.json # #c:ingots/copper
blocks/
my_mod/soft.json # the block tag #my_mod:soft
```
`<registry>` is `blocks`, `items` or `entities`. A block tag and an item tag with the same id are two different tags, so
a block that should be in both, like planks, needs a file for each.
```json
{
"format_version": 1,
"tag": {
"values": [
"my_mod:maple_planks",
"#my_mod:painted_planks",
{ "id": "other_mod:birch_planks", "required": false }
]
}
}
```
| Field | Default | Meaning |
| --------- | ------- | -------------------------------------------------------------------------------------- |
| `values` | | What's in the tag: ids, and `#tags` whose contents are all in it too. |
| `replace` | `false` | Throws away what mods loaded before this one put in the tag. |
| `remove` | none | Ids and `#tags` to take out of the tag again, if they're in it. Written like `values`. |
An entry in `values` must exist, or the tag doesn't load and the server doesn't start. Write it as
`{ "id": ..., "required": false }` when it's fine for it to be missing, like another mod's item that may not be
installed. What `remove` lists never has to exist.
A tag can't contain itself, directly or through other tags.
## Adding to Other Mods' Tags
A mod's tag files can be in any namespace. Every mod's file for the same tag is merged, in
[load order](../concepts/registries.md#loading), so adding to someone else's tag only adds to it. This is
`mods/maple/tags/items/bworld/planks.json`:
```json
{ "format_version": 1, "tag": { "values": ["maple:maple_planks"] } }
```
`replace` and `remove` apply in load order too: a mod can take out what an earlier mod added, and a later mod can add it
back. Depend on the mod whose tag you change, so your file loads after its. check-mods warns when you don't.
## Choosing a Namespace
- A tag for your own mod's behavior, like the blocks your drill can't break, goes in your namespace.
- A tag other mods would want to share, like a new metal's ingots, goes in the `c` namespace, like NeoForge's and
Fabric's shared tags. No mod owns `c`, so using it needs no dependency.
- Tag names are plural (`planks`, `ingots`). Group them with folders, with a tag for the whole folder holding each tag
in it: `#c:ingots` holds `#c:ingots/iron`, `#c:ingots/copper` and so on.
## The Base Game's Tags
| Tag | Registry | What's in it |
| ---------------- | ------------- | ------------------------------------------------------------------------ |
| `#bworld:planks` | items, blocks | Every kind of planks. |
| `#bworld:logs` | items, blocks | Every kind of log. |
| `#bworld:leaves` | blocks | Every kind of leaves. |
| `#c:ingots` | items | `#c:ingots/copper`, `#c:ingots/tin`, `#c:ingots/iron`, `#c:ingots/gold`. |
## Using Tags in Data
- **Recipes**: anywhere a recipe takes an item (shaped `key` values, furnace `input`, fuel `item`) it can take an item
tag, on its own or in a list: `"key": { "P": "#bworld:planks" }`. See [Choices](recipes.md#choices).
- **Blocks**: `place_on` and `place_in` take block tags, like `"place_on": ["#bworld:logs"]` for a fungus that grows on
any log. See [Placement](../blocks/index.md#placement).
A tag nobody defines is a check-mods error there.
## Using Tags in Scripts
Server and client scripts both have `ctx.tags`. Tags can be written with or without their `#`:
```ts
ctx.tags.has("items", "bworld:planks", item.id); // whether it's in the tag
ctx.tags.get("blocks", "#bworld:logs"); // every id in it, including its tags' ids
ctx.tags.of("items", "bworld:iron_ingot"); // every tag it's in: ["c:ingots", "c:ingots/iron"]
ctx.tags.exists("items", "c:ingots/tin"); // whether any mod defines it
ctx.tags.expand(["#bworld:planks", "bworld:stick"]); // every item a recipe's choice stands for
```
`has` and `get` treat a tag nobody defines as empty.
Mods' own [recipe types](recipes.md#custom-recipe-types) should take tags like the base game's do. `expand` turns a
choice into the items it stands for, so the mod's server script can check and match them:
```ts
const ingredient = ctx.tags.expand(json.ingredient); // "#bworld:planks" -> ["bworld:planks", "bworld:spruce_planks", ...]
```
+1 -9
View File
@@ -7,15 +7,7 @@
" P "
],
"key": {
"P": [
"bworld:planks",
"bworld:spruce_planks",
"bworld:birch_planks",
"bworld:jungle_planks",
"bworld:acacia_planks",
"bworld:dark_oak_planks",
"bworld:cherry_planks"
]
"P": "#bworld:planks"
},
"result": {
"id": "bworld:bowl",
+1 -9
View File
@@ -8,15 +8,7 @@
"PPP"
],
"key": {
"P": [
"bworld:planks",
"bworld:spruce_planks",
"bworld:birch_planks",
"bworld:jungle_planks",
"bworld:acacia_planks",
"bworld:dark_oak_planks",
"bworld:cherry_planks"
]
"P": "#bworld:planks"
},
"result": {
"id": "bworld:chest",
@@ -9,15 +9,7 @@
],
"key": {
"S": "bworld:stone",
"P": [
"bworld:planks",
"bworld:spruce_planks",
"bworld:birch_planks",
"bworld:jungle_planks",
"bworld:acacia_planks",
"bworld:dark_oak_planks",
"bworld:cherry_planks"
]
"P": "#bworld:planks"
},
"result": {
"id": "bworld:smithing_table",
+1 -9
View File
@@ -7,15 +7,7 @@
"P"
],
"key": {
"P": [
"bworld:planks",
"bworld:spruce_planks",
"bworld:birch_planks",
"bworld:jungle_planks",
"bworld:acacia_planks",
"bworld:dark_oak_planks",
"bworld:cherry_planks"
]
"P": "#bworld:planks"
},
"result": {
"id": "bworld:stick",
+1 -9
View File
@@ -8,15 +8,7 @@
" S"
],
"key": {
"P": [
"bworld:planks",
"bworld:spruce_planks",
"bworld:birch_planks",
"bworld:jungle_planks",
"bworld:acacia_planks",
"bworld:dark_oak_planks",
"bworld:cherry_planks"
],
"P": "#bworld:planks",
"S": "bworld:stick"
},
"result": {
+1 -9
View File
@@ -8,15 +8,7 @@
" S"
],
"key": {
"P": [
"bworld:planks",
"bworld:spruce_planks",
"bworld:birch_planks",
"bworld:jungle_planks",
"bworld:acacia_planks",
"bworld:dark_oak_planks",
"bworld:cherry_planks"
],
"P": "#bworld:planks",
"S": "bworld:stick"
},
"result": {
@@ -8,15 +8,7 @@
" S "
],
"key": {
"P": [
"bworld:planks",
"bworld:spruce_planks",
"bworld:birch_planks",
"bworld:jungle_planks",
"bworld:acacia_planks",
"bworld:dark_oak_planks",
"bworld:cherry_planks"
],
"P": "#bworld:planks",
"S": "bworld:stick"
},
"result": {
@@ -8,15 +8,7 @@
"S"
],
"key": {
"P": [
"bworld:planks",
"bworld:spruce_planks",
"bworld:birch_planks",
"bworld:jungle_planks",
"bworld:acacia_planks",
"bworld:dark_oak_planks",
"bworld:cherry_planks"
],
"P": "#bworld:planks",
"S": "bworld:stick"
},
"result": {
@@ -8,15 +8,7 @@
" PP"
],
"key": {
"P": [
"bworld:planks",
"bworld:spruce_planks",
"bworld:birch_planks",
"bworld:jungle_planks",
"bworld:acacia_planks",
"bworld:dark_oak_planks",
"bworld:cherry_planks"
],
"P": "#bworld:planks",
"S": "bworld:stick"
},
"result": {
+1 -9
View File
@@ -2,15 +2,7 @@
"format_version": 1,
"recipe": {
"type": "fuel",
"item": [
"bworld:log",
"bworld:spruce_log",
"bworld:birch_log",
"bworld:jungle_log",
"bworld:acacia_log",
"bworld:dark_oak_log",
"bworld:cherry_log"
],
"item": "#bworld:logs",
"burn_time": 100
}
}
+1 -9
View File
@@ -2,15 +2,7 @@
"format_version": 1,
"recipe": {
"type": "furnace",
"input": [
"bworld:log",
"bworld:spruce_log",
"bworld:birch_log",
"bworld:jungle_log",
"bworld:acacia_log",
"bworld:dark_oak_log",
"bworld:cherry_log"
],
"input": "#bworld:logs",
"output": {
"id": "bworld:coal",
"count": 1
@@ -0,0 +1,14 @@
{
"format_version": 1,
"tag": {
"values": [
"bworld:leaves",
"bworld:spruce_leaves",
"bworld:birch_leaves",
"bworld:jungle_leaves",
"bworld:acacia_leaves",
"bworld:dark_oak_leaves",
"bworld:cherry_leaves"
]
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"format_version": 1,
"tag": {
"values": [
"bworld:log",
"bworld:spruce_log",
"bworld:birch_log",
"bworld:jungle_log",
"bworld:acacia_log",
"bworld:dark_oak_log",
"bworld:cherry_log"
]
}
}
@@ -0,0 +1,14 @@
{
"format_version": 1,
"tag": {
"values": [
"bworld:planks",
"bworld:spruce_planks",
"bworld:birch_planks",
"bworld:jungle_planks",
"bworld:acacia_planks",
"bworld:dark_oak_planks",
"bworld:cherry_planks"
]
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"format_version": 1,
"tag": {
"values": [
"bworld:log",
"bworld:spruce_log",
"bworld:birch_log",
"bworld:jungle_log",
"bworld:acacia_log",
"bworld:dark_oak_log",
"bworld:cherry_log"
]
}
}
+14
View File
@@ -0,0 +1,14 @@
{
"format_version": 1,
"tag": {
"values": [
"bworld:planks",
"bworld:spruce_planks",
"bworld:birch_planks",
"bworld:jungle_planks",
"bworld:acacia_planks",
"bworld:dark_oak_planks",
"bworld:cherry_planks"
]
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"format_version": 1,
"tag": {
"values": [
"#c:ingots/copper",
"#c:ingots/tin",
"#c:ingots/iron",
"#c:ingots/gold"
]
}
}
@@ -0,0 +1,8 @@
{
"format_version": 1,
"tag": {
"values": [
"bworld:copper_ingot"
]
}
}
@@ -0,0 +1,8 @@
{
"format_version": 1,
"tag": {
"values": [
"bworld:gold_ingot"
]
}
}
@@ -0,0 +1,8 @@
{
"format_version": 1,
"tag": {
"values": [
"bworld:iron_ingot"
]
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"format_version": 1,
"tag": {
"values": [
"bworld:tin_ingot"
]
}
}
@@ -2,19 +2,17 @@
"format_version": 1,
"recipe": {
"type": "shaped",
"pattern": ["SPP", "SPP"],
"pattern": [
"SPP",
"SPP"
],
"key": {
"S": "bworld:stick",
"P": [
"bworld:planks",
"bworld:spruce_planks",
"bworld:birch_planks",
"bworld:jungle_planks",
"bworld:acacia_planks",
"bworld:dark_oak_planks",
"bworld:cherry_planks"
]
"P": "#bworld:planks"
},
"result": { "id": "farmersdelight:cutting_board", "count": 1 }
"result": {
"id": "farmersdelight:cutting_board",
"count": 1
}
}
}
@@ -7,15 +7,7 @@
"S"
],
"key": {
"P": [
"bworld:planks",
"bworld:spruce_planks",
"bworld:birch_planks",
"bworld:jungle_planks",
"bworld:acacia_planks",
"bworld:dark_oak_planks",
"bworld:cherry_planks"
],
"P": "#bworld:planks",
"S": "bworld:stick"
},
"result": {
+26 -10
View File
@@ -72,9 +72,10 @@ const HEAT_SOURCES: Record<string, string | undefined> = {
"farmersdelight:stove": "lit",
};
// a farmersdelight:cooking recipe: the ingredients in any slots, each an item id or a list of ids any of which will do
// a farmersdelight:cooking recipe: the ingredients in any slots. in the json each is an item id or #tag, or a list of
// those any of which will do. here each is every item that will do
interface CookingRecipe {
ingredients: (string | string[])[];
ingredients: string[][];
result: { id: string; count: number };
// what the meal is served in, like a bowl. without it the meal comes out as soon as it's cooked
container?: string;
@@ -111,6 +112,15 @@ const POT_BARS = [
},
];
// an ingredient: an item, or a #tag of items any of which will do
function item_or_tag(ctx: ServerContext, where: string, id: unknown) {
if (typeof id === "string" && id.startsWith("#")) {
if (!ctx.tags.exists("items", id)) throw new Error(`${where}: there's no item tag ${id}`);
} else if (typeof id !== "string" || !ctx.items.exists(id)) {
throw new Error(`${where}: there's no item ${id}`);
}
}
// checked when the server starts, so a broken recipe is a load error naming it
function load_recipes(ctx: ServerContext): CookingRecipe[] {
return ctx.recipes.list("farmersdelight:cooking").map((json, i) => {
@@ -126,9 +136,9 @@ function load_recipes(ctx: ServerContext): CookingRecipe[] {
for (const ingredient of ingredients) {
if (Array.isArray(ingredient)) {
if (ingredient.length === 0) throw new Error(`${where}: an ingredient's list of items is empty`);
ingredient.forEach(item);
ingredient.forEach((id) => item_or_tag(ctx, where, id));
} else {
item(ingredient);
item_or_tag(ctx, where, ingredient);
}
}
item(json.result?.id);
@@ -140,7 +150,12 @@ function load_recipes(ctx: ServerContext): CookingRecipe[] {
if (!Number.isInteger(cook_time) || cook_time < 1) {
throw new Error(`${where}: cook_time must be positive ticks`);
}
return { ingredients, result: json.result, container: json.container, cook_time };
return {
ingredients: ingredients.map((ingredient: string | string[]) => ctx.tags.expand(ingredient)),
result: json.result,
container: json.container,
cook_time,
};
});
}
@@ -156,10 +171,10 @@ function find_recipe(recipes: CookingRecipe[], container: Container): CookingRec
}
// pairs every ingredient with a different item, trying each way round, like a shapeless recipe
function matches(ingredients: (string | string[])[], items: string[], used = new Set<number>()): boolean {
function matches(ingredients: string[][], items: string[], used = new Set<number>()): boolean {
if (ingredients.length === 0) return true;
const [first, ...rest] = ingredients;
const fits = (id: string) => Array.isArray(first) ? first.includes(id) : first === id;
const fits = (id: string) => first.includes(id);
for (let i = 0; i < items.length; i++) {
if (used.has(i) || !fits(items[i])) continue;
used.add(i);
@@ -336,9 +351,10 @@ function load_cutting_recipes(ctx: ServerContext): CuttingRecipe[] {
if (!Array.isArray(json.ingredients) || json.ingredients.length !== 1) {
throw new Error(`${where}: ingredients must be one item, or one list of items any of which will do`);
}
const ingredient = [json.ingredients[0]].flat();
if (ingredient.length === 0) throw new Error(`${where}: the ingredient's list of items is empty`);
ingredient.forEach(item);
const choice = [json.ingredients[0]].flat();
if (choice.length === 0) throw new Error(`${where}: the ingredient's list of items is empty`);
choice.forEach((id) => item_or_tag(ctx, where, id));
const ingredient = ctx.tags.expand(choice);
if (typeof json.tool !== "string") throw new Error(`${where}: tool must be a tool type, like "knife"`);
if (!Array.isArray(json.result) || json.result.length === 0) {
throw new Error(`${where}: result must be a list of { id, count }`);
+29 -31
View File
@@ -1,7 +1,7 @@
// a recipe viewer like just enough items: every item in a list next to the inventory, searchable, and clicking one (or
// R and U over any item) shows the recipes that make it and the ones that use it. it only reads recipes, so it works
// with any mod's, and draws the ones it doesn't know as their items in, then what comes out
import type { ClientContext, Color, Graphics, InventoryScreenView } from "bworld/client";
import type { ClientContext, Color, Graphics, InventoryScreenView, TagApi } from "bworld/client";
// items and slots are drawn this big
const CELL = 54;
@@ -81,7 +81,7 @@ class RecipeViewer {
return this.#recipes.filter((recipe) =>
mode === "recipes"
? outputs(recipe).some((output) => output.ids.includes(item))
: inputs(recipe).some((input) => input.ids.includes(item))
: inputs(recipe, this.ctx.tags).some((input) => input.ids.includes(item))
);
}
@@ -165,14 +165,14 @@ class RecipeViewer {
const recipes = this.#find(view.item, view.mode);
const top = y + GAP + BUTTON;
const bottom = y + height - GAP - BUTTON;
const pages = paginate(recipes, bottom - top);
const pages = paginate(recipes, bottom - top, this.ctx.tags);
view.page = Math.min(view.page, pages.length - 1);
let hovered: string | undefined;
let card_y = top;
for (const recipe of pages[view.page]) {
hovered = this.#card(g, recipe, x + GAP, card_y, width - GAP * 2) ?? hovered;
card_y += card_height(recipe);
card_y += card_height(recipe, this.ctx.tags);
}
const page_count = pages.length;
@@ -223,7 +223,7 @@ class RecipeViewer {
const letter = recipe.pattern[row]?.[column];
const choice = letter && letter !== " " && column < width_in ? recipe.key[letter] : undefined;
cell(
choice ? { ids: choice_ids(choice), count: 1 } : undefined,
choice ? { ids: this.ctx.tags.expand(choice), count: 1 } : undefined,
x + column * CELL,
top + row * CELL,
);
@@ -234,14 +234,14 @@ class RecipeViewer {
break;
}
case "furnace":
cell({ ids: choice_ids(recipe.input), count: 1 }, x, top);
cell({ ids: this.ctx.tags.expand(recipe.input), count: 1 }, x, top);
texture("bworld:fire_full", x, top + CELL);
texture("bworld:arrow_full", x + 1.5 * CELL, top + CELL / 2);
cell(stack(recipe.output), x + 3 * CELL, top + CELL / 2);
g.text(seconds(recipe.cook_time), x + 1.5 * CELL, top + CELL * 1.5, { color: LABEL_COLOR });
break;
case "fuel":
cell({ ids: choice_ids(recipe.item), count: 1 }, x, top);
cell({ ids: this.ctx.tags.expand(recipe.item), count: 1 }, x, top);
texture("bworld:fire_full", x, top + CELL);
g.text(`Burns for ${seconds(recipe.burn_time)}`, x + 1.5 * CELL, top + CELL / 2, {
color: LABEL_COLOR,
@@ -257,7 +257,7 @@ class RecipeViewer {
default: {
// a mod's own type: the items in its lists in a grid, single items (like a bowl to serve in) under
// the arrow, then what it makes, one under the other
const { grid, extras } = mod_recipe_inputs(recipe);
const { grid, extras } = mod_recipe_inputs(recipe, this.ctx.tags);
grid.slice(0, 9).forEach((ingredient, i) =>
cell(ingredient, x + (i % 3) * CELL, top + Math.floor(i / 3) * CELL)
);
@@ -281,21 +281,21 @@ class RecipeViewer {
}
// a card's height: its label, its rows of items, and a gap
function card_height(recipe: Recipe): number {
function card_height(recipe: Recipe, tags: TagApi): number {
let rows = 2;
if (recipe.type === "shaped") rows = 3;
else if (!(recipe.type in CATEGORY_NAMES)) {
rows = Math.max(2, Math.ceil(mod_recipe_inputs(recipe).grid.length / 3), outputs(recipe).length);
rows = Math.max(2, Math.ceil(mod_recipe_inputs(recipe, tags).grid.length / 3), outputs(recipe).length);
}
return LINE + Math.min(rows, 3) * CELL + GAP;
}
// as many cards on each page as fit, at least one
function paginate(recipes: Recipe[], height: number): Recipe[][] {
function paginate(recipes: Recipe[], height: number, tags: TagApi): Recipe[][] {
const pages: Recipe[][] = [[]];
let used = 0;
for (const recipe of recipes) {
const needed = card_height(recipe);
const needed = card_height(recipe, tags);
if (used + needed > height && pages.at(-1)!.length > 0) {
pages.push([]);
used = 0;
@@ -306,11 +306,6 @@ function paginate(recipes: Recipe[], height: number): Recipe[][] {
return pages;
}
// shaped keys, furnace inputs and fuels can be one item or a list any of which fits
function choice_ids(choice: string | string[]): string[] {
return typeof choice === "string" ? [choice] : choice;
}
// what a recipe makes
export function outputs(recipe: Recipe): Ingredient[] {
switch (recipe.type) {
@@ -334,50 +329,53 @@ export function outputs(recipe: Recipe): Ingredient[] {
}
}
// what a recipe takes
export function inputs(recipe: Recipe): Ingredient[] {
// what a recipe takes. shaped keys, furnace inputs and fuels can be an item or #tag, or a list any of which fits
export function inputs(recipe: Recipe, tags: TagApi): Ingredient[] {
switch (recipe.type) {
case "shaped":
return Object.values(recipe.key as Record<string, string | string[]>).map((choice) => ({
ids: choice_ids(choice),
ids: tags.expand(choice),
count: 1,
}));
case "furnace":
return [{ ids: choice_ids(recipe.input), count: 1 }];
return [{ ids: tags.expand(recipe.input), count: 1 }];
case "fuel":
return [{ ids: choice_ids(recipe.item), count: 1 }];
return [{ ids: tags.expand(recipe.item), count: 1 }];
case "smithing":
return [{ ids: [recipe.tool], count: 1 }, stack(recipe.material)].concat(
recipe.addition ? [{ ids: [recipe.addition], count: 1 }] : [],
);
default: {
const { grid, extras } = mod_recipe_inputs(recipe);
const { grid, extras } = mod_recipe_inputs(recipe, tags);
return [...grid, ...extras];
}
}
}
// the items in a mod recipe's fields besides its type and result: each item in a list is an ingredient (a list in a
// list is one ingredient any of whose items fit), and a field that's one item is an extra, like a container
function mod_recipe_inputs(recipe: Recipe): { grid: Ingredient[]; extras: Ingredient[] } {
// the items in a mod recipe's fields besides its type and result: each item or #tag in a list is an ingredient (a list
// in a list is one ingredient any of whose items fit), and a field that's one item is an extra, like a container
function mod_recipe_inputs(recipe: Recipe, tags: TagApi): { grid: Ingredient[]; extras: Ingredient[] } {
const grid: Ingredient[] = [];
const extras: Ingredient[] = [];
const is_id = (value: unknown): value is string =>
typeof value === "string" && /^[a-z0-9_]+:[a-z0-9_/]+$/.test(value);
const ingredient = (choice: string | string[]) => ({ ids: tags.expand(choice), count: 1 });
for (const [field, value] of Object.entries(recipe)) {
if (field === "type" || field === "result" || field === "output") continue;
if (is_id(value)) {
extras.push({ ids: [value], count: 1 });
extras.push(ingredient(value));
} else if (Array.isArray(value)) {
for (const entry of value) {
if (is_id(entry)) grid.push({ ids: [entry], count: 1 });
else if (Array.isArray(entry) && entry.every(is_id)) grid.push({ ids: entry, count: 1 });
if (is_id(entry) || (Array.isArray(entry) && entry.every(is_id))) grid.push(ingredient(entry));
}
}
}
return { grid, extras };
}
// an item id or #tag
function is_id(value: unknown): value is string {
return typeof value === "string" && /^#?[a-z0-9_]+:[a-z0-9_/]+$/.test(value);
}
function stack(value: { id: string; count: number }): Ingredient {
return { ids: [value.id], count: value.count };
}
+2 -2
View File
@@ -1,6 +1,6 @@
import { Container, ItemStack } from "$/common/inventory.ts";
import { CRAFTING_RESULT_SLOT } from "$/common/protocol.ts";
import { choice_ids, type GridRecipe } from "$/common/mod_data.ts";
import { choice_matches, type GridRecipe } from "$/common/mod_data.ts";
// recipes come from mods, see RecipeBook in common/mod_loader.ts
@@ -28,7 +28,7 @@ function matches_recipe(grid: (string | undefined)[], recipe: GridRecipe): boole
if (
choice === undefined
? item !== undefined
: item === undefined || !choice_ids(choice).includes(item)
: item === undefined || !choice_matches(choice, item)
) {
match = false;
break;
+2
View File
@@ -3,6 +3,7 @@
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
import { Container as EngineContainer, ItemStack as EngineItemStack } from "$/common/inventory.ts";
import { get_state_value, set_state_value } from "$/common/utils.ts";
import { tag_api } from "$/common/tags.ts";
import type {
BlockComponent,
BlockRef,
@@ -514,6 +515,7 @@ export class ModRuntime {
},
list: (type) => structuredClone(game().recipes.by_type.get(type) ?? []),
},
tags: tag_api(),
containers: {
create: (size) => {
if (!Number.isInteger(size) || size < 1 || size > MAX_CONTAINER_SIZE) {
+1
View File
@@ -102,6 +102,7 @@ function as_loaded_mod(file: string, bmod: Bmod): LoadedMod {
ores: entries(bmod.data.ores),
entities: entries(bmod.data.entities),
entity_models: entries(bmod.data.entity_models),
tags: entries(bmod.data.tags),
textures: [...bmod.textures.keys()],
texture_files: new Map(),
};
+1 -1
View File
@@ -240,7 +240,7 @@ Deno.test("the atlas fits textures of any size, tallest first, without overlappi
Deno.test("a mod with only data packs and reads", () => {
const bmod = {
manifest: { format_version: 1, id: "tiny", name: "Tiny", version: "1.0.0" },
data: { blocks: [], models: [], items: [], recipes: [], ores: [], entities: [], entity_models: [] },
data: { blocks: [], models: [], items: [], recipes: [], ores: [], entities: [], entity_models: [], tags: [] },
scripts: {},
textures: new Map(),
};
+1
View File
@@ -34,6 +34,7 @@ export function mod_sources(mods_dir: string): ServerModSource[] {
ores: mod.ores.map((o) => o.json),
entities: mod.entities.map((e) => e.json),
entity_models: mod.entity_models.map((m) => m.json),
tags: mod.tags.map((t) => t.json),
},
server_url: url(scripts.server),
worldgen_url: url(scripts.worldgen),
+4 -1
View File
@@ -1,9 +1,12 @@
// the recipe viewer mod reads every mod's recipes, its own types included
import { assert, assertEquals } from "@std/assert";
import { category_name, inputs, outputs } from "../mods/recipe_viewer/scripts/client.ts";
import { category_name, inputs as recipe_inputs, outputs } from "../mods/recipe_viewer/scripts/client.ts";
import { tag_api } from "$/common/tags.ts";
import { test_game } from "./helpers.ts";
const ids = (ingredients: { ids: string[] }[]) => ingredients.map((i) => i.ids.join("|"));
// deno-lint-ignore no-explicit-any
const inputs = (recipe: any) => recipe_inputs(recipe, tag_api());
Deno.test("the recipe viewer finds what makes and uses an item, in any recipe type", async () => {
const { game } = await test_game("mods");
+212
View File
@@ -0,0 +1,212 @@
// tags: lists of blocks, items or entities that every mod can add to, see docs/modding/resources/tags.md
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 { 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";
import { update_crafting_result } from "$/server/game/crafting.ts";
import { check_mods } from "$/tools/check_mods.ts";
import { copy_dir, test_game } from "./helpers.ts";
// tag files in load order, all item tags unless they say otherwise
function resolve(files: [mod: string, json: Partial<TagJson> & { id: string }][], existing: string[]) {
const sources: TagSource[] = files.map(([mod, json], i) => ({
mod,
file: `file${i}`,
json: { registry: "items", values: [], ...json },
}));
const known = new Set(existing);
const { tags, problems } = resolve_tags(sources, (_, id) => known.has(id));
return { items: tags.get("items") ?? new Map(), problems: problems.map((p) => `${p.mod} ${p.file}: ${p.message}`) };
}
Deno.test("tags from every mod merge in load order, and hold other tags", () => {
const { items, problems } = resolve([
["a", { id: "c:ingots/iron", values: ["a:iron"] }],
["a", { id: "c:ingots", values: ["#c:ingots/iron", "#c:ingots/tin"] }],
["b", { id: "c:ingots/tin", values: ["b:tin"] }],
["b", { id: "c:ingots/iron", values: ["b:iron", "a:iron"] }],
], ["a:iron", "b:iron", "b:tin"]);
assertEquals(problems, []);
assertEquals(items.get("c:ingots/iron"), ["a:iron", "b:iron"]);
// a tag can hold one defined after it
assertEquals(items.get("c:ingots"), ["a:iron", "b:iron", "b:tin"]);
});
Deno.test("replace drops what came before, and removes apply in order", () => {
const { items, problems } = resolve([
["a", { id: "a:things", values: ["a:one", "a:two", "a:three"] }],
["b", { id: "a:things", values: [], remove: ["a:two", "#a:others"] }],
["c", { id: "a:others", values: ["a:three"] }],
// added back after b removed it
["c", { id: "a:things", values: ["a:two"] }],
["d", { id: "a:replaced", values: ["a:one"] }],
["e", { id: "a:replaced", values: ["a:two"], replace: true }],
], ["a:one", "a:two", "a:three"]);
assertEquals(problems, []);
assertEquals(items.get("a:things"), ["a:one", "a:two"]);
assertEquals(items.get("a:replaced"), ["a:two"]);
});
Deno.test("optional entries can be missing, required ones and circles stop a tag loading", () => {
const { items, problems } = resolve([
["a", {
id: "a:soft",
values: ["a:real", { id: "other:maybe", required: false }, { id: "#x:y", required: false }],
}],
// removing what doesn't exist is fine
["a", { id: "a:soft", values: [], remove: ["other:gone", "#nobody:defines"] }],
["a", { id: "a:hard", values: ["a:real", "other:missing"] }],
["a", { id: "a:undefined", values: ["#nobody:defines"] }],
["a", { id: "a:loop1", values: ["#a:loop2"] }],
["a", { id: "a:loop2", values: ["#a:loop1"] }],
["a", { id: "a:self", values: ["#a:self"] }],
// holding a tag that failed fails too, without repeating why
["a", { id: "a:outer", values: ["#a:hard"] }],
], ["a:real"]);
assertEquals(items.get("a:soft"), ["a:real"]);
for (const failed of ["a:hard", "a:undefined", "a:loop1", "a:loop2", "a:self", "a:outer"]) {
assert(!items.has(failed), failed);
}
assertEquals(problems, [
"a file2: #a:hard needs other:missing, which doesn't exist",
"a file3: #a:undefined needs #nobody:defines, which no mod defines",
"a file5: tags contain each other in a circle: #a:loop1 -> #a:loop2 -> #a:loop1",
"a file6: tags contain each other in a circle: #a:self -> #a:self",
]);
});
Deno.test("the base game's tags, from scripts", async () => {
await test_game("mods");
const tags = tag_api();
assertEquals(tags.get("items", "bworld:planks").length, 7);
assert(tags.has("items", "#bworld:logs", "bworld:cherry_log"));
assert(tags.has("blocks", "bworld:leaves", "bworld:birch_leaves"));
assert(!tags.has("items", "bworld:planks", "bworld:stone"));
assertEquals(tags.get("items", "c:ingots"), [
"bworld:copper_ingot",
"bworld:tin_ingot",
"bworld:iron_ingot",
"bworld:gold_ingot",
]);
// in the order the tags were defined
assertEquals(tags.of("items", "bworld:iron_ingot"), ["c:ingots", "c:ingots/iron"]);
// nobody's tag is empty, not an error
assert(!tags.exists("items", "nobody:tag"));
assertEquals(tags.get("items", "nobody:tag"), []);
assertEquals(tags.expand(["#c:ingots/tin", "bworld:coal", "bworld:tin_ingot"]), [
"bworld:tin_ingot",
"bworld:coal",
]);
// copies
tags.get("items", "bworld:planks").pop();
assertEquals(tags.get("items", "bworld:planks").length, 7);
// deno-lint-ignore no-explicit-any
assertThrows(() => tags.has("recipes" as any, "bworld:planks", "bworld:planks"), Error, 'not "recipes"');
});
// mods/bworld and a mod that adds maple wood to the base game's tags
function mods_with_maple() {
const dir = Deno.makeTempDirSync({ prefix: "bworld_tags_" });
copy_dir("mods/bworld", `${dir}/bworld`);
const write = (path: string, json: unknown) => write_json(`${dir}/maple/${path}`, json);
write("manifest.json", {
format_version: 1,
id: "maple",
name: "Maple",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
});
write("blocks/maple_planks.json", {
format_version: 1,
block: { id: "maple:maple_planks", textures: "bworld:oak_planks" },
});
write("blocks/maple_log.json", { format_version: 1, block: { id: "maple:maple_log", textures: "bworld:oak_log" } });
write("blocks/shelf_fungus.json", {
format_version: 1,
block: { id: "maple:shelf_fungus", textures: "bworld:dirt", place_on: ["#bworld:logs"] },
});
write("tags/items/bworld/planks.json", { format_version: 1, tag: { values: ["maple:maple_planks"] } });
write("tags/blocks/bworld/logs.json", { format_version: 1, tag: { values: ["maple:maple_log"] } });
// the shared namespace, with a folder
write("tags/items/c/wood/maple.json", {
format_version: 1,
tag: { values: ["maple:maple_planks", { id: "other_mod:maple_syrup", required: false }] },
});
return dir;
}
function write_json(path: string, json: unknown) {
Deno.mkdirSync(path.replace(/\/[^/]+$/, ""), { recursive: true });
Deno.writeTextFileSync(path, JSON.stringify(json));
}
Deno.test("a mod's planks work in every recipe that takes #bworld:planks", async () => {
const dir = mods_with_maple();
const { game } = await test_game(dir);
const grid = new Container(10);
grid.set_item(0, new ItemStack("maple:maple_planks", 1));
grid.set_item(3, new ItemStack("bworld:birch_planks", 1));
update_crafting_result(grid, game.recipes.shaped);
assertEquals(grid.get_item(CRAFTING_RESULT_SLOT)?.type_id, "bworld:stick");
// place_on takes block tags
const fungus = EverythingRegistry.get<BlockRegistry>("blocks", "maple:shelf_fungus");
assert(can_stand_on(fungus, "maple:maple_log"));
assert(can_stand_on(fungus, "bworld:spruce_log"));
assert(!can_stand_on(fungus, "bworld:stone"));
assertEquals(tag_api().get("items", "c:wood/maple"), ["maple:maple_planks"]);
const report = (await check_mods(dir, { typecheck: false })).find((r) => r.id === "maple")!;
assertEquals(report, { id: "maple", errors: [], warnings: [] });
Deno.removeSync(dir, { recursive: true });
});
Deno.test("check-mods finds broken tags and tags nobody defines", async () => {
const dir = mods_with_maple();
const write = (path: string, json: unknown) => write_json(`${dir}/maple/${path}`, json);
write("tags/items/maple/broken.json", { format_version: 1, tag: { values: ["maple:no_such_item"] } });
write("tags/items/maple/bad.json", { format_version: 1, tag: { values: ["Not An Id"], replace: "yes" } });
write("tags/items/misplaced.json", { format_version: 1, tag: { values: [] } });
write("tags/fluids/maple/sap.json", { format_version: 1, tag: { values: [] } });
write("recipes/uses_missing_tag.json", {
format_version: 1,
recipe: { type: "fuel", item: "#maple:nothing_here", burn_time: 100 },
});
// another mod's namespace, without depending on it
write("tags/items/farmersdelight/knives.json", { format_version: 1, tag: { values: ["maple:maple_planks"] } });
const report = (await check_mods(dir, { typecheck: false })).find((r) => r.id === "maple")!;
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: 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, "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
assert(!report.warnings.some((w) => w.includes("c:wood") || w.includes("other_mod")), report.warnings.join("\n"));
Deno.removeSync(dir, { recursive: true });
});
Deno.test("tags survive packing into a .bmod", () => {
const tag: TagJson = { registry: "items", id: "c:ingots/tin", values: ["x:tin", { id: "y:tin", required: false }] };
const data = {
blocks: [],
models: [],
items: [],
recipes: [],
ores: [],
entities: [],
entity_models: [],
tags: [tag],
};
const manifest = { 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]);
});
+23
View File
@@ -4,6 +4,7 @@ import {
entity_model_from_geo,
FORMAT_VERSION,
OreJson,
type TagJson,
validate_block,
validate_entity,
validate_item,
@@ -11,6 +12,7 @@ import {
validate_model,
validate_ore,
validate_recipe,
validate_tag,
} from "$/common/mod_data.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";
@@ -70,6 +72,7 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
ores: [],
entities: [],
entity_models: [],
tags: [],
textures: [],
texture_files: new Map(),
};
@@ -133,6 +136,26 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
if (model) mod.entity_models.push({ file: path, json: model });
}
// 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 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 });
}
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)) {
+1
View File
@@ -33,6 +33,7 @@ export async function pack_mod(mod: LoadedMod): Promise<Uint8Array<ArrayBuffer>>
ores: mod.ores.map((o) => o.json),
entities: mod.entities.map((e) => e.json),
entity_models: mod.entity_models.map((m) => m.json),
tags: mod.tags.map((t) => t.json),
},
scripts,
textures,