Add various generic models

This commit is contained in:
2026-10-12 17:56:47 -03:00
parent e5baeab193
commit d4eff11f3e
34 changed files with 786 additions and 251 deletions
+2 -3
View File
@@ -25,7 +25,7 @@ options:
--output PATH the file (for one input file) or the folder to write. one model without it is printed
--namespace NS the namespace, when the input isn't inside assets/<namespace>/, or the only one to take from a
folder with several
--parents FOLDER another folder to find parent models in, like another mod's resources. can be repeated
--parents FOLDER another folder to follow parent models through, like another mod's resources. can be repeated
--remap FILE json that renames locations before they become ids, longest match first:
{ "textures": { "minecraft:block/": "bworld:" }, "models": {} }
minecraft's block and item textures become bworld's of the same name unless it says otherwise`;
@@ -71,9 +71,8 @@ function print_report(report: ImportReport) {
console.error(`warning: ${warning} (${locations.length === 1 ? locations[0] : `${locations.length} files`})`);
}
const converted = new Set(report.written.map(({ location }) => location)).size;
const parents = report.parents.length > 0 ? `${report.parents.length} only parents, ` : "";
console.error(
`${converted} converted, ${parents}${report.skipped.length} skipped, ${report.errors.length} with errors`,
`${converted} converted, ${report.skipped.length} skipped, ${report.errors.length} with errors`,
);
}
+71 -63
View File
@@ -1,10 +1,10 @@
// 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";
// java block models (assets/<namespace>/models/**.json) to bworld's models/. the formats are close: faces are top and
// bottom instead of up and down, ids lose their folders, a parent keeps being a parent (bworld merges them when it
// loads, see resolve_models), and what bworld has no use for (blockbench's names, display transforms) is left out
import type { ModelElementJson, ModelFace, ModelFaceJson, ModelFileJson } from "$/common/block_models.ts";
import { FORMAT_VERSION } from "$/common/mod_data.ts";
import { join } from "@std/path";
import {
@@ -25,15 +25,12 @@ import {
to_id,
write_report,
} 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: "model"; id: string; json: { format_version: number; model: ModelFileJson }; warnings: string[] }
| { kind: "skipped"; reason: string }
| { kind: "error"; problems: string[] };
@@ -47,18 +44,30 @@ const FACE_NAMES: Record<string, ModelFace> = {
};
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;
// item models that are a flat sprite or drawn by code, not boxes, and so is anything that has one as a parent
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",
};
// minecraft's roots, which hold nothing a bworld model can use: block/block is only display transforms
const EMPTY_PARENTS = ["minecraft:block/block", "minecraft:block/air"];
// whether a model holds nothing a bworld model can use, all the way up its parents, like block/block or a mod's own
// root of display transforms. a model with one as its parent leaves it out, since it isn't written
function is_empty(location: string, read: ModelSource, seen = new Set<string>()): boolean {
if (EMPTY_PARENTS.includes(location)) return true;
const json = read(location);
if (!json || seen.has(location) || json.elements !== undefined) return false;
if (Object.keys((json.textures ?? {}) as Record<string, string>).length > 0) return false;
seen.add(location);
return typeof json.parent !== "string" || is_empty(location_string(parse_location(json.parent)), read, seen);
}
class ImportError extends Error {}
// converts one model, or every model in a folder. parents can be anywhere in the same roots or in options.parents, not
// only in what's being converted
// converts one model, or every model in a folder. other models are only read to tell whether a model is really a
// sprite or made by code: its parents can be anywhere in the same roots or in options.parents
export function import_models(input: string, options: ImportOptions = {}): ImportReport {
const remaps = options.remaps ?? DEFAULT_REMAPS;
const single = is_file(input);
@@ -93,8 +102,7 @@ export function import_models(input: string, options: ImportOptions = {}): Impor
const where = location_of(root, file, ".json");
const location = location_string(where);
const result = convert_model(location, read, remaps);
if (result.kind === "parent") report.parents.push(location);
else if (result.kind === "skipped") report.skipped.push({ location, reason: result.reason });
if (result.kind === "skipped") report.skipped.push({ location, reason: result.reason });
else 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 });
@@ -110,20 +118,16 @@ export function import_models(input: string, options: ImportOptions = {}): Impor
}
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 json = read(location_string(parse_location(location)));
if (!json) return { kind: "error", problems: [`${location} wasn't found`] };
const made = made_by(location, read);
if (made) return { kind: "skipped", reason: made };
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`);
if (typeof json.render_type === "string") {
warnings.add(`render_type "${json.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);
@@ -131,48 +135,52 @@ export function convert_model(location: string, read: ModelSource, remaps: Remap
return id;
};
const elements = flat.elements.map((element, i) =>
convert_element(element, `elements[${i}]`, texture, problems, warnings)
let parent: string | undefined;
if (typeof json.parent === "string") {
const from = location_string(parse_location(json.parent));
if (!is_empty(from, read)) {
parent = to_id(from, remaps.models);
if (parent.startsWith("minecraft:")) {
problems.push(`its parent ${from} is minecraft's, and no --remap names a bworld model for it`);
}
}
}
// every variable comes along, since it may be filling in a parent's faces. even "particle": some models draw with it
const textures = Object.fromEntries(
Object.entries((json.textures ?? {}) as Record<string, string>)
.map(([name, value]) => [name, texture(value, `textures.${name}`)]),
);
// 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 elements = Array.isArray(json.elements)
? json.elements.map((element, i) => convert_element(element, `elements[${i}]`, texture, problems, warnings))
: undefined;
if (parent === undefined && elements === undefined && Object.keys(textures).length === 0) {
return { kind: "skipped", reason: "it has nothing a bworld model holds, like only display transforms" };
}
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 };
const model: ModelFileJson = {
id,
...(parent !== undefined ? { parent } : {}),
...(Object.keys(textures).length > 0 ? { textures } : {}),
...(elements !== undefined ? { 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`,
);
// why a model isn't boxes bworld can draw, going up its parents: an item sprite, or one a loader makes (obj files,
// composites). undefined for boxes, or when its parents can't be followed, which check-mods then reports
function made_by(location: string, read: ModelSource): string | undefined {
const seen = new Set<string>();
for (let at: string | undefined = location_string(parse_location(location)); at && !seen.has(at);) {
seen.add(at);
if (NOT_BOXES[at]) return `${NOT_BOXES[at]} (${at})`;
const json = read(at);
if (typeof json?.loader === "string") return `it uses the "${json.loader}" loader`;
at = typeof json?.parent === "string" ? location_string(parse_location(json.parent)) : undefined;
}
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,
};
return undefined;
}
function convert_element(
+14 -4
View File
@@ -35,9 +35,21 @@ export interface Remaps {
export const DEFAULT_REMAPS: Remaps = {
textures: { "minecraft:block/": "bworld:", "minecraft:item/": "bworld:" },
models: {},
models: template_remaps(),
};
// minecraft's template models (cube_all, stairs, walls, panes, ...) are the base game's in models/templates, which are
// named after their files
function template_remaps(): Remap {
const dir = new URL("../../mods/bworld/models/templates/", import.meta.url);
return Object.fromEntries(
[...Deno.readDirSync(dir)].filter((entry) => entry.name.endsWith(".json")).map((entry) => {
const name = entry.name.slice(0, -".json".length);
return [`minecraft:block/${name}`, `bworld:${name}`];
}),
);
}
export function remap_location(location: string, remap: Remap = {}): Location {
const full = location_string(parse_location(location));
for (const from of Object.keys(remap).sort((a, b) => b.length - a.length)) {
@@ -192,15 +204,13 @@ export interface Written {
export interface ImportReport {
written: Written[];
// models with no boxes of their own, only there for others to use as a parent
parents: string[];
skipped: { location: string; reason: string }[];
errors: { location: string; problems: string[] }[];
warnings: { location: string; warning: string }[];
}
export function empty_report(): ImportReport {
return { written: [], parents: [], skipped: [], errors: [], warnings: [] };
return { written: [], skipped: [], errors: [], warnings: [] };
}
// two locations that would become the same id are an error, since one would overwrite the other. claim returns false
-128
View File
@@ -1,128 +0,0 @@
// 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",
};