361 lines
16 KiB
TypeScript
361 lines
16 KiB
TypeScript
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
// java blockstates (assets/<namespace>/blockstates/*.json) to bworld's blocks/, so a mod's blocks can be placed and look
|
|
// right: their states, and the model each state is drawn with, turned. how a block behaves isn't in any data file (java
|
|
// mods set mining, sounds and what blocks do in code), so every block gets the same placeholders: a second to break with
|
|
// anything, dropping itself, and what they really have is written by hand after
|
|
import { dirname, join } from "@std/path";
|
|
import { FORMAT_VERSION } from "@/common/mod_data.ts";
|
|
import { is_empty, made_by, model_source, type ModelSource } from "./models.ts";
|
|
import {
|
|
DEFAULT_REMAPS,
|
|
empty_report,
|
|
find_roots,
|
|
format_json,
|
|
id_claims,
|
|
type ImportOptions,
|
|
type ImportReport,
|
|
input_files,
|
|
is_file,
|
|
location_of,
|
|
location_string,
|
|
parse_location,
|
|
type Remaps,
|
|
type ResourceRoot,
|
|
skips,
|
|
to_id,
|
|
write_report,
|
|
} from "./resources.ts";
|
|
|
|
// a model a blockstate draws, turned
|
|
interface Apply {
|
|
model: string;
|
|
x?: number;
|
|
y?: number;
|
|
uvlock?: boolean;
|
|
}
|
|
// a java state condition, property to value
|
|
type Condition = Record<string, string>;
|
|
|
|
// what a block whose model wasn't imported is drawn with: a cube with the missing texture on every side
|
|
const PLACEHOLDER = "bworld:cube";
|
|
|
|
export type BlockResult =
|
|
| {
|
|
kind: "block";
|
|
id: string;
|
|
json: { format_version: number; block: Record<string, unknown> };
|
|
warnings: string[];
|
|
}
|
|
| { kind: "error"; problems: string[] };
|
|
|
|
// the orders values are numbered in, so the ones bworld knows mean what it means by them: a 2 bit "facing" state faces
|
|
// the player who places it with 0 to 3 for north, east, south and west
|
|
const ORDERS = [
|
|
["false", "true"],
|
|
["north", "east", "south", "west", "up", "down"],
|
|
["x", "y", "z"],
|
|
["bottom", "top", "double"],
|
|
["lower", "upper"],
|
|
];
|
|
// which value a block is placed with, for properties java usually starts at something other than the first: a shaft
|
|
// stands up
|
|
const DEFAULTS: Record<string, string> = { axis: "y" };
|
|
// minecraft's full cube models, which blocks built on are solid
|
|
const CUBES = [
|
|
"cube",
|
|
"cube_all",
|
|
"cube_column",
|
|
"cube_column_horizontal",
|
|
"cube_bottom_top",
|
|
"orientable",
|
|
"orientable_with_bottom",
|
|
].map((name) => `minecraft:block/${name}`);
|
|
|
|
export function import_blocks(input: string, options: ImportOptions = {}): ImportReport {
|
|
if (options.output === undefined) throw new Error("--output is needed for blocks");
|
|
const remaps = options.remaps ?? DEFAULT_REMAPS;
|
|
const files = input_files(input, "blockstates", ".json", options.namespace, options.output);
|
|
// models say how a block is drawn (a full cube or not, cutout or translucent) and whether it has an item
|
|
const read = model_source(models_near(input, files.map(({ root }) => root), options));
|
|
const report = empty_report();
|
|
const claim = id_claims(report);
|
|
for (const { root, file } of files) {
|
|
const where = location_of(root, file, ".json");
|
|
const location = location_string(where);
|
|
if (skips(location, remaps, report)) continue;
|
|
let json: unknown;
|
|
try {
|
|
json = JSON.parse(Deno.readTextFileSync(file));
|
|
} catch (e) {
|
|
report.errors.push({ location, problems: [`it isn't valid json: ${(e as Error).message}`] });
|
|
continue;
|
|
}
|
|
const result = convert_blockstate(location, json, read, remaps);
|
|
if (result.kind === "error") report.errors.push({ location, problems: result.problems });
|
|
else if (claim(result.id, location)) {
|
|
for (const warning of result.warnings) report.warnings.push({ location, warning });
|
|
const text = format_json(result.json) + "\n";
|
|
report.written.push({ location, id: result.id, file: join(options.output, `${where.path}.json`), text });
|
|
}
|
|
}
|
|
write_report(report);
|
|
return report;
|
|
}
|
|
|
|
// the models roots that go with some resources: every one in the input, the one next to each root (assets/<ns>/models
|
|
// beside assets/<ns>/blockstates), and --parents
|
|
export function models_near(input: string, roots: ResourceRoot[], options: ImportOptions): ResourceRoot[] {
|
|
const near = roots.map((root) => ({ namespace: root.namespace, dir: join(dirname(root.dir), "models") }));
|
|
return [
|
|
...(is_file(input) ? [] : find_roots(input, "models", options.namespace)),
|
|
...near,
|
|
...(options.parents ?? []).flatMap((dir) => find_roots(dir, "models")),
|
|
];
|
|
}
|
|
|
|
export function convert_blockstate(location: string, json: unknown, read: ModelSource, remaps: Remaps): BlockResult {
|
|
const { namespace, path } = parse_location(location);
|
|
const id = to_id(location);
|
|
const problems: string[] = [];
|
|
const warnings = new Set<string>();
|
|
const state = (json ?? {}) as { variants?: Record<string, unknown>; multipart?: unknown[] };
|
|
|
|
const apply = (value: unknown, where: string): Apply | undefined => {
|
|
// a list is java's random pick between models, of which the first is as good as any
|
|
const first = (Array.isArray(value) ? value[0] : value) as Apply | undefined;
|
|
if (typeof first?.model !== "string") {
|
|
problems.push(`${where} has no model`);
|
|
return undefined;
|
|
}
|
|
if (Array.isArray(value) && value.length > 1) {
|
|
warnings.add("random models were left out, the first is always used");
|
|
}
|
|
return first;
|
|
};
|
|
|
|
// each case: its conditions (several for an "or") and what it draws
|
|
let cases: { conditions: Condition[]; apply: Apply }[];
|
|
if (state.variants !== undefined) {
|
|
cases = Object.entries(state.variants).flatMap(([key, value]) => {
|
|
const drawn = apply(value, `variants["${key}"]`);
|
|
return drawn ? [{ conditions: [parse_key(key)], apply: drawn }] : [];
|
|
});
|
|
cases = without_unused_properties(cases);
|
|
} else if (Array.isArray(state.multipart)) {
|
|
cases = state.multipart.flatMap((part, i) => {
|
|
const { when, apply: value } = (part ?? {}) as { when?: unknown; apply?: unknown };
|
|
const drawn = apply(value, `multipart[${i}].apply`);
|
|
return drawn ? [{ conditions: when_conditions(when), apply: drawn }] : [];
|
|
});
|
|
} else {
|
|
return { kind: "error", problems: ["it has neither variants nor multipart"] };
|
|
}
|
|
if (problems.length > 0) return { kind: "error", problems };
|
|
|
|
// properties as numbered states
|
|
const values = new Map<string, string[]>();
|
|
for (const { conditions } of cases) {
|
|
for (const condition of conditions) {
|
|
for (const [name, value] of Object.entries(condition)) {
|
|
const seen = values.get(name) ?? [];
|
|
if (!seen.includes(value)) values.set(name, [...seen, value]);
|
|
}
|
|
}
|
|
}
|
|
for (const [name, seen] of values) values.set(name, ordered(seen, state.variants !== undefined));
|
|
const states = [...values].map(([name, seen]) => ({
|
|
name,
|
|
bits: Math.max(1, Math.ceil(Math.log2(seen.length))),
|
|
default: Math.max(0, seen.indexOf(DEFAULTS[name] ?? seen[0])),
|
|
}));
|
|
const key = (condition: Condition) =>
|
|
Object.entries(condition).map(([name, value]) => `${name}=${values.get(name)!.indexOf(value)}`).join(",");
|
|
const drawn = (apply: Apply) => {
|
|
const from = location_string(parse_location(apply.model));
|
|
let model = to_id(from, remaps.models);
|
|
const missing = model_missing(from, model, read, remaps);
|
|
if (missing) {
|
|
warnings.add(`${from} ${missing}, so it's drawn as a placeholder cube`);
|
|
model = PLACEHOLDER;
|
|
}
|
|
// java takes -90 for 270
|
|
const x = ((apply.x ?? 0) % 360 + 360) % 360;
|
|
const y = ((apply.y ?? 0) % 360 + 360) % 360;
|
|
return { model, ...(x ? { x } : {}), ...(y ? { y } : {}), ...(apply.uvlock ? { uvlock: true } : {}) };
|
|
};
|
|
|
|
const block: Record<string, unknown> = { id, textures: {} };
|
|
if (state.variants !== undefined) {
|
|
// the model it falls back to is the one it's placed with
|
|
const placed = cases.find(({ conditions: [condition] }) =>
|
|
Object.entries(condition).every(([name, value]) =>
|
|
values.get(name)!.indexOf(value) === states.find((s) =>
|
|
s.name === name
|
|
)!.default
|
|
)
|
|
) ?? cases[0];
|
|
block.model = drawn(placed.apply).model;
|
|
const only = cases.length === 1 && key(cases[0].conditions[0]) === "";
|
|
if (!only || cases[0].apply.x || cases[0].apply.y) {
|
|
block.variants = Object.fromEntries(
|
|
cases.map(({ conditions: [condition], apply }) => [key(condition), drawn(apply)]),
|
|
);
|
|
}
|
|
} else {
|
|
// a block placed as nothing can't be seen to have been placed, like a wall without its post. java places those
|
|
// in a state that draws something, which here is the first part's
|
|
const defaults = (condition: Condition) =>
|
|
Object.entries(condition).every(([name, value]) =>
|
|
values.get(name)!.indexOf(value) === states.find((s) => s.name === name)!.default
|
|
);
|
|
if (!cases.some(({ conditions }) => conditions.some(defaults)) && cases.length > 0) {
|
|
for (const [name, value] of Object.entries(cases[0].conditions[0])) {
|
|
states.find((s) => s.name === name)!.default = values.get(name)!.indexOf(value);
|
|
}
|
|
}
|
|
block.parts = cases.flatMap(({ conditions, apply }) =>
|
|
conditions.map((condition) => {
|
|
const when = key(condition);
|
|
return when === "" ? drawn(apply) : { when, ...drawn(apply) };
|
|
})
|
|
);
|
|
}
|
|
if (states.length > 0) block.states = states;
|
|
|
|
// non-cubes are cutout, so what's behind them isn't hidden, and models can ask for translucent
|
|
const looks = cases.map(({ apply }) => model_looks(location_string(parse_location(apply.model)), read));
|
|
if (looks.some((look) => look.render_type?.includes("translucent"))) block.render_layer = "translucent";
|
|
else if (looks.some((look) => !look.cube || look.render_type?.includes("cutout"))) block.render_layer = "cutout";
|
|
|
|
block.mining = { toughness: 1 };
|
|
const item = `${namespace}:item/${path}`;
|
|
if (!read(item) || remaps.skip?.some((pattern) => new RegExp(pattern).test(item))) {
|
|
// java blocks without an item model have no item, like a block made by another
|
|
block.item = false;
|
|
} else {
|
|
block.drops = id;
|
|
const sprite = made_by(item, read);
|
|
if (sprite === undefined) {
|
|
block.item_model = to_id(item, remaps.models);
|
|
} else {
|
|
// a block's item is drawn flat as its first texture when it has no item model: the sprite's, here
|
|
const layer = merged_textures(item, read).layer0;
|
|
if (layer && !layer.startsWith("#")) block.textures = { item: to_id(layer, remaps.textures) };
|
|
}
|
|
}
|
|
return { kind: "block", id, json: { format_version: FORMAT_VERSION, block }, warnings: [...warnings] };
|
|
}
|
|
|
|
// why the model kind won't have written a model for a block or item to be drawn with, if it won't: one the remaps skip,
|
|
// one made by a loader (obj files, composites), one that doesn't exist, or minecraft's that no remap gives bworld's for
|
|
export function model_missing(from: string, id: string, read: ModelSource, remaps: Remaps): string | undefined {
|
|
if (remaps.skip?.some((pattern) => new RegExp(pattern).test(from))) return "is skipped by the remaps";
|
|
if (parse_location(from).namespace === "minecraft") {
|
|
return id.startsWith("minecraft:") ? "is minecraft's, and no --remap names a bworld model for it" : undefined;
|
|
}
|
|
if (!read(from)) return "doesn't exist";
|
|
if (is_empty(from, read)) return "has nothing in it";
|
|
const made = made_by(from, read);
|
|
return made ? `isn't boxes (${made})` : undefined;
|
|
}
|
|
|
|
// "axis=x,powered=true" as a condition, "" as none
|
|
function parse_key(key: string): Condition {
|
|
return Object.fromEntries(
|
|
key.split(",").filter((part) => part.includes("=")).map((part) => part.split("=").map((s) => s.trim())),
|
|
);
|
|
}
|
|
|
|
// a multipart "when" as the conditions any of which draw it: { "north": "true|side" } is two, and so is
|
|
// { "OR": [{...}, {...}] }. bworld's parts have no "or", so a part that's drawn for several becomes several parts
|
|
function when_conditions(when: unknown): Condition[] {
|
|
if (when === undefined || when === null) return [{}];
|
|
const object = when as Record<string, unknown>;
|
|
if (Array.isArray(object.OR)) return object.OR.flatMap(when_conditions);
|
|
if (Array.isArray(object.AND)) {
|
|
return object.AND.reduce<Condition[]>(
|
|
(all, next) => all.flatMap((a) => when_conditions(next).map((b) => ({ ...a, ...b }))),
|
|
[{}],
|
|
);
|
|
}
|
|
return Object.entries(object).reduce<Condition[]>(
|
|
(all, [name, value]) => all.flatMap((a) => String(value).split("|").map((v) => ({ ...a, [name]: v }))),
|
|
[{}],
|
|
);
|
|
}
|
|
|
|
// variants without the properties that never change what's drawn, like waterlogged, which only take bits and multiply
|
|
// the variants
|
|
function without_unused_properties(cases: { conditions: Condition[]; apply: Apply }[]) {
|
|
const names = new Set(cases.flatMap(({ conditions: [condition] }) => Object.keys(condition)));
|
|
const unused = [...names].filter((name) => {
|
|
const drawn_by_rest = new Map<string, Set<string>>();
|
|
for (const { conditions: [condition], apply } of cases) {
|
|
const rest = JSON.stringify(Object.entries(condition).filter(([other]) => other !== name).sort());
|
|
drawn_by_rest.set(rest, (drawn_by_rest.get(rest) ?? new Set()).add(JSON.stringify(apply)));
|
|
}
|
|
return [...drawn_by_rest.values()].every((drawn) => drawn.size === 1);
|
|
});
|
|
const seen = new Set<string>();
|
|
return cases.flatMap(({ conditions: [condition], apply }) => {
|
|
const kept = Object.fromEntries(Object.entries(condition).filter(([name]) => !unused.includes(name)));
|
|
const key = JSON.stringify(Object.entries(kept).sort());
|
|
if (seen.has(key)) return [];
|
|
seen.add(key);
|
|
return [{ conditions: [kept], apply }];
|
|
});
|
|
}
|
|
|
|
// a property's values in the order they become numbers. variants name every value a property has, but a multipart only
|
|
// the ones its parts are drawn for: a pipe's arm is drawn for "north=true", and "false" is nowhere. so in a multipart,
|
|
// booleans and the properties bworld knows the orders of get all their values, and any other starts with a value no part
|
|
// is drawn for, which blocks are placed with
|
|
function ordered(values: string[], all_named: boolean): string[] {
|
|
const order = ORDERS.find((order) => values.every((value) => order.includes(value)));
|
|
if (order === ORDERS[0] || (order && !all_named)) return order;
|
|
if (order) return order.filter((value) => values.includes(value));
|
|
const sorted = values.every((value) => /^\d+$/.test(value))
|
|
? [...values].sort((a, b) => Number(a) - Number(b))
|
|
: values;
|
|
return all_named ? sorted : ["", ...sorted];
|
|
}
|
|
|
|
// whether a java model is a full cube, and the render type it asks for, going up its parents to the first that has
|
|
// elements or is one of minecraft's cubes
|
|
function model_looks(location: string, read: ModelSource): { cube: boolean; render_type?: string } {
|
|
let render_type: string | undefined;
|
|
const seen = new Set<string>();
|
|
for (let at: string | undefined = location; at && !seen.has(at);) {
|
|
seen.add(at);
|
|
if (CUBES.includes(at)) return { cube: true, render_type };
|
|
const json = read(at);
|
|
if (!json) break;
|
|
if (typeof json.render_type === "string") render_type ??= json.render_type;
|
|
if (json.elements !== undefined) return { cube: is_full_box(json.elements), render_type };
|
|
at = typeof json.parent === "string" ? location_string(parse_location(json.parent)) : undefined;
|
|
}
|
|
return { cube: false, render_type };
|
|
}
|
|
|
|
function is_full_box(elements: unknown): boolean {
|
|
if (!Array.isArray(elements) || elements.length !== 1) return false;
|
|
const { from, to, rotation } = elements[0] as { from?: number[]; to?: number[]; rotation?: { angle?: number } };
|
|
return String(from) === "0,0,0" && String(to) === "16,16,16" && !rotation?.angle;
|
|
}
|
|
|
|
// a java model's texture variables with its parents', its own winning
|
|
export function merged_textures(location: string, read: ModelSource): Record<string, string> {
|
|
const chain: Record<string, string>[] = [];
|
|
const seen = new Set<string>();
|
|
for (let at: string | undefined = location; at && !seen.has(at);) {
|
|
seen.add(at);
|
|
const json = read(at);
|
|
if (!json) break;
|
|
chain.push((json.textures ?? {}) as Record<string, string>);
|
|
at = typeof json.parent === "string" ? location_string(parse_location(json.parent)) : undefined;
|
|
}
|
|
return Object.assign({}, ...chain.reverse());
|
|
}
|