// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // java block models (assets//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 for places bworld // doesn't show items, like third person) is left out import type { ModelDisplay, ModelElementJson, ModelFaceJson, ModelFileJson } from "@/common/block_models.ts"; import { DISPLAY_CONTEXTS, FORMAT_VERSION, type ModelFace } from "@/common/mod_data.ts"; import { join } from "@std/path"; import { DEFAULT_REMAPS, empty_report, find_roots, format_json, id_claims, type ImportOptions, type ImportReport, input_files, is_file, is_valid_id, location_of, location_string, parse_location, type Remaps, type ResourceRoot, skips, to_id, write_report, } from "./resources.ts"; // reads a java model by location ("create:block/cogwheel"), undefined when there's none export type ModelSource = (location: string) => Record | undefined; export type ModelResult = | { kind: "model"; id: string; json: { format_version: number; model: ModelFileJson }; warnings: string[] } | { kind: "skipped"; reason: string } | { kind: "error"; problems: string[] }; const FACE_NAMES: Record = { down: "bottom", up: "top", north: "north", south: "south", west: "west", east: "east", }; // 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 = { "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 needs: block/block is only the display transforms of blocks' // items, which bworld has its own of 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 third person display transforms. a model with one as its parent leaves it out, since it isn't written export function is_empty(location: string, read: ModelSource, seen = new Set()): 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).length > 0) return false; if (convert_display(json.display) !== undefined) return false; seen.add(location); return typeof json.parent !== "string" || is_empty(location_string(parse_location(json.parent)), read, seen); } // 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); if (!single && options.output === undefined) throw new Error("--output is needed to convert a folder"); const files = input_files(input, "models", ".json", options.namespace, options.output); const read = model_source([ ...new Set(files.map(({ root }) => root)), ...(options.parents ?? []).flatMap((dir) => find_roots(dir, "models")), ]); const several_namespaces = new Set(files.map(({ root }) => root.namespace)).size > 1; 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; // a loose file's bare texture names are its own, like blockbench writes them const result = convert_model(location, read, remaps, root.loose ? root.namespace : "minecraft"); 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 }); // a model's id is inside it, so its file can keep the folders it had 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" }); } } write_report(report); return report; } // reads java models by location from these models roots, the first that has it, each file once export function model_source(roots: ResourceRoot[]): ModelSource { const cache = new Map | undefined>(); return (location) => { if (cache.has(location)) return cache.get(location); const { namespace, path } = parse_location(location); const file = roots.filter((root) => root.namespace === namespace).map((root) => `${root.dir}/${path}.json`) .find(is_file); let json: Record | undefined; if (file) { try { json = JSON.parse(Deno.readTextFileSync(file)); } catch (e) { throw new Error(`${file} isn't valid json: ${(e as Error).message}`); } } cache.set(location, json); return json; }; } // bare is the namespace of textures named without one export function convert_model(location: string, read: ModelSource, remaps: Remaps, bare = "minecraft"): ModelResult { 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(); 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, bare); if (!is_valid_id(id)) problems.push(`${where}: "${value}" doesn't make a valid texture id (${id})`); return id; }; 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) .map(([name, value]) => [name, texture(value, `textures.${name}`)]), ); const elements = Array.isArray(json.elements) ? json.elements.map((element, i) => convert_element(element, `elements[${i}]`, texture, problems, warnings)) : undefined; const display = convert_display(json.display); if (parent === undefined && elements === undefined && Object.keys(textures).length === 0 && !display) { return { kind: "skipped", reason: "it has nothing a bworld model holds, like only third person 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: ModelFileJson = { id, ...(parent !== undefined ? { parent } : {}), ...(Object.keys(textures).length > 0 ? { textures } : {}), ...(elements !== undefined ? { elements } : {}), ...(display ? { display } : {}), }; return { kind: "model", id, json: { format_version: FORMAT_VERSION, model }, warnings: [...warnings] }; } // the display transforms of the places bworld shows items, undefined when there are none function convert_display(json: unknown): ModelDisplay | undefined { const display: ModelDisplay = {}; for (const context of DISPLAY_CONTEXTS) { const transform = (json as Record> | undefined)?.[context]; if (typeof transform !== "object" || transform === null) continue; display[context] = Object.fromEntries( ["rotation", "translation", "scale"] .filter((key) => Array.isArray(transform[key])) .map((key) => [key, transform[key]]), ); } return Object.keys(display).length > 0 ? display : undefined; } // 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 export function made_by(location: string, read: ModelSource): string | undefined { const seen = new Set(); 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; } return undefined; } function convert_element( json: unknown, where: string, texture: (value: string, where: string) => string, problems: string[], warnings: Set, ): ModelElementJson { const element = (json ?? {}) as Record; 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; // { axis, angle }, or blockbench's newer { x, y, z } with a turn around each const rotation = element.rotation as Record | undefined; const turns = rotation === undefined ? [] : typeof rotation.axis === "string" ? [[rotation.axis, rotation.angle]] : ["x", "y", "z"].map((axis) => [axis, rotation[axis] ?? 0]); const turned = turns.filter(([, angle]) => angle !== 0); if (turned.length > 1) { problems.push( `${where}.rotation turns around ${turned.map(([axis]) => axis).join(" and ")} at once, bworld only one`, ); } else if (turned.length === 1) { const [[axis, angle]] = turned; if (typeof angle !== "number" || Math.abs(angle) > 180) { problems.push(`${where}.rotation: ${angle} isn't an angle from -180 to 180`); } out.rotation = { origin: rotation!.origin as [number, number, number], axis: axis as "x" | "y" | "z", angle: 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>)) { 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; }