Validate caves and leftover cave profiles in packs

Unknown cave keys and values outside their bounds block the pack, a leftover caveProfile warns
This commit is contained in:
piexel committed 2026-11-14 21:02:36 +01:00
1 parent f8041b22ec
commit 71cac65f91
5 files changed
+344 -44

No files matched your search

@@ -20,69 +20,85 @@ package art.arcane.iris.generation.cave;
import art.arcane.iris.pack.schema.annotation.MaxNumber;
import art.arcane.iris.pack.schema.annotation.MinNumber;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* The numbers a cave writes outside what their keys allow, read from the {@link MinNumber} and {@link MaxNumber} of
* each key. A {@link CaveValue} is not a plain number, so the schema cannot bound its ends: this does.
* The numbers a cave file writes outside what their keys allow, read from the {@link MinNumber} and {@link MaxNumber} of
* each key and reported by their place in the file. A {@link CaveValue} is not a plain number, so the schema cannot
* bound its ends: this does. It reads the file as written, so a style that names a snippet needs no resolving.
*/
public final class CaveBounds {
private static final String CAVE_PACKAGE = IrisCave.class.getPackageName();
private static final String MIN = "min";
private static final String MAX = "max";
private static final String COVERAGE_SHARE = "share";
private CaveBounds() {
}
/** Each value of the cave outside the numbers its key allows, such as {@code fade is 200; it must be at most 128}. */
public static List<String> valuesOutOfBounds(IrisCave cave) {
/** Each number of the cave file outside what its key allows, such as {@code fade is 200; it must be at most 128}. */
public static List<String> valuesOutOfBounds(JsonObject cave) {
List<String> problems = new ArrayList<>();
collect(cave, "", problems);
collect(IrisCave.class, cave, "", problems);
return problems;
}
private static void collect(Object holder, String path, List<String> problems) {
for (Field field : holder.getClass().getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
continue;
}
Object value = valueOf(field, holder);
if (value == null) {
continue;
}
String fieldPath = path.isEmpty() ? field.getName() : path + "." + field.getName();
if (value instanceof CaveValue caveValue) {
requireWithin(field, caveValue, fieldPath, problems);
} else if (value instanceof Number number) {
requireWithin(field, number.doubleValue(), fieldPath, problems);
} else if (isCaveSetting(value)) {
collect(value, fieldPath, problems);
private static void collect(Class<?> type, JsonObject written, String path, List<String> problems) {
for (Map.Entry<String, JsonElement> member : written.entrySet()) {
Field field = declaredField(type, member.getKey());
if (field != null) {
collectMember(field, member.getValue(), path.isEmpty() ? member.getKey() : path + "." + member.getKey(), problems);
}
}
}
private static boolean isCaveSetting(Object value) {
return value.getClass().getPackageName().equals(CAVE_PACKAGE) && !(value instanceof IrisCave);
}
private static Object valueOf(Field field, Object holder) {
try {
field.setAccessible(true);
return field.get(holder);
} catch (ReflectiveOperationException | RuntimeException failure) {
throw new IllegalStateException("Cannot read " + holder.getClass().getSimpleName() + "." + field.getName(), failure);
private static void collectMember(Field field, JsonElement value, String path, List<String> problems) {
Class<?> type = field.getType();
if (type == CaveValue.class) {
collectValue(field, value, path, problems);
} else if (type == CaveTunnelCoverage.class && value.isJsonPrimitive()) {
collectValue(declaredField(CaveTunnelCoverage.class, COVERAGE_SHARE), value, path + "." + COVERAGE_SHARE, problems);
} else if (value.isJsonObject() && type.getPackageName().equals(CAVE_PACKAGE)) {
collect(type, value.getAsJsonObject(), path, problems);
} else if (isNumber(value)) {
requireWithin(field, value.getAsDouble(), path, problems);
}
}
private static void requireWithin(Field field, CaveValue value, String path, List<String> problems) {
if (!value.varies()) {
requireWithin(field, value.min(), path, problems);
private static void collectValue(Field field, JsonElement value, String path, List<String> problems) {
if (isNumber(value)) {
requireWithin(field, value.getAsDouble(), path, problems);
return;
}
requireWithin(field, value.min(), path + ".min", problems);
requireWithin(field, value.max(), path + ".max", problems);
if (!value.isJsonObject() || !isNumber(value.getAsJsonObject().get(MIN)) || !isNumber(value.getAsJsonObject().get(MAX))) {
return;
}
double min = value.getAsJsonObject().get(MIN).getAsDouble();
double max = value.getAsJsonObject().get(MAX).getAsDouble();
if (min == max) {
requireWithin(field, min, path, problems);
return;
}
requireWithin(field, min, path + "." + MIN, problems);
requireWithin(field, max, path + "." + MAX, problems);
}
private static boolean isNumber(JsonElement element) {
return element != null && element.isJsonPrimitive() && element.getAsJsonPrimitive().isNumber();
}
private static Field declaredField(Class<?> type, String name) {
try {
return type.getDeclaredField(name);
} catch (NoSuchFieldException unknown) {
return null;
}
}
private static void requireWithin(Field field, double value, String path, List<String> problems) {
@@ -0,0 +1,151 @@
/*
* Iris is a World Generator for Minecraft Bukkit Servers
* Copyright (c) 2022 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.pack;
import art.arcane.iris.generation.cave.CaveBounds;
import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Checks a pack's caves: a leftover {@code caveProfile}, which carves nothing any more, the caves that dimensions,
* regions and biomes list under {@code caves} against the files of the {@code caves/} folder, and the numbers of each
* cave file against what their keys allow.
*/
final class PackCaveValidator {
static final String CAVES_FOLDER = "caves";
static final String CAVES_KEY = "caves";
static final String REMOVED_PROFILE_KEY = "caveProfile";
static final String REMOVED_PROFILE_SNIPPET_FOLDER = "snippet/cave-profile";
private static final String REMOVED_PROFILE_ADVICE = "was removed and carves no caves; list caves under \"" + CAVES_KEY + "\" instead";
record Validation(List<String> errors, List<String> warnings) {
Validation {
errors = List.copyOf(errors);
warnings = List.copyOf(warnings);
}
}
private PackCaveValidator() {
}
static Validation validate(File packFolder) {
List<String> errors = new ArrayList<>();
List<String> warnings = new ArrayList<>();
if (packFolder == null || !packFolder.isDirectory()) {
return new Validation(errors, warnings);
}
File cavesFolder = new File(packFolder, CAVES_FOLDER);
Set<String> caveKeys = validateCaveFiles(cavesFolder, errors);
for (String folderName : PackValidator.STRUCTURE_HOST_FOLDERS) {
validateHosts(packFolder, folderName, caveKeys, errors, warnings);
}
validateRemovedProfileSnippets(packFolder, warnings);
return new Validation(errors, warnings);
}
private static Set<String> validateCaveFiles(File cavesFolder, List<String> errors) {
Set<String> keys = new HashSet<>();
if (!cavesFolder.isDirectory()) {
return keys;
}
List<File> files = PackValidationIo.listJsonRecursive(cavesFolder);
files.sort(Comparator.comparing(File::getPath));
for (File file : files) {
String key = PackValidationIo.deriveKey(cavesFolder, file);
keys.add(key);
validateCaveFile(key, file, errors);
}
return keys;
}
private static void validateCaveFile(String key, File file, List<String> errors) {
try {
var cave = JsonParser.parseString(Files.readString(file.toPath(), StandardCharsets.UTF_8));
if (!cave.isJsonObject()) {
errors.add("Cave '" + key + "' must be a JSON object.");
return;
}
CaveBounds.valuesOutOfBounds(cave.getAsJsonObject()).forEach(problem -> errors.add("Cave '" + key + "' " + problem + "."));
} catch (IOException | JsonParseException unreadable) {
errors.add("Cave '" + key + "' is not valid JSON: " + unreadable.getMessage());
}
}
private static void validateHosts(File packFolder, String folderName, Set<String> caveKeys, List<String> errors, List<String> warnings) {
File hostFolder = new File(packFolder, folderName);
if (!hostFolder.isDirectory()) {
return;
}
List<File> files = PackValidationIo.listJsonRecursive(hostFolder);
files.sort(Comparator.comparing(File::getPath));
String hostType = PackStructurePlacementValidator.structureHostType(folderName);
for (File file : files) {
JSONObject host = PackValidationIo.readJson(file);
if (host == null) {
continue;
}
String hostLabel = hostType + " '" + PackValidationIo.deriveKey(hostFolder, file) + "'";
if (host.has(REMOVED_PROFILE_KEY)) {
warnings.add(hostLabel + " still has " + REMOVED_PROFILE_KEY + ", which " + REMOVED_PROFILE_ADVICE + ".");
}
validateListedCaves(hostLabel, host.optJSONArray(CAVES_KEY), caveKeys, errors);
}
}
private static void validateListedCaves(String host, JSONArray listed, Set<String> caveKeys, List<String> errors) {
if (listed == null) {
return;
}
for (int index = 0; index < listed.length(); index++) {
Object entry = listed.opt(index);
if (!(entry instanceof String key) || key.isBlank()) {
errors.add(host + " " + CAVES_KEY + "[" + index + "] must be the name of a file in " + CAVES_FOLDER + "/.");
continue;
}
if (!caveKeys.contains(key)) {
errors.add(host + " lists the cave '" + key + "', but the pack has no " + CAVES_FOLDER + "/" + key + ".json.");
}
}
}
private static void validateRemovedProfileSnippets(File packFolder, List<String> warnings) {
File snippetFolder = new File(packFolder, REMOVED_PROFILE_SNIPPET_FOLDER);
if (!snippetFolder.isDirectory()) {
return;
}
List<File> files = PackValidationIo.listJsonRecursive(snippetFolder);
files.sort(Comparator.comparing(File::getPath));
for (File file : files) {
warnings.add("Snippet '" + REMOVED_PROFILE_SNIPPET_FOLDER + "/" + PackValidationIo.deriveKey(snippetFolder, file)
+ "' is a " + REMOVED_PROFILE_KEY + ", which " + REMOVED_PROFILE_ADVICE + ".");
}
}
}
@@ -130,7 +130,9 @@ public final class PackValidator {
PackHydrologyValidator.validate(packFolder, dimensionFiles);
addDistinct(blockingErrors, hydrologyValidation.errors());
addDistinct(warnings, hydrologyValidation.warnings());
blockingErrors.addAll(PackCaveProfileValidator.validateLegacyFields(packFolder));
PackCaveValidator.Validation caveValidation = PackCaveValidator.validate(packFolder);
addDistinct(blockingErrors, caveValidation.errors());
addDistinct(warnings, caveValidation.warnings());
addDistinct(blockingErrors, PackTerrain3DValidator.validate(packFolder));
PackLootValidator.LootGraphIssues lootIssues = PackLootValidator.validateLootGraph(packFolder);
addDistinct(blockingErrors, lootIssues.errors());
@@ -5,7 +5,9 @@ import art.arcane.iris.generation.cave.CaveValue;
import art.arcane.iris.generation.cave.IrisCave;
import art.arcane.iris.generation.cave.TestSettings;
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import org.junit.Test;
import java.util.BitSet;
@@ -205,14 +207,25 @@ public class CaveValuesTest {
@Test
public void valuesOutsideTheirBoundsAreReportedByTheirPlaceInTheFile() {
IrisCave cave = TestSettings.of(IrisCave.class, """
{"fade": 200, "tunnel": {"width": {"min": 0, "max": 6}, "coverage": {"share": 2}},
JsonObject cave = JsonParser.parseString("""
{"fade": 200, "tunnel": {"width": {"min": 0, "max": 6}, "coverage": {"share": 2}, "spacing": {"horizontal": 8}},
"cavern": {"pillars": {"flare": 0.5}}}
""");
""").getAsJsonObject();
assertEquals(List.of("tunnel.width.min is 0; it must be at least 1", "tunnel.coverage.share is 2; it must be at most 1",
"cavern.pillars.flare is 0.5; it must be at least 1", "fade is 200; it must be at most 128"), CaveBounds.valuesOutOfBounds(cave));
assertEquals(List.of(), CaveBounds.valuesOutOfBounds(TestSettings.of(IrisCave.class, "{\"tunnel\": {}, \"cavern\": {\"pillars\": {}}}")));
assertEquals(List.of("fade is 200; it must be at most 128", "tunnel.width.min is 0; it must be at least 1",
"tunnel.coverage.share is 2; it must be at most 1", "tunnel.spacing.horizontal is 8; it must be at least 16",
"cavern.pillars.flare is 0.5; it must be at least 1"), CaveBounds.valuesOutOfBounds(cave));
assertEquals(List.of(), CaveBounds.valuesOutOfBounds(JsonParser.parseString("{\"tunnel\": {}, \"cavern\": {\"pillars\": {}}}").getAsJsonObject()));
}
@Test
public void aPlainCoverageIsAShareAndAnEqualRangeIsAPlainNumber() {
assertEquals(List.of("tunnel.coverage.share is 1.5; it must be at most 1"),
CaveBounds.valuesOutOfBounds(JsonParser.parseString("{\"tunnel\": {\"coverage\": 1.5}}").getAsJsonObject()));
assertEquals(List.of("fade is 300; it must be at most 128"),
CaveBounds.valuesOutOfBounds(JsonParser.parseString("{\"fade\": {\"min\": 300, \"max\": 300}}").getAsJsonObject()));
assertEquals(List.of("fade.max is 300; it must be at most 128"),
CaveBounds.valuesOutOfBounds(JsonParser.parseString("{\"fade\": {\"min\": 10, \"max\": 300, \"style\": \"snippet/style/any\"}}").getAsJsonObject()));
}
@Test
@@ -0,0 +1,118 @@
package art.arcane.iris.pack;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class PackCaveValidatorTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void aPackWithoutCavesHasNothingToReport() throws Exception {
File pack = temporaryFolder.newFolder("pack");
write(pack, "dimensions/main.json", "{\"regions\":[\"region\"]}");
PackCaveValidator.Validation validation = PackCaveValidator.validate(pack);
assertTrue(validation.errors().isEmpty());
assertTrue(validation.warnings().isEmpty());
}
@Test
public void everyFileThatStillHasACaveProfileGetsOneWarning() throws Exception {
File pack = temporaryFolder.newFolder("pack");
write(pack, "dimensions/main.json", "{\"caveProfile\":{\"enabled\":true}}");
write(pack, "regions/hot.json", "{\"caveProfile\":{\"enabled\":false}}");
write(pack, "biomes/nested/deep.json", "{\"caveProfile\":{}}");
write(pack, "snippet/cave-profile/old.json", "{\"enabled\":true}");
write(pack, "biomes/fine.json", "{}");
PackCaveValidator.Validation validation = PackCaveValidator.validate(pack);
assertTrue(validation.errors().isEmpty());
assertEquals(validation.warnings().toString(), 4, validation.warnings().size());
assertTrue(validation.warnings().contains("Dimension 'main' still has caveProfile, which was removed and carves no caves; list caves under \"caves\" instead."));
assertTrue(validation.warnings().stream().anyMatch(warning -> warning.startsWith("Region 'hot' still has caveProfile")));
assertTrue(validation.warnings().stream().anyMatch(warning -> warning.startsWith("Biome 'nested/deep' still has caveProfile")));
assertTrue(validation.warnings().stream().anyMatch(warning -> warning.startsWith("Snippet 'snippet/cave-profile/old'")));
assertTrue(validation.warnings().stream().allMatch(warning -> warning.contains("list caves under \"caves\"")));
}
@Test
public void aCaveKeyThatNamesNoFileIsAnErrorWhereverItIsListed() throws Exception {
File pack = temporaryFolder.newFolder("pack");
write(pack, "caves/tunnels.json", "{\"tunnel\":{}}");
write(pack, "caves/deep/halls.json", "{\"cavern\":{}}");
write(pack, "dimensions/main.json", "{\"caves\":[\"tunnels\",\"deep/halls\",\"ghost\"]}");
write(pack, "regions/hot.json", "{\"caves\":[\"missing\"]}");
write(pack, "biomes/b.json", "{\"caves\":[\"tunnels\",\"gone\",7]}");
PackCaveValidator.Validation validation = PackCaveValidator.validate(pack);
assertEquals(validation.errors().toString(), List.of(
"Dimension 'main' lists the cave 'ghost', but the pack has no caves/ghost.json.",
"Region 'hot' lists the cave 'missing', but the pack has no caves/missing.json.",
"Biome 'b' lists the cave 'gone', but the pack has no caves/gone.json.",
"Biome 'b' caves[2] must be the name of a file in caves/."), validation.errors());
}
@Test
public void valuesOutsideTheirBoundsAreErrorsNamingTheCaveAndTheKey() throws Exception {
File pack = temporaryFolder.newFolder("pack");
write(pack, "caves/bad.json", "{\"fade\": 200, \"tunnel\": {\"width\": {\"min\": 0, \"max\": 6, \"style\": \"snippet/style/wobble\"}}}");
write(pack, "caves/good.json", "{\"fade\": 20, \"cavern\": {\"size\": 60, \"pillars\": {\"flare\": 2}}}");
PackCaveValidator.Validation validation = PackCaveValidator.validate(pack);
assertEquals(List.of("Cave 'bad' fade is 200; it must be at most 128.",
"Cave 'bad' tunnel.width.min is 0; it must be at least 1."), validation.errors());
}
@Test
public void aCaveThatIsNotJsonIsAnError() throws Exception {
File pack = temporaryFolder.newFolder("pack");
write(pack, "caves/broken.json", "{\"fade\": ");
PackCaveValidator.Validation validation = PackCaveValidator.validate(pack);
assertEquals(1, validation.errors().size());
assertTrue(validation.errors().getFirst().startsWith("Cave 'broken' is not valid JSON"));
}
@Test
public void theFullValidationBlocksOnAnUnknownCaveAndOnlyWarnsAboutALeftoverProfile() throws Exception {
File pack = temporaryFolder.newFolder("pack");
write(pack, "dimensions/main.json", "{\"regions\":[\"region\"],\"caves\":[\"ghost\"],\"caveProfile\":{\"enabled\":true}}");
write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"]}");
write(pack, "biomes/biome.json", "{\"name\":\"Biome\"}");
PackValidationResult blocked = PackValidator.validate(pack);
assertFalse(blocked.isLoadable());
assertTrue(blocked.getBlockingErrors().toString(), blocked.getBlockingErrors().stream().anyMatch(error -> error.contains("lists the cave 'ghost'")));
assertTrue(blocked.getWarnings().toString(), blocked.getWarnings().stream().anyMatch(warning -> warning.contains("still has caveProfile")));
write(pack, "dimensions/main.json", "{\"regions\":[\"region\"],\"caveProfile\":{\"enabled\":true}}");
PackValidationResult warned = PackValidator.validate(pack);
assertTrue(warned.getBlockingErrors().toString(), warned.getBlockingErrors().stream().noneMatch(error -> error.contains("cave")));
assertTrue(warned.getWarnings().stream().anyMatch(warning -> warning.contains("still has caveProfile")));
}
private void write(File root, String relative, String content) throws Exception {
Path target = new File(root, relative).toPath();
Files.createDirectories(target.getParent());
Files.writeString(target, content, StandardCharsets.UTF_8);
}
}