diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackJsonText.java b/core/src/main/java/art/arcane/iris/core/pack/PackJsonText.java new file mode 100644 index 000000000..ee4d57af5 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/pack/PackJsonText.java @@ -0,0 +1,224 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.pack; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +/** + * Positions in the text of a JSON file as Iris reads it, with comments and trailing commas, so a file can be edited + * in place without rewriting the formatting around the edit. + */ +final class PackJsonText { + private PackJsonText() { + } + + /** A member of an object: the key and where its value starts and ends in the text. */ + record Member(String key, int keyStart, int valueStart, int valueEnd) { + } + + /** A value inside an array: where it starts and ends in the text. */ + record Item(int start, int end) { + } + + /** A replacement of the text from {@code start} up to {@code end}. */ + record Edit(int start, int end, String replacement) { + } + + static List members(String text, int objectStart) { + if (text.charAt(objectStart) != '{') { + throw new IllegalArgumentException("An object was expected at " + objectStart); + } + + List members = new ArrayList<>(); + int index = skipBlank(text, objectStart + 1); + while (index < text.length() && text.charAt(index) != '}') { + if (text.charAt(index) == ',') { + index = skipBlank(text, index + 1); + continue; + } + + if (text.charAt(index) != '"') { + throw new IllegalArgumentException("A key was expected at " + index); + } + + int keyEnd = stringEnd(text, index); + int colon = skipBlank(text, keyEnd + 1); + int valueStart = skipBlank(text, colon + 1); + int valueEnd = valueEnd(text, valueStart); + members.add(new Member(text.substring(index + 1, keyEnd), index, valueStart, valueEnd)); + index = skipBlank(text, valueEnd); + } + return members; + } + + static Member member(List members, String key) { + return members.stream().filter(member -> member.key().equals(key)).findFirst().orElse(null); + } + + static List items(String text, int arrayStart) { + if (text.charAt(arrayStart) != '[') { + throw new IllegalArgumentException("An array was expected at " + arrayStart); + } + + List items = new ArrayList<>(); + int index = skipBlank(text, arrayStart + 1); + while (index < text.length() && text.charAt(index) != ']') { + if (text.charAt(index) == ',') { + index = skipBlank(text, index + 1); + continue; + } + + int end = valueEnd(text, index); + items.add(new Item(index, end)); + index = skipBlank(text, end); + } + return items; + } + + /** The text of the file with every edit applied; the edits must not overlap. */ + static String apply(String text, List edits) { + StringBuilder edited = new StringBuilder(text); + edits.stream().sorted(Comparator.comparingInt(Edit::start).reversed()) + .forEach(edit -> edited.replace(edit.start(), edit.end(), edit.replacement())); + return edited.toString(); + } + + /** The edit that takes the member out, together with its comma and, when it stands alone there, its lines. */ + static Edit removal(String text, Member member) { + int start = member.keyStart(); + int end = member.valueEnd(); + int after = skipBlank(text, end); + if (after < text.length() && text.charAt(after) == ',') { + end = after + 1; + } else { + int before = start - 1; + while (before >= 0 && Character.isWhitespace(text.charAt(before))) { + before--; + } + if (before >= 0 && text.charAt(before) == ',') { + start = before; + } + } + + int lineStart = text.lastIndexOf('\n', start - 1) + 1; + int lineEnd = text.indexOf('\n', end); + if (lineEnd < 0) { + lineEnd = text.length(); + } + + boolean alone = text.substring(lineStart, start).isBlank() && text.substring(end, lineEnd).isBlank(); + if (!alone) { + return new Edit(start, end, ""); + } + return new Edit(lineStart, Math.min(lineEnd + 1, text.length()), ""); + } + + /** The whitespace the line holding {@code position} starts with. */ + static String indentAt(String text, int position) { + int lineStart = text.lastIndexOf('\n', position - 1) + 1; + int index = lineStart; + while (index < position && (text.charAt(index) == ' ' || text.charAt(index) == '\t')) { + index++; + } + return text.substring(lineStart, index); + } + + static int skipBlank(String text, int index) { + int position = index; + while (position < text.length()) { + if (Character.isWhitespace(text.charAt(position))) { + position++; + } else if (isComment(text, position)) { + position = commentEnd(text, position); + } else { + break; + } + } + return position; + } + + static int valueEnd(String text, int start) { + char first = text.charAt(start); + if (first == '"') { + return stringEnd(text, start) + 1; + } + + if (first != '[' && first != '{') { + return literalEnd(text, start); + } + + int depth = 0; + int index = start; + while (index < text.length()) { + char current = text.charAt(index); + if (current == '"') { + index = stringEnd(text, index); + } else if (isComment(text, index)) { + index = commentEnd(text, index) - 1; + } else if (current == '[' || current == '{') { + depth++; + } else if (current == ']' || current == '}') { + depth--; + if (depth == 0) { + return index + 1; + } + } + index++; + } + throw new IllegalArgumentException("The value at " + start + " is not closed"); + } + + private static int literalEnd(String text, int start) { + int index = start; + while (index < text.length() && ",]} \t\r\n".indexOf(text.charAt(index)) < 0 && !isComment(text, index)) { + index++; + } + return index; + } + + private static int stringEnd(String text, int quote) { + int index = quote + 1; + while (index < text.length() && text.charAt(index) != '"') { + index += text.charAt(index) == '\\' ? 2 : 1; + } + if (index >= text.length()) { + throw new IllegalArgumentException("The string at " + quote + " is not closed"); + } + return index; + } + + private static boolean isComment(String text, int index) { + return text.startsWith("//", index) || text.startsWith("/*", index); + } + + private static int commentEnd(String text, int start) { + if (text.startsWith("//", start)) { + int lineEnd = text.indexOf('\n', start); + return lineEnd < 0 ? text.length() : lineEnd; + } + + int close = text.indexOf("*/", start + 2); + if (close < 0) { + throw new IllegalArgumentException("The comment at " + start + " is not closed"); + } + return close + 2; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackWeightConverter.java b/core/src/main/java/art/arcane/iris/core/pack/PackWeightConverter.java new file mode 100644 index 000000000..fe6c0719f --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/pack/PackWeightConverter.java @@ -0,0 +1,514 @@ +/* + * Iris is a World Generator for Minecraft Servers + * Copyright (c) 2026 Arcane Arts (Volmit Software) + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package art.arcane.iris.core.pack; + +import art.arcane.iris.core.pack.PackJsonText.Edit; +import art.arcane.iris.core.pack.PackJsonText.Item; +import art.arcane.iris.core.pack.PackJsonText.Member; +import com.google.gson.JsonParser; +import com.volmit.world.Weighted; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeSet; +import java.util.stream.Stream; + +/** + * Converts a pack from rarity to weighted list entries, keeping the share every list entry had in its pick: + *
+ * "landBiomes": [{"biome": "plains", "weight": 3}, ...]        (also seaBiomes, shoreBiomes, caveBiomes)
+ * "regions":    [{"region": "temperate", "weight": 2}, ...]     (in the dimension)
+ * "children":   [{"biome": "forest", "weight": 2}, {"biome": "plains", "weight": 5}, ...]
+ * "carving":    [{"id": "deep", "children": [{"id": "lush", "weight": 2}, {"id": "deep", "weight": 5}]}]
+ * 
+ * Region, biome and dimension lists were picked with a share of 1 / rarity per entry, so an entry's weight is the least + * common multiple of the list's rarities divided by its rarity, reduced by the greatest common divisor. Children were + * picked from rounded slots, the rarer a biome the fewer, alternating from both ends, with the parent among them; the + * parent is listed among its children wherever it kept the spot, in half slots, since the first and last slot only + * held half a slot of noise. A carving entry's children pick the same way by the rarity of the entries' biomes. The + * top-level {@code rarity} of biomes and regions is removed; nested rarities (loot, spawns, objects) stay. + *

+ * Files are edited as text, so formatting elsewhere stays; a rewritten list gets one entry per line. A list that would need + * a weight above {@link Weighted#MAX_WEIGHT} stops the conversion. A pack with lists already converted and lists not yet + * converted cannot be told apart from rarity 1 and is refused. + *

+ * Usage: {@code PackWeightConverter [--dry-run] ...} + */ +public final class PackWeightConverter { + private static final String INDENT_STEP = " "; + private static final String JSON_EXTENSION = ".json"; + private static final int DEFAULT_RARITY = 1; + private static final List BIOME_LISTS = List.of("landBiomes", "seaBiomes", "shoreBiomes", "caveBiomes"); + + /** The files a conversion changed (relative to the pack) and what it could not carry over exactly. */ + public record Result(List changedFiles, List warnings) { + } + + /** A pack the converter cannot convert while keeping every pick. */ + public static final class ConversionException extends RuntimeException { + ConversionException(String message) { + super(message); + } + } + + private record Entry(String key, int weight) { + } + + private record Option(String key, int rarity) { + } + + private record CarvingBand(String biome, boolean enabled) { + } + + private final Path pack; + private final Map biomeRarities; + private final Map regionRarities; + private final TreeSet warnings = new TreeSet<>(); + private String currentFile = ""; + + private PackWeightConverter(Path pack) throws IOException { + this.pack = pack; + this.biomeRarities = rarities("biomes"); + this.regionRarities = rarities("regions"); + } + + public static Result convert(Path pack, boolean dryRun) throws IOException { + PackWeightConverter converter = new PackWeightConverter(pack); + converter.refusePartlyConverted(); + Map converted = new LinkedHashMap<>(); + for (String folder : List.of("biomes", "regions", "dimensions")) { + for (Path file : converter.files(folder)) { + String text = converter.convertFile(folder, file); + if (text != null) { + converted.put(file, text); + } + } + } + + List changed = new ArrayList<>(); + for (Map.Entry file : converted.entrySet()) { + changed.add(relative(pack, file.getKey())); + if (!dryRun) { + Files.writeString(file.getKey(), file.getValue(), StandardCharsets.UTF_8); + } + } + return new Result(changed, List.copyOf(converter.warnings)); + } + + public static void main(String[] arguments) throws IOException { + boolean dryRun = false; + List packs = new ArrayList<>(); + for (String argument : arguments) { + if (argument.equals("--dry-run")) { + dryRun = true; + } else { + packs.add(Path.of(argument)); + } + } + + if (packs.isEmpty()) { + System.err.println("Usage: PackWeightConverter [--dry-run] ..."); + System.exit(2); + } + + for (Path folder : packs) { + try { + Result result = convert(folder, dryRun); + result.changedFiles().forEach(System.out::println); + result.warnings().forEach(warning -> System.out.println("warning: " + warning)); + System.out.println(folder + ": " + result.changedFiles().size() + " files " + (dryRun ? "would change" : "changed")); + } catch (ConversionException refusal) { + System.err.println(folder + ": " + refusal.getMessage()); + System.exit(1); + } + } + } + + /** The converted text of the file; null when nothing in it changes. */ + private String convertFile(String folder, Path file) throws IOException { + currentFile = relative(pack, file); + String text = Files.readString(file, StandardCharsets.UTF_8); + String converted = switch (folder) { + case "biomes" -> convertBiome(keyOf(pack.resolve(folder), file), text); + case "regions" -> convertRegion(text); + default -> convertDimension(text); + }; + if (converted.equals(text)) { + return null; + } + + verifyParses(converted); + return converted; + } + + private static String relative(Path pack, Path file) { + return pack.relativize(file).toString().replace('\\', '/'); + } + + private String convertBiome(String key, String text) { + List members = rootMembers(text); + List edits = new ArrayList<>(); + Member children = PackJsonText.member(members, "children"); + List childKeys = stringItems(text, children); + if (childKeys != null) { + edits.add(replaceList(text, children, "biome", childEntries(key, childKeys))); + } + addRarityRemoval(text, members, edits); + return PackJsonText.apply(text, edits); + } + + private String convertRegion(String text) { + List members = rootMembers(text); + List edits = new ArrayList<>(); + for (String list : BIOME_LISTS) { + Member member = PackJsonText.member(members, list); + List keys = stringItems(text, member); + if (keys != null) { + edits.add(replaceList(text, member, "biome", listEntries(keys, biomeRarities))); + } + } + addRarityRemoval(text, members, edits); + return PackJsonText.apply(text, edits); + } + + private String convertDimension(String text) { + List members = rootMembers(text); + List edits = new ArrayList<>(); + Member regions = PackJsonText.member(members, "regions"); + List regionKeys = stringItems(text, regions); + if (regionKeys != null) { + edits.add(replaceList(text, regions, "region", listEntries(regionKeys, regionRarities))); + } + + Member carving = PackJsonText.member(members, "carving"); + if (carving != null && text.charAt(carving.valueStart()) == '[') { + edits.addAll(convertCarving(text, carving)); + } + return PackJsonText.apply(text, edits); + } + + private List convertCarving(String text, Member carving) { + List> bands = new ArrayList<>(); + for (Item item : PackJsonText.items(text, carving.valueStart())) { + bands.add(text.charAt(item.start()) == '{' ? PackJsonText.members(text, item.start()) : List.of()); + } + + Map bandsById = new HashMap<>(); + for (List members : bands) { + String id = stringValue(text, PackJsonText.member(members, "id")).trim(); + if (!id.isEmpty()) { + bandsById.put(id, carvingBand(text, members)); + } + } + + List edits = new ArrayList<>(); + for (List members : bands) { + Member children = PackJsonText.member(members, "children"); + List childIds = stringItems(text, children); + if (childIds != null) { + edits.add(replaceList(text, children, "id", carvingChildEntries(text, members, childIds, bandsById))); + } + } + return edits; + } + + private CarvingBand carvingBand(String text, List members) { + Member enabled = PackJsonText.member(members, "enabled"); + boolean isEnabled = enabled == null || !text.startsWith("false", enabled.valueStart()); + return new CarvingBand(stringValue(text, PackJsonText.member(members, "biome")).trim(), isEnabled); + } + + private List carvingChildEntries(String text, List members, List childIds, Map bandsById) { + String parentId = stringValue(text, PackJsonText.member(members, "id")).trim(); + if (parentId.isEmpty()) { + throw new ConversionException(currentFile + ": a carving entry with children needs an id, so that it can list itself among them"); + } + + List