Import textures
This commit is contained in:
@@ -6,7 +6,25 @@
|
||||
// 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 { 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,
|
||||
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
|
||||
@@ -39,6 +57,58 @@ interface Flat {
|
||||
|
||||
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
|
||||
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);
|
||||
const lookup = [
|
||||
...new Set(files.map(({ root }) => root)),
|
||||
...(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);
|
||||
const file = lookup.filter((root) => root.namespace === namespace).map((root) => `${root.dir}/${path}.json`)
|
||||
.find(is_file);
|
||||
let json: Record<string, unknown> | 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;
|
||||
};
|
||||
|
||||
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);
|
||||
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 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;
|
||||
}
|
||||
|
||||
export function convert_model(location: string, read: ModelSource, remaps: Remaps): ModelResult {
|
||||
let flat: Flat;
|
||||
try {
|
||||
|
||||
+104
-10
@@ -5,7 +5,7 @@
|
||||
// "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";
|
||||
import { dirname, relative, resolve, SEPARATOR } from "@std/path";
|
||||
|
||||
export interface Location {
|
||||
namespace: string;
|
||||
@@ -38,17 +38,19 @@ export const DEFAULT_REMAPS: Remaps = {
|
||||
models: {},
|
||||
};
|
||||
|
||||
export function to_id(location: string, remap: Remap = {}): string {
|
||||
export function remap_location(location: string, remap: Remap = {}): Location {
|
||||
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;
|
||||
return parse_location(remap[from] + full.slice(from.length));
|
||||
}
|
||||
}
|
||||
const { namespace, path } = parse_location(mapped);
|
||||
return parse_location(full);
|
||||
}
|
||||
|
||||
export function to_id(location: string, remap: Remap = {}): string {
|
||||
const { namespace, path } = remap_location(location, remap);
|
||||
return `${namespace}:${path.replaceAll("/", "_")}`;
|
||||
}
|
||||
|
||||
@@ -62,8 +64,8 @@ export interface ResourceRoot {
|
||||
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
|
||||
// the roots of a kind inside a folder: every assets/<namespace>/<kind> under it (only namespace's, when it's given), 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
|
||||
export function find_roots(input: string, kind: string, namespace?: string): ResourceRoot[] {
|
||||
const dir = resolve(input);
|
||||
const enclosing = enclosing_root(dir, kind);
|
||||
@@ -76,8 +78,32 @@ export function find_roots(input: string, kind: string, namespace?: string): Res
|
||||
}
|
||||
}
|
||||
}
|
||||
if (roots.length === 0 && namespace) roots.push({ namespace, dir });
|
||||
return roots;
|
||||
if (roots.length === 0) return namespace ? [{ namespace, dir }] : [];
|
||||
return namespace ? roots.filter((root) => root.namespace === namespace) : roots;
|
||||
}
|
||||
|
||||
// a file to convert and the root it's in
|
||||
export interface InputFile {
|
||||
root: ResourceRoot;
|
||||
file: string;
|
||||
}
|
||||
|
||||
// what to convert: one file, or every file with the extension in a folder's roots of a kind
|
||||
export function input_files(input: string, kind: string, extension: string, namespace?: string): InputFile[] {
|
||||
if (is_file(input)) {
|
||||
const root = enclosing_root(input, kind) ?? (namespace && { namespace, dir: dirname(resolve(input)) });
|
||||
if (!root) throw new Error(`can't tell ${input}'s namespace: pass --namespace`);
|
||||
return [{ root, file: resolve(input) }];
|
||||
}
|
||||
const roots = find_roots(input, kind, namespace);
|
||||
if (roots.length === 0) {
|
||||
throw new Error(`no ${kind} in ${input}: pass --namespace when it isn't inside assets/<namespace>/${kind}`);
|
||||
}
|
||||
const full = resolve(input);
|
||||
return roots.flatMap((root) => {
|
||||
const inside = full === root.dir || full.startsWith(root.dir + SEPARATOR);
|
||||
return walk_files(inside ? full : root.dir, extension).map((file) => ({ root, file }));
|
||||
});
|
||||
}
|
||||
|
||||
// the assets/<namespace>/<kind> folder a path is in, if it's in one
|
||||
@@ -128,6 +154,14 @@ function read_dir(dir: string): Deno.DirEntry[] {
|
||||
}
|
||||
}
|
||||
|
||||
export function is_file(path: string): boolean {
|
||||
try {
|
||||
return Deno.statSync(path).isFile;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function is_dir(path: string): boolean {
|
||||
try {
|
||||
return Deno.statSync(path).isDirectory;
|
||||
@@ -136,6 +170,66 @@ function is_dir(path: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
export interface ImportOptions {
|
||||
// the file (for one input file) or folder to write
|
||||
output?: string;
|
||||
// the namespace of an input outside assets/<namespace>/, or the only one to take from a folder with several
|
||||
namespace?: string;
|
||||
// more folders to look things up in, like parent models from another mod
|
||||
parents?: string[];
|
||||
remaps?: Remaps;
|
||||
}
|
||||
|
||||
// one file an import makes: text to write, or a file to copy
|
||||
export interface Written {
|
||||
location: string;
|
||||
id: string;
|
||||
// where it goes, undefined to print it
|
||||
file?: string;
|
||||
text?: string;
|
||||
copy?: string;
|
||||
}
|
||||
|
||||
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: [] };
|
||||
}
|
||||
|
||||
// two locations that would become the same id are an error, since one would overwrite the other. claim returns false
|
||||
// for the second, after reporting it
|
||||
export function id_claims(report: ImportReport) {
|
||||
const owners = new Map<string, string>();
|
||||
return (id: string, location: string) => {
|
||||
const owner = owners.get(id);
|
||||
if (owner === undefined) {
|
||||
owners.set(id, location);
|
||||
return true;
|
||||
}
|
||||
report.errors.push({
|
||||
location,
|
||||
problems: [`its id ${id} is the same as ${owner}'s, so give one of them another with --remap`],
|
||||
});
|
||||
return false;
|
||||
};
|
||||
}
|
||||
|
||||
export function write_report(report: ImportReport) {
|
||||
for (const { file, text, copy } of report.written) {
|
||||
if (file === undefined) continue;
|
||||
Deno.mkdirSync(dirname(file), { recursive: true });
|
||||
if (copy !== undefined) Deno.copyFileSync(copy, file);
|
||||
else Deno.writeTextFileSync(file, text ?? "");
|
||||
}
|
||||
}
|
||||
|
||||
// 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);
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// java textures (assets/<namespace>/textures/**.png) to a bworld mod's textures/. bworld names a texture in a subfolder
|
||||
// by joining the folders with _, like resources.ts does for every id, so the folders stay as they are and models
|
||||
// converted from the same mod find their textures. a .png.mcmeta becomes the .json next to the png: bworld reads the
|
||||
// same animation format
|
||||
import { join } from "@std/path";
|
||||
import { png_size, texture_size_problem } from "$/common/bmod.ts";
|
||||
import { type TextureJson, validate_texture_json } from "$/common/texture_animation.ts";
|
||||
import {
|
||||
DEFAULT_REMAPS,
|
||||
empty_report,
|
||||
format_json,
|
||||
id_claims,
|
||||
type ImportOptions,
|
||||
type ImportReport,
|
||||
input_files,
|
||||
is_file,
|
||||
is_valid_id,
|
||||
location_of,
|
||||
location_string,
|
||||
remap_location,
|
||||
to_id,
|
||||
write_report,
|
||||
} from "./resources.ts";
|
||||
|
||||
const ANIMATION_FIELDS = ["frametime", "interpolate", "frames", "width", "height"];
|
||||
|
||||
export type MetaResult = { json?: TextureJson; warnings: string[]; problems: string[] };
|
||||
|
||||
// a .png.mcmeta's animation, for a png of the size, or no json for one with no animation. the other sections (blur and
|
||||
// clamping, a gui's nine-slice scaling) have nothing in bworld to go to
|
||||
export function convert_mcmeta(mcmeta: unknown, size: { width: number; height: number }): MetaResult {
|
||||
if (mcmeta === null || typeof mcmeta !== "object" || Array.isArray(mcmeta)) {
|
||||
return { warnings: [], problems: ["the .mcmeta must be an object"] };
|
||||
}
|
||||
const warnings = Object.keys(mcmeta).filter((key) => key !== "animation")
|
||||
.map((key) => `the .mcmeta's "${key}" section was left out`);
|
||||
const animation = (mcmeta as Record<string, unknown>).animation as Record<string, unknown> | undefined;
|
||||
if (animation === undefined) return { warnings, problems: [] };
|
||||
for (const key of Object.keys(animation ?? {})) {
|
||||
if (!ANIMATION_FIELDS.includes(key)) warnings.push(`the animation's "${key}" was left out`);
|
||||
}
|
||||
const json = {
|
||||
animation: Object.fromEntries(
|
||||
Object.entries(animation ?? {}).filter(([key]) => ANIMATION_FIELDS.includes(key)),
|
||||
),
|
||||
};
|
||||
const problems = validate_texture_json(json, size);
|
||||
return problems.length > 0 ? { warnings, problems } : { json: json as TextureJson, warnings, problems };
|
||||
}
|
||||
|
||||
// copies one texture, or every texture in a folder, with their animations. minecraft's own textures aren't copied:
|
||||
// models refer to them through the remap, which by default makes them the base game's
|
||||
export function import_textures(input: string, options: ImportOptions = {}): ImportReport {
|
||||
if (options.output === undefined) throw new Error("--output is needed for textures");
|
||||
const remaps = options.remaps ?? DEFAULT_REMAPS;
|
||||
const single = is_file(input);
|
||||
const report = empty_report();
|
||||
const claim = id_claims(report);
|
||||
const files = input_files(input, "textures", ".png", options.namespace);
|
||||
// a texture gets its namespace from the mod it's in, so two namespaces' textures can't share one folder
|
||||
const namespaces = [...new Set(files.map(({ root }) => root.namespace))].filter((ns) => ns !== "minecraft");
|
||||
if (namespaces.length > 1) {
|
||||
throw new Error(`${input} has textures of ${namespaces.join(", ")}: pick one with --namespace`);
|
||||
}
|
||||
for (const { root, file } of files) {
|
||||
const location = location_string(location_of(root, file, ".png"));
|
||||
if (root.namespace === "minecraft") {
|
||||
report.skipped.push({
|
||||
location,
|
||||
reason: "minecraft's own textures aren't copied, the remap points at bworld's",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const id = to_id(location, remaps.textures);
|
||||
if (!is_valid_id(id)) {
|
||||
report.errors.push({ location, problems: [`it doesn't make a valid texture id (${id})`] });
|
||||
continue;
|
||||
}
|
||||
const size = png_size(Deno.readFileSync(file));
|
||||
if (!size) {
|
||||
report.errors.push({ location, problems: ["it isn't a png"] });
|
||||
continue;
|
||||
}
|
||||
|
||||
let json: TextureJson | undefined;
|
||||
if (is_file(`${file}.mcmeta`)) {
|
||||
let mcmeta: unknown;
|
||||
try {
|
||||
mcmeta = JSON.parse(Deno.readTextFileSync(`${file}.mcmeta`));
|
||||
} catch (e) {
|
||||
report.errors.push({ location, problems: [`its .mcmeta isn't valid json: ${(e as Error).message}`] });
|
||||
continue;
|
||||
}
|
||||
const result = convert_mcmeta(mcmeta, size);
|
||||
if (result.problems.length > 0) {
|
||||
report.errors.push({ location, problems: result.problems });
|
||||
continue;
|
||||
}
|
||||
for (const warning of result.warnings) report.warnings.push({ location, warning });
|
||||
json = result.json;
|
||||
}
|
||||
// the limits a .bmod checks, like a title screen's 512×512 panorama being too big
|
||||
const too_big = texture_size_problem(size, json);
|
||||
if (too_big) {
|
||||
report.skipped.push({ location, reason: `it ${too_big}` });
|
||||
continue;
|
||||
}
|
||||
if (!claim(id, location)) continue;
|
||||
|
||||
// where it goes is what names it, so a remapped texture goes where its new name says
|
||||
const png = single
|
||||
? options.output
|
||||
: join(options.output, `${remap_location(location, remaps.textures).path}.png`);
|
||||
report.written.push({ location, id, file: png, copy: file });
|
||||
if (json) {
|
||||
report.written.push({
|
||||
location,
|
||||
id,
|
||||
file: png.replace(/\.png$/, "") + ".json",
|
||||
text: format_json(json) + "\n",
|
||||
});
|
||||
}
|
||||
}
|
||||
write_report(report);
|
||||
return report;
|
||||
}
|
||||
Reference in New Issue
Block a user