Importer
This commit is contained in:
@@ -0,0 +1,165 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// java block models (assets/<namespace>/models/**.json) to bworld's models/. the formats are close: what changes is
|
||||
// that parents are flattened into each model, faces are top and bottom instead of up and down, ids lose their folders,
|
||||
// and what bworld has no use for (blockbench's names, display transforms, particle textures) is left out
|
||||
import type { ModelElementJson, ModelFace, ModelFaceJson, ModelJson } from "$/common/block_models.ts";
|
||||
import { FORMAT_VERSION } from "$/common/mod_data.ts";
|
||||
import { is_valid_id, location_string, parse_location, type Remaps, to_id } from "./resources.ts";
|
||||
import { NOT_BOXES, VANILLA_MODELS } from "./vanilla_models.ts";
|
||||
|
||||
// reads a java model by location ("create:block/cogwheel"), undefined when there's none
|
||||
export type ModelSource = (location: string) => Record<string, unknown> | undefined;
|
||||
|
||||
export type ModelResult =
|
||||
| { kind: "model"; id: string; json: { format_version: number; model: ModelJson }; warnings: string[] }
|
||||
// only there to be a parent, like minecraft's block/block
|
||||
| { kind: "parent" }
|
||||
| { kind: "skipped"; reason: string }
|
||||
| { kind: "error"; problems: string[] };
|
||||
|
||||
const FACE_NAMES: Record<string, ModelFace> = {
|
||||
down: "bottom",
|
||||
up: "top",
|
||||
north: "north",
|
||||
south: "south",
|
||||
west: "west",
|
||||
east: "east",
|
||||
};
|
||||
const ANGLES = [-45, -22.5, 0, 22.5, 45];
|
||||
|
||||
interface Flat {
|
||||
textures: Record<string, string>;
|
||||
elements?: unknown[];
|
||||
loader?: string;
|
||||
render_type?: string;
|
||||
not_boxes?: string;
|
||||
}
|
||||
|
||||
class ImportError extends Error {}
|
||||
|
||||
export function convert_model(location: string, read: ModelSource, remaps: Remaps): ModelResult {
|
||||
let flat: Flat;
|
||||
try {
|
||||
flat = flatten(location_string(parse_location(location)), read, []);
|
||||
} catch (e) {
|
||||
if (e instanceof ImportError) return { kind: "error", problems: [e.message] };
|
||||
throw e;
|
||||
}
|
||||
if (flat.not_boxes) return { kind: "skipped", reason: flat.not_boxes };
|
||||
if (flat.loader) return { kind: "skipped", reason: `it uses the "${flat.loader}" loader` };
|
||||
if (!flat.elements || flat.elements.length === 0) return { kind: "parent" };
|
||||
|
||||
const problems: string[] = [];
|
||||
const warnings = new Set<string>();
|
||||
if (flat.render_type) warnings.add(`render_type "${flat.render_type}" was left out, set the block's render layer`);
|
||||
const texture = (value: string, where: string) => {
|
||||
if (value.startsWith("#")) return value;
|
||||
const id = to_id(value, remaps.textures);
|
||||
if (!is_valid_id(id)) problems.push(`${where}: "${value}" doesn't make a valid texture id (${id})`);
|
||||
return id;
|
||||
};
|
||||
|
||||
const elements = flat.elements.map((element, i) =>
|
||||
convert_element(element, `elements[${i}]`, texture, problems, warnings)
|
||||
);
|
||||
|
||||
// only the variables faces reach, so particle textures and ones children overrode don't come along
|
||||
const textures: Record<string, string> = {};
|
||||
const pending = elements.flatMap((element) => Object.values(element.faces).map((face) => face!.texture));
|
||||
for (let reference = pending.pop(); reference !== undefined; reference = pending.pop()) {
|
||||
const name = reference.slice(1);
|
||||
if (!reference.startsWith("#") || name in textures || flat.textures[name] === undefined) continue;
|
||||
textures[name] = texture(flat.textures[name], `textures.${name}`);
|
||||
pending.push(textures[name]);
|
||||
}
|
||||
|
||||
const id = to_id(location, remaps.models);
|
||||
if (!is_valid_id(id)) problems.push(`"${location}" doesn't make a valid model id (${id})`);
|
||||
if (problems.length > 0) return { kind: "error", problems };
|
||||
const model: ModelJson = Object.keys(textures).length > 0 ? { id, textures, elements } : { id, elements };
|
||||
return { kind: "model", id, json: { format_version: FORMAT_VERSION, model }, warnings: [...warnings] };
|
||||
}
|
||||
|
||||
// a model with its parents' textures and elements merged in, like minecraft's BlockModel does when it bakes: the child's
|
||||
// textures win, and its elements replace its parent's when it has any
|
||||
function flatten(location: string, read: ModelSource, chain: string[]): Flat {
|
||||
if (chain.includes(location)) throw new ImportError(`its parents loop: ${[...chain, location].join(" -> ")}`);
|
||||
if (NOT_BOXES[location]) return { textures: {}, not_boxes: `${NOT_BOXES[location]} (${location})` };
|
||||
const json = VANILLA_MODELS[location] ?? read(location);
|
||||
if (!json) {
|
||||
throw new ImportError(
|
||||
chain.length === 0 ? `${location} wasn't found` : `its parent ${location} wasn't found, pass --parents`,
|
||||
);
|
||||
}
|
||||
const parent: Flat = typeof json.parent === "string"
|
||||
? flatten(location_string(parse_location(json.parent)), read, [...chain, location])
|
||||
: { textures: {} };
|
||||
return {
|
||||
textures: { ...parent.textures, ...(json.textures as Record<string, string> | undefined) },
|
||||
elements: Array.isArray(json.elements) ? json.elements : parent.elements,
|
||||
loader: typeof json.loader === "string" ? json.loader : parent.loader,
|
||||
render_type: typeof json.render_type === "string" ? json.render_type : parent.render_type,
|
||||
not_boxes: parent.not_boxes,
|
||||
};
|
||||
}
|
||||
|
||||
function convert_element(
|
||||
json: unknown,
|
||||
where: string,
|
||||
texture: (value: string, where: string) => string,
|
||||
problems: string[],
|
||||
warnings: Set<string>,
|
||||
): ModelElementJson {
|
||||
const element = (json ?? {}) as Record<string, unknown>;
|
||||
const point = (key: string) => {
|
||||
const value = element[key];
|
||||
if (Array.isArray(value) && value.length === 3 && value.every((v) => typeof v === "number")) {
|
||||
return value as [number, number, number];
|
||||
}
|
||||
problems.push(`${where}.${key} must be [x, y, z]`);
|
||||
return [0, 0, 0] as [number, number, number];
|
||||
};
|
||||
const out = { from: point("from"), to: point("to") } as ModelElementJson;
|
||||
|
||||
const rotation = element.rotation as Record<string, unknown> | undefined;
|
||||
if (rotation && rotation.angle !== 0) {
|
||||
if (!ANGLES.includes(rotation.angle as number)) {
|
||||
problems.push(`${where}.rotation: an angle of ${rotation.angle} isn't one of ${ANGLES.join(", ")}`);
|
||||
}
|
||||
out.rotation = {
|
||||
origin: rotation.origin as [number, number, number],
|
||||
axis: rotation.axis as "x" | "y" | "z",
|
||||
angle: rotation.angle as number,
|
||||
...(rotation.rescale === true ? { rescale: true } : {}),
|
||||
};
|
||||
}
|
||||
if (element.shade === false) out.shade = false;
|
||||
if (element.light_emission !== undefined) warnings.add("light_emission on elements was left out");
|
||||
|
||||
out.faces = {};
|
||||
for (const [side, value] of Object.entries((element.faces ?? {}) as Record<string, Record<string, unknown>>)) {
|
||||
const name = FACE_NAMES[side];
|
||||
if (!name) {
|
||||
problems.push(`${where}.faces: "${side}" isn't a side`);
|
||||
continue;
|
||||
}
|
||||
if (typeof value.texture !== "string") {
|
||||
problems.push(`${where}.faces.${side} has no texture`);
|
||||
continue;
|
||||
}
|
||||
const face: ModelFaceJson = { texture: texture(value.texture, `${where}.faces.${side}`) };
|
||||
if (Array.isArray(value.uv)) face.uv = value.uv as [number, number, number, number];
|
||||
if (typeof value.rotation === "number" && value.rotation !== 0) face.rotation = value.rotation;
|
||||
if (typeof value.cullface === "string") {
|
||||
// java also takes "bottom" for down
|
||||
const cullface = FACE_NAMES[value.cullface] ?? (value.cullface === "bottom" ? "bottom" : undefined);
|
||||
if (cullface) face.cullface = cullface;
|
||||
else problems.push(`${where}.faces.${side}.cullface: "${value.cullface}" isn't a side`);
|
||||
}
|
||||
if (value.tintindex !== undefined) warnings.add("tintindex on faces was left out");
|
||||
out.faces[name] = face;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// 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 } from "$/common/mod_data.ts";
|
||||
import { relative, resolve, SEPARATOR } from "@std/path";
|
||||
|
||||
export interface Location {
|
||||
namespace: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export function parse_location(value: string): Location {
|
||||
const colon = value.indexOf(":");
|
||||
return colon < 0
|
||||
? { namespace: "minecraft", path: value }
|
||||
: { namespace: value.slice(0, colon), path: value.slice(colon + 1) };
|
||||
}
|
||||
|
||||
export function location_string({ namespace, path }: Location): string {
|
||||
return `${namespace}:${path}`;
|
||||
}
|
||||
|
||||
// rewrites applied to a location before it becomes an id, longest match first: { "minecraft:block/": "bworld:" } turns
|
||||
// minecraft's block textures into the base game's, which are named the same. a key without a trailing / only matches
|
||||
// that location exactly
|
||||
export type Remap = Record<string, string>;
|
||||
|
||||
export interface Remaps {
|
||||
textures: Remap;
|
||||
models: Remap;
|
||||
}
|
||||
|
||||
export const DEFAULT_REMAPS: Remaps = {
|
||||
textures: { "minecraft:block/": "bworld:", "minecraft:item/": "bworld:" },
|
||||
models: {},
|
||||
};
|
||||
|
||||
export function to_id(location: string, remap: Remap = {}): string {
|
||||
const full = location_string(parse_location(location));
|
||||
let mapped = full;
|
||||
for (const from of Object.keys(remap).sort((a, b) => b.length - a.length)) {
|
||||
const prefix = from.endsWith("/") || from.endsWith(":");
|
||||
if (prefix ? full.startsWith(from) : full === from) {
|
||||
mapped = remap[from] + full.slice(from.length);
|
||||
break;
|
||||
}
|
||||
}
|
||||
const { namespace, path } = parse_location(mapped);
|
||||
return `${namespace}:${path.replaceAll("/", "_")}`;
|
||||
}
|
||||
|
||||
export function is_valid_id(id: string): boolean {
|
||||
return ID_PATTERN.test(id);
|
||||
}
|
||||
|
||||
// a folder of one kind of resource (models, textures, ...) for one namespace: assets/<namespace>/<kind>
|
||||
export interface ResourceRoot {
|
||||
namespace: string;
|
||||
dir: string;
|
||||
}
|
||||
|
||||
// the roots of a kind inside a folder: every assets/<namespace>/<kind> under it, or the folder itself when it's one, or
|
||||
// is inside one. a folder that's none of those is a root of the given namespace, if there is one
|
||||
export function find_roots(input: string, kind: string, namespace?: string): ResourceRoot[] {
|
||||
const dir = resolve(input);
|
||||
const enclosing = enclosing_root(dir, kind);
|
||||
if (enclosing) return [enclosing];
|
||||
const roots: ResourceRoot[] = [];
|
||||
for (const assets of find_dirs(dir, "assets")) {
|
||||
for (const entry of read_dir(assets)) {
|
||||
if (entry.isDirectory && is_dir(`${assets}/${entry.name}/${kind}`)) {
|
||||
roots.push({ namespace: entry.name, dir: `${assets}/${entry.name}/${kind}` });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (roots.length === 0 && namespace) roots.push({ namespace, dir });
|
||||
return roots;
|
||||
}
|
||||
|
||||
// the assets/<namespace>/<kind> folder a path is in, if it's in one
|
||||
export function enclosing_root(path: string, kind: string): ResourceRoot | undefined {
|
||||
const parts = resolve(path).split(SEPARATOR);
|
||||
for (let i = parts.length - 1; i >= 2; i--) {
|
||||
if (parts[i] === kind && parts[i - 2] === "assets") {
|
||||
return { namespace: parts[i - 1], dir: parts.slice(0, i + 1).join(SEPARATOR) };
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// a file's location inside its root: assets/create/models/block/cogwheel.json is create:block/cogwheel
|
||||
export function location_of(root: ResourceRoot, file: string, extension: string): Location {
|
||||
const path = relative(root.dir, resolve(file)).split(SEPARATOR).join("/");
|
||||
return { namespace: root.namespace, path: path.slice(0, -extension.length) };
|
||||
}
|
||||
|
||||
// every file with the extension under a folder, as full paths
|
||||
export function walk_files(dir: string, extension: string): string[] {
|
||||
const files: string[] = [];
|
||||
for (const entry of read_dir(dir)) {
|
||||
const path = `${dir}/${entry.name}`;
|
||||
if (entry.isDirectory) files.push(...walk_files(path, extension));
|
||||
else if (entry.name.endsWith(extension)) files.push(path);
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
function find_dirs(dir: string, name: string): string[] {
|
||||
const found: string[] = [];
|
||||
for (const entry of read_dir(dir)) {
|
||||
if (!entry.isDirectory) continue;
|
||||
const path = `${dir}/${entry.name}`;
|
||||
if (entry.name === name) found.push(path);
|
||||
else found.push(...find_dirs(path, name));
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
function read_dir(dir: string): Deno.DirEntry[] {
|
||||
try {
|
||||
return [...Deno.readDirSync(dir)].sort((a, b) => a.name.localeCompare(b.name));
|
||||
} catch (e) {
|
||||
if (e instanceof Deno.errors.NotFound || e instanceof Deno.errors.NotADirectory) return [];
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
function is_dir(path: string): boolean {
|
||||
try {
|
||||
return Deno.statSync(path).isDirectory;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// json in the style of the repo's data files: tabs, and short lists and objects of plain values on one line
|
||||
export function format_json(value: unknown, indent = ""): string {
|
||||
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
||||
const entries = Array.isArray(value)
|
||||
? value.map((v) => format_json(v, indent + "\t"))
|
||||
: Object.entries(value).filter(([, v]) => v !== undefined).map(([k, v]) =>
|
||||
`${JSON.stringify(k)}: ${format_json(v, indent + "\t")}`
|
||||
);
|
||||
const [open, close] = Array.isArray(value) ? ["[", "]"] : ["{", "}"];
|
||||
if (entries.length === 0) return open + close;
|
||||
const flat = Object.values(value).every((v) =>
|
||||
v === null || typeof v !== "object" || (Array.isArray(v) && v.every((x) => x === null || typeof x !== "object"))
|
||||
);
|
||||
const one_line = Array.isArray(value) ? `[${entries.join(", ")}]` : `{ ${entries.join(", ")} }`;
|
||||
if (flat && !one_line.includes("\n") && indent.length * 4 + one_line.length <= 100) return one_line;
|
||||
return `${open}\n${entries.map((e) => indent + "\t" + e).join(",\n")}\n${indent}${close}`;
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// the vanilla parent models mods build on, so their models convert without minecraft's own files: cubes, slabs,
|
||||
// stairs, walls and panes. each is boxes with texture variables for the children to fill in. faces leave out uv, which
|
||||
// then comes from where the face is on the block, as it does in java
|
||||
type Side = "down" | "up" | "north" | "south" | "west" | "east";
|
||||
type Faces = Partial<Record<Side, string>>;
|
||||
type Model = Record<string, unknown>;
|
||||
|
||||
const SIDES: Side[] = ["down", "up", "north", "south", "west", "east"];
|
||||
|
||||
// a box whose faces are given as "#texture", with "!" in front for one hidden by a solid neighbor on that side
|
||||
function box(from: number[], to: number[], faces: Faces, rotations: Partial<Record<Side, number>> = {}) {
|
||||
return {
|
||||
from,
|
||||
to,
|
||||
faces: Object.fromEntries(
|
||||
Object.entries(faces).map(([side, texture]) => [side, {
|
||||
texture: texture.replace("!", ""),
|
||||
...(texture.startsWith("!") ? { cullface: side } : {}),
|
||||
...(rotations[side as Side] ? { rotation: rotations[side as Side] } : {}),
|
||||
}]),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
const all = (texture: (side: Side) => string): Faces => Object.fromEntries(SIDES.map((side) => [side, texture(side)]));
|
||||
const sides = (top: string, bottom: string, side: string) =>
|
||||
all((s) => s === "up" ? top : s === "down" ? bottom : side);
|
||||
|
||||
// a full cube's faces, all hidden by solid neighbors
|
||||
const cube_faces = all((side) => `!#${side}`);
|
||||
const slab = box([0, 0, 0], [16, 8, 16], { ...all((side) => `!#side`), down: "!#bottom", up: "#top" });
|
||||
// the stairs' step is the back (east) half, the way they face with no turn
|
||||
const step = (from: number[], to: number[], culled: Side[]) =>
|
||||
box(from, to, {
|
||||
...Object.fromEntries(
|
||||
(["up", "north", "south", "west", "east"] as Side[]).map((
|
||||
side,
|
||||
) => [side, side === "up" ? "#top" : "#side"]),
|
||||
),
|
||||
...Object.fromEntries(culled.map((side) => [side, side === "up" ? "!#top" : "!#side"])),
|
||||
});
|
||||
const wall_post = box([4, 0, 4], [12, 16, 12], { ...all(() => "#wall"), down: "!#wall", up: "!#wall" });
|
||||
const wall_side = (height: number) =>
|
||||
box([5, 0, 0], [11, height, 8], {
|
||||
down: "!#wall",
|
||||
up: height === 16 ? "!#wall" : "#wall",
|
||||
north: "!#wall",
|
||||
west: "#wall",
|
||||
east: "#wall",
|
||||
});
|
||||
|
||||
export const VANILLA_MODELS: Record<string, Model> = {
|
||||
"minecraft:block/block": {},
|
||||
"minecraft:block/air": {},
|
||||
"minecraft:block/cube": { elements: [box([0, 0, 0], [16, 16, 16], cube_faces)] },
|
||||
"minecraft:block/cube_all": { parent: "block/cube", textures: all(() => "#all") },
|
||||
"minecraft:block/cube_column": { parent: "block/cube", textures: sides("#end", "#end", "#side") },
|
||||
"minecraft:block/cube_bottom_top": { parent: "block/cube", textures: sides("#top", "#bottom", "#side") },
|
||||
"minecraft:block/orientable_with_bottom": {
|
||||
parent: "block/cube",
|
||||
textures: { ...sides("#top", "#bottom", "#side"), north: "#front" },
|
||||
},
|
||||
"minecraft:block/orientable": { parent: "block/orientable_with_bottom", textures: { bottom: "#top" } },
|
||||
// a column lying along north to south, its sides turned so their grain runs the same way
|
||||
"minecraft:block/cube_column_horizontal": {
|
||||
elements: [box(
|
||||
[0, 0, 0],
|
||||
[16, 16, 16],
|
||||
{ down: "!#side", up: "!#side", north: "!#end", south: "!#end", west: "!#side", east: "!#side" },
|
||||
{ down: 180, west: 270, east: 90 },
|
||||
)],
|
||||
},
|
||||
"minecraft:block/slab": { elements: [slab] },
|
||||
"minecraft:block/slab_top": {
|
||||
elements: [box([0, 8, 0], [16, 16, 16], { ...all(() => "!#side"), down: "#bottom", up: "!#top" })],
|
||||
},
|
||||
"minecraft:block/stairs": { elements: [slab, step([8, 8, 0], [16, 16, 16], ["up", "north", "south", "east"])] },
|
||||
"minecraft:block/inner_stairs": {
|
||||
elements: [
|
||||
slab,
|
||||
step([8, 8, 0], [16, 16, 16], ["up", "north", "south", "east"]),
|
||||
step([0, 8, 8], [8, 16, 16], ["up", "south", "west"]),
|
||||
],
|
||||
},
|
||||
"minecraft:block/outer_stairs": { elements: [slab, step([8, 8, 8], [16, 16, 16], ["up", "south", "east"])] },
|
||||
"minecraft:block/template_wall_post": { elements: [wall_post] },
|
||||
"minecraft:block/template_wall_side": { elements: [wall_side(14)] },
|
||||
"minecraft:block/template_wall_side_tall": { elements: [wall_side(16)] },
|
||||
"minecraft:block/wall_inventory": {
|
||||
elements: [
|
||||
wall_post,
|
||||
box([5, 0, 0], [11, 13, 16], { ...all(() => "#wall"), north: "!#wall", south: "!#wall" }),
|
||||
],
|
||||
},
|
||||
"minecraft:block/template_glass_pane_post": {
|
||||
elements: [box([7, 0, 7], [9, 16, 9], { down: "!#edge", up: "!#edge" })],
|
||||
},
|
||||
"minecraft:block/template_glass_pane_side": {
|
||||
elements: [
|
||||
box([7, 0, 0], [9, 16, 7], { down: "!#edge", up: "!#edge", north: "!#edge", west: "#pane", east: "#pane" }),
|
||||
],
|
||||
},
|
||||
"minecraft:block/template_glass_pane_side_alt": {
|
||||
elements: [
|
||||
box([7, 0, 9], [9, 16, 16], {
|
||||
down: "!#edge",
|
||||
up: "!#edge",
|
||||
south: "!#edge",
|
||||
west: "#pane",
|
||||
east: "#pane",
|
||||
}),
|
||||
],
|
||||
},
|
||||
"minecraft:block/template_glass_pane_noside": { elements: [box([7, 0, 7], [9, 16, 9], { north: "#pane" })] },
|
||||
"minecraft:block/template_glass_pane_noside_alt": { elements: [box([7, 0, 7], [9, 16, 9], { east: "#pane" })] },
|
||||
};
|
||||
|
||||
// item models that are a flat sprite or drawn by code, not boxes
|
||||
export const NOT_BOXES: Record<string, string> = {
|
||||
"minecraft:item/generated": "an item sprite",
|
||||
"minecraft:item/handheld": "an item sprite",
|
||||
"minecraft:item/barrier": "an item sprite",
|
||||
"minecraft:builtin/generated": "an item sprite",
|
||||
"minecraft:builtin/entity": "drawn by code",
|
||||
};
|
||||
Reference in New Issue
Block a user