Add all textures and models from create

This commit is contained in:
2026-10-12 18:47:41 -03:00
parent d4eff11f3e
commit 99bdcaeffc
3775 changed files with 66614 additions and 58 deletions
+10 -2
View File
@@ -6,6 +6,8 @@
// deno run -A tools/importer.ts texture path/to/resources --output mods/example/textures
// a folder can be a whole mod's resources (every assets/<namespace>/<kind> in it), one assets/<namespace>/<kind>, or a
// folder inside one. each kind is in tools/importer/, see USAGE for the options
import { import_blocks } from "./importer/blocks.ts";
import { import_items } from "./importer/items.ts";
import { import_models } from "./importer/models.ts";
import { DEFAULT_REMAPS, type ImportOptions, type ImportReport } from "./importer/resources.ts";
import { import_textures } from "./importer/textures.ts";
@@ -13,6 +15,8 @@ import { import_textures } from "./importer/textures.ts";
const KINDS: Record<string, (input: string, options: ImportOptions) => ImportReport> = {
model: import_models,
texture: import_textures,
blockstate: import_blocks,
item: import_items,
};
const USAGE = `deno run -A tools/importer.ts <kind> <file or folder> [options]
@@ -20,14 +24,17 @@ const USAGE = `deno run -A tools/importer.ts <kind> <file or folder> [options]
kinds:
model java block models to bworld models
texture textures, with their .png.mcmeta animations
blockstate blockstates to blocks, with their states, models and items, and placeholder mining
item item models to items, for the items that aren't a block's
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 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": {} }
--remap FILE json that renames locations before they become ids, longest match first, and leaves out
locations that match a "skip" pattern:
{ "textures": { "minecraft:block/": "bworld:" }, "models": {}, "skip": ["crimson"] }
minecraft's block and item textures become bworld's of the same name unless it says otherwise`;
function parse_args(args: string[]) {
@@ -48,6 +55,7 @@ function parse_args(args: string[]) {
options.remaps = {
textures: { ...DEFAULT_REMAPS.textures, ...remap.textures },
models: { ...DEFAULT_REMAPS.models, ...remap.models },
...(remap.skip ? { skip: remap.skip } : {}),
};
} else if (arg.startsWith("--")) throw new Error(`unknown option ${arg}`);
else positional.push(arg);
+361
View File
@@ -0,0 +1,361 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// java blockstates (assets/<namespace>/blockstates/*.json) to bworld's blocks/, so a mod's blocks can be placed and look
// right: their states, and the model each state is drawn with, turned. how a block behaves isn't in any data file (java
// mods set mining, sounds and what blocks do in code), so every block gets the same placeholders: a second to break with
// anything, dropping itself
import { dirname, join } from "@std/path";
import { FORMAT_VERSION } from "$/common/mod_data.ts";
import { is_empty, made_by, model_source, type ModelSource } from "./models.ts";
import {
DEFAULT_REMAPS,
empty_report,
find_roots,
format_json,
id_claims,
type ImportOptions,
type ImportReport,
input_files,
is_file,
location_of,
location_string,
parse_location,
type Remaps,
type ResourceRoot,
skips,
to_id,
write_report,
} from "./resources.ts";
// a model a blockstate draws, turned
interface Apply {
model: string;
x?: number;
y?: number;
uvlock?: boolean;
}
// a java state condition, property to value
type Condition = Record<string, string>;
// what a block whose model wasn't imported is drawn with: a cube with the missing texture on every side
const PLACEHOLDER = "bworld:cube";
export type BlockResult =
| {
kind: "block";
id: string;
json: { format_version: number; block: Record<string, unknown> };
warnings: string[];
}
| { kind: "error"; problems: string[] };
// the orders values are numbered in, so the ones bworld knows mean what it means by them: a 2 bit "facing" state faces
// the player who places it with 0 to 3 for north, east, south and west
const ORDERS = [
["false", "true"],
["north", "east", "south", "west", "up", "down"],
["x", "y", "z"],
["bottom", "top", "double"],
["lower", "upper"],
];
// which value a block is placed with, for properties java usually starts at something other than the first: a shaft
// stands up
const DEFAULTS: Record<string, string> = { axis: "y" };
// minecraft's full cube models, which blocks built on are solid
const CUBES = [
"cube",
"cube_all",
"cube_column",
"cube_column_horizontal",
"cube_bottom_top",
"orientable",
"orientable_with_bottom",
].map((name) => `minecraft:block/${name}`);
export function import_blocks(input: string, options: ImportOptions = {}): ImportReport {
if (options.output === undefined) throw new Error("--output is needed for blocks");
const remaps = options.remaps ?? DEFAULT_REMAPS;
const files = input_files(input, "blockstates", ".json", options.namespace);
// models say how a block is drawn (a full cube or not, cutout or translucent) and whether it has an item
const read = model_source(models_near(input, files.map(({ root }) => root), options));
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;
let json: unknown;
try {
json = JSON.parse(Deno.readTextFileSync(file));
} catch (e) {
report.errors.push({ location, problems: [`it isn't valid json: ${(e as Error).message}`] });
continue;
}
const result = convert_blockstate(location, json, read, remaps);
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 });
const text = format_json(result.json) + "\n";
report.written.push({ location, id: result.id, file: join(options.output, `${where.path}.json`), text });
}
}
write_report(report);
return report;
}
// the models roots that go with some resources: every one in the input, the one next to each root (assets/<ns>/models
// beside assets/<ns>/blockstates), and --parents
export function models_near(input: string, roots: ResourceRoot[], options: ImportOptions): ResourceRoot[] {
const near = roots.map((root) => ({ namespace: root.namespace, dir: join(dirname(root.dir), "models") }));
return [
...(is_file(input) ? [] : find_roots(input, "models", options.namespace)),
...near,
...(options.parents ?? []).flatMap((dir) => find_roots(dir, "models")),
];
}
export function convert_blockstate(location: string, json: unknown, read: ModelSource, remaps: Remaps): BlockResult {
const { namespace, path } = parse_location(location);
const id = to_id(location);
const problems: string[] = [];
const warnings = new Set<string>();
const state = (json ?? {}) as { variants?: Record<string, unknown>; multipart?: unknown[] };
const apply = (value: unknown, where: string): Apply | undefined => {
// a list is java's random pick between models, of which the first is as good as any
const first = (Array.isArray(value) ? value[0] : value) as Apply | undefined;
if (typeof first?.model !== "string") {
problems.push(`${where} has no model`);
return undefined;
}
if (Array.isArray(value) && value.length > 1) {
warnings.add("random models were left out, the first is always used");
}
if (first.uvlock) warnings.add("uvlock was left out, so turned textures turn with their model");
return first;
};
// each case: its conditions (several for an "or") and what it draws
let cases: { conditions: Condition[]; apply: Apply }[];
if (state.variants !== undefined) {
cases = Object.entries(state.variants).flatMap(([key, value]) => {
const drawn = apply(value, `variants["${key}"]`);
return drawn ? [{ conditions: [parse_key(key)], apply: drawn }] : [];
});
cases = without_unused_properties(cases);
} else if (Array.isArray(state.multipart)) {
cases = state.multipart.flatMap((part, i) => {
const { when, apply: value } = (part ?? {}) as { when?: unknown; apply?: unknown };
const drawn = apply(value, `multipart[${i}].apply`);
return drawn ? [{ conditions: when_conditions(when), apply: drawn }] : [];
});
} else {
return { kind: "error", problems: ["it has neither variants nor multipart"] };
}
if (problems.length > 0) return { kind: "error", problems };
// properties as numbered states
const values = new Map<string, string[]>();
for (const { conditions } of cases) {
for (const condition of conditions) {
for (const [name, value] of Object.entries(condition)) {
const seen = values.get(name) ?? [];
if (!seen.includes(value)) values.set(name, [...seen, value]);
}
}
}
for (const [name, seen] of values) values.set(name, ordered(seen, state.variants !== undefined));
const states = [...values].map(([name, seen]) => ({
name,
bits: Math.max(1, Math.ceil(Math.log2(seen.length))),
default: Math.max(0, seen.indexOf(DEFAULTS[name] ?? seen[0])),
}));
const key = (condition: Condition) =>
Object.entries(condition).map(([name, value]) => `${name}=${values.get(name)!.indexOf(value)}`).join(",");
const drawn = (apply: Apply) => {
const from = location_string(parse_location(apply.model));
let model = to_id(from, remaps.models);
const missing = model_missing(from, model, read, remaps);
if (missing) {
warnings.add(`${from} ${missing}, so it's drawn as a placeholder cube`);
model = PLACEHOLDER;
}
// java takes -90 for 270
const x = ((apply.x ?? 0) % 360 + 360) % 360;
const y = ((apply.y ?? 0) % 360 + 360) % 360;
return { model, ...(x ? { x } : {}), ...(y ? { y } : {}) };
};
const block: Record<string, unknown> = { id, textures: {} };
if (state.variants !== undefined) {
// the model it falls back to is the one it's placed with
const placed = cases.find(({ conditions: [condition] }) =>
Object.entries(condition).every(([name, value]) =>
values.get(name)!.indexOf(value) === states.find((s) =>
s.name === name
)!.default
)
) ?? cases[0];
block.model = drawn(placed.apply).model;
const only = cases.length === 1 && key(cases[0].conditions[0]) === "";
if (!only || cases[0].apply.x || cases[0].apply.y) {
block.variants = Object.fromEntries(
cases.map(({ conditions: [condition], apply }) => [key(condition), drawn(apply)]),
);
}
} else {
// a block placed as nothing can't be seen to have been placed, like a wall without its post. java places those
// in a state that draws something, which here is the first part's
const defaults = (condition: Condition) =>
Object.entries(condition).every(([name, value]) =>
values.get(name)!.indexOf(value) === states.find((s) => s.name === name)!.default
);
if (!cases.some(({ conditions }) => conditions.some(defaults)) && cases.length > 0) {
for (const [name, value] of Object.entries(cases[0].conditions[0])) {
states.find((s) => s.name === name)!.default = values.get(name)!.indexOf(value);
}
}
block.parts = cases.flatMap(({ conditions, apply }) =>
conditions.map((condition) => {
const when = key(condition);
return when === "" ? drawn(apply) : { when, ...drawn(apply) };
})
);
}
if (states.length > 0) block.states = states;
// non-cubes are cutout, so what's behind them isn't hidden, and models can ask for translucent
const looks = cases.map(({ apply }) => model_looks(location_string(parse_location(apply.model)), read));
if (looks.some((look) => look.render_type?.includes("translucent"))) block.render_layer = "translucent";
else if (looks.some((look) => !look.cube || look.render_type?.includes("cutout"))) block.render_layer = "cutout";
block.mining = { toughness: 1 };
const item = `${namespace}:item/${path}`;
if (!read(item) || remaps.skip?.some((pattern) => new RegExp(pattern).test(item))) {
// java blocks without an item model have no item, like a block made by another
block.item = false;
} else {
block.drops = id;
const sprite = made_by(item, read);
if (sprite === undefined) {
block.item_model = to_id(item, remaps.models);
} else {
// a block's item is drawn flat as its first texture when it has no item model: the sprite's, here
const layer = merged_textures(item, read).layer0;
if (layer && !layer.startsWith("#")) block.textures = { item: to_id(layer, remaps.textures) };
}
}
return { kind: "block", id, json: { format_version: FORMAT_VERSION, block }, warnings: [...warnings] };
}
// why the model kind won't have written a model for a block to be drawn with, if it won't: one the remaps skip, one
// made by a loader (obj files, composites), one that doesn't exist, or minecraft's that no remap gives bworld's for
function model_missing(from: string, id: string, read: ModelSource, remaps: Remaps): string | undefined {
if (remaps.skip?.some((pattern) => new RegExp(pattern).test(from))) return "is skipped by the remaps";
if (parse_location(from).namespace === "minecraft") {
return id.startsWith("minecraft:") ? "is minecraft's, and no --remap names a bworld model for it" : undefined;
}
if (!read(from)) return "doesn't exist";
if (is_empty(from, read)) return "has nothing in it";
const made = made_by(from, read);
return made ? `isn't boxes (${made})` : undefined;
}
// "axis=x,powered=true" as a condition, "" as none
function parse_key(key: string): Condition {
return Object.fromEntries(
key.split(",").filter((part) => part.includes("=")).map((part) => part.split("=").map((s) => s.trim())),
);
}
// a multipart "when" as the conditions any of which draw it: { "north": "true|side" } is two, and so is
// { "OR": [{...}, {...}] }. bworld's parts have no "or", so a part that's drawn for several becomes several parts
function when_conditions(when: unknown): Condition[] {
if (when === undefined || when === null) return [{}];
const object = when as Record<string, unknown>;
if (Array.isArray(object.OR)) return object.OR.flatMap(when_conditions);
if (Array.isArray(object.AND)) {
return object.AND.reduce<Condition[]>(
(all, next) => all.flatMap((a) => when_conditions(next).map((b) => ({ ...a, ...b }))),
[{}],
);
}
return Object.entries(object).reduce<Condition[]>(
(all, [name, value]) => all.flatMap((a) => String(value).split("|").map((v) => ({ ...a, [name]: v }))),
[{}],
);
}
// variants without the properties that never change what's drawn, like waterlogged, which only take bits and multiply
// the variants
function without_unused_properties(cases: { conditions: Condition[]; apply: Apply }[]) {
const names = new Set(cases.flatMap(({ conditions: [condition] }) => Object.keys(condition)));
const unused = [...names].filter((name) => {
const drawn_by_rest = new Map<string, Set<string>>();
for (const { conditions: [condition], apply } of cases) {
const rest = JSON.stringify(Object.entries(condition).filter(([other]) => other !== name).sort());
drawn_by_rest.set(rest, (drawn_by_rest.get(rest) ?? new Set()).add(JSON.stringify(apply)));
}
return [...drawn_by_rest.values()].every((drawn) => drawn.size === 1);
});
const seen = new Set<string>();
return cases.flatMap(({ conditions: [condition], apply }) => {
const kept = Object.fromEntries(Object.entries(condition).filter(([name]) => !unused.includes(name)));
const key = JSON.stringify(Object.entries(kept).sort());
if (seen.has(key)) return [];
seen.add(key);
return [{ conditions: [kept], apply }];
});
}
// a property's values in the order they become numbers. variants name every value a property has, but a multipart only
// the ones its parts are drawn for: a pipe's arm is drawn for "north=true", and "false" is nowhere. so in a multipart,
// booleans and the properties bworld knows the orders of get all their values, and any other starts with a value no part
// is drawn for, which blocks are placed with
function ordered(values: string[], all_named: boolean): string[] {
const order = ORDERS.find((order) => values.every((value) => order.includes(value)));
if (order === ORDERS[0] || (order && !all_named)) return order;
if (order) return order.filter((value) => values.includes(value));
const sorted = values.every((value) => /^\d+$/.test(value))
? [...values].sort((a, b) => Number(a) - Number(b))
: values;
return all_named ? sorted : ["", ...sorted];
}
// whether a java model is a full cube, and the render type it asks for, going up its parents to the first that has
// elements or is one of minecraft's cubes
function model_looks(location: string, read: ModelSource): { cube: boolean; render_type?: string } {
let render_type: string | undefined;
const seen = new Set<string>();
for (let at: string | undefined = location; at && !seen.has(at);) {
seen.add(at);
if (CUBES.includes(at)) return { cube: true, render_type };
const json = read(at);
if (!json) break;
if (typeof json.render_type === "string") render_type ??= json.render_type;
if (json.elements !== undefined) return { cube: is_full_box(json.elements), render_type };
at = typeof json.parent === "string" ? location_string(parse_location(json.parent)) : undefined;
}
return { cube: false, render_type };
}
function is_full_box(elements: unknown): boolean {
if (!Array.isArray(elements) || elements.length !== 1) return false;
const { from, to, rotation } = elements[0] as { from?: number[]; to?: number[]; rotation?: { angle?: number } };
return String(from) === "0,0,0" && String(to) === "16,16,16" && !rotation?.angle;
}
// a java model's texture variables with its parents', its own winning
export function merged_textures(location: string, read: ModelSource): Record<string, string> {
const chain: Record<string, string>[] = [];
const seen = new Set<string>();
for (let at: string | undefined = location; at && !seen.has(at);) {
seen.add(at);
const json = read(at);
if (!json) break;
chain.push((json.textures ?? {}) as Record<string, string>);
at = typeof json.parent === "string" ? location_string(parse_location(json.parent)) : undefined;
}
return Object.assign({}, ...chain.reverse());
}
+93
View File
@@ -0,0 +1,93 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// java item models (assets/<namespace>/models/item/*.json) to bworld's items/, for the items that aren't a block's: a
// block's item comes with the block (see blocks.ts). java says an item is a flat sprite with item/generated and its
// layer0 texture, which is what a bworld item is. one java draws in 3D (a wrench, goggles) is drawn flat here, with a
// texture of its model, until bworld items can have models
import { join } from "@std/path";
import { FORMAT_VERSION } from "$/common/mod_data.ts";
import { made_by, model_source } from "./models.ts";
import { merged_textures, models_near } from "./blocks.ts";
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,
skips,
to_id,
write_report,
} from "./resources.ts";
export function import_items(input: string, options: ImportOptions = {}): ImportReport {
if (options.output === undefined) throw new Error("--output is needed for items");
const remaps = options.remaps ?? DEFAULT_REMAPS;
// an item is a model directly in models/item, the folders under it are parts of models
const files = input_files(input, "models", ".json", options.namespace)
.filter(({ root, file }) => /^item\/[^/]+$/.test(location_of(root, file, ".json").path));
const roots = [...new Set(files.map(({ root }) => root))];
const read = model_source(models_near(input, roots, options));
// blockstates beside the models, so a block's item is left to the block
const blockstates = [
...(is_file(input) ? [] : find_roots(input, "blockstates", options.namespace)),
...roots.map((root) => ({ namespace: root.namespace, dir: root.dir.replace(/models$/, "blockstates") })),
];
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;
const name = where.path.slice("item/".length);
if (blockstates.some((dir) => dir.namespace === where.namespace && is_file(`${dir.dir}/${name}.json`))) {
continue;
}
const id = to_id(`${where.namespace}:${name}`);
const textures = merged_textures(location, read);
const resolve = (reference: string | undefined) => {
for (let depth = 0; depth < 8 && reference?.startsWith("#"); depth++) {
reference = textures[reference.slice(1)];
}
return reference?.startsWith("#") ? undefined : reference;
};
let texture: string | undefined;
if (made_by(location, read)?.startsWith("an item sprite")) {
texture = resolve(textures.layer0);
if (textures.layer1 !== undefined) {
report.warnings.push({ location, warning: "only the first layer of sprites with several was kept" });
}
} else {
texture = resolve(textures.particle) ?? Object.values(textures).map(resolve).find((t) => t !== undefined);
report.warnings.push({ location, warning: "drawn in 3D in java, it's a flat texture of its model here" });
}
if (texture === undefined) {
// like item/pane, a template other item models use as their parent
report.skipped.push({ location, reason: "it has no texture, so it's only a parent of other item models" });
continue;
}
const texture_id = to_id(texture, remaps.textures);
if (!is_valid_id(id) || !is_valid_id(texture_id)) {
report.errors.push({ location, problems: [`its id ${id} or texture ${texture_id} isn't a valid id`] });
continue;
}
if (!claim(id, location)) continue;
const json = { format_version: FORMAT_VERSION, item: { id, texture: texture_id } };
report.written.push({
location,
id,
file: join(options.output, `${name}.json`),
text: format_json(json) + "\n",
});
}
write_report(report);
return report;
}
+28 -21
View File
@@ -22,6 +22,8 @@ import {
location_string,
parse_location,
type Remaps,
type ResourceRoot,
skips,
to_id,
write_report,
} from "./resources.ts";
@@ -57,7 +59,7 @@ 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 {
export 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;
@@ -73,27 +75,10 @@ export function import_models(input: string, options: ImportOptions = {}): Impor
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 = [
const read = model_source([
...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();
@@ -101,6 +86,7 @@ export function import_models(input: string, options: ImportOptions = {}): Impor
for (const { root, file } of files) {
const where = location_of(root, file, ".json");
const location = location_string(where);
if (skips(location, remaps, report)) continue;
const result = convert_model(location, read, remaps);
if (result.kind === "skipped") report.skipped.push({ location, reason: result.reason });
else if (result.kind === "error") report.errors.push({ location, problems: result.problems });
@@ -117,6 +103,27 @@ export function import_models(input: string, options: ImportOptions = {}): Impor
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<string, Record<string, unknown> | 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<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;
};
}
export function convert_model(location: string, read: ModelSource, remaps: Remaps): ModelResult {
const json = read(location_string(parse_location(location)));
if (!json) return { kind: "error", problems: [`${location} wasn't found`] };
@@ -171,7 +178,7 @@ export function convert_model(location: string, read: ModelSource, remaps: Remap
// 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 {
export 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);
+24 -6
View File
@@ -31,6 +31,9 @@ export type Remap = Record<string, string>;
export interface Remaps {
textures: Remap;
models: Remap;
// patterns (regular expressions) for locations to leave out of every kind, like a mod's blocks for content bworld
// doesn't have: "crimson" leaves out create:crimson_window, its models and its textures
skip?: string[];
}
export const DEFAULT_REMAPS: Remaps = {
@@ -209,6 +212,13 @@ export interface ImportReport {
warnings: { location: string; warning: string }[];
}
// whether the remaps leave a location out, which is reported as skipped
export function skips(location: string, remaps: Remaps, report: ImportReport): boolean {
const pattern = remaps.skip?.find((pattern) => new RegExp(pattern).test(location));
if (pattern !== undefined) report.skipped.push({ location, reason: `the remaps skip "${pattern}"` });
return pattern !== undefined;
}
export function empty_report(): ImportReport {
return { written: [], skipped: [], errors: [], warnings: [] };
}
@@ -240,20 +250,28 @@ export function write_report(report: ImportReport) {
}
}
// 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 {
// how wide deno fmt lets a line be, with a tab as 4 columns, see deno.json
const LINE_WIDTH = 120;
const TAB_WIDTH = 4;
// json in the style of the repo's data files, the way deno fmt leaves it: tabs, and short lists and objects of plain
// values on one line when the whole line fits. indent is the line it starts on, after prefix (like a key) on that line
export function format_json(value: unknown, indent = "", prefix = 0): 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")}`
);
: Object.entries(value).filter(([, v]) => v !== undefined).map(([k, v]) => {
const key = `${JSON.stringify(k)}: `;
return key + format_json(v, indent + "\t", key.length);
});
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;
// and a comma after it
const width = indent.length * TAB_WIDTH + prefix + one_line.length + 1;
if (flat && !one_line.includes("\n") && width <= LINE_WIDTH) return one_line;
return `${open}\n${entries.map((e) => indent + "\t" + e).join(",\n")}\n${indent}${close}`;
}
+2
View File
@@ -21,6 +21,7 @@ import {
location_of,
location_string,
remap_location,
skips,
to_id,
write_report,
} from "./resources.ts";
@@ -67,6 +68,7 @@ export function import_textures(input: string, options: ImportOptions = {}): Imp
}
for (const { root, file } of files) {
const location = location_string(location_of(root, file, ".png"));
if (skips(location, remaps, report)) continue;
if (root.namespace === "minecraft") {
report.skipped.push({
location,