mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-27 16:25:36 +00:00
Add a pack converter from rarity to weighted entries
A pack written with rarity needs its dimension regions, region biome lists, biome children and carving children rewritten to weighted entries. Lists that picked by 1 / rarity get the integer weights proportional to it (the least common multiple of the rarities over each, reduced by the greatest common divisor) and a list that would need a weight above 1000 stops the conversion; children keep their old rounded slots as half-slot weights with the parent listed among them. Files are edited as text so comments and formatting stay, and the conversion is all or nothing per pack. Next to the other pack tooling in core, run as PackWeightConverter [--dry-run] <pack folder>. The converter's test checks the fixture packs are already what it would write. v3: 96beb86e0
This commit is contained in:
1 parent
3d55236f97
commit
08f4bffca9
3 files changed
+1005
No files matched your search
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<Member> members(String text, int objectStart) {
|
||||
if (text.charAt(objectStart) != '{') {
|
||||
throw new IllegalArgumentException("An object was expected at " + objectStart);
|
||||
}
|
||||
|
||||
List<Member> 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<Member> members, String key) {
|
||||
return members.stream().filter(member -> member.key().equals(key)).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
static List<Item> items(String text, int arrayStart) {
|
||||
if (text.charAt(arrayStart) != '[') {
|
||||
throw new IllegalArgumentException("An array was expected at " + arrayStart);
|
||||
}
|
||||
|
||||
List<Item> 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<Edit> 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;
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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:
|
||||
* <pre>
|
||||
* "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}]}]
|
||||
* </pre>
|
||||
* 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.
|
||||
* <p>
|
||||
* 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.
|
||||
* <p>
|
||||
* Usage: {@code PackWeightConverter [--dry-run] <pack folder>...}
|
||||
*/
|
||||
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<String> 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<String> changedFiles, List<String> 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<String, Integer> biomeRarities;
|
||||
private final Map<String, Integer> regionRarities;
|
||||
private final TreeSet<String> 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<Path, String> 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<String> changed = new ArrayList<>();
|
||||
for (Map.Entry<Path, String> 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<Path> 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] <pack folder>...");
|
||||
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<Member> members = rootMembers(text);
|
||||
List<Edit> edits = new ArrayList<>();
|
||||
Member children = PackJsonText.member(members, "children");
|
||||
List<String> 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<Member> members = rootMembers(text);
|
||||
List<Edit> edits = new ArrayList<>();
|
||||
for (String list : BIOME_LISTS) {
|
||||
Member member = PackJsonText.member(members, list);
|
||||
List<String> 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<Member> members = rootMembers(text);
|
||||
List<Edit> edits = new ArrayList<>();
|
||||
Member regions = PackJsonText.member(members, "regions");
|
||||
List<String> 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<Edit> convertCarving(String text, Member carving) {
|
||||
List<List<Member>> 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<String, CarvingBand> bandsById = new HashMap<>();
|
||||
for (List<Member> members : bands) {
|
||||
String id = stringValue(text, PackJsonText.member(members, "id")).trim();
|
||||
if (!id.isEmpty()) {
|
||||
bandsById.put(id, carvingBand(text, members));
|
||||
}
|
||||
}
|
||||
|
||||
List<Edit> edits = new ArrayList<>();
|
||||
for (List<Member> members : bands) {
|
||||
Member children = PackJsonText.member(members, "children");
|
||||
List<String> 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<Member> 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<Entry> carvingChildEntries(String text, List<Member> members, List<String> childIds, Map<String, CarvingBand> 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<Option> options = new ArrayList<>();
|
||||
for (String listed : childIds) {
|
||||
String childId = listed.trim();
|
||||
CarvingBand child = bandsById.get(childId);
|
||||
if (child == null || !child.enabled() || !biomeRarities.containsKey(child.biome())) {
|
||||
warnings.add(currentFile + ": the carving child '" + childId + "' is not an enabled entry with a biome of this pack; Iris skipped it");
|
||||
continue;
|
||||
}
|
||||
options.add(new Option(childId, biomeRarities.get(child.biome())));
|
||||
}
|
||||
|
||||
CarvingBand parent = bandsById.get(parentId);
|
||||
options.add(new Option(parentId, biomeRarities.getOrDefault(parent.biome(), DEFAULT_RARITY)));
|
||||
return halfSlotRuns(oldChildSlots(options));
|
||||
}
|
||||
|
||||
private List<Entry> childEntries(String parent, List<String> children) {
|
||||
List<Option> options = new ArrayList<>();
|
||||
for (String child : children) {
|
||||
if (!biomeRarities.containsKey(child)) {
|
||||
warnings.add(currentFile + ": the child '" + child + "' has no file in this pack; Iris skipped it");
|
||||
continue;
|
||||
}
|
||||
options.add(new Option(child, biomeRarities.get(child)));
|
||||
}
|
||||
options.add(new Option(parent, biomeRarities.getOrDefault(parent, DEFAULT_RARITY)));
|
||||
return halfSlotRuns(oldChildSlots(options));
|
||||
}
|
||||
|
||||
private List<Entry> listEntries(List<String> keys, Map<String, Integer> rarities) {
|
||||
List<Integer> loadedRarities = new ArrayList<>();
|
||||
for (String key : keys) {
|
||||
if (rarities.containsKey(key)) {
|
||||
loadedRarities.add(rarities.get(key));
|
||||
} else {
|
||||
warnings.add(currentFile + ": '" + key + "' is listed but has no file in this pack; Iris skips it");
|
||||
}
|
||||
}
|
||||
|
||||
List<Integer> weights = shareWeights(loadedRarities);
|
||||
List<Entry> entries = new ArrayList<>();
|
||||
int loaded = 0;
|
||||
for (String key : keys) {
|
||||
entries.add(new Entry(key, rarities.containsKey(key) ? weights.get(loaded++) : Weighted.MIN_WEIGHT));
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/** Weights proportional to 1 / rarity: the least common multiple of the rarities divided by each, reduced. */
|
||||
private List<Integer> shareWeights(List<Integer> rarities) {
|
||||
if (rarities.size() <= 1) {
|
||||
return rarities.stream().map(rarity -> Weighted.MIN_WEIGHT).toList();
|
||||
}
|
||||
|
||||
long commonMultiple = 1;
|
||||
for (int rarity : rarities) {
|
||||
commonMultiple = commonMultiple / gcd(commonMultiple, rarity) * rarity;
|
||||
if (commonMultiple > Integer.MAX_VALUE) {
|
||||
throw new ConversionException(currentFile + ": the rarities " + rarities + " share no weights up to " + Weighted.MAX_WEIGHT);
|
||||
}
|
||||
}
|
||||
|
||||
long divisor = 0;
|
||||
for (int rarity : rarities) {
|
||||
divisor = gcd(divisor, commonMultiple / rarity);
|
||||
}
|
||||
|
||||
List<Integer> weights = new ArrayList<>();
|
||||
for (int rarity : rarities) {
|
||||
long weight = commonMultiple / rarity / divisor;
|
||||
if (weight > Weighted.MAX_WEIGHT) {
|
||||
throw new ConversionException(currentFile + ": the rarities " + rarities + " need a weight of " + weight
|
||||
+ ", above the maximum of " + Weighted.MAX_WEIGHT + "; list them with weights by hand");
|
||||
}
|
||||
weights.add((int) weight);
|
||||
}
|
||||
return weights;
|
||||
}
|
||||
|
||||
/** The old child picker's slots: rarer options get fewer, and each option adds its slots to alternating ends. */
|
||||
private static List<String> oldChildSlots(List<Option> options) {
|
||||
int most = options.stream().mapToInt(option -> Math.max(DEFAULT_RARITY, option.rarity())).max().orElse(DEFAULT_RARITY) + 1;
|
||||
List<String> slots = new ArrayList<>();
|
||||
boolean atEnd = false;
|
||||
for (Option option : options) {
|
||||
for (int copy = 0; copy < most - Math.max(DEFAULT_RARITY, option.rarity()); copy++) {
|
||||
atEnd = !atEnd;
|
||||
if (atEnd) {
|
||||
slots.add(option.key());
|
||||
} else {
|
||||
slots.addFirst(option.key());
|
||||
}
|
||||
}
|
||||
}
|
||||
return slots;
|
||||
}
|
||||
|
||||
/** The old picker rounded the noise onto the slots, so the first and last slot had half a slot of noise. */
|
||||
private List<Entry> halfSlotRuns(List<String> slots) {
|
||||
List<String> keys = new ArrayList<>();
|
||||
List<Integer> halves = new ArrayList<>();
|
||||
for (int index = 0; index < slots.size(); index++) {
|
||||
int slotHalves = index == 0 || index == slots.size() - 1 ? 1 : 2;
|
||||
if (!keys.isEmpty() && keys.getLast().equals(slots.get(index))) {
|
||||
halves.set(halves.size() - 1, halves.getLast() + slotHalves);
|
||||
} else {
|
||||
keys.add(slots.get(index));
|
||||
halves.add(slotHalves);
|
||||
}
|
||||
}
|
||||
|
||||
List<Entry> entries = new ArrayList<>();
|
||||
for (int run = 0; run < keys.size(); run++) {
|
||||
if (halves.get(run) > Weighted.MAX_WEIGHT) {
|
||||
throw new ConversionException(currentFile + ": the children of one biome need a weight of " + halves.get(run)
|
||||
+ ", above the maximum of " + Weighted.MAX_WEIGHT + "; list them with weights by hand");
|
||||
}
|
||||
entries.add(new Entry(keys.get(run), halves.get(run)));
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
private Edit replaceList(String text, Member list, String field, List<Entry> entries) {
|
||||
String indent = PackJsonText.indentAt(text, list.keyStart());
|
||||
StringBuilder replacement = new StringBuilder("[\n");
|
||||
for (int index = 0; index < entries.size(); index++) {
|
||||
Entry entry = entries.get(index);
|
||||
replacement.append(indent).append(INDENT_STEP)
|
||||
.append("{\"").append(field).append("\": \"").append(entry.key()).append("\", \"weight\": ").append(entry.weight()).append('}')
|
||||
.append(index < entries.size() - 1 ? ",\n" : "\n");
|
||||
}
|
||||
replacement.append(indent).append(']');
|
||||
return new Edit(list.valueStart(), list.valueEnd(), replacement.toString());
|
||||
}
|
||||
|
||||
private void addRarityRemoval(String text, List<Member> members, List<Edit> edits) {
|
||||
Member rarity = PackJsonText.member(members, "rarity");
|
||||
if (rarity != null) {
|
||||
edits.add(PackJsonText.removal(text, rarity));
|
||||
}
|
||||
}
|
||||
|
||||
/** The strings of a list, or null when the list is missing, empty or already holds entries. */
|
||||
private List<String> stringItems(String text, Member list) {
|
||||
if (list == null || text.charAt(list.valueStart()) != '[') {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<Item> items = PackJsonText.items(text, list.valueStart());
|
||||
if (items.isEmpty() || items.stream().anyMatch(item -> text.charAt(item.start()) != '"')) {
|
||||
return null;
|
||||
}
|
||||
return items.stream().map(item -> plainString(text.substring(item.start() + 1, item.end() - 1))).toList();
|
||||
}
|
||||
|
||||
private String stringValue(String text, Member member) {
|
||||
if (member == null || text.charAt(member.valueStart()) != '"') {
|
||||
return "";
|
||||
}
|
||||
return plainString(text.substring(member.valueStart() + 1, member.valueEnd() - 1));
|
||||
}
|
||||
|
||||
private String plainString(String content) {
|
||||
if (content.indexOf('\\') >= 0) {
|
||||
throw new ConversionException(currentFile + ": the key \"" + content + "\" holds an escape; rewrite it by hand");
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
private List<Member> rootMembers(String text) {
|
||||
int start = PackJsonText.skipBlank(text, 0);
|
||||
if (start >= text.length() || text.charAt(start) != '{') {
|
||||
throw new ConversionException(currentFile + ": the file is not a JSON object");
|
||||
}
|
||||
|
||||
try {
|
||||
return PackJsonText.members(text, start);
|
||||
} catch (IllegalArgumentException unreadable) {
|
||||
throw new ConversionException(currentFile + ": " + unreadable.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void verifyParses(String converted) {
|
||||
try {
|
||||
JsonParser.parseString(converted);
|
||||
} catch (RuntimeException broken) {
|
||||
throw new ConversionException(currentFile + ": the converted file does not parse: " + broken.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Integer> rarities(String folder) throws IOException {
|
||||
Map<String, Integer> rarities = new HashMap<>();
|
||||
for (Path file : files(folder)) {
|
||||
currentFile = relative(pack, file);
|
||||
String text = Files.readString(file, StandardCharsets.UTF_8);
|
||||
Member rarity = PackJsonText.member(rootMembers(text), "rarity");
|
||||
rarities.put(keyOf(pack.resolve(folder), file), rarity == null ? DEFAULT_RARITY : rarityOf(text, rarity));
|
||||
}
|
||||
return rarities;
|
||||
}
|
||||
|
||||
private int rarityOf(String text, Member rarity) {
|
||||
try {
|
||||
return (int) Math.round(Double.parseDouble(text.substring(rarity.valueStart(), rarity.valueEnd())));
|
||||
} catch (NumberFormatException notANumber) {
|
||||
throw new ConversionException(currentFile + ": the rarity is not a number");
|
||||
}
|
||||
}
|
||||
|
||||
private void refusePartlyConverted() throws IOException {
|
||||
boolean convertedLists = false;
|
||||
boolean legacyLists = false;
|
||||
for (String folder : List.of("biomes", "regions", "dimensions")) {
|
||||
for (Path file : files(folder)) {
|
||||
currentFile = relative(pack, file);
|
||||
String text = Files.readString(file, StandardCharsets.UTF_8);
|
||||
List<Member> members = rootMembers(text);
|
||||
for (String list : listKeys(folder)) {
|
||||
Member member = PackJsonText.member(members, list);
|
||||
if (member == null || text.charAt(member.valueStart()) != '[') {
|
||||
continue;
|
||||
}
|
||||
List<Item> items = PackJsonText.items(text, member.valueStart());
|
||||
boolean hasStrings = items.stream().anyMatch(item -> text.charAt(item.start()) == '"');
|
||||
boolean hasEntries = items.stream().anyMatch(item -> text.charAt(item.start()) == '{');
|
||||
legacyLists |= hasStrings;
|
||||
convertedLists |= hasEntries;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (convertedLists && legacyLists) {
|
||||
throw new ConversionException("some lists are weighted entries already and some are not; the rarities of the converted"
|
||||
+ " files are gone, so restore the pack and convert it in one run");
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> listKeys(String folder) {
|
||||
return switch (folder) {
|
||||
case "biomes" -> List.of("children");
|
||||
case "regions" -> BIOME_LISTS;
|
||||
default -> List.of("regions");
|
||||
};
|
||||
}
|
||||
|
||||
private List<Path> files(String folder) throws IOException {
|
||||
Path root = pack.resolve(folder);
|
||||
if (!Files.isDirectory(root)) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
try (Stream<Path> walk = Files.walk(root)) {
|
||||
return walk.filter(file -> Files.isRegularFile(file) && file.getFileName().toString().endsWith(JSON_EXTENSION)).sorted().toList();
|
||||
}
|
||||
}
|
||||
|
||||
private static String keyOf(Path folder, Path file) {
|
||||
String relative = folder.relativize(file).toString().replace('\\', '/');
|
||||
return relative.substring(0, relative.length() - JSON_EXTENSION.length());
|
||||
}
|
||||
|
||||
private static long gcd(long first, long second) {
|
||||
return second == 0 ? first : gcd(second, first % second);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
package art.arcane.iris.core.pack;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.volmit.world.Weighted;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.TemporaryFolder;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertThrows;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class PackWeightConverterTest {
|
||||
private static final String FIXTURES = "/art/arcane/iris/core/modules/";
|
||||
private static final List<String> FIXTURE_PACKS = List.of("pack-before-the-port", "pack-before-loot-and-spawn", "pack-terrain");
|
||||
|
||||
@Rule
|
||||
public TemporaryFolder folder = new TemporaryFolder();
|
||||
|
||||
@Test
|
||||
public void listsGetTheWeightsThatKeepEachEntrysShareOfOneOverItsRarity() throws IOException {
|
||||
Path pack = folder.newFolder("pack").toPath();
|
||||
write(pack, "biomes/plains.json", "{\"name\": \"Plains\", \"rarity\": 2}");
|
||||
write(pack, "biomes/forest.json", "{\"name\": \"Forest\", \"rarity\": 3}");
|
||||
write(pack, "biomes/ocean.json", "{\"name\": \"Ocean\"}");
|
||||
write(pack, "regions/temperate.json", """
|
||||
{
|
||||
"name": "Temperate",
|
||||
"rarity": 4,
|
||||
"landBiomes": ["plains", "forest", "gone"],
|
||||
"seaBiomes": ["ocean"]
|
||||
}
|
||||
""");
|
||||
|
||||
PackWeightConverter.Result result = PackWeightConverter.convert(pack, false);
|
||||
|
||||
assertEquals("""
|
||||
{
|
||||
"name": "Temperate",
|
||||
"landBiomes": [
|
||||
{"biome": "plains", "weight": 3},
|
||||
{"biome": "forest", "weight": 2},
|
||||
{"biome": "gone", "weight": 1}
|
||||
],
|
||||
"seaBiomes": [
|
||||
{"biome": "ocean", "weight": 1}
|
||||
]
|
||||
}
|
||||
""", read(pack, "regions/temperate.json"));
|
||||
assertEquals(List.of("biomes/forest.json", "biomes/plains.json", "regions/temperate.json"), result.changedFiles());
|
||||
assertEquals("{\"name\": \"Plains\"}", read(pack, "biomes/plains.json"));
|
||||
assertEquals(1, result.warnings().size());
|
||||
assertTrue(result.warnings().getFirst().contains("'gone'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void theDimensionsRegionsAreConvertedLikeAnyList() throws IOException {
|
||||
Path pack = folder.newFolder("pack").toPath();
|
||||
write(pack, "regions/hot.json", "{\"rarity\": 3}");
|
||||
write(pack, "regions/mushroom.json", "{\"rarity\": 15}");
|
||||
write(pack, "regions/swamp.json", "{\"rarity\": 2}");
|
||||
write(pack, "regions/terralost.json", "{\"rarity\": 5}");
|
||||
write(pack, "dimensions/overworld.json", "{\"regions\": [\"hot\", \"mushroom\", \"swamp\", \"terralost\"]}");
|
||||
|
||||
PackWeightConverter.convert(pack, false);
|
||||
|
||||
assertEquals(List.of(10, 2, 15, 6), weightsOf(pack, "dimensions/overworld.json", "regions"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aListThatNeedsAWeightAboveTheMaximumStopsTheConversion() throws IOException {
|
||||
Path pack = folder.newFolder("pack").toPath();
|
||||
write(pack, "biomes/a.json", "{\"rarity\": 512}");
|
||||
write(pack, "biomes/b.json", "{\"rarity\": 511}");
|
||||
write(pack, "biomes/c.json", "{\"rarity\": 509}");
|
||||
write(pack, "regions/wide.json", "{\"landBiomes\": [\"a\", \"b\", \"c\"]}");
|
||||
|
||||
PackWeightConverter.ConversionException refusal =
|
||||
assertThrows(PackWeightConverter.ConversionException.class, () -> PackWeightConverter.convert(pack, false));
|
||||
|
||||
assertTrue(refusal.getMessage(), refusal.getMessage().startsWith("regions/wide.json"));
|
||||
assertTrue(refusal.getMessage(), refusal.getMessage().contains("above the maximum of " + Weighted.MAX_WEIGHT));
|
||||
assertEquals("{\"landBiomes\": [\"a\", \"b\", \"c\"]}", read(pack, "regions/wide.json"));
|
||||
assertEquals("{\"rarity\": 512}", read(pack, "biomes/a.json"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void childrenKeepTheirPicksThroughHalfSlotsWithTheParentListedAmongThem() throws IOException {
|
||||
List<List<Integer>> scenarios = List.of(List.of(1, 1, 3, 5, 2), List.of(2, 7, 2, 2, 6, 1), List.of(4, 2), List.of(3, 1), List.of(1, 1, 1));
|
||||
for (List<Integer> rarities : scenarios) {
|
||||
Path pack = folder.newFolder().toPath();
|
||||
List<String> childKeys = new ArrayList<>();
|
||||
for (int child = 1; child < rarities.size(); child++) {
|
||||
write(pack, "biomes/child" + child + ".json", "{\"rarity\": " + rarities.get(child) + "}");
|
||||
childKeys.add("\"child" + child + "\"");
|
||||
}
|
||||
write(pack, "biomes/root.json", "{\"rarity\": " + rarities.getFirst() + ", \"children\": [" + String.join(", ", childKeys) + "]}");
|
||||
|
||||
PackWeightConverter.convert(pack, false);
|
||||
|
||||
List<Weighted<String>> converted = entriesOf(pack, "biomes/root.json", "children", "biome");
|
||||
List<String> oldSlots = oldSlots(rarities);
|
||||
for (int step = 0; step <= 1000; step++) {
|
||||
double noise = step / 1000D;
|
||||
String oldPick = oldSlots.get((int) Math.round(noise * (oldSlots.size() - 1)));
|
||||
assertEquals("rarities " + rarities + " noise " + noise, oldPick, Weighted.pick(converted, noise, Weighted.Edge.LATER));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aParentWithoutLoadedChildrenListsItselfOnce() throws IOException {
|
||||
Path pack = folder.newFolder("pack").toPath();
|
||||
write(pack, "biomes/yellow.json", "{\"rarity\": 1, \"children\": [\"dark\"]}");
|
||||
|
||||
PackWeightConverter.Result result = PackWeightConverter.convert(pack, false);
|
||||
|
||||
assertEquals(List.of(new Weighted<>("yellow", 1)), entriesOf(pack, "biomes/yellow.json", "children", "biome"));
|
||||
assertTrue(result.warnings().getFirst().contains("'dark'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void carvingChildrenFollowTheRarityOfTheirEntrysBiome() throws IOException {
|
||||
Path pack = folder.newFolder("pack").toPath();
|
||||
write(pack, "biomes/deep.json", "{\"rarity\": 1}");
|
||||
write(pack, "biomes/lush.json", "{\"rarity\": 2}");
|
||||
write(pack, "dimensions/overworld.json", """
|
||||
{
|
||||
"carving": [
|
||||
{"id": "deep", "biome": "deep", "children": ["lush", " off ", "ghost"]},
|
||||
{"id": "lush", "biome": "lush"},
|
||||
{"id": "off", "biome": "lush", "enabled": false},
|
||||
{"id": "ghost", "biome": "missing"}
|
||||
]
|
||||
}
|
||||
""");
|
||||
|
||||
PackWeightConverter.Result result = PackWeightConverter.convert(pack, false);
|
||||
|
||||
JsonObject dimension = JsonParser.parseString(read(pack, "dimensions/overworld.json")).getAsJsonObject();
|
||||
JsonObject deep = dimension.getAsJsonArray("carving").get(0).getAsJsonObject();
|
||||
assertEquals(List.of(new Weighted<>("deep", 1), new Weighted<>("lush", 2), new Weighted<>("deep", 1)), entriesOf(deep.getAsJsonArray("children"), "id"));
|
||||
assertEquals(2, result.warnings().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void commentsTrailingCommasAndFormattingStayAndRarityGoesWhereverItIs() throws IOException {
|
||||
Path pack = folder.newFolder("pack").toPath();
|
||||
write(pack, "biomes/b.json", "{\"name\": \"B\"}");
|
||||
write(pack, "regions/r.json", "{\n // the region\n \"name\": \"R\", /* inline */\n \"landBiomes\": [\"b\",],\n \"rarity\": 7\n}\n");
|
||||
|
||||
PackWeightConverter.convert(pack, false);
|
||||
|
||||
assertEquals("{\n // the region\n \"name\": \"R\", /* inline */\n \"landBiomes\": [\n {\"biome\": \"b\", \"weight\": 1}\n ]\n}\n",
|
||||
read(pack, "regions/r.json"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aDryRunChangesNothingAndAConvertedPackStaysAsItIs() throws IOException {
|
||||
Path pack = folder.newFolder("pack").toPath();
|
||||
write(pack, "biomes/b.json", "{\"rarity\": 2}");
|
||||
write(pack, "regions/r.json", "{\"landBiomes\": [\"b\"]}");
|
||||
|
||||
PackWeightConverter.Result dry = PackWeightConverter.convert(pack, true);
|
||||
assertEquals(2, dry.changedFiles().size());
|
||||
assertEquals("{\"rarity\": 2}", read(pack, "biomes/b.json"));
|
||||
|
||||
PackWeightConverter.convert(pack, false);
|
||||
assertTrue(PackWeightConverter.convert(pack, false).changedFiles().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void aPackWithSomeListsConvertedAndSomeNotIsRefused() throws IOException {
|
||||
Path pack = folder.newFolder("pack").toPath();
|
||||
write(pack, "biomes/b.json", "{}");
|
||||
write(pack, "regions/done.json", "{\"landBiomes\": [{\"biome\": \"b\", \"weight\": 1}]}");
|
||||
write(pack, "regions/todo.json", "{\"landBiomes\": [\"b\"]}");
|
||||
|
||||
assertThrows(PackWeightConverter.ConversionException.class, () -> PackWeightConverter.convert(pack, false));
|
||||
assertEquals("{\"landBiomes\": [\"b\"]}", read(pack, "regions/todo.json"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void theFixturePacksAreAlreadyWhatTheConverterWouldWrite() throws IOException, URISyntaxException {
|
||||
for (String fixture : FIXTURE_PACKS) {
|
||||
Path copy = folder.newFolder().toPath();
|
||||
copyTree(Path.of(getClass().getResource(FIXTURES + fixture).toURI()), copy);
|
||||
|
||||
PackWeightConverter.Result result = PackWeightConverter.convert(copy, true);
|
||||
|
||||
assertEquals(fixture, List.of(), result.changedFiles());
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> oldSlots(List<Integer> rarities) {
|
||||
int most = rarities.stream().mapToInt(Integer::intValue).max().orElse(1) + 1;
|
||||
List<String> options = new ArrayList<>();
|
||||
for (int child = 1; child < rarities.size(); child++) {
|
||||
options.add("child" + child);
|
||||
}
|
||||
options.add("root");
|
||||
List<String> slots = new ArrayList<>();
|
||||
boolean atEnd = false;
|
||||
for (String option : options) {
|
||||
int rarity = option.equals("root") ? rarities.getFirst() : rarities.get(Integer.parseInt(option.substring("child".length())));
|
||||
for (int copy = 0; copy < most - rarity; copy++) {
|
||||
atEnd = !atEnd;
|
||||
if (atEnd) {
|
||||
slots.add(option);
|
||||
} else {
|
||||
slots.addFirst(option);
|
||||
}
|
||||
}
|
||||
}
|
||||
return slots;
|
||||
}
|
||||
|
||||
private static List<Integer> weightsOf(Path pack, String file, String list) throws IOException {
|
||||
return entriesOf(pack, file, list, "region").stream().map(Weighted::weight).toList();
|
||||
}
|
||||
|
||||
private static List<Weighted<String>> entriesOf(Path pack, String file, String list, String field) throws IOException {
|
||||
JsonObject json = JsonParser.parseString(read(pack, file)).getAsJsonObject();
|
||||
return entriesOf(json.getAsJsonArray(list), field);
|
||||
}
|
||||
|
||||
private static List<Weighted<String>> entriesOf(JsonArray array, String field) {
|
||||
List<Weighted<String>> entries = new ArrayList<>();
|
||||
for (JsonElement element : array) {
|
||||
JsonObject entry = element.getAsJsonObject();
|
||||
entries.add(new Weighted<>(entry.get(field).getAsString(), entry.get("weight").getAsInt()));
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
private static void write(Path pack, String file, String content) throws IOException {
|
||||
Path target = pack.resolve(file);
|
||||
Files.createDirectories(target.getParent());
|
||||
Files.writeString(target, content);
|
||||
}
|
||||
|
||||
private static String read(Path pack, String file) throws IOException {
|
||||
return Files.readString(pack.resolve(file));
|
||||
}
|
||||
|
||||
private static void copyTree(Path from, Path to) throws IOException {
|
||||
try (Stream<Path> walk = Files.walk(from)) {
|
||||
for (Path source : walk.filter(Files::isRegularFile).toList()) {
|
||||
Path target = to.resolve(from.relativize(source).toString());
|
||||
Files.createDirectories(target.getParent());
|
||||
Files.copy(source, target);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user