Importer
This commit is contained in:
@@ -0,0 +1,210 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// converts a minecraft java mod's resources into bworld's formats, one kind at a time:
|
||||
// deno run -A tools/importer.ts model MODEL.json --output PATH
|
||||
// deno run -A tools/importer.ts model path/to/resources --output mods/example/models
|
||||
// a folder can be a whole mod's resources (every assets/<namespace>/models in it), one assets/<namespace>/models, or a
|
||||
// folder inside one. see USAGE for the options
|
||||
import { dirname, join, resolve, SEPARATOR } from "@std/path";
|
||||
import { convert_model, type ModelSource } from "./importer/models.ts";
|
||||
import {
|
||||
DEFAULT_REMAPS,
|
||||
enclosing_root,
|
||||
find_roots,
|
||||
format_json,
|
||||
location_of,
|
||||
location_string,
|
||||
parse_location,
|
||||
type Remaps,
|
||||
type ResourceRoot,
|
||||
walk_files,
|
||||
} from "./importer/resources.ts";
|
||||
|
||||
const USAGE = `deno run -A tools/importer.ts <kind> <file or folder> [options]
|
||||
|
||||
kinds:
|
||||
model java block models to bworld models
|
||||
|
||||
options:
|
||||
--output PATH the file (for one model) or the folder to write. one model without it is printed
|
||||
--namespace NS the namespace, when the input isn't inside assets/<namespace>/models
|
||||
--parents FOLDER another folder to find parent models in, 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`;
|
||||
|
||||
export interface ImportOptions {
|
||||
output?: string;
|
||||
namespace?: string;
|
||||
parents?: string[];
|
||||
remaps?: Remaps;
|
||||
}
|
||||
|
||||
export interface ImportReport {
|
||||
written: { location: string; id: string; file?: string; text: string }[];
|
||||
// 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 import_models(input: string, options: ImportOptions = {}): ImportReport {
|
||||
const remaps = options.remaps ?? DEFAULT_REMAPS;
|
||||
const single = is_file(input);
|
||||
const roots = single ? file_root(input, options.namespace) : find_roots(input, "models", options.namespace);
|
||||
if (roots.length === 0) {
|
||||
throw new Error(`no models in ${input}: pass --namespace when it isn't inside assets/<namespace>/models`);
|
||||
}
|
||||
if (!single && options.output === undefined) throw new Error("--output is needed to convert a folder");
|
||||
|
||||
// parents can be anywhere in the same roots, or in --parents, not only in what's being converted
|
||||
const lookup = [...roots, ...(options.parents ?? []).flatMap((dir) => find_roots(dir, "models"))];
|
||||
const cache = new Map<string, Record<string, unknown> | undefined>();
|
||||
const read: ModelSource = (location) => {
|
||||
if (cache.has(location)) return cache.get(location);
|
||||
const { namespace, path } = parse_location(location);
|
||||
let json: Record<string, unknown> | undefined;
|
||||
for (const root of lookup.filter((root) => root.namespace === namespace)) {
|
||||
const file = `${root.dir}/${path}.json`;
|
||||
if (!is_file(file)) continue;
|
||||
try {
|
||||
json = JSON.parse(Deno.readTextFileSync(file));
|
||||
} catch (e) {
|
||||
throw new Error(`${file} isn't valid json: ${(e as Error).message}`);
|
||||
}
|
||||
break;
|
||||
}
|
||||
cache.set(location, json);
|
||||
return json;
|
||||
};
|
||||
|
||||
const files = single
|
||||
? [{ root: roots[0], file: resolve(input) }]
|
||||
: roots.flatMap((root) =>
|
||||
walk_files(inside(input, root) ? resolve(input) : root.dir, ".json").map((file) => ({ root, file }))
|
||||
);
|
||||
const several_namespaces = new Set(files.map(({ root }) => root.namespace)).size > 1;
|
||||
|
||||
const report: ImportReport = { written: [], parents: [], skipped: [], errors: [], warnings: [] };
|
||||
const locations = new Map<string, string>();
|
||||
for (const { root, file } of files) {
|
||||
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 });
|
||||
else if (result.kind === "error") report.errors.push({ location, problems: result.problems });
|
||||
else {
|
||||
const other = locations.get(result.id);
|
||||
if (other) {
|
||||
const problem =
|
||||
`its id ${result.id} is the same as ${other}'s, so give one of them another with --remap`;
|
||||
report.errors.push({ location, problems: [problem] });
|
||||
continue;
|
||||
}
|
||||
locations.set(result.id, location);
|
||||
for (const warning of result.warnings) report.warnings.push({ location, warning });
|
||||
const output = single
|
||||
? options.output
|
||||
: join(options.output!, ...(several_namespaces ? [where.namespace] : []), `${where.path}.json`);
|
||||
report.written.push({ location, id: result.id, file: output, text: format_json(result.json) + "\n" });
|
||||
}
|
||||
}
|
||||
for (const { file, text } of report.written) {
|
||||
if (file === undefined) continue;
|
||||
Deno.mkdirSync(dirname(file), { recursive: true });
|
||||
Deno.writeTextFileSync(file, text);
|
||||
}
|
||||
return report;
|
||||
}
|
||||
|
||||
function file_root(file: string, namespace?: string): ResourceRoot[] {
|
||||
const root = enclosing_root(file, "models");
|
||||
if (root) return [root];
|
||||
if (!namespace) throw new Error(`can't tell ${file}'s namespace: pass --namespace`);
|
||||
return [{ namespace, dir: dirname(resolve(file)) }];
|
||||
}
|
||||
|
||||
function inside(path: string, root: ResourceRoot) {
|
||||
const full = resolve(path);
|
||||
return full === root.dir || full.startsWith(root.dir + SEPARATOR);
|
||||
}
|
||||
|
||||
function is_file(path: string) {
|
||||
try {
|
||||
return Deno.statSync(path).isFile;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function parse_args(args: string[]) {
|
||||
const positional: string[] = [];
|
||||
const options: ImportOptions & { parents: string[] } = { parents: [] };
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
const value = () => {
|
||||
const next = args[++i];
|
||||
if (next === undefined) throw new Error(`${arg} needs a value`);
|
||||
return next;
|
||||
};
|
||||
if (arg === "--output") options.output = value();
|
||||
else if (arg === "--namespace") options.namespace = value();
|
||||
else if (arg === "--parents") options.parents.push(value());
|
||||
else if (arg === "--remap") {
|
||||
const remap = JSON.parse(Deno.readTextFileSync(value()));
|
||||
options.remaps = {
|
||||
textures: { ...DEFAULT_REMAPS.textures, ...remap.textures },
|
||||
models: { ...DEFAULT_REMAPS.models, ...remap.models },
|
||||
};
|
||||
} else if (arg.startsWith("--")) throw new Error(`unknown option ${arg}`);
|
||||
else positional.push(arg);
|
||||
}
|
||||
return { positional, options };
|
||||
}
|
||||
|
||||
function print_report(report: ImportReport) {
|
||||
if (report.written.length === 1 && report.written[0].file === undefined) {
|
||||
console.log(report.written[0].text.trimEnd());
|
||||
}
|
||||
for (const { location, reason } of report.skipped) console.error(`skipped ${location}: ${reason}`);
|
||||
for (const { location, problems } of report.errors) {
|
||||
for (const problem of problems) console.error(`error in ${location}: ${problem}`);
|
||||
}
|
||||
// the same warning on many models is one line
|
||||
const warnings = new Map<string, string[]>();
|
||||
for (const { location, warning } of report.warnings) {
|
||||
warnings.set(warning, [...(warnings.get(warning) ?? []), location]);
|
||||
}
|
||||
for (const [warning, locations] of warnings) {
|
||||
const which = locations.length === 1 ? locations[0] : `${locations.length} models`;
|
||||
console.error(`warning: ${warning} (${which})`);
|
||||
}
|
||||
console.error(
|
||||
`${report.written.length} converted, ${report.parents.length} only parents, ${report.skipped.length} skipped, ` +
|
||||
`${report.errors.length} with errors`,
|
||||
);
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
if (Deno.args.includes("--help") || Deno.args.includes("-h")) {
|
||||
console.log(USAGE);
|
||||
Deno.exit(0);
|
||||
}
|
||||
try {
|
||||
const { positional: [kind, input], options } = parse_args(Deno.args);
|
||||
if (!kind || !input) {
|
||||
console.error(USAGE);
|
||||
Deno.exit(2);
|
||||
}
|
||||
if (kind !== "model") throw new Error(`"${kind}" isn't a kind that can be imported yet, see --help`);
|
||||
const report = import_models(input, options);
|
||||
print_report(report);
|
||||
if (report.errors.length > 0) Deno.exit(1);
|
||||
} catch (e) {
|
||||
console.error((e as Error).message);
|
||||
Deno.exit(1);
|
||||
}
|
||||
}
|
||||
@@ -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