From ab32568550ea9875cb37c754f5721da4bbddb2e2 Mon Sep 17 00:00:00 2001 From: piexel Date: Fri, 6 Nov 2026 10:07:19 +0100 Subject: [PATCH] Check structure placements and references as typed settings The 800-line JSON placement validator is gone. StructurePlacementValidation checks what the placement types cannot state (one backend, separation below spacing, the height band, the ring radius, placement ids and anonymous grids, editable structures that exist and avoid VACUUM/ENCASE, registered native sources and start pools). StructureReferenceValidation checks the structure, pool, piece and object references of every file, placed or not. Shapes, enum names and bounds are the decoder's. Validators read the platform's registries through ValidationContext.platform(), empty in a build and at datapack bootstrap. The live jigsaw metadata, start-element span and terrain-envelope checks are cut (design call 3.7). Object and matter loaders no longer read the runtime settings outside a runtime pack, so a pack validates without a platform. A number option written as text now names its path: "structures[0].terrain.lobeStrength must be a number". --- .../loader/MatterObjectResourceLoader.java | 5 +- .../core/loader/ObjectResourceLoader.java | 5 +- .../core/modules/IrisPlatformRegistryIds.java | 104 +++ .../core/modules/IrisValidationContext.java | 25 +- .../core/modules/ModuleSettingsDecoder.java | 39 +- .../iris/core/modules/NonNumericOptions.java | 141 +++ .../iris/core/pack/ModulePackValidation.java | 26 +- .../core/pack/PackObjectSurfaceValidator.java | 49 +- .../pack/PackStructurePlacementValidator.java | 844 ------------------ .../arcane/iris/core/pack/PackValidator.java | 7 +- .../StructurePlacementValidation.java | 245 +++++ .../StructureReferenceValidation.java | 158 ++++ .../structure/StructureValidator.java | 16 +- .../pack/PackValidatorStructureGraphTest.java | 720 ++++----------- ...kValidatorStructureTerrainBackendTest.java | 83 +- .../service/StudioSVCProjectSafetyTest.java | 10 +- .../iris/engine/loot/LootValidatorTest.java | 7 + 17 files changed, 984 insertions(+), 1500 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/core/modules/IrisPlatformRegistryIds.java create mode 100644 core/src/main/java/art/arcane/iris/core/modules/NonNumericOptions.java delete mode 100644 core/src/main/java/art/arcane/iris/core/pack/PackStructurePlacementValidator.java create mode 100644 core/src/main/java/art/arcane/iris/engine/framework/structure/StructurePlacementValidation.java create mode 100644 core/src/main/java/art/arcane/iris/engine/framework/structure/StructureReferenceValidation.java diff --git a/core/src/main/java/art/arcane/iris/core/loader/MatterObjectResourceLoader.java b/core/src/main/java/art/arcane/iris/core/loader/MatterObjectResourceLoader.java index 6bddf1c40..84c7951f2 100644 --- a/core/src/main/java/art/arcane/iris/core/loader/MatterObjectResourceLoader.java +++ b/core/src/main/java/art/arcane/iris/core/loader/MatterObjectResourceLoader.java @@ -33,7 +33,10 @@ import java.util.HashSet; public class MatterObjectResourceLoader extends ResourceLoader { public MatterObjectResourceLoader(File root, IrisData idm, String folderName, String resourceTypeName, Options options) { super(root, idm, folderName, resourceTypeName, IrisMatterObject.class, options); - loadCache = new KCache<>(this::loadRaw, IrisSettings.get().getPerformance().getObjectLoaderCacheSize()); + int cacheSize = options.registerPreservation() + ? IrisSettings.get().getPerformance().getObjectLoaderCacheSize() + : options.cacheSize(); + loadCache = new KCache<>(this::loadRaw, cacheSize); } public boolean supportsSchemas() { diff --git a/core/src/main/java/art/arcane/iris/core/loader/ObjectResourceLoader.java b/core/src/main/java/art/arcane/iris/core/loader/ObjectResourceLoader.java index d5570a0ae..8e660dca5 100644 --- a/core/src/main/java/art/arcane/iris/core/loader/ObjectResourceLoader.java +++ b/core/src/main/java/art/arcane/iris/core/loader/ObjectResourceLoader.java @@ -33,7 +33,10 @@ import java.util.HashSet; public class ObjectResourceLoader extends ResourceLoader { public ObjectResourceLoader(File root, IrisData idm, String folderName, String resourceTypeName, Options options) { super(root, idm, folderName, resourceTypeName, IrisObject.class, options); - loadCache = new KCache<>(this::loadRaw, IrisSettings.get().getPerformance().getObjectLoaderCacheSize()); + int cacheSize = options.registerPreservation() + ? IrisSettings.get().getPerformance().getObjectLoaderCacheSize() + : options.cacheSize(); + loadCache = new KCache<>(this::loadRaw, cacheSize); } public boolean supportsSchemas() { diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisPlatformRegistryIds.java b/core/src/main/java/art/arcane/iris/core/modules/IrisPlatformRegistryIds.java new file mode 100644 index 000000000..0bee1d1fc --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisPlatformRegistryIds.java @@ -0,0 +1,104 @@ +/* + * 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 . + */ + +package art.arcane.iris.core.modules; + +import art.arcane.iris.spi.IrisPlatform; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformStructureHooks; +import com.volmit.config.Reference; +import com.volmit.resource.PlatformRegistries; +import com.volmit.resource.ResourceId; + +import java.util.EnumMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; + +/** + * The registries of the platform Iris runs on, as validators read them: the same lists studio completes options from. + * Each registry is read once, when a validator first asks for it. + */ +final class IrisPlatformRegistryIds implements PlatformRegistries { + private static final String DEFAULT_NAMESPACE = "minecraft:"; + + private final IrisPlatform platform; + private final Map> idsByRegistry = new EnumMap<>(Reference.class); + + private IrisPlatformRegistryIds(IrisPlatform platform) { + this.platform = platform; + } + + /** The bound platform's registries; empty when no platform is bound, such as in a build. */ + static Optional ofBoundPlatform() { + return IrisPlatforms.isBound() ? Optional.of(new IrisPlatformRegistryIds(IrisPlatforms.get())) : Optional.empty(); + } + + @Override + public synchronized Set ids(Reference registry) { + return idsByRegistry.computeIfAbsent(registry, this::read); + } + + private Set read(Reference registry) { + return switch (registry) { + case BLOCK -> idsOf(platform.registries().blockTypeKeys()); + case ITEM -> idsOf(platform.registries().itemKeys()); + case ENTITY -> idsOf(platform.registries().entityKeys()); + case STRUCTURE -> idsOf(platform.registries().structureKeys()); + case STRUCTURE_SET -> idsOf(structureHook(PlatformStructureHooks::structureSetKeys)); + case TEMPLATE_POOL -> idsOf(structureHook(PlatformStructureHooks::templatePoolKeys)); + case POTION_EFFECT -> idsOf(platform.registries().potionEffectKeys()); + case ENCHANTMENT -> idsOf(platform.registries().enchantmentKeys()); + case LOOT_TABLE -> idsOf(platform.registries().lootTableKeys()); + case STRUCTURE_PREFIX, SPECIAL_ENTITY, NOISE_STYLE -> Set.of(); + }; + } + + private List structureHook(Function> keys) { + PlatformStructureHooks hooks = platform.structureHooks(); + return hooks == null ? List.of() : keys.apply(hooks); + } + + private static Set idsOf(List keys) { + if (keys == null) { + return Set.of(); + } + Set ids = new LinkedHashSet<>(); + for (String key : keys) { + parsedId(key).ifPresent(ids::add); + } + return Set.copyOf(ids); + } + + /** {@code key} as an id, {@code minecraft:} when it names no namespace; empty for a key that is no valid id. */ + private static Optional parsedId(String key) { + if (key == null || key.isBlank()) { + return Optional.empty(); + } + String normalized = key.trim().toLowerCase(Locale.ROOT); + try { + return Optional.of(ResourceId.parse(normalized.indexOf(':') >= 0 ? normalized : DEFAULT_NAMESPACE + normalized)); + } catch (IllegalArgumentException invalid) { + return Optional.empty(); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/IrisValidationContext.java b/core/src/main/java/art/arcane/iris/core/modules/IrisValidationContext.java index f4e3815aa..455064e89 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/IrisValidationContext.java +++ b/core/src/main/java/art/arcane/iris/core/modules/IrisValidationContext.java @@ -21,12 +21,14 @@ package art.arcane.iris.core.modules; import art.arcane.iris.core.loader.IrisData; import com.volmit.config.PackSettings; import com.volmit.resource.PackResources; +import com.volmit.resource.PlatformRegistries; import com.volmit.validation.Problem; import com.volmit.validation.ValidationContext; import java.util.ArrayList; import java.util.List; import java.util.Objects; +import java.util.Optional; /** * What one module validator sees of a pack Iris validates: the pack's resources and its settings as Iris loads them @@ -36,16 +38,28 @@ import java.util.Objects; public final class IrisValidationContext implements ValidationContext { private final IrisData data; private final PackSettings settings; + private final Optional platform; private final List problems = new ArrayList<>(); - private IrisValidationContext(IrisData data) { + private IrisValidationContext(IrisData data, Optional platform) { this.data = data; this.settings = new PackDeclaredSettings(data); + this.platform = platform; } - /** A context for one validator run over the pack {@code data} holds. */ + /** A context for one validator run over the pack {@code data} holds, without the platform's registries. */ public static IrisValidationContext forPack(IrisData data) { - return new IrisValidationContext(Objects.requireNonNull(data, "data")); + return forPack(data, Optional.empty()); + } + + /** A context for one validator run over the pack {@code data} holds, seeing {@code platform}'s registries. */ + public static IrisValidationContext forPack(IrisData data, Optional platform) { + return new IrisValidationContext(Objects.requireNonNull(data, "data"), Objects.requireNonNull(platform, "platform")); + } + + /** The registries of the platform Iris is bound to, read on first use; empty when none is bound, such as in a build. */ + public static Optional boundPlatformRegistries() { + return IrisPlatformRegistryIds.ofBoundPlatform(); } /** Iris's own view of {@code context}, which Iris hands to every validator it runs. */ @@ -71,6 +85,11 @@ public final class IrisValidationContext implements ValidationContext { return settings; } + @Override + public Optional platform() { + return platform; + } + @Override public void report(Problem problem) { problems.add(Objects.requireNonNull(problem, "problem")); diff --git a/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java index 68338456b..33c438ed2 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java +++ b/core/src/main/java/art/arcane/iris/core/modules/ModuleSettingsDecoder.java @@ -27,6 +27,7 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; @@ -56,6 +57,7 @@ import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Supplier; +import java.util.function.UnaryOperator; /** * Reads the module settings a dimension, region or biome declares: each settings feature of the pack at @@ -146,7 +148,7 @@ public final class ModuleSettingsDecoder { * @throws RuntimeException when the JSON does not decode into {@code type} */ public T decodeResource(Class type, String json) { - T decoded = gson.fromJson(json, type); + T decoded = fromJsonNamingWrongKinds(json, type, path -> path); if (decoded == null) { throw new JsonParseException("the file holds null"); } @@ -179,7 +181,7 @@ public final class ModuleSettingsDecoder { try { requireShape(feature, value); String json = settingsJson(feature, value); - IrisFeature decoded = gson.fromJson(json, feature.type()); + IrisFeature decoded = fromJsonNamingWrongKinds(json, feature.type(), path -> writtenPath(feature, path)); if (decoded == null) { throw new JsonParseException("the value is null"); } @@ -191,6 +193,39 @@ public final class ModuleSettingsDecoder { } } + /** + * Reads {@code json} into {@code type}; a number option written as something else fails naming its path, which + * {@code writtenPath} turns from the path inside {@code json} into the path the pack wrote. + */ + private T fromJsonNamingWrongKinds(String json, Class type, UnaryOperator writtenPath) { + try { + return gson.fromJson(json, type); + } catch (NumberFormatException notANumber) { + throw namingTheOption(json, type, writtenPath, notANumber); + } catch (JsonSyntaxException malformed) { + if (malformed.getCause() instanceof NumberFormatException notANumber) { + throw namingTheOption(json, type, writtenPath, notANumber); + } + throw malformed; + } + } + + private static RuntimeException namingTheOption(String json, Class type, UnaryOperator writtenPath, + NumberFormatException failure) { + return NonNumericOptions.first(type, JsonParser.parseString(json)) + .map(path -> new JsonParseException(writtenPath.apply(path) + " must be a number", failure)) + .orElse(failure); + } + + /** The path the pack wrote for {@code insideSettings}, a path inside the settings JSON the decoder reads. */ + private static String writtenPath(FeatureDescriptor feature, String insideSettings) { + if (feature.root().isEmpty()) { + return feature.key() + "." + insideSettings; + } + String root = feature.root().get(); + return insideSettings.startsWith(root) ? feature.key() + insideSettings.substring(root.length()) : insideSettings; + } + /** Checks the bounds of the options the pack wrote; a snippet reference's file is not checked. */ private static void requireDeclaredBounds(FeatureDescriptor feature, IrisFeature decoded, JsonElement written) { if (!written.isJsonObject()) { diff --git a/core/src/main/java/art/arcane/iris/core/modules/NonNumericOptions.java b/core/src/main/java/art/arcane/iris/core/modules/NonNumericOptions.java new file mode 100644 index 000000000..883ebc103 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/NonNumericOptions.java @@ -0,0 +1,141 @@ +/* + * 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.modules; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.annotations.SerializedName; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +/** + * Finds the option a pack wrote as something other than a number although its type holds one, so a failed decode can + * name it: Gson reports only the text it could not parse. + */ +final class NonNumericOptions { + private static final List LIBRARY_PACKAGES = List.of("java.", "javax.", "com.google.gson."); + + private NonNumericOptions() { + } + + /** The path of the first number option of {@code type} that {@code written} holds as a non-number, if any. */ + static Optional first(Type type, JsonElement written) { + return find(type, written, ""); + } + + private static Optional find(Type type, JsonElement written, String path) { + Class raw = rawClass(type); + if (raw == null || written == null || written.isJsonNull()) { + return Optional.empty(); + } + if (isNumber(raw)) { + return readsAsNumber(written) ? Optional.empty() : Optional.of(path); + } + if (Collection.class.isAssignableFrom(raw) && written.isJsonArray()) { + return findInItems(itemType(type), written.getAsJsonArray(), path); + } + if (raw.isArray() && written.isJsonArray()) { + return findInItems(raw.getComponentType(), written.getAsJsonArray(), path); + } + if (written.isJsonObject() && readsFields(raw)) { + return findInOptions(raw, written.getAsJsonObject(), path); + } + return Optional.empty(); + } + + private static Optional findInItems(Type itemType, JsonArray items, String path) { + for (int index = 0; index < items.size(); index++) { + Optional found = find(itemType, items.get(index), path + "[" + index + "]"); + if (found.isPresent()) { + return found; + } + } + return Optional.empty(); + } + + private static Optional findInOptions(Class owner, JsonObject options, String path) { + for (Class type = owner; readsFields(type); type = type.getSuperclass()) { + for (Field field : type.getDeclaredFields()) { + if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) { + continue; + } + String name = memberName(field); + Optional found = find(field.getGenericType(), options.get(name), path.isEmpty() ? name : path + "." + name); + if (found.isPresent()) { + return found; + } + } + } + return Optional.empty(); + } + + /** Whether Gson reads {@code written} as a number: a number, or a string that spells one. */ + private static boolean readsAsNumber(JsonElement written) { + if (!written.isJsonPrimitive()) { + return false; + } + if (written.getAsJsonPrimitive().isNumber()) { + return true; + } + try { + Double.parseDouble(written.getAsString()); + return true; + } catch (NumberFormatException notANumber) { + return false; + } + } + + private static boolean isNumber(Class type) { + return Number.class.isAssignableFrom(type) + || (type.isPrimitive() && type != boolean.class && type != char.class && type != void.class); + } + + private static Type itemType(Type collection) { + return collection instanceof ParameterizedType parameterized && parameterized.getActualTypeArguments().length == 1 + ? parameterized.getActualTypeArguments()[0] + : Object.class; + } + + private static Class rawClass(Type type) { + if (type instanceof Class raw) { + return raw; + } + return type instanceof ParameterizedType parameterized && parameterized.getRawType() instanceof Class raw ? raw : null; + } + + private static boolean readsFields(Class type) { + if (type == null || type == Object.class || type.isPrimitive() || type.isArray() || type.isEnum() || type.isInterface()) { + return false; + } + String name = type.getName(); + return LIBRARY_PACKAGES.stream().noneMatch(name::startsWith); + } + + private static String memberName(Field field) { + SerializedName serializedName = field.getAnnotation(SerializedName.class); + return serializedName == null ? field.getName() : serializedName.value(); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/pack/ModulePackValidation.java b/core/src/main/java/art/arcane/iris/core/pack/ModulePackValidation.java index c38f5a037..24d18bbdb 100644 --- a/core/src/main/java/art/arcane/iris/core/pack/ModulePackValidation.java +++ b/core/src/main/java/art/arcane/iris/core/pack/ModulePackValidation.java @@ -23,12 +23,14 @@ import art.arcane.iris.core.modules.IrisValidationContext; import art.arcane.iris.core.modules.PackModulesException; import art.arcane.iris.spi.IrisLogging; import com.volmit.host.ValidatorRegistration; +import com.volmit.resource.PlatformRegistries; import com.volmit.validation.Problem; import com.volmit.validation.Severity; import java.io.File; import java.util.ArrayList; import java.util.List; +import java.util.Optional; /** * Runs the validators of a pack's modules, built-in ones included, on the pack as Iris loads it, opened just for @@ -50,16 +52,17 @@ final class ModulePackValidation { } } - static Findings validate(File packFolder) { + /** @param withPlatformRegistries whether validators see the bound platform's registries ({@link IrisValidationContext#platform()}) */ + static Findings validate(File packFolder, boolean withPlatformRegistries) { IrisData data = IrisData.openValidation(packFolder); try { - return validate(data); + return validate(data, withPlatformRegistries); } finally { data.close(); } } - private static Findings validate(IrisData data) { + private static Findings validate(IrisData data, boolean withPlatformRegistries) { List validators; try { validators = data.getModules().pack().catalog().validators(); @@ -67,23 +70,30 @@ final class ModulePackValidation { return new Findings(List.of(failure.getMessage()), List.of()); } List errors = new ArrayList<>(PackLoadFailures.of(data)); - Findings modules = validate(data, validators); + Findings modules = validate(data, validators, withPlatformRegistries); errors.addAll(modules.errors()); return new Findings(errors, modules.warnings()); } - /** Runs {@code validators} on the pack {@code data} holds, in order. */ + /** Runs {@code validators} on the pack {@code data} holds, in order, without the platform's registries. */ static Findings validate(IrisData data, List validators) { + return validate(data, validators, false); + } + + private static Findings validate(IrisData data, List validators, boolean withPlatformRegistries) { List errors = new ArrayList<>(); List warnings = new ArrayList<>(); + Optional platform = withPlatformRegistries + ? IrisValidationContext.boundPlatformRegistries() + : Optional.empty(); for (ValidatorRegistration validator : validators) { - run(validator, data, errors, warnings); + run(validator, IrisValidationContext.forPack(data, platform), errors, warnings); } return new Findings(errors, warnings); } - private static void run(ValidatorRegistration registration, IrisData data, List errors, List warnings) { - IrisValidationContext context = IrisValidationContext.forPack(data); + private static void run(ValidatorRegistration registration, IrisValidationContext context, List errors, + List warnings) { try { registration.validator().validate(context); } catch (RuntimeException failure) { diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackObjectSurfaceValidator.java b/core/src/main/java/art/arcane/iris/core/pack/PackObjectSurfaceValidator.java index 98684e3d3..cfd59280c 100644 --- a/core/src/main/java/art/arcane/iris/core/pack/PackObjectSurfaceValidator.java +++ b/core/src/main/java/art/arcane/iris/core/pack/PackObjectSurfaceValidator.java @@ -22,10 +22,12 @@ import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONObject; 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.List; -import java.util.Set; final class PackObjectSurfaceValidator { private PackObjectSurfaceValidator() { @@ -45,40 +47,33 @@ final class PackObjectSurfaceValidator { } List resourceFiles = PackValidationIo.listJsonRecursive(resourceFolder); resourceFiles.sort(Comparator.comparing(File::getPath)); - String resourceType = PackStructurePlacementValidator.structureHostType(folderName); + String resourceType = structureHostType(folderName); for (File resourceFile : resourceFiles) { String resourceKey = PackValidationIo.deriveKey(resourceFolder, resourceFile); - PackStructurePlacementValidator.readGraphJson(resourceFile, resourceType, resourceKey, blockingErrors); + requireJsonObject(resourceFile, resourceType, resourceKey, blockingErrors); } } return blockingErrors; } - static List validateStructureGraph(File packFolder) { - return validateStructureGraph(packFolder, true); + private static void requireJsonObject(File file, String resourceType, String resourceKey, List blockingErrors) { + try { + new JSONObject(Files.readString(file.toPath(), StandardCharsets.UTF_8)); + } catch (IOException | RuntimeException unreadable) { + String reason = unreadable.getMessage() == null || unreadable.getMessage().isBlank() + ? unreadable.getClass().getSimpleName() + : unreadable.getMessage(); + blockingErrors.add(resourceType + " '" + resourceKey + "' has invalid JSON: " + reason); + } } - static List validateStructureGraph(File packFolder, boolean validateLiveRegistries) { - List blockingErrors = new ArrayList<>(); - if (packFolder == null || !packFolder.isDirectory()) { - return blockingErrors; - } - - File structuresFolder = new File(packFolder, PackValidator.STRUCTURES_FOLDER); - File poolsFolder = new File(packFolder, PackValidator.JIGSAW_POOLS_FOLDER); - File piecesFolder = new File(packFolder, PackValidator.JIGSAW_PIECES_FOLDER); - File objectsFolder = new File(packFolder, PackValidator.OBJECTS_FOLDER); - Set structureKeys = ContentKeyValidator.deriveRegistrantKeysExact(structuresFolder); - Set poolKeys = ContentKeyValidator.deriveRegistrantKeysExact(poolsFolder); - Set pieceKeys = ContentKeyValidator.deriveRegistrantKeysExact(piecesFolder); - Set objectKeys = ContentKeyValidator.deriveObjectKeysExact(objectsFolder); - - PackStructurePlacementValidator.validateStructurePlacements( - packFolder, structureKeys, validateLiveRegistries, blockingErrors); - PackStructurePlacementValidator.validateStructureStartPools(structuresFolder, poolKeys, blockingErrors); - PackStructurePlacementValidator.validateJigsawPools(poolsFolder, poolKeys, pieceKeys, blockingErrors); - PackStructurePlacementValidator.validateJigsawPieces(piecesFolder, poolKeys, objectKeys, blockingErrors); - return blockingErrors; + private static String structureHostType(String folderName) { + return switch (folderName) { + case "dimensions" -> "Dimension"; + case "regions" -> "Region"; + case "biomes" -> "Biome"; + default -> "Resource"; + }; } static List validateObjectSurfaceSupport(File packFolder) { @@ -94,7 +89,7 @@ final class PackObjectSurfaceValidator { } List resourceFiles = PackValidationIo.listJsonRecursive(resourceFolder); resourceFiles.sort(Comparator.comparing(File::getPath)); - String resourceType = PackStructurePlacementValidator.structureHostType(folderName); + String resourceType = structureHostType(folderName); for (File resourceFile : resourceFiles) { JSONObject resource = PackValidationIo.readJson(resourceFile); if (resource == null) { diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackStructurePlacementValidator.java b/core/src/main/java/art/arcane/iris/core/pack/PackStructurePlacementValidator.java deleted file mode 100644 index 801d17f42..000000000 --- a/core/src/main/java/art/arcane/iris/core/pack/PackStructurePlacementValidator.java +++ /dev/null @@ -1,844 +0,0 @@ -/* - * 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 . - */ - -package art.arcane.iris.core.pack; - -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformStructureHooks; -import art.arcane.iris.spi.PlatformStructureHooks.JigsawSourceMetadata; -import art.arcane.volmlib.util.json.JSONArray; -import art.arcane.volmlib.util.json.JSONObject; - -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.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -final class PackStructurePlacementValidator { - private static final Set TERRAIN_ENVELOPE_MODES = Set.of( - "BORE", "FORCE_CARVE", "VACUUM", "ENCASE"); - - private PackStructurePlacementValidator() { - } - - static void validateStructurePlacements(File packFolder, - Set structureKeys, - boolean validateLiveRegistries, - List blockingErrors) { - RegistrySnapshot registries = registrySnapshot(validateLiveRegistries, blockingErrors); - if (registries == null) { - return; - } - Map placementIds = new HashMap<>(); - Map anonymousGridIdentities = new HashMap<>(); - for (String folderName : PackValidator.STRUCTURE_HOST_FOLDERS) { - File resourceFolder = new File(packFolder, folderName); - if (!resourceFolder.isDirectory()) { - continue; - } - List resourceFiles = PackValidationIo.listJsonRecursive(resourceFolder); - resourceFiles.sort(Comparator.comparing(File::getPath)); - String resourceType = structureHostType(folderName); - for (File resourceFile : resourceFiles) { - JSONObject resource = PackValidationIo.readJson(resourceFile); - if (resource == null) { - continue; - } - String resourceKey = PackValidationIo.deriveKey(resourceFolder, resourceFile); - if (PackValidator.DIMENSIONS_FOLDER.equals(folderName)) { - validateImportedStructureAdjustmentEnvelopes( - resourceKey, resource, registries, blockingErrors); - } - Object rawPlacements = resource.opt("structures"); - JSONArray placements = resource.optJSONArray("structures"); - if (placements == null) { - if (resource.has("structures") && rawPlacements != JSONObject.NULL) { - blockingErrors.add(resourceType + " '" + resourceKey + "'.structures must be an array."); - } - continue; - } - for (int placementIndex = 0; placementIndex < placements.length(); placementIndex++) { - JSONObject placement = placements.optJSONObject(placementIndex); - String placementPath = resourceType + " '" + resourceKey + "' structures[" - + placementIndex + "]"; - if (placement == null) { - blockingErrors.add(placementPath + " must be an object."); - continue; - } - validatePlacementConfiguration(placementPath, placement, blockingErrors); - validatePlacementIdentity( - placementPath, placement, placementIds, anonymousGridIdentities, blockingErrors); - JSONArray references = placement.optJSONArray("structures"); - JSONArray nativeStructures = placement.optJSONArray("nativeStructures"); - if (placement.has("structures") && placement.opt("structures") != JSONObject.NULL - && references == null) { - blockingErrors.add(placementPath + ".structures must be an array."); - } - if (placement.has("nativeStructures") && placement.opt("nativeStructures") != JSONObject.NULL - && nativeStructures == null) { - blockingErrors.add(placementPath + ".nativeStructures must be an array."); - } - boolean hasIrisStructures = references != null && references.length() > 0; - boolean hasNativeStructures = nativeStructures != null && nativeStructures.length() > 0; - if (hasIrisStructures == hasNativeStructures) { - blockingErrors.add(placementPath - + " must declare exactly one non-empty backend: structures or nativeStructures."); - continue; - } - if (hasNativeStructures) { - validateNativeStructures( - placementPath, nativeStructures, - registries.structures(), registries.jigsaws(), - registries.pools(), registries.jigsawMetadataResolver(), - registries.hooks(), blockingErrors); - continue; - } - validateEditableStructureTerrain(placementPath, placement, blockingErrors); - Set editableStructureKeys = new HashSet<>(); - for (int referenceIndex = 0; referenceIndex < references.length(); referenceIndex++) { - Object rawReference = references.opt(referenceIndex); - if (!(rawReference instanceof String structureKey) || structureKey.isBlank()) { - blockingErrors.add(placementPath + ".structures[" + referenceIndex - + "] must name a non-blank Iris structure."); - continue; - } - String normalizedStructureKey = structureKey.trim().toLowerCase(Locale.ROOT); - if (!editableStructureKeys.add(normalizedStructureKey)) { - blockingErrors.add(placementPath + ".structures[" + referenceIndex - + "] duplicates Iris structure '" + structureKey + "'."); - continue; - } - if (!structureKeys.contains(structureKey)) { - blockingErrors.add(resourceType + " '" + resourceKey + "' structures[" - + placementIndex + "].structures[" + referenceIndex - + "] references missing structure '" + structureKey + "'."); - } - } - } - } - } - } - - private static RegistrySnapshot registrySnapshot(boolean validateLiveRegistries, - List blockingErrors) { - if (!validateLiveRegistries || !IrisPlatforms.isBound()) { - return new RegistrySnapshot(Set.of(), Set.of(), Set.of(), null, null); - } - try { - PlatformStructureHooks hooks = IrisPlatforms.get().structureHooks(); - if (hooks == null) { - throw new IllegalStateException("The active platform did not provide structure registry hooks"); - } - Set structures = normalizeRegistryKeys( - hooks.structureKeys(), "structure"); - Set jigsaws = normalizeRegistryKeys( - hooks.jigsawStructureKeys(), "jigsaw structure"); - Set pools = normalizeRegistryKeys( - hooks.templatePoolKeys(), "template pool"); - if (structures.isEmpty()) { - throw new IllegalStateException("The active structure registry is empty"); - } - if (jigsaws.isEmpty()) { - throw new IllegalStateException("The active jigsaw structure registry is empty"); - } - if (pools.isEmpty()) { - throw new IllegalStateException("The active template pool registry is empty"); - } - return new RegistrySnapshot( - structures, jigsaws, pools, new JigsawMetadataResolver(hooks), hooks); - } catch (RuntimeException | LinkageError e) { - IrisLogging.reportError("Could not read the live structure registries during pack validation", e); - blockingErrors.add("Could not validate native structure references against the live registries: " - + failureMessage(e) + "."); - return null; - } - } - - private static Set normalizeRegistryKeys(List registered, String registryName) { - if (registered == null) { - throw new IllegalStateException("The active " + registryName + " registry returned null"); - } - Set keys = new HashSet<>(); - for (String key : registered) { - if (key != null && !key.isBlank()) { - keys.add(key.toLowerCase(Locale.ROOT)); - } - } - return Set.copyOf(keys); - } - - private static String failureMessage(Throwable throwable) { - String message = throwable.getMessage(); - return message == null || message.isBlank() ? throwable.getClass().getSimpleName() : message; - } - - private static void validatePlacementConfiguration(String path, JSONObject placement, - List blockingErrors) { - PackJsonFieldChecks.validateOptionalEnum(path, placement, "distribution", - Set.of("RANDOM_SPREAD", "DENSITY", "CONCENTRIC_RINGS"), blockingErrors); - PackJsonFieldChecks.validateOptionalIntegerRange(path, placement, "spacing", 1, 4096, blockingErrors); - PackJsonFieldChecks.validateOptionalIntegerRange( - path, placement, "separation", 0, Integer.MAX_VALUE, blockingErrors); - PackJsonFieldChecks.validateOptionalIntegerRange( - path, placement, "salt", Integer.MIN_VALUE, Integer.MAX_VALUE, blockingErrors); - PackJsonFieldChecks.validateOptionalDoubleRange(path, placement, "density", 0D, 1D, blockingErrors); - PackJsonFieldChecks.validateOptionalIntegerRange( - path, placement, "ringCount", 1, Integer.MAX_VALUE, blockingErrors); - PackJsonFieldChecks.validateOptionalIntegerRange( - path, placement, "ringDistance", 1, Integer.MAX_VALUE, blockingErrors); - PackJsonFieldChecks.validateOptionalIntegerRange( - path, placement, "ringSpread", 1, Integer.MAX_VALUE, blockingErrors); - PackJsonFieldChecks.validateOptionalIntegerRange( - path, placement, "minHeight", Integer.MIN_VALUE, Integer.MAX_VALUE, blockingErrors); - PackJsonFieldChecks.validateOptionalIntegerRange( - path, placement, "maxHeight", Integer.MIN_VALUE, Integer.MAX_VALUE, blockingErrors); - PackJsonFieldChecks.validateOptionalBoolean(path, placement, "underground", blockingErrors); - PackJsonFieldChecks.validateOptionalBoolean(path, placement, "underwater", blockingErrors); - PackJsonFieldChecks.validateOptionalEnum(path, placement, "nativeSuppression", - Set.of("NONE", "REPLACE_SOURCE"), blockingErrors); - - Integer spacing = integerValue(placement, "spacing", 32); - Integer separation = integerValue(placement, "separation", 8); - if (spacing != null && separation != null && separation >= spacing) { - blockingErrors.add(path + ".separation must be smaller than spacing."); - } - Integer minimumHeight = integerValue(placement, "minHeight", -2032); - Integer maximumHeight = integerValue(placement, "maxHeight", 2032); - if (minimumHeight != null && maximumHeight != null && minimumHeight > maximumHeight) { - blockingErrors.add(path + " has an inverted height band: minHeight must not exceed maxHeight."); - } - Integer ringCount = integerValue(placement, "ringCount", 128); - Integer ringDistance = integerValue(placement, "ringDistance", 32); - Integer ringSpread = integerValue(placement, "ringSpread", 3); - if (ringCount != null && ringDistance != null && ringSpread != null - && ringCount > 0 && ringDistance > 0 && ringSpread > 0) { - long ringRadius = (long) Math.ceilDiv(ringCount, ringSpread) * ringDistance; - if (ringRadius > Integer.MAX_VALUE) { - blockingErrors.add(path + " concentric ring radius exceeds the supported chunk coordinate range."); - } - } - - if (placement.has("placementId")) { - Object rawPlacementId = placement.opt("placementId"); - if (!(rawPlacementId instanceof String placementId)) { - blockingErrors.add(path + ".placementId must be a string."); - } else if (!placementId.isEmpty() && placementId.isBlank()) { - blockingErrors.add(path + ".placementId must be omitted or non-blank."); - } else if (!placementId.equals(placementId.trim())) { - blockingErrors.add(path + ".placementId must not contain leading or trailing whitespace."); - } - } - validateStilt(path, placement, blockingErrors); - validateNativeTerrain(path, placement, blockingErrors); - } - - private static void validatePlacementIdentity(String path, JSONObject placement, - Map placementIds, - Map anonymousGridIdentities, - List blockingErrors) { - Object rawPlacementId = placement.opt("placementId"); - if (rawPlacementId instanceof String placementId && !placementId.isBlank()) { - String normalizedId = placementId.trim(); - String existing = placementIds.putIfAbsent(normalizedId, path); - if (existing != null) { - blockingErrors.add(path + ".placementId duplicates '" + normalizedId - + "' already declared by " + existing + "."); - } - return; - } - String gridIdentity = anonymousGridIdentity(placement); - String existing = anonymousGridIdentities.putIfAbsent(gridIdentity, path); - if (existing != null) { - blockingErrors.add(path + " duplicates an anonymous placement grid already declared by " - + existing + "; give distinct placements unique placementId values."); - } - } - - private static String anonymousGridIdentity(JSONObject placement) { - StringBuilder identity = new StringBuilder(); - appendIdentity(identity, placement.optString("distribution", "RANDOM_SPREAD")); - appendIdentity(identity, integerValue(placement, "salt", 165745296)); - appendIdentity(identity, integerValue(placement, "spacing", 32)); - appendIdentity(identity, integerValue(placement, "separation", 8)); - Object rawDensity = placement.has("density") ? placement.opt("density") : 0.02D; - appendIdentity(identity, rawDensity instanceof Number number - ? Double.doubleToLongBits(number.doubleValue()) : rawDensity); - appendIdentity(identity, integerValue(placement, "ringCount", 128)); - appendIdentity(identity, integerValue(placement, "ringDistance", 32)); - appendIdentity(identity, integerValue(placement, "ringSpread", 3)); - appendIdentity(identity, integerValue(placement, "minHeight", -2032)); - appendIdentity(identity, integerValue(placement, "maxHeight", 2032)); - appendIdentity(identity, placement.opt("underground") instanceof Boolean underground && underground); - appendIdentity(identity, placement.opt("underwater") instanceof Boolean underwater && underwater); - JSONArray structures = placement.optJSONArray("structures"); - JSONArray nativeStructures = placement.optJSONArray("nativeStructures"); - if (structures != null && structures.length() > 0) { - appendIdentity(identity, "iris"); - List orderedStructures = new ArrayList<>(structures.length()); - for (int index = 0; index < structures.length(); index++) { - orderedStructures.add(String.valueOf(structures.opt(index))); - } - orderedStructures.sort(String::compareTo); - for (String structure : orderedStructures) { - appendIdentity(identity, structure); - } - } else { - appendIdentity(identity, "native"); - if (nativeStructures != null) { - List orderedSources = new ArrayList<>(nativeStructures.length()); - for (int index = 0; index < nativeStructures.length(); index++) { - JSONObject source = nativeStructures.optJSONObject(index); - String sourceKey = source == null ? "null" : source.optString("structure", ""); - Integer weight = source == null ? null : integerValue(source, "weight", 1); - orderedSources.add(sourceKey.length() + ":" + sourceKey + ":" + weight); - } - orderedSources.sort(String::compareTo); - for (String source : orderedSources) { - appendIdentity(identity, source); - } - } - } - return identity.toString(); - } - - private static void appendIdentity(StringBuilder identity, Object value) { - String text = String.valueOf(value); - identity.append(text.length()).append(':').append(text).append('|'); - } - - private static void validateStilt(String path, JSONObject placement, List blockingErrors) { - if (!placement.has("stilt") || placement.opt("stilt") == JSONObject.NULL) { - return; - } - JSONObject stilt = placement.optJSONObject("stilt"); - if (stilt == null) { - blockingErrors.add(path + ".stilt must be an object."); - return; - } - PackJsonFieldChecks.validateOptionalIntegerRange( - path + ".stilt", stilt, "maxDepth", 1, 4064, blockingErrors); - PackJsonFieldChecks.validateOptionalIntegerRange( - path + ".stilt", stilt, "spacing", 1, 64, blockingErrors); - PackJsonFieldChecks.validateOptionalBoolean( - path + ".stilt", stilt, "supportNonOccluding", blockingErrors); - if (stilt.has("palette") && stilt.opt("palette") != JSONObject.NULL - && stilt.optJSONObject("palette") == null) { - blockingErrors.add(path + ".stilt.palette must be an object."); - } - } - - private static Integer integerValue(JSONObject object, String field, int defaultValue) { - if (!object.has(field)) { - return defaultValue; - } - Object rawValue = object.opt(field); - if (!(rawValue instanceof Number number)) { - return null; - } - double doubleValue = number.doubleValue(); - if (!Double.isFinite(doubleValue) || Math.rint(doubleValue) != doubleValue - || doubleValue < Integer.MIN_VALUE || doubleValue > Integer.MAX_VALUE) { - return null; - } - return number.intValue(); - } - - private static void validateNativeStructures(String placementPath, - JSONArray nativeStructures, - Set registeredStructures, - Set registeredJigsaws, - Set registeredPools, - JigsawMetadataResolver jigsawMetadataResolver, - PlatformStructureHooks hooks, - List blockingErrors) { - Set sourceKeys = new HashSet<>(); - long totalWeight = 0L; - for (int sourceIndex = 0; sourceIndex < nativeStructures.length(); sourceIndex++) { - String sourcePath = placementPath + ".nativeStructures[" + sourceIndex + "]"; - JSONObject source = nativeStructures.optJSONObject(sourceIndex); - if (source == null) { - blockingErrors.add(sourcePath + " must be an object."); - continue; - } - String structureKey = source.optString("structure", "").trim(); - if (!PackValidator.RESOURCE_KEY_PATTERN.matcher(structureKey).matches()) { - blockingErrors.add(sourcePath + ".structure must be a namespaced registry key."); - } else if (!registeredStructures.isEmpty() - && !registeredStructures.contains(structureKey.toLowerCase(Locale.ROOT))) { - blockingErrors.add(sourcePath + ".structure '" + structureKey - + "' is not a registered structure."); - } - if (!structureKey.isEmpty() && !sourceKeys.add(structureKey.toLowerCase(Locale.ROOT))) { - blockingErrors.add(sourcePath + ".structure duplicates native source '" + structureKey + "'."); - } - Integer weight = PackIntegerChecks.integerField(source, "weight", 1, sourcePath, blockingErrors); - PackIntegerChecks.requireMinimum(sourcePath + ".weight", weight, 1, blockingErrors); - if (weight != null && weight > 0) { - totalWeight += weight; - } - String normalizedStructureKey = structureKey.toLowerCase(Locale.ROOT); - boolean registeredJigsaw = registeredJigsaws.contains(normalizedStructureKey); - JSONObject jigsaw = source.optJSONObject("jigsaw"); - if (source.has("jigsaw") && source.opt("jigsaw") != JSONObject.NULL && jigsaw == null) { - blockingErrors.add(sourcePath + ".jigsaw must be an object."); - } else if (jigsaw != null) { - if (!registeredJigsaws.isEmpty() && !registeredJigsaw) { - blockingErrors.add(sourcePath - + ".jigsaw requires a registered jigsaw structure."); - } - validateJigsawAssembly( - sourcePath + ".jigsaw", jigsaw, registeredPools, blockingErrors); - } - JigsawSourceMetadata sourceMetadata = registeredJigsaw - ? resolveJigsawMetadata(sourcePath, normalizedStructureKey, - jigsawMetadataResolver, blockingErrors) - : null; - if (registeredJigsaw && sourceMetadata == null) { - continue; - } - if (registeredJigsaw || jigsaw != null) { - validateReferenceEnvelope( - sourcePath, normalizedStructureKey, jigsaw, - sourceMetadata, hooks, blockingErrors); - } - } - if (totalWeight > Integer.MAX_VALUE) { - blockingErrors.add(placementPath + ".nativeStructures total weight exceeds " - + Integer.MAX_VALUE + "."); - } - } - - private static void validateReferenceEnvelope(String sourcePath, String structureKey, - JSONObject jigsaw, JigsawSourceMetadata sourceMetadata, - PlatformStructureHooks hooks, - List blockingErrors) { - boolean overriddenDistance = jigsaw != null && jigsaw.has("maxDistanceHorizontal"); - Integer maximumDistance = overriddenDistance - ? integerValue(jigsaw, "maxDistanceHorizontal", -1) - : sourceMetadata == null ? null : sourceMetadata.maxDistanceHorizontal(); - if (maximumDistance == null || maximumDistance < 0) { - return; - } - Integer startElementSpan = effectiveStartElementSpan( - sourcePath, structureKey, jigsaw, sourceMetadata, hooks, blockingErrors); - if (startElementSpan == null) { - return; - } - long assemblySpan = Math.max(maximumDistance, startElementSpan); - if (assemblySpan > 128L) { - String distancePath = overriddenDistance - ? ".jigsaw.maxDistanceHorizontal" : " registered jigsaw source max-distance"; - blockingErrors.add(sourcePath + distancePath + " and its actual structure content" - + " (" + startElementSpan + "-block maximum start element and " - + maximumDistance + "-block maximum assembly distance) must not exceed Minecraft's" - + " 128-block (8-chunk) structure reference range."); - } - } - - private static Integer effectiveStartElementSpan(String sourcePath, String structureKey, - JSONObject jigsaw, - JigsawSourceMetadata sourceMetadata, - PlatformStructureHooks hooks, - List blockingErrors) { - int sourceSpan = sourceMetadata == null ? 0 : sourceMetadata.maxStartElementHorizontalSpan(); - if (jigsaw == null || !jigsaw.has("startPool")) { - return sourceSpan; - } - String startPool = jigsaw.optString("startPool", "").trim(); - if (startPool.isEmpty() || hooks == null) { - return sourceSpan; - } - try { - int resolvedSpan = hooks.jigsawStartPoolHorizontalSpan(structureKey, startPool); - if (resolvedSpan < 0) { - throw new IllegalStateException("negative horizontal span " + resolvedSpan); - } - return resolvedSpan; - } catch (RuntimeException | LinkageError error) { - IrisLogging.reportError("Could not resolve the effective native jigsaw start-pool span", error); - blockingErrors.add(sourcePath + ".jigsaw.startPool '" + startPool - + "' could not resolve a bounded live horizontal span: " - + failureMessage(error) + "."); - return null; - } - } - - private static void validateImportedStructureAdjustmentEnvelopes( - String dimensionKey, JSONObject dimension, RegistrySnapshot registries, - List blockingErrors) { - JSONObject policy = dimension.optJSONObject("importedStructures"); - if (policy == null) { - return; - } - JSONArray adjustments = policy.optJSONArray("adjustments"); - if (adjustments == null) { - return; - } - List orderedStructureKeys = new ArrayList<>(registries.structures()); - orderedStructureKeys.sort(String::compareTo); - Map effective = new HashMap<>(); - for (int adjustmentIndex = 0; adjustmentIndex < adjustments.length(); adjustmentIndex++) { - JSONObject adjustment = adjustments.optJSONObject(adjustmentIndex); - if (adjustment == null || adjustment.optJSONObject("terrain") == null) { - continue; - } - JSONArray matches = adjustment.optJSONArray("match"); - if (matches == null || matches.length() == 0) { - continue; - } - String path = "Dimension '" + dimensionKey - + "' importedStructures.adjustments[" + adjustmentIndex + "]"; - for (String structureKey : orderedStructureKeys) { - if (matchesStructure(matches, structureKey)) { - effective.put(structureKey, new EffectiveTerrainAdjustment(path, adjustment)); - } - } - } - for (String structureKey : orderedStructureKeys) { - EffectiveTerrainAdjustment adjustment = effective.get(structureKey); - if (adjustment == null) { - continue; - } - JSONObject terrain = adjustment.adjustment().optJSONObject("terrain"); - if (terrain == null || !TERRAIN_ENVELOPE_MODES.contains( - terrain.optString("mode", "SOURCE").toUpperCase(Locale.ROOT))) { - continue; - } - String sourcePath = adjustment.path() + " matched registered structure '" - + structureKey + "'"; - if (registries.jigsaws().contains(structureKey)) { - JigsawSourceMetadata metadata = resolveJigsawMetadata( - sourcePath, structureKey, - registries.jigsawMetadataResolver(), blockingErrors); - if (metadata == null) { - continue; - } - validateReferenceEnvelope( - sourcePath, structureKey, null, metadata, - registries.hooks(), blockingErrors); - } - } - } - - private static boolean matchesStructure(JSONArray matches, String structureKey) { - for (int matchIndex = 0; matchIndex < matches.length(); matchIndex++) { - Object rawPattern = matches.opt(matchIndex); - if (rawPattern instanceof String pattern - && matchesStructurePattern(pattern, structureKey)) { - return true; - } - } - return false; - } - - private static JigsawSourceMetadata resolveJigsawMetadata( - String sourcePath, String structureKey, - JigsawMetadataResolver resolver, List blockingErrors) { - if (resolver == null) { - return null; - } - MetadataResolution resolution = resolver.resolve(structureKey); - if (resolution.metadata() != null) { - return resolution.metadata(); - } - blockingErrors.add(sourcePath + " could not resolve live metadata for registered jigsaw source '" - + structureKey + "': " + resolution.failure() + "."); - return null; - } - - private static boolean matchesStructurePattern(String pattern, String structureKey) { - String normalizedPattern = pattern == null ? "" : pattern.trim().toLowerCase(Locale.ROOT); - String normalizedKey = structureKey == null ? "" : structureKey.trim().toLowerCase(Locale.ROOT); - if (normalizedPattern.isEmpty() || !normalizedKey.startsWith(normalizedPattern)) { - return false; - } - if (normalizedKey.length() == normalizedPattern.length()) { - return true; - } - char patternEnd = normalizedPattern.charAt(normalizedPattern.length() - 1); - if (patternEnd == ':' || patternEnd == '/' || patternEnd == '_') { - return true; - } - char boundary = normalizedKey.charAt(normalizedPattern.length()); - return boundary == '/' || boundary == '_'; - } - - private static void validateJigsawAssembly(String path, JSONObject assembly, - Set registeredPools, - List blockingErrors) { - PackJsonFieldChecks.validateOptionalResourceKey(path, assembly, "startPool", false, blockingErrors); - String startPool = assembly.optString("startPool", "").trim(); - if (!startPool.isEmpty() && !registeredPools.isEmpty() - && !registeredPools.contains(startPool.toLowerCase(Locale.ROOT))) { - blockingErrors.add(path + ".startPool '" + startPool - + "' is not a registered template pool."); - } - PackJsonFieldChecks.validateOptionalResourceKey(path, assembly, "startJigsawName", true, blockingErrors); - PackJsonFieldChecks.validateOptionalIntegerRange(path, assembly, "maxDepth", 0, 20, blockingErrors); - PackJsonFieldChecks.validateOptionalIntegerRange(path, assembly, "maxDistanceHorizontal", 1, 128, blockingErrors); - PackJsonFieldChecks.validateOptionalIntegerRange(path, assembly, "maxDistanceVertical", 1, 4064, blockingErrors); - PackJsonFieldChecks.validateOptionalIntegerRange( - path, assembly, "dimensionPaddingBottom", 0, Integer.MAX_VALUE, blockingErrors); - PackJsonFieldChecks.validateOptionalIntegerRange( - path, assembly, "dimensionPaddingTop", 0, Integer.MAX_VALUE, blockingErrors); - if (assembly.has("useExpansionHack") - && !(assembly.opt("useExpansionHack") instanceof Boolean)) { - blockingErrors.add(path + ".useExpansionHack must be a boolean."); - } - PackJsonFieldChecks.validateOptionalEnum(path, assembly, "projectStartToHeightmap", - Set.of("SOURCE", "NONE", "WORLD_SURFACE_WG", "WORLD_SURFACE", - "OCEAN_FLOOR_WG", "OCEAN_FLOOR", "MOTION_BLOCKING", - "MOTION_BLOCKING_NO_LEAVES"), blockingErrors); - PackJsonFieldChecks.validateOptionalEnum(path, assembly, "liquidSettings", - Set.of("SOURCE", "IGNORE_WATERLOGGING", "APPLY_WATERLOGGING"), blockingErrors); - } - - static void validateNativeTerrain(String path, JSONObject placement, - List blockingErrors) { - JSONObject terrain = placement.optJSONObject("terrain"); - if (placement.has("terrain") && placement.opt("terrain") != JSONObject.NULL && terrain == null) { - blockingErrors.add(path + ".terrain must be an object."); - return; - } - if (terrain == null) { - return; - } - PackJsonFieldChecks.validateOptionalEnum(path + ".terrain", terrain, "mode", - Set.of("SOURCE", "PRESERVE", "BORE", "FORCE_CARVE", "VACUUM", "ENCASE"), blockingErrors); - PackJsonFieldChecks.validateOptionalEnum(path + ".terrain", terrain, "shape", - Set.of("BOX", "ROUNDED", "ERODED"), blockingErrors); - PackJsonFieldChecks.validateOptionalIntegerRange(path + ".terrain", terrain, - "horizontalPadding", 0, 128, blockingErrors); - PackJsonFieldChecks.validateOptionalIntegerRange(path + ".terrain", terrain, - "ceilingPadding", 0, 128, blockingErrors); - PackJsonFieldChecks.validateOptionalIntegerRange(path + ".terrain", terrain, - "floorPadding", 0, 64, blockingErrors); - PackJsonFieldChecks.validateOptionalDoubleRange(path + ".terrain", terrain, - "erosionStrength", 0D, 1D, blockingErrors); - PackJsonFieldChecks.validateOptionalDoubleRange(path + ".terrain", terrain, - "erosionFrequency", 0.001D, 1D, blockingErrors); - PackJsonFieldChecks.validateOptionalDoubleRange(path + ".terrain", terrain, - "lobeFrequency", 0D, 1D, blockingErrors); - PackJsonFieldChecks.validateOptionalDoubleRange(path + ".terrain", terrain, - "lobeStrength", 0D, 1D, blockingErrors); - if (terrain.has("encasePalette") && terrain.opt("encasePalette") != JSONObject.NULL - && terrain.optJSONObject("encasePalette") == null) { - blockingErrors.add(path + ".terrain.encasePalette must be an object."); - } - } - - private static void validateEditableStructureTerrain( - String path, JSONObject placement, List blockingErrors) { - JSONObject terrain = placement.optJSONObject("terrain"); - if (terrain == null) { - return; - } - String mode = terrain.optString("mode", "SOURCE"); - if ("VACUUM".equals(mode) || "ENCASE".equals(mode)) { - blockingErrors.add(path + ".terrain.mode " + mode - + " cannot target editable Iris structures; use nativeStructures or " - + "importedStructures.adjustments for native terrain preparation."); - } - } - - static void validateStructureStartPools(File structuresFolder, - Set poolKeys, - List blockingErrors) { - if (!structuresFolder.isDirectory()) { - return; - } - List structureFiles = PackValidationIo.listJsonRecursive(structuresFolder); - structureFiles.sort(Comparator.comparing(File::getPath)); - for (File structureFile : structureFiles) { - String structureKey = PackValidationIo.deriveKey(structuresFolder, structureFile); - JSONObject structure = readGraphJson(structureFile, "Structure", structureKey, blockingErrors); - if (structure == null || isLegacyStructureIndex(structureKey, structure)) { - continue; - } - String startPool = structure.optString("startPool", "").trim(); - if (startPool.isEmpty()) { - blockingErrors.add("Structure '" + structureKey + "' does not declare a startPool."); - } else if (!poolKeys.contains(startPool)) { - blockingErrors.add("Structure '" + structureKey + "' references missing start pool '" - + startPool + "'."); - } - } - } - - static void validateJigsawPools(File poolsFolder, - Set poolKeys, - Set pieceKeys, - List blockingErrors) { - if (!poolsFolder.isDirectory()) { - return; - } - List poolFiles = PackValidationIo.listJsonRecursive(poolsFolder); - poolFiles.sort(Comparator.comparing(File::getPath)); - for (File poolFile : poolFiles) { - String poolKey = PackValidationIo.deriveKey(poolsFolder, poolFile); - JSONObject pool = readGraphJson(poolFile, "Jigsaw pool", poolKey, blockingErrors); - if (pool == null) { - continue; - } - JSONArray entries = pool.optJSONArray("pieces"); - if (entries != null) { - for (int entryIndex = 0; entryIndex < entries.length(); entryIndex++) { - JSONObject entry = entries.optJSONObject(entryIndex); - if (entry == null) { - continue; - } - String pieceKey = entry.optString("piece", "").trim(); - if (!pieceKey.isEmpty() && !pieceKeys.contains(pieceKey)) { - blockingErrors.add("Jigsaw pool '" + poolKey + "' pieces[" + entryIndex - + "] references missing piece '" + pieceKey + "'."); - } - } - } - String fallback = pool.optString("fallback", "").trim(); - if (!fallback.isEmpty() && !poolKeys.contains(fallback)) { - blockingErrors.add("Jigsaw pool '" + poolKey + "' references missing fallback pool '" - + fallback + "'."); - } - } - } - - static void validateJigsawPieces(File piecesFolder, - Set poolKeys, - Set objectKeys, - List blockingErrors) { - if (!piecesFolder.isDirectory()) { - return; - } - List pieceFiles = PackValidationIo.listJsonRecursive(piecesFolder); - pieceFiles.sort(Comparator.comparing(File::getPath)); - for (File pieceFile : pieceFiles) { - String pieceKey = PackValidationIo.deriveKey(piecesFolder, pieceFile); - JSONObject piece = readGraphJson(pieceFile, "Jigsaw piece", pieceKey, blockingErrors); - if (piece == null) { - continue; - } - String objectKey = piece.optString("object", "").trim(); - if (objectKey.isEmpty()) { - blockingErrors.add("Jigsaw piece '" + pieceKey + "' does not declare an object."); - } else if (!objectKeys.contains(objectKey)) { - blockingErrors.add("Jigsaw piece '" + pieceKey + "' references missing object '" - + objectKey + "'."); - } - JSONArray connectors = piece.optJSONArray("connectors"); - if (connectors == null) { - continue; - } - for (int connectorIndex = 0; connectorIndex < connectors.length(); connectorIndex++) { - JSONObject connector = connectors.optJSONObject(connectorIndex); - if (connector == null) { - continue; - } - String poolKey = connector.optString("pool", "").trim(); - if (!poolKey.isEmpty() && !poolKeys.contains(poolKey)) { - blockingErrors.add("Jigsaw piece '" + pieceKey + "' connectors[" + connectorIndex - + "] references missing pool '" + poolKey + "'."); - } - } - } - } - - static JSONObject readGraphJson(File file, - String resourceType, - String resourceKey, - List blockingErrors) { - try { - return new JSONObject(Files.readString(file.toPath(), StandardCharsets.UTF_8)); - } catch (IOException | RuntimeException e) { - String reason = e.getMessage(); - if (reason == null || reason.isBlank()) { - reason = e.getClass().getSimpleName(); - } - blockingErrors.add(resourceType + " '" + resourceKey + "' has invalid JSON: " + reason); - return null; - } - } - - private static boolean isLegacyStructureIndex(String structureKey, JSONObject structure) { - return "structure-index".equals(structureKey) - && structure.has("counts") - && structure.has("structureSets") - && structure.has("iris"); - } - - static String structureHostType(String folderName) { - return switch (folderName) { - case "dimensions" -> "Dimension"; - case "regions" -> "Region"; - case "biomes" -> "Biome"; - default -> "Resource"; - }; - } - - private record RegistrySnapshot(Set structures, Set jigsaws, Set pools, - JigsawMetadataResolver jigsawMetadataResolver, - PlatformStructureHooks hooks) { - } - - private static final class JigsawMetadataResolver { - private final PlatformStructureHooks hooks; - private final Map resolutions = new HashMap<>(); - - private JigsawMetadataResolver(PlatformStructureHooks hooks) { - this.hooks = hooks; - } - - private MetadataResolution resolve(String structureKey) { - MetadataResolution cached = resolutions.get(structureKey); - if (cached != null) { - return cached; - } - MetadataResolution resolved; - try { - JigsawSourceMetadata metadata = hooks.jigsawSourceMetadata(structureKey); - if (metadata == null) { - throw new IllegalStateException( - "The active structure registry returned null jigsaw metadata for '" - + structureKey + "'"); - } - resolved = new MetadataResolution(metadata, null); - } catch (RuntimeException | LinkageError error) { - IrisLogging.reportError( - "Could not resolve live jigsaw metadata for registered structure '" - + structureKey + "' during pack validation", error); - resolved = new MetadataResolution(null, failureMessage(error)); - } - resolutions.put(structureKey, resolved); - return resolved; - } - } - - private record MetadataResolution(JigsawSourceMetadata metadata, String failure) { - } - - private record EffectiveTerrainAdjustment(String path, JSONObject adjustment) { - } -} diff --git a/core/src/main/java/art/arcane/iris/core/pack/PackValidator.java b/core/src/main/java/art/arcane/iris/core/pack/PackValidator.java index d5b5b7720..23d598657 100644 --- a/core/src/main/java/art/arcane/iris/core/pack/PackValidator.java +++ b/core/src/main/java/art/arcane/iris/core/pack/PackValidator.java @@ -37,9 +37,6 @@ public final class PackValidator { static final String CACHE_FOLDER = "cache"; static final String OBJECTS_FOLDER = "objects"; static final String DIMENSIONS_FOLDER = "dimensions"; - static final String STRUCTURES_FOLDER = "structures"; - static final String JIGSAW_POOLS_FOLDER = "jigsaw-pools"; - static final String JIGSAW_PIECES_FOLDER = "jigsaw-pieces"; static final List STRUCTURE_HOST_FOLDERS = List.of(DIMENSIONS_FOLDER, "regions", "biomes"); static final Pattern RESOURCE_KEY_PATTERN = Pattern.compile("[a-z0-9_.-]+:[a-z0-9/._-]+"); @@ -88,8 +85,6 @@ public final class PackValidator { addDistinct(warnings, imageMaps.warnings()); blockingErrors.addAll(PackObjectSurfaceValidator.validateObjectSurfaceSupport(packFolder)); blockingErrors.addAll(PackObjectSurfaceValidator.validateHostFilesParse(packFolder)); - blockingErrors.addAll(PackObjectSurfaceValidator.validateStructureGraph( - packFolder, validateLiveRegistries)); blockingErrors.addAll(PackSpawnValidator.validateSpawnerEntityReferences( new File(packFolder, "spawners"), new File(packFolder, "entities"))); blockingErrors.addAll(PackSpawnValidator.validateCustomBiomeSpawns( @@ -108,7 +103,7 @@ public final class PackValidator { addDistinct(ContentKeyValidator.strictContent() ? blockingErrors : warnings, contentKeys.strict()); addDistinct(warnings, contentKeys.advisory()); - ModulePackValidation.Findings modules = ModulePackValidation.validate(packFolder); + ModulePackValidation.Findings modules = ModulePackValidation.validate(packFolder, validateLiveRegistries); addDistinct(blockingErrors, modules.errors()); addDistinct(warnings, modules.warnings()); diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructurePlacementValidation.java b/core/src/main/java/art/arcane/iris/engine/framework/structure/StructurePlacementValidation.java new file mode 100644 index 000000000..37ea68c43 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/framework/structure/StructurePlacementValidation.java @@ -0,0 +1,245 @@ +/* + * 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 . + */ + +package art.arcane.iris.engine.framework.structure; + +import art.arcane.iris.builtin.structure.NativeStructureSource; +import art.arcane.iris.builtin.structure.StructureDistribution; +import art.arcane.iris.builtin.structure.StructurePlacement; +import art.arcane.iris.builtin.structure.StructurePlacementSettings; +import art.arcane.iris.builtin.structure.StructureTerrainMode; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.Reference; +import com.volmit.resource.ResourceId; +import com.volmit.validation.Problem; +import com.volmit.validation.Subject; +import com.volmit.validation.ValidationContext; +import com.volmit.vanilla.JigsawOverrides; + +import java.util.EnumSet; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** + * Checks of the structure placements the pack's dimensions, regions and biomes declare that their types cannot state: + * each picks exactly one backend, names structures that exist (the pack's, or the platform's when Iris runs on one), + * lays out a grid that can generate, and is told apart from every other placement. Shapes, enum names and bounds + * are the decoder's. + */ +final class StructurePlacementValidation { + private static final String PLACEMENTS_KEY = "structures"; + private static final Pattern REGISTRY_KEY = Pattern.compile("[a-z0-9_.-]+:[a-z0-9/._-]+"); + private static final Set NATIVE_ONLY_TERRAIN_MODES = + EnumSet.of(StructureTerrainMode.VACUUM, StructureTerrainMode.ENCASE); + + private final ValidationContext pack; + private final Set packStructureKeys; + private final Map placementIds = new HashMap<>(); + private final Map anonymousGrids = new HashMap<>(); + + private StructurePlacementValidation(ValidationContext pack) { + this.pack = pack; + this.packStructureKeys = pack.resources().ids(StructureResources.STRUCTURES).stream() + .map(ResourceId::path) + .collect(Collectors.toUnmodifiableSet()); + } + + static void validate(ValidationContext pack) { + new StructurePlacementValidation(pack).validateDeclaredPlacements(); + } + + private void validateDeclaredPlacements() { + for (Entry entry : pack.settings().declared(StructurePlacementSettings.class)) { + Subject subject = Subject.resource(entry.source()); + List placements = entry.value().placements(); + for (int index = 0; index < placements.size(); index++) { + validatePlacement(new Site(subject, PLACEMENTS_KEY + "[" + index + "]"), placements.get(index)); + } + } + } + + private void validatePlacement(Site site, StructurePlacement placement) { + validateGrid(site, placement); + validateIdentity(site, placement); + if (placement.hasIrisStructures() == placement.hasNativeStructures()) { + error(site, " must declare exactly one non-empty backend: structures or nativeStructures"); + return; + } + if (placement.hasNativeStructures()) { + validateNativeSources(site, placement.nativeStructures()); + return; + } + validateEditableStructures(site, placement); + } + + private void validateGrid(Site site, StructurePlacement placement) { + if (placement.separation() >= placement.spacing()) { + error(site, ".separation must be smaller than spacing"); + } + if (placement.minHeight() > placement.maxHeight()) { + error(site, " has an inverted height band: minHeight must not exceed maxHeight"); + } + if (placement.distribution() == StructureDistribution.CONCENTRIC_RINGS && ringRadius(placement) > Integer.MAX_VALUE) { + error(site, " concentric ring radius exceeds the supported chunk coordinate range"); + } + } + + private static long ringRadius(StructurePlacement placement) { + return (long) Math.ceilDiv(placement.ringCount(), placement.ringSpread()) * placement.ringDistance(); + } + + private void validateIdentity(Site site, StructurePlacement placement) { + String placementId = placement.placementId(); + if (!placementId.isEmpty() && placementId.isBlank()) { + error(site, ".placementId must be omitted or non-blank"); + return; + } + if (!placementId.equals(placementId.trim())) { + error(site, ".placementId must not contain leading or trailing whitespace"); + return; + } + if (!placementId.isEmpty()) { + requireUnique(placementIds, placementId, site, ".placementId duplicates '" + placementId + "' already declared by "); + return; + } + requireUnique(anonymousGrids, GridIdentity.of(placement), site, + " duplicates an anonymous placement grid already declared by ", "; give distinct placements unique placementId values"); + } + + private void requireUnique(Map declared, K key, Site site, String message) { + requireUnique(declared, key, site, message, ""); + } + + private void requireUnique(Map declared, K key, Site site, String message, String advice) { + Site first = declared.putIfAbsent(key, site); + if (first != null) { + error(site, message + first + advice); + } + } + + private void validateEditableStructures(Site site, StructurePlacement placement) { + StructureTerrainMode terrainMode = placement.resolvedTerrain().resolvedMode(); + if (NATIVE_ONLY_TERRAIN_MODES.contains(terrainMode)) { + error(site, ".terrain.mode " + terrainMode + " cannot target editable Iris structures; use nativeStructures or" + + " importedStructures.adjustments for native terrain preparation"); + } + Set seenKeys = new HashSet<>(); + List structures = placement.structures(); + for (int index = 0; index < structures.size(); index++) { + validateEditableStructure(site.at(".structures[" + index + "]"), structures.get(index), seenKeys); + } + } + + private void validateEditableStructure(Site site, String structureKey, Set seenKeys) { + if (structureKey == null || structureKey.isBlank()) { + error(site, " must name a non-blank Iris structure"); + return; + } + if (!seenKeys.add(structureKey.trim().toLowerCase(Locale.ROOT))) { + error(site, " duplicates Iris structure '" + structureKey + "'"); + return; + } + if (!packStructureKeys.contains(structureKey)) { + error(site, " references missing structure '" + structureKey + "'"); + } + } + + private void validateNativeSources(Site site, List sources) { + Set seenKeys = new HashSet<>(); + long totalWeight = 0L; + for (int index = 0; index < sources.size(); index++) { + NativeStructureSource source = sources.get(index); + Site sourceSite = site.at(".nativeStructures[" + index + "]"); + validateNativeStructureKey(sourceSite, source.structure().trim(), seenKeys); + source.jigsaw().ifPresent(overrides -> validateJigsawOverrides(sourceSite.at(".jigsaw"), overrides)); + totalWeight += source.weight(); + } + if (totalWeight > Integer.MAX_VALUE) { + error(site, ".nativeStructures total weight exceeds " + Integer.MAX_VALUE); + } + } + + private void validateNativeStructureKey(Site site, String structureKey, Set seenKeys) { + if (!REGISTRY_KEY.matcher(structureKey).matches()) { + error(site, ".structure must be a namespaced registry key"); + return; + } + if (!seenKeys.add(structureKey.toLowerCase(Locale.ROOT))) { + error(site, ".structure duplicates native source '" + structureKey + "'"); + return; + } + if (isUnregistered(Reference.STRUCTURE, ResourceId.ofPlatformKey(structureKey))) { + error(site, ".structure '" + structureKey + "' is not a registered structure"); + } + } + + private void validateJigsawOverrides(Site site, JigsawOverrides overrides) { + Optional startPool; + try { + startPool = overrides.startPool(); + } catch (IllegalArgumentException invalid) { + error(site, ".startPool must be a namespaced registry key"); + return; + } + startPool.filter(pool -> isUnregistered(Reference.TEMPLATE_POOL, pool)) + .ifPresent(pool -> error(site, ".startPool '" + pool + "' is not a registered template pool")); + } + + /** Whether the platform registers no {@code id} under {@code registry}; false without a platform, which cannot tell. */ + private boolean isUnregistered(Reference registry, ResourceId id) { + Set registered = pack.platform().map(platform -> platform.ids(registry)).orElse(Set.of()); + return !registered.isEmpty() && !registered.contains(id); + } + + private void error(Site site, String message) { + pack.report(Problem.error(site.subject(), site.path() + message)); + } + + /** Where in the pack a check looks: a dimension, region or biome and the option path inside it. */ + private record Site(Subject subject, String path) { + Site at(String suffix) { + return new Site(subject, path + suffix); + } + + @Override + public String toString() { + return subject + " " + path; + } + } + + /** What makes two placements without a placementId start the same structures on the same grid. */ + private record GridIdentity(StructureDistribution distribution, int salt, int spacing, int separation, long densityBits, + int ringCount, int ringDistance, int ringSpread, int minHeight, int maxHeight, + boolean underground, boolean underwater, List irisStructures, + List nativeSources) { + static GridIdentity of(StructurePlacement placement) { + return new GridIdentity(placement.distribution(), placement.salt(), placement.spacing(), placement.separation(), + Double.doubleToLongBits(placement.density()), placement.ringCount(), placement.ringDistance(), + placement.ringSpread(), placement.minHeight(), placement.maxHeight(), placement.underground(), + placement.underwater(), placement.structures().stream().sorted().toList(), + placement.nativeStructures().stream().map(source -> source.structure() + "@" + source.weight()).sorted().toList()); + } + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureReferenceValidation.java b/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureReferenceValidation.java new file mode 100644 index 000000000..fb9dfb6ea --- /dev/null +++ b/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureReferenceValidation.java @@ -0,0 +1,158 @@ +/* + * 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 . + */ + +package art.arcane.iris.engine.framework.structure; + +import art.arcane.iris.engine.object.structure.IrisStructure; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawConnector; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPieceEntry; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; +import com.volmit.resource.PackResources; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKind; +import com.volmit.validation.Problem; +import com.volmit.validation.Subject; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.function.BiConsumer; +import java.util.stream.Collectors; + +/** + * The references between the pack's structures, jigsaw pools, jigsaw pieces and objects, checked for every file, + * placed or not, so a structure under construction reports a missing pool before anything places it. Assembling a + * placed structure ({@link StructureGraphValidation}) finds the same problems and words them the same way. + */ +final class StructureReferenceValidation { + private static final String JSON_EXTENSION = ".json"; + + private final PackResources pack; + private final Set poolKeys; + private final Set pieceKeys; + private final Set objectKeys; + private final List problems = new ArrayList<>(); + + private StructureReferenceValidation(PackResources pack) { + this.pack = pack; + this.poolKeys = keys(pack, StructureResources.POOLS); + this.pieceKeys = keys(pack, StructureResources.PIECES); + this.objectKeys = keys(pack, PackResources.OBJECTS); + } + + static List validate(PackResources pack) { + StructureReferenceValidation validation = new StructureReferenceValidation(pack); + validation.validateStructures(); + validation.validatePools(); + validation.validatePieces(); + return List.copyOf(validation.problems); + } + + private void validateStructures() { + forEachReadable(StructureResources.STRUCTURES, "Structure", this::validateStructure); + } + + /** Hands each resource of {@code kind} to {@code check}; a file that cannot be read is an error instead. */ + private void forEachReadable(ResourceKind kind, String typeName, BiConsumer check) { + for (ResourceId id : pack.ids(kind)) { + Optional resource; + try { + resource = pack.find(kind, id); + } catch (RuntimeException unreadable) { + problems.add(Problem.error(file(kind, id.path()), typeName + " '" + id.path() + "' cannot be loaded: " + + failureMessage(unreadable))); + continue; + } + resource.ifPresent(found -> check.accept(id.path(), found)); + } + } + + private static String failureMessage(RuntimeException failure) { + return failure.getMessage() == null || failure.getMessage().isBlank() + ? failure.getClass().getSimpleName() + : failure.getMessage(); + } + + private void validateStructure(String key, IrisStructure structure) { + Subject file = file(StructureResources.STRUCTURES, key); + String startPool = trimmed(structure.getStartPool()); + if (startPool.isEmpty()) { + problems.add(Problem.error(file, "Structure '" + key + "' does not declare a start pool.")); + return; + } + if (!poolKeys.contains(startPool)) { + problems.add(Problem.error(file, "Structure '" + key + "' references missing start pool '" + startPool + "'.")); + } + } + + private void validatePools() { + forEachReadable(StructureResources.POOLS, "Jigsaw pool", this::validatePool); + } + + private void validatePool(String key, IrisJigsawPool pool) { + Subject file = file(StructureResources.POOLS, key); + List entries = pool.getPieces() == null ? List.of() : pool.getPieces(); + for (int index = 0; index < entries.size(); index++) { + String pieceKey = entries.get(index) == null ? "" : trimmed(entries.get(index).getPiece()); + if (!pieceKey.isEmpty() && !pieceKeys.contains(pieceKey)) { + problems.add(Problem.error(file, "Jigsaw pool '" + key + "' pieces[" + index + + "] references missing piece '" + pieceKey + "'.")); + } + } + String fallback = trimmed(pool.getFallback()); + if (!fallback.isEmpty() && !poolKeys.contains(fallback)) { + problems.add(Problem.error(file, "Jigsaw pool '" + key + "' references missing fallback pool '" + fallback + "'.")); + } + } + + private void validatePieces() { + forEachReadable(StructureResources.PIECES, "Jigsaw piece", this::validatePiece); + } + + private void validatePiece(String key, IrisJigsawPiece piece) { + Subject file = file(StructureResources.PIECES, key); + String objectKey = trimmed(piece.getObject()); + if (objectKey.isEmpty()) { + problems.add(Problem.error(file, "Jigsaw piece '" + key + "' does not declare an object.")); + } else if (!objectKeys.contains(objectKey)) { + problems.add(Problem.error(file, "Jigsaw piece '" + key + "' references missing object '" + objectKey + "'.")); + } + List connectors = piece.getConnectors() == null ? List.of() : piece.getConnectors(); + for (int index = 0; index < connectors.size(); index++) { + String poolKey = connectors.get(index) == null ? "" : trimmed(connectors.get(index).getPool()); + if (!poolKey.isEmpty() && !poolKeys.contains(poolKey)) { + problems.add(Problem.error(file, "Jigsaw piece '" + key + "' connectors[" + index + + "] references missing pool '" + poolKey + "'.")); + } + } + } + + private static Set keys(PackResources pack, ResourceKind kind) { + return pack.ids(kind).stream().map(ResourceId::path).collect(Collectors.toUnmodifiableSet()); + } + + private static Subject file(ResourceKind kind, String key) { + return Subject.file(kind.folder() + "/" + key + JSON_EXTENSION); + } + + private static String trimmed(String key) { + return key == null ? "" : key.trim(); + } +} diff --git a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureValidator.java b/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureValidator.java index d09f58c14..80bf6b758 100644 --- a/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureValidator.java +++ b/core/src/main/java/art/arcane/iris/engine/framework/structure/StructureValidator.java @@ -23,6 +23,7 @@ import art.arcane.iris.core.modules.IrisValidationContext; import art.arcane.iris.core.pack.PackValidationIo; import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONObject; +import com.volmit.validation.Problem; import com.volmit.validation.ValidationContext; import com.volmit.validation.Validator; @@ -30,12 +31,15 @@ import java.io.File; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; +import java.util.stream.Collectors; /** * Module {@code iris:structure}'s check of a pack: every structure a dimension, region or biome places must assemble * ({@link StructureGraphValidation}), and a dimension that replaces a vanilla structure with an Iris one may only use - * structures that always assemble and fit ({@link NativeReplacementValidation}), and its {@code importedStructures} - * name real keys ({@link ImportedStructuresValidation}). Graph diagnostics keep their + * structures that always assemble and fit ({@link NativeReplacementValidation}), every structure, pool and piece names + * resources that exist ({@link StructureReferenceValidation}), every structure placement can generate + * ({@link StructurePlacementValidation}), and its {@code importedStructures} name real keys + * ({@link ImportedStructuresValidation}). Graph diagnostics keep their * severity; everything else is an error, as when Iris's own pack validator ran these checks. */ public final class StructureValidator implements Validator { @@ -47,11 +51,19 @@ public final class StructureValidator implements Validator { IrisData data = IrisValidationContext.of(pack).data(); StructureGraphValidation.Validation graphs = StructureGraphValidation.validate(data, placedStructureKeys(data.getDataFolder())); graphs.problems().forEach(pack::report); + reportUnlessAssemblyReported(pack, StructureReferenceValidation.validate(pack.resources()), graphs.problems()); NativeReplacementValidation.validate(data.getDataFolder(), graphs.replacementOutputStructures(), graphs.sampledVerticalEnvelopes()) .forEach(pack::report); + StructurePlacementValidation.validate(pack); ImportedStructuresValidation.validate(pack); } + /** Reports {@code references} whose message assembling a placed structure did not already report. */ + private static void reportUnlessAssemblyReported(ValidationContext pack, List references, List assembly) { + Set reported = assembly.stream().map(Problem::message).collect(Collectors.toSet()); + references.stream().filter(problem -> !reported.contains(problem.message())).forEach(pack::report); + } + /** * The keys of the structures the dimension, region and biome files of the pack in {@code packFolder} place, read * from their JSON as written, like the other checks of these files. diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorStructureGraphTest.java b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorStructureGraphTest.java index 1e755626a..e6a527048 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorStructureGraphTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorStructureGraphTest.java @@ -6,8 +6,7 @@ import art.arcane.iris.engine.framework.structure.StructureValidator; import com.volmit.validation.Problem; import art.arcane.iris.spi.IrisPlatform; import art.arcane.iris.spi.IrisPlatforms; -import art.arcane.iris.spi.PlatformStructureHooks; -import art.arcane.iris.spi.PlatformStructureHooks.JigsawSourceMetadata; +import art.arcane.iris.spi.PlatformRegistries; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -25,9 +24,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class PackValidatorStructureGraphTest { @@ -36,15 +32,15 @@ public class PackValidatorStructureGraphTest { @Test public void acceptsCompleteStructureGraph() throws Exception { - File pack = temporaryFolder.newFolder("pack"); - write(pack, "dimensions/main.json", "{\"structures\":[{\"structures\":[\"castle\"]}]}"); + File pack = pack("\"structures\":[{\"structures\":[\"castle\"]}]"); write(pack, "structures/castle.json", "{\"startPool\":\"castle/start\"}"); - write(pack, "jigsaw-pools/castle/start.json", "{\"pieces\":[{\"piece\":\"castle/start\"}],\"fallback\":\"castle/end\"}"); - write(pack, "jigsaw-pools/castle/end.json", "{\"pieces\":[]}"); - write(pack, "jigsaw-pieces/castle/start.json", "{\"object\":\"castle/start\",\"connectors\":[{\"pool\":\"castle/end\"}]}"); - write(pack, "objects/castle/start.iob", "object"); + write(pack, "jigsaw-pools/castle/start.json", "{\"pieces\":[{\"piece\":\"castle/start\"}]}"); + write(pack, "jigsaw-pieces/castle/start.json", "{\"object\":\"castle/start\",\"connectors\":[]}"); + writeObjectHeader(pack, "objects/castle/start.iob", 3, 9, 3); - assertTrue(PackObjectSurfaceValidator.validateStructureGraph(pack).isEmpty()); + List errors = blockingErrors(pack); + + assertTrue(errors.toString(), errors.isEmpty()); } @Test @@ -62,35 +58,29 @@ public class PackValidatorStructureGraphTest { @Test public void acceptsNativeStructureBackendWithoutConvertedIrisResources() throws Exception { - File pack = temporaryFolder.newFolder("native-structure"); - write(pack, "dimensions/main.json", "{\"structures\":[{" + File pack = pack("\"structures\":[{" + "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\",\"weight\":2," + "\"jigsaw\":{\"maxDepth\":7,\"maxDistanceHorizontal\":96," + "\"maxDistanceVertical\":64,\"liquidSettings\":\"IGNORE_WATERLOGGING\"}}]," + "\"underground\":true,\"minHeight\":-48,\"maxHeight\":-20," + "\"terrain\":{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":24," + "\"ceilingPadding\":12,\"floorPadding\":2," - + "\"lobeFrequency\":0.02,\"lobeStrength\":0.85}}]}"); + + "\"lobeFrequency\":0.02,\"lobeStrength\":0.85}}]"); - assertTrue(PackObjectSurfaceValidator.validateStructureGraph(pack).isEmpty()); - assertTrue(nativeReplacementErrors( - pack, Set.of(), Map.of()).isEmpty()); + List errors = blockingErrors(pack); + + assertTrue(errors.toString(), errors.isEmpty()); + assertTrue(nativeReplacementErrors(pack, Set.of(), Map.of()).isEmpty()); } @Test public void datapackBootstrapDefersOnlyLiveRegistryValidation() throws Exception { - File pack = temporaryFolder.newFolder("bootstrap-native-structure"); - write(pack, "dimensions/main.json", "{\"structures\":[{" - + "\"nativeStructures\":[{\"structure\":\"test:structure\"}]}]," - + "\"regions\":[\"main\"]}"); - write(pack, "regions/main.json", "{\"landBiomes\":[\"main\"]}"); - write(pack, "biomes/main.json", "{\"name\":\"Main\"}"); + File pack = pack("\"structures\":[{\"nativeStructures\":[{\"structure\":\"test:structure\"}]}]"); IrisPlatform previous = IrisPlatforms.isBound() ? IrisPlatforms.get() : null; IrisPlatform platform = mock(IrisPlatform.class); - PlatformStructureHooks hooks = mock(PlatformStructureHooks.class); - when(platform.structureHooks()).thenReturn(hooks); - when(hooks.structureKeys()).thenThrow( - new IllegalStateException("server unavailable")); + PlatformRegistries registries = mock(PlatformRegistries.class); + when(platform.registries()).thenReturn(registries); + when(registries.structureKeys()).thenThrow(new IllegalStateException("server unavailable")); IrisPlatforms.unbind(); IrisPlatforms.bind(platform); try { @@ -109,476 +99,190 @@ public class PackValidatorStructureGraphTest { } } + @Test + public void liveValidationRejectsAnUnregisteredNativeStructure() throws Exception { + File pack = pack("\"structures\":[{\"nativeStructures\":[{\"structure\":\"test:missing\"}]}]"); + IrisPlatform previous = IrisPlatforms.isBound() ? IrisPlatforms.get() : null; + IrisPlatform platform = mock(IrisPlatform.class); + PlatformRegistries registries = mock(PlatformRegistries.class); + when(platform.registries()).thenReturn(registries); + when(registries.structureKeys()).thenReturn(List.of("test:structure")); + IrisPlatforms.unbind(); + IrisPlatforms.bind(platform); + try { + assertEquals(List.of("pack:dimension/main: structures[0].nativeStructures[0].structure 'test:missing'" + + " is not a registered structure"), PackValidator.validate(pack).getBlockingErrors()); + assertTrue(PackValidator.validateForDatapackBootstrap(pack).isLoadable()); + } finally { + IrisPlatforms.unbind(); + if (previous != null) { + IrisPlatforms.bind(previous); + } + } + } + @Test public void datapackBootstrapStillRejectsMalformedPlacementConfiguration() throws Exception { - File pack = temporaryFolder.newFolder("bootstrap-invalid-placement"); - write(pack, "dimensions/main.json", "{\"structures\":[{" - + "\"nativeStructures\":[{\"structure\":\"test:structure\"}]," - + "\"spacing\":0}]}"); + File pack = pack("\"structures\":[{\"nativeStructures\":[{\"structure\":\"test:structure\"}],\"spacing\":0}]"); PackValidationResult result = PackValidator.validateForDatapackBootstrap(pack); assertFalse(result.isLoadable()); assertTrue(result.getBlockingErrors().toString(), result.getBlockingErrors().stream().anyMatch( - error -> error.contains("spacing must be at least 1"))); + error -> error.contains("structures[0].spacing is 0; it must be at least 1"))); } @Test - public void rejectsNativeTerrainLobeSettingsOutsideTheirRange() throws Exception { - File pack = temporaryFolder.newFolder("invalid-lobe"); - write(pack, "dimensions/main.json", "{\"structures\":[{" - + "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]," - + "\"terrain\":{\"mode\":\"FORCE_CARVE\",\"lobeFrequency\":1.5," - + "\"lobeStrength\":-0.2}}]}"); - - List errors = PackObjectSurfaceValidator.validateStructureGraph(pack); - - assertTrue(errors.toString(), errors.stream().anyMatch( - message -> message.contains("terrain.lobeFrequency must be at most 1"))); - assertTrue(errors.toString(), errors.stream().anyMatch( - message -> message.contains("terrain.lobeStrength must be at least 0"))); + public void rejectsANativeTerrainLobeFrequencyAboveItsRange() throws Exception { + assertBlockedNaming("structures[0].terrain.lobeFrequency is 1.5; it must be at most 1", + nativePlacement("\"terrain\":{\"mode\":\"FORCE_CARVE\",\"lobeFrequency\":1.5}")); } @Test - public void rejectsNativeTerrainErosionSettingsOutsideTheirRange() throws Exception { - File pack = temporaryFolder.newFolder("invalid-erosion"); - write(pack, "dimensions/main.json", "{\"structures\":[{" - + "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]," - + "\"terrain\":{\"mode\":\"FORCE_CARVE\",\"erosionStrength\":1.4," - + "\"erosionFrequency\":0}}]}"); + public void rejectsANativeTerrainLobeStrengthBelowItsRange() throws Exception { + assertBlockedNaming("structures[0].terrain.lobeStrength is -0.2; it must be at least 0", + nativePlacement("\"terrain\":{\"mode\":\"FORCE_CARVE\",\"lobeStrength\":-0.2}")); + } - List errors = PackObjectSurfaceValidator.validateStructureGraph(pack); + @Test + public void rejectsANativeTerrainErosionStrengthAboveItsRange() throws Exception { + assertBlockedNaming("structures[0].terrain.erosionStrength is 1.4; it must be at most 1", + nativePlacement("\"terrain\":{\"mode\":\"FORCE_CARVE\",\"erosionStrength\":1.4}")); + } - assertTrue(errors.toString(), errors.stream().anyMatch( - message -> message.contains("terrain.erosionStrength must be at most 1"))); - assertTrue(errors.toString(), errors.stream().anyMatch( - message -> message.contains("terrain.erosionFrequency must be at least 0.001"))); + @Test + public void rejectsANativeTerrainErosionFrequencyBelowItsRange() throws Exception { + assertBlockedNaming("structures[0].terrain.erosionFrequency is 0", + nativePlacement("\"terrain\":{\"mode\":\"FORCE_CARVE\",\"erosionFrequency\":0}")); } @Test public void rejectsNonNumericNativeTerrainLobeSettings() throws Exception { - File pack = temporaryFolder.newFolder("non-numeric-lobe"); - write(pack, "dimensions/main.json", "{\"structures\":[{" - + "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]," - + "\"terrain\":{\"mode\":\"FORCE_CARVE\",\"lobeStrength\":\"strong\"}}]}"); - - List errors = PackObjectSurfaceValidator.validateStructureGraph(pack); - - assertTrue(errors.toString(), errors.stream().anyMatch( - message -> message.contains("terrain.lobeStrength must be a number"))); + assertBlockedNaming("in Dimension main: structures[0].terrain.lobeStrength must be a number", + nativePlacement("\"terrain\":{\"mode\":\"FORCE_CARVE\",\"lobeStrength\":\"strong\"}")); } @Test public void rejectsMixedStructureBackends() throws Exception { - File pack = temporaryFolder.newFolder("mixed-native"); - write(pack, "dimensions/main.json", "{\"structures\":[{" - + "\"structures\":[\"city\"]," - + "\"nativeStructures\":[{\"structure\":\"ancient_city\",\"weight\":0," - + "\"jigsaw\":{\"maxDepth\":21}}]}]}"); + File pack = pack("\"structures\":[{\"structures\":[\"city\"]," + + "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]}]"); write(pack, "structures/city.json", "{}"); - List errors = PackObjectSurfaceValidator.validateStructureGraph(pack); - - assertTrue(errors.toString(), errors.stream().anyMatch( - message -> message.contains("exactly one non-empty backend"))); + assertTrue(blockingErrors(pack).contains("pack:dimension/main: structures[0] must declare exactly one non-empty" + + " backend: structures or nativeStructures")); } @Test - public void rejectsInvalidNativeStructureSourceAndOverrides() throws Exception { - File pack = temporaryFolder.newFolder("invalid-native"); - write(pack, "dimensions/main.json", "{\"structures\":[{" - + "\"nativeStructures\":[{\"structure\":\"ancient_city\",\"weight\":0," - + "\"jigsaw\":{\"maxDepth\":21}}]}]}"); - - List errors = PackObjectSurfaceValidator.validateStructureGraph(pack); - - assertTrue(errors.toString(), errors.stream().anyMatch( - message -> message.contains(".structure must be a namespaced registry key"))); - assertTrue(errors.toString(), errors.stream().anyMatch( - message -> message.contains(".weight must be at least 1"))); - assertTrue(errors.toString(), errors.stream().anyMatch( - message -> message.contains(".maxDepth must be at most 20"))); + public void rejectsANativeStructureWithoutNamespace() throws Exception { + assertEquals(List.of("pack:dimension/main: structures[0].nativeStructures[0].structure must be a namespaced registry key"), + blockingErrors(pack("\"structures\":[{\"nativeStructures\":[{\"structure\":\"ancient_city\"}]}]"))); } @Test - public void rejectsMalformedPlacementGridAndPolicyFields() throws Exception { - File pack = temporaryFolder.newFolder("invalid-placement-grid"); - write(pack, "dimensions/main.json", "{\"structures\":[{" - + "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]," - + "\"placementId\":42,\"distribution\":\"UNKNOWN\",\"spacing\":0," - + "\"separation\":32,\"density\":\"often\",\"ringCount\":0," - + "\"minHeight\":90,\"maxHeight\":20,\"underwater\":\"yes\"," - + "\"nativeSuppression\":\"SOMETIMES\"," - + "\"terrain\":{\"mode\":\"SURFACE_FIT\",\"shape\":\"CUBE\"}}]}"); + public void rejectsANativeSourceWeightBelowItsRange() throws Exception { + assertBlockedNaming("structures[0].nativeStructures[0].weight is 0; it must be at least 1", + pack("\"structures\":[{\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\",\"weight\":0}]}]")); + } - List errors = PackObjectSurfaceValidator.validateStructureGraph(pack); + @Test + public void rejectsANativeJigsawDepthAboveItsRange() throws Exception { + assertBlockedNaming("structures[0].nativeStructures[0].jigsaw.maxDepth is 21; it must be at most 20", + pack("\"structures\":[{\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"," + + "\"jigsaw\":{\"maxDepth\":21}}]}]")); + } - assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("placementId must be a string"))); - assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("distribution must be one of"))); - assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("spacing must be at least 1"))); - assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("density must be a number"))); - assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("inverted height band"))); - assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("underwater must be a boolean"))); - assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("terrain.mode must be one of"))); - assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("terrain.shape must be one of"))); + @Test + public void rejectsAnUnknownDistribution() throws Exception { + assertBlockedNaming("\"UNKNOWN\" is not one of", nativePlacement("\"distribution\":\"UNKNOWN\"")); + } + + @Test + public void rejectsAnInvertedHeightBandAndSeparationNotBelowSpacing() throws Exception { + List errors = blockingErrors(nativePlacement("\"spacing\":16,\"separation\":16,\"minHeight\":90,\"maxHeight\":20")); + + assertEquals(List.of( + "pack:dimension/main: structures[0].separation must be smaller than spacing", + "pack:dimension/main: structures[0] has an inverted height band: minHeight must not exceed maxHeight"), errors); } @Test public void rejectsDuplicatePlacementIdsAcrossResources() throws Exception { - File pack = temporaryFolder.newFolder("duplicate-placement-id"); - write(pack, "dimensions/main.json", "{\"structures\":[{\"placementId\":\"shared\"," - + "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]}]}"); - write(pack, "regions/forest.json", "{\"structures\":[{\"placementId\":\"shared\"," + File pack = pack("\"structures\":[{\"placementId\":\"shared\"," + + "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]}]"); + write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"],\"structures\":[{\"placementId\":\"shared\"," + "\"nativeStructures\":[{\"structure\":\"minecraft:village_plains\"}]}]}"); - List errors = PackObjectSurfaceValidator.validateStructureGraph(pack); + List errors = blockingErrors(pack); assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("placementId duplicates 'shared'"))); } @Test public void rejectsCanonicalAnonymousGridDuplicatesAcrossResources() throws Exception { - File pack = temporaryFolder.newFolder("duplicate-anonymous-grid"); - write(pack, "dimensions/main.json", "{\"structures\":[{" - + "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]}]}"); - write(pack, "regions/forest.json", "{\"structures\":[{" + File pack = pack("\"structures\":[{\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}]}]"); + write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"],\"structures\":[{" + "\"spacing\":32,\"separation\":8,\"density\":0.02," + "\"nativeStructures\":[{\"weight\":1,\"structure\":\"minecraft:ancient_city\"}]}]}"); - List errors = PackObjectSurfaceValidator.validateStructureGraph(pack); + List errors = blockingErrors(pack); assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("duplicates an anonymous placement grid"))); } @Test public void rejectsDuplicateEditableStructureKeysIgnoringCase() throws Exception { - File pack = temporaryFolder.newFolder("duplicate-editable-key"); - write(pack, "dimensions/main.json", "{\"structures\":[{\"structures\":[" - + "\"castle\",\"CASTLE\"]}]}"); + File pack = pack("\"structures\":[{\"structures\":[\"castle\",\"CASTLE\"]}]"); write(pack, "structures/castle.json", "{}"); - List errors = PackObjectSurfaceValidator.validateStructureGraph(pack); + List errors = blockingErrors(pack); - assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains("duplicates Iris structure"))); + assertTrue(errors.toString(), errors.contains( + "pack:dimension/main: structures[0].structures[1] duplicates Iris structure 'CASTLE'")); } @Test - public void optionalJigsawTerrainEnvelopeOverflowDoesNotBlockThePack() throws Exception { - File pack = temporaryFolder.newFolder("oversized-envelope"); - write(pack, "dimensions/main.json", "{\"structures\":[{" - + "\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"," - + "\"jigsaw\":{\"maxDistanceHorizontal\":96}}]," - + "\"terrain\":{\"mode\":\"FORCE_CARVE\",\"horizontalPadding\":40}}]}"); - - assertTrue(PackObjectSurfaceValidator.validateStructureGraph(pack).isEmpty()); - } - - @Test - public void sharedOverworldAncientCityTerrainEnvelopeDoesNotBlockThePack() throws Exception { - File pack = nativeSourceEnvelopePack( - "shared-overworld-ancient-city", "minecraft:ancient_city", "FORCE_CARVE", 24); - - assertTrue(validateWithJigsawMetadata( - pack, "minecraft:ancient_city", 116, 12, 0, 0).isEmpty()); - } - - @Test - public void sourceAndPreserveIgnoreConfiguredEnvelopePadding() throws Exception { - File source = nativeEnvelopePack("source-padding", "SOURCE", 128, 128); - File preserve = nativeEnvelopePack("preserve-padding", "PRESERVE", 128, 128); - - assertTrue(validateWithReferenceExpansion(source, 0).isEmpty()); - assertTrue(validateWithReferenceExpansion(preserve, 12).isEmpty()); - } - - @Test - public void sourceTerrainAdjustmentOverflowDoesNotBlockThePack() throws Exception { - File boundary = nativeEnvelopePack("source-adjustment-boundary", "SOURCE", 116, 64); - File oversized = nativeEnvelopePack("source-adjustment-oversized", "SOURCE", 117, 0); - - assertTrue(validateWithReferenceExpansion(boundary, 12).isEmpty()); - assertTrue(validateWithReferenceExpansion(oversized, 12).isEmpty()); - } - - @Test - public void customTerrainEnvelopeOverflowDoesNotBlockThePack() throws Exception { - File boundary = nativeEnvelopePack("custom-envelope-boundary", "ENCASE", 96, 32); - File oversized = nativeEnvelopePack("custom-envelope-oversized", "ENCASE", 96, 33); - - assertTrue(validateWithReferenceExpansion(boundary, 12).isEmpty()); - assertTrue(validateWithReferenceExpansion(oversized, 12).isEmpty()); - } - - @Test - public void registeredJigsawOptionalPaddingDoesNotExpandItsBlockingSpan() throws Exception { - File boundary = nativeSourceEnvelopePack("dnt-source-boundary", "ENCASE", 48); - File oversized = nativeSourceEnvelopePack("dnt-source-oversized", "ENCASE", 49); - - assertTrue(validateWithJigsawMetadata(boundary, 80, 12).isEmpty()); - assertTrue(validateWithJigsawMetadata(oversized, 80, 12).isEmpty()); - } - - @Test - public void jigsawOverrideReplacesLiveSourceDistance() throws Exception { - File pack = nativeEnvelopePack("source-distance-override", "ENCASE", 80, 36); - - assertTrue(validateWithJigsawMetadata(pack, 120, 12).isEmpty()); - } - - @Test - public void oversizedLiveStartElementCannotBypassAssemblyDistance() throws Exception { - File pack = nativeSourceEnvelopePack("oversized-live-start", "SOURCE", 0); - - List errors = validateWithJigsawMetadata(pack, 80, 0, 129, 0); - - assertTrue(errors.toString(), errors.stream().anyMatch(message -> - message.contains("129-block maximum start element") - && message.contains("128-block (8-chunk)"))); - } - - @Test - public void liveStartElementSpanUsesInclusiveReferenceBoundary() throws Exception { - File pack = nativeSourceEnvelopePack("live-start-boundary", "SOURCE", 0); - - assertTrue(validateWithJigsawMetadata(pack, 80, 12, 116, 0).isEmpty()); - } - - @Test - public void overriddenStartPoolUsesItsLiveSpan() throws Exception { - File pack = nativePoolOverrideEnvelopePack("oversized-pool-override"); - - List errors = validateWithJigsawMetadata(pack, 80, 0, 20, 129); - - assertTrue(errors.toString(), errors.stream().anyMatch(message -> - message.contains("129-block maximum start element") - && message.contains("128-block (8-chunk)"))); - } - - @Test - public void smallerOverriddenStartPoolReplacesTheSourcePoolSpan() throws Exception { - File pack = nativePoolOverrideEnvelopePack("smaller-pool-override"); - - assertTrue(validateWithJigsawMetadata(pack, 80, 0, 129, 20).isEmpty()); - } - - @Test - public void unresolvedOverriddenStartPoolSpanFailsClosed() throws Exception { - File pack = nativePoolOverrideEnvelopePack("unresolved-pool-override"); - IrisPlatform previous = IrisPlatforms.isBound() ? IrisPlatforms.get() : null; - IrisPlatform platform = mock(IrisPlatform.class); - PlatformStructureHooks hooks = mock(PlatformStructureHooks.class); - when(platform.structureHooks()).thenReturn(hooks); - when(hooks.structureKeys()).thenReturn(List.of("test:structure")); - when(hooks.jigsawStructureKeys()).thenReturn(List.of("test:structure")); - when(hooks.templatePoolKeys()).thenReturn(List.of("test:start", "test:override")); - when(hooks.jigsawSourceMetadata("test:structure")) - .thenReturn(new JigsawSourceMetadata(80, 0, 20)); - when(hooks.jigsawStartPoolHorizontalSpan("test:structure", "test:override")) - .thenThrow(new IllegalStateException("missing template")); - IrisPlatforms.unbind(); - IrisPlatforms.bind(platform); - try { - List errors = PackObjectSurfaceValidator.validateStructureGraph(pack); - - assertTrue(errors.toString(), errors.stream().anyMatch(message -> - message.contains("could not resolve a bounded live horizontal span") - && message.contains("missing template"))); - } finally { - IrisPlatforms.unbind(); - if (previous != null) { - IrisPlatforms.bind(previous); - } - } - } - - @Test - public void registeredJigsawSourceAdjustmentOverflowDoesNotBlockThePack() throws Exception { - File pack = nativeSourceEnvelopePack("source-adjustment-no-override", "SOURCE", 0); - - assertTrue(validateWithJigsawMetadata(pack, 117, 12).isEmpty()); - } - - @Test - public void registeredJigsawAssemblyBeyondReferenceRangeStillBlocksThePack() throws Exception { - File pack = nativeEnvelopePack("oversized-live-assembly", "ENCASE", 129, 0); - - List errors = PackObjectSurfaceValidator.validateStructureGraph(pack); - - assertTrue(errors.toString(), errors.stream().anyMatch(message -> - message.contains(".jigsaw.maxDistanceHorizontal") - && message.contains("129-block maximum assembly distance") - && message.contains("128-block (8-chunk)"))); - } - - @Test - public void liveJigsawMetadataFailureBlocksValidation() throws Exception { - File pack = nativeSourceEnvelopePack("missing-source-metadata", "SOURCE", 0); - - List errors = validateWithUnavailableJigsawMetadata(pack); - - assertTrue(errors.toString(), errors.stream().anyMatch(message -> - message.contains("returned null jigsaw metadata for 'test:structure'"))); - } - - @Test - public void validationResolvesOnlyReferencedJigsawMetadataAndCachesDuplicates() throws Exception { - File pack = temporaryFolder.newFolder("lazy-jigsaw-metadata"); - write(pack, "dimensions/main.json", "{\"structures\":[" - + "{\"placementId\":\"first\",\"nativeStructures\":[" - + "{\"structure\":\"test:used\"}]}," - + "{\"placementId\":\"second\",\"nativeStructures\":[" - + "{\"structure\":\"test:used\"}]}]}"); - IrisPlatform previous = IrisPlatforms.isBound() ? IrisPlatforms.get() : null; - IrisPlatform platform = mock(IrisPlatform.class); - PlatformStructureHooks hooks = mock(PlatformStructureHooks.class); - when(platform.structureHooks()).thenReturn(hooks); - when(hooks.structureKeys()).thenReturn(List.of("test:used", "test:unused")); - when(hooks.jigsawStructureKeys()).thenReturn(List.of("test:used", "test:unused")); - when(hooks.templatePoolKeys()).thenReturn(List.of("test:start")); - when(hooks.jigsawSourceMetadata("test:used")) - .thenReturn(new JigsawSourceMetadata(80, 0, 20)); - IrisPlatforms.unbind(); - IrisPlatforms.bind(platform); - try { - List errors = PackObjectSurfaceValidator.validateStructureGraph(pack); - - assertTrue(errors.toString(), errors.isEmpty()); - verify(hooks, times(1)).jigsawSourceMetadata("test:used"); - verify(hooks, never()).jigsawSourceMetadata("test:unused"); - } finally { - IrisPlatforms.unbind(); - if (previous != null) { - IrisPlatforms.bind(previous); - } - } - } - - @Test - public void optionalTerrainPaddingForNonJigsawSourceDoesNotBlockThePack() throws Exception { - File pack = nativeSourceEnvelopePack("non-jigsaw-envelope", "ENCASE", 1); - - assertTrue(validateWithNonJigsawSource(pack).isEmpty()); - } - - @Test - public void acceptsZeroReferencePaddingForRegisteredNonJigsawSource() throws Exception { - File pack = nativeSourceEnvelopePack("non-jigsaw-zero-envelope", "ENCASE", 0); - - assertTrue(validateWithNonJigsawSource(pack).isEmpty()); - } - - @Test - public void optionalTerrainPaddingForNaturalNonJigsawAdjustmentDoesNotBlockThePack() throws Exception { - File pack = nativeAdjustmentEnvelopePack( - "natural-non-jigsaw-envelope", "test:structure", "ENCASE", 1); - - assertTrue(validateWithNonJigsawSource(pack).isEmpty()); - } - - @Test - public void optionalTerrainPaddingForNaturalJigsawAdjustmentDoesNotBlockThePack() throws Exception { - File boundary = nativeAdjustmentEnvelopePack( - "natural-jigsaw-envelope-boundary", "test:structure", "ENCASE", 48); - File oversized = nativeAdjustmentEnvelopePack( - "natural-jigsaw-envelope-oversized", "test:structure", "ENCASE", 49); - - assertTrue(validateWithJigsawMetadata(boundary, 80, 12).isEmpty()); - assertTrue(validateWithJigsawMetadata(oversized, 80, 12).isEmpty()); - } - - @Test - public void actualNaturalJigsawContentBeyondReferenceRangeStillBlocksThePack() throws Exception { - File pack = nativeAdjustmentEnvelopePack( - "natural-jigsaw-oversized-content", "test:structure", "ENCASE", 1); - - List errors = validateWithJigsawMetadata(pack, 80, 0, 129, 0); - - assertTrue(errors.toString(), errors.stream().anyMatch(message -> - message.contains("importedStructures.adjustments[0]") - && message.contains("129-block maximum start element") - && message.contains("128-block (8-chunk)"))); - } - - @Test - public void lastMatchingNaturalTerrainAdjustmentControlsEnvelopeValidation() throws Exception { - File pack = temporaryFolder.newFolder("natural-adjustment-precedence"); - write(pack, "dimensions/main.json", "{\"importedStructures\":{\"adjustments\":[" - + "{\"match\":[\"test:structure\"],\"terrain\":{\"mode\":\"ENCASE\"," - + "\"horizontalPadding\":128}}," - + "{\"match\":[\"test:structure\"],\"terrain\":{\"mode\":\"PRESERVE\"}}]}}}"); - - assertTrue(validateWithNonJigsawSource(pack).isEmpty()); - } - - @Test - public void reportsMissingReferencesInDeterministicGraphOrder() throws Exception { - File pack = temporaryFolder.newFolder("pack"); - write(pack, "dimensions/main.json", "{\"structures\":[{\"structures\":[\"missing-structure\"]}]}"); + public void reportsMissingReferencesOfPlacedAndUnplacedResources() throws Exception { + File pack = pack("\"structures\":[{\"structures\":[\"missing-structure\"]}]"); write(pack, "structures/castle.json", "{\"startPool\":\"missing-start\"}"); write(pack, "jigsaw-pools/castle/start.json", "{\"pieces\":[{\"piece\":\"missing-piece\"}],\"fallback\":\"missing-fallback\"}"); write(pack, "jigsaw-pieces/castle/start.json", "{\"object\":\"castle/start\",\"connectors\":[{\"pool\":\"missing-connector-pool\"}]}"); - write(pack, "objects/castle/start.iob", "object"); - - List errors = PackObjectSurfaceValidator.validateStructureGraph(pack); + writeObjectHeader(pack, "objects/castle/start.iob", 3, 9, 3); assertEquals(List.of( - "Dimension 'main' structures[0].structures[0] references missing structure 'missing-structure'.", - "Structure 'castle' references missing start pool 'missing-start'.", - "Jigsaw pool 'castle/start' pieces[0] references missing piece 'missing-piece'.", - "Jigsaw pool 'castle/start' references missing fallback pool 'missing-fallback'.", - "Jigsaw piece 'castle/start' connectors[0] references missing pool 'missing-connector-pool'." - ), errors); - } - - @Test - public void ignoresLegacyGeneratedStructureIndex() throws Exception { - File pack = temporaryFolder.newFolder("pack"); - write(pack, "structures/structure-index.json", "{\"counts\":{},\"structureSets\":{},\"iris\":[]}"); - - assertTrue(PackObjectSurfaceValidator.validateStructureGraph(pack).isEmpty()); + "structures/castle.json: Structure 'castle' references missing start pool 'missing-start'.", + "jigsaw-pools/castle/start.json: Jigsaw pool 'castle/start' pieces[0] references missing piece 'missing-piece'.", + "jigsaw-pools/castle/start.json: Jigsaw pool 'castle/start' references missing fallback pool 'missing-fallback'.", + "jigsaw-pieces/castle/start.json: Jigsaw piece 'castle/start' connectors[0] references missing pool" + + " 'missing-connector-pool'.", + "pack:dimension/main: structures[0].structures[0] references missing structure 'missing-structure'" + ), blockingErrors(pack)); } @Test public void reportsMalformedStructureJson() throws Exception { - File pack = temporaryFolder.newFolder("pack"); - write(pack, "structures/castle.json", "{"); - - List errors = PackObjectSurfaceValidator.validateStructureGraph(pack); - - assertEquals(1, errors.size()); - assertTrue(errors.get(0).startsWith("Structure 'castle' has invalid JSON:")); + assertSingleErrorStartsWith("structures/castle.json: Structure 'castle' cannot be loaded: ", "structures/castle.json"); } @Test public void reportsMalformedJigsawPoolJson() throws Exception { - File pack = temporaryFolder.newFolder("pack"); - write(pack, "jigsaw-pools/castle/start.json", "{"); - - List errors = PackObjectSurfaceValidator.validateStructureGraph(pack); - - assertEquals(1, errors.size()); - assertTrue(errors.get(0).startsWith("Jigsaw pool 'castle/start' has invalid JSON:")); + assertSingleErrorStartsWith("jigsaw-pools/castle/start.json: Jigsaw pool 'castle/start' cannot be loaded: ", + "jigsaw-pools/castle/start.json"); } @Test public void reportsMalformedJigsawPieceJson() throws Exception { - File pack = temporaryFolder.newFolder("pack"); - write(pack, "jigsaw-pieces/castle/start.json", "{"); - - List errors = PackObjectSurfaceValidator.validateStructureGraph(pack); - - assertEquals(1, errors.size()); - assertTrue(errors.get(0).startsWith("Jigsaw piece 'castle/start' has invalid JSON:")); + assertSingleErrorStartsWith("jigsaw-pieces/castle/start.json: Jigsaw piece 'castle/start' cannot be loaded: ", + "jigsaw-pieces/castle/start.json"); } @Test public void reportsMissingJigsawPieceObject() throws Exception { - File pack = temporaryFolder.newFolder("pack"); + File pack = pack(""); write(pack, "jigsaw-pieces/castle/start.json", "{\"object\":\"castle/missing\"}"); assertEquals(List.of( - "Jigsaw piece 'castle/start' references missing object 'castle/missing'." - ), PackObjectSurfaceValidator.validateStructureGraph(pack)); + "jigsaw-pieces/castle/start.json: Jigsaw piece 'castle/start' references missing object 'castle/missing'." + ), blockingErrors(pack)); } @Test @@ -767,6 +471,44 @@ public class PackValidatorStructureGraphTest { message -> message.contains("references missing object 'castle/start'"))); } + /** + * A loadable pack named {@code pack}: one dimension declaring {@code dimensionMembers} besides its region, the + * region and its biome. + */ + private File pack(String dimensionMembers) throws Exception { + File pack = temporaryFolder.newFolder("pack"); + String members = dimensionMembers.isEmpty() ? "" : ", " + dimensionMembers; + write(pack, "dimensions/main.json", "{\"regions\": [\"region\"]" + members + "}"); + write(pack, "regions/region.json", "{\"landBiomes\": [\"biome\"]}"); + write(pack, "biomes/biome.json", "{\"name\": \"Biome\"}"); + return pack; + } + + /** A pack whose dimension places a native ancient city with {@code placementMembers} added to the placement. */ + private File nativePlacement(String placementMembers) throws Exception { + return pack("\"structures\":[{\"nativeStructures\":[{\"structure\":\"minecraft:ancient_city\"}], " + + placementMembers + "}]"); + } + + private static List blockingErrors(File pack) { + return PackValidator.validate(pack).getBlockingErrors(); + } + + private static void assertBlockedNaming(String fragment, File pack) { + List errors = blockingErrors(pack); + assertTrue(errors.toString(), errors.stream().anyMatch(message -> message.contains(fragment))); + } + + private void assertSingleErrorStartsWith(String prefix, String malformedFile) throws Exception { + File pack = pack(""); + write(pack, malformedFile, "{"); + + List errors = blockingErrors(pack); + + assertEquals(errors.toString(), 1, errors.size()); + assertTrue(errors.get(0), errors.get(0).startsWith(prefix)); + } + private File replacementPack( String name, String placeMode, @@ -784,156 +526,6 @@ public class PackValidatorStructureGraphTest { return pack; } - private File nativeEnvelopePack(String name, String mode, int maximumDistance, - int horizontalPadding) throws Exception { - File pack = temporaryFolder.newFolder(name); - write(pack, "dimensions/main.json", "{\"structures\":[{" - + "\"nativeStructures\":[{\"structure\":\"test:structure\"," - + "\"jigsaw\":{\"maxDistanceHorizontal\":" + maximumDistance + "}}]," - + "\"terrain\":{\"mode\":\"" + mode + "\",\"horizontalPadding\":" - + horizontalPadding + "}}]}"); - return pack; - } - - private File nativeSourceEnvelopePack(String name, String mode, - int horizontalPadding) throws Exception { - return nativeSourceEnvelopePack(name, "test:structure", mode, horizontalPadding); - } - - private File nativeSourceEnvelopePack(String name, String structureKey, String mode, - int horizontalPadding) throws Exception { - File pack = temporaryFolder.newFolder(name); - write(pack, "dimensions/main.json", "{\"structures\":[{" - + "\"nativeStructures\":[{\"structure\":\"" + structureKey + "\"}]," - + "\"terrain\":{\"mode\":\"" + mode + "\",\"horizontalPadding\":" - + horizontalPadding + "}}]}"); - return pack; - } - - private File nativePoolOverrideEnvelopePack(String name) throws Exception { - File pack = temporaryFolder.newFolder(name); - write(pack, "dimensions/main.json", "{\"structures\":[{" - + "\"nativeStructures\":[{\"structure\":\"test:structure\"," - + "\"jigsaw\":{\"startPool\":\"test:override\"," - + "\"maxDistanceHorizontal\":80}}]," - + "\"terrain\":{\"mode\":\"SOURCE\"}}]}"); - return pack; - } - - private File nativeAdjustmentEnvelopePack(String name, String match, String mode, - int horizontalPadding) throws Exception { - File pack = temporaryFolder.newFolder(name); - write(pack, "dimensions/main.json", "{\"importedStructures\":{\"adjustments\":[{" - + "\"match\":[\"" + match + "\"],\"terrain\":{\"mode\":\"" + mode - + "\",\"horizontalPadding\":" + horizontalPadding + "}}]}}}"); - return pack; - } - - private List validateWithReferenceExpansion(File pack, int expansion) { - IrisPlatform previous = IrisPlatforms.isBound() ? IrisPlatforms.get() : null; - IrisPlatform platform = mock(IrisPlatform.class); - PlatformStructureHooks hooks = mock(PlatformStructureHooks.class); - when(platform.structureHooks()).thenReturn(hooks); - when(hooks.structureKeys()).thenReturn(List.of("test:structure")); - when(hooks.jigsawStructureKeys()).thenReturn(List.of("test:structure")); - when(hooks.templatePoolKeys()).thenReturn(List.of("test:start")); - when(hooks.jigsawSourceMetadata("test:structure")) - .thenReturn(new JigsawSourceMetadata(80, expansion)); - IrisPlatforms.unbind(); - IrisPlatforms.bind(platform); - try { - return PackObjectSurfaceValidator.validateStructureGraph(pack); - } finally { - IrisPlatforms.unbind(); - if (previous != null) { - IrisPlatforms.bind(previous); - } - } - } - - private List validateWithJigsawMetadata(File pack, int maximumDistance, int expansion) { - return validateWithJigsawMetadata(pack, maximumDistance, expansion, 0, 0); - } - - private List validateWithJigsawMetadata(File pack, int maximumDistance, int expansion, - int sourceSpan, int overrideSpan) { - return validateWithJigsawMetadata( - pack, "test:structure", maximumDistance, expansion, sourceSpan, overrideSpan); - } - - private List validateWithJigsawMetadata( - File pack, - String structureKey, - int maximumDistance, - int expansion, - int sourceSpan, - int overrideSpan - ) { - IrisPlatform previous = IrisPlatforms.isBound() ? IrisPlatforms.get() : null; - IrisPlatform platform = mock(IrisPlatform.class); - PlatformStructureHooks hooks = mock(PlatformStructureHooks.class); - when(platform.structureHooks()).thenReturn(hooks); - when(hooks.structureKeys()).thenReturn(List.of(structureKey)); - when(hooks.jigsawStructureKeys()).thenReturn(List.of(structureKey)); - when(hooks.templatePoolKeys()).thenReturn(List.of("test:start", "test:override")); - when(hooks.jigsawSourceMetadata(structureKey)) - .thenReturn(new JigsawSourceMetadata(maximumDistance, expansion, sourceSpan)); - when(hooks.jigsawStartPoolHorizontalSpan( - structureKey, "test:override")).thenReturn(overrideSpan); - IrisPlatforms.unbind(); - IrisPlatforms.bind(platform); - try { - return PackObjectSurfaceValidator.validateStructureGraph(pack); - } finally { - IrisPlatforms.unbind(); - if (previous != null) { - IrisPlatforms.bind(previous); - } - } - } - - private List validateWithUnavailableJigsawMetadata(File pack) { - IrisPlatform previous = IrisPlatforms.isBound() ? IrisPlatforms.get() : null; - IrisPlatform platform = mock(IrisPlatform.class); - PlatformStructureHooks hooks = mock(PlatformStructureHooks.class); - when(platform.structureHooks()).thenReturn(hooks); - when(hooks.structureKeys()).thenReturn(List.of("test:structure")); - when(hooks.jigsawStructureKeys()).thenReturn(List.of("test:structure")); - when(hooks.templatePoolKeys()).thenReturn(List.of("test:start")); - IrisPlatforms.unbind(); - IrisPlatforms.bind(platform); - try { - return PackObjectSurfaceValidator.validateStructureGraph(pack); - } finally { - IrisPlatforms.unbind(); - if (previous != null) { - IrisPlatforms.bind(previous); - } - } - } - - private List validateWithNonJigsawSource(File pack) { - IrisPlatform previous = IrisPlatforms.isBound() ? IrisPlatforms.get() : null; - IrisPlatform platform = mock(IrisPlatform.class); - PlatformStructureHooks hooks = mock(PlatformStructureHooks.class); - when(platform.structureHooks()).thenReturn(hooks); - when(hooks.structureKeys()).thenReturn(List.of("test:structure", "test:jigsaw")); - when(hooks.jigsawStructureKeys()).thenReturn(List.of("test:jigsaw")); - when(hooks.templatePoolKeys()).thenReturn(List.of("test:start")); - when(hooks.jigsawSourceMetadata("test:jigsaw")) - .thenReturn(new JigsawSourceMetadata(80, 0)); - IrisPlatforms.unbind(); - IrisPlatforms.bind(platform); - try { - return PackObjectSurfaceValidator.validateStructureGraph(pack); - } finally { - IrisPlatforms.unbind(); - if (previous != null) { - IrisPlatforms.bind(previous); - } - } - } - private static List nativeReplacementErrors( File pack, Set replacementOutputStructures, diff --git a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorStructureTerrainBackendTest.java b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorStructureTerrainBackendTest.java index 57c5b8e50..a2b1b5525 100644 --- a/core/src/test/java/art/arcane/iris/core/pack/PackValidatorStructureTerrainBackendTest.java +++ b/core/src/test/java/art/arcane/iris/core/pack/PackValidatorStructureTerrainBackendTest.java @@ -8,81 +8,84 @@ import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.util.ArrayList; import java.util.List; import java.util.Locale; -import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class PackValidatorStructureTerrainBackendTest { + private static final String TERRAIN_MODE_PATH = ".terrain.mode "; + @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Test public void rejectsNativeOnlyTerrainModesForEditablePlacementsAcrossEveryHost() throws Exception { for (String mode : List.of("VACUUM", "ENCASE")) { - String folderName = "editable-" + mode.toLowerCase(Locale.ROOT); - File pack = temporaryFolder.newFolder(folderName); - writePlacement(pack, "dimensions/main.json", "dimension-" + folderName, - "dimension_city", false, mode); - writePlacement(pack, "regions/forest.json", "region-" + folderName, - "forest_tower", false, mode); - writePlacement(pack, "biomes/plains.json", "biome-" + folderName, - "plains_farm", false, mode); - List errors = new ArrayList<>(); + String packName = "editable-" + mode.toLowerCase(Locale.ROOT); + File pack = temporaryFolder.newFolder(packName); + write(pack, "dimensions/main.json", "{\"regions\":[\"forest\"]," + placement("dimension", "city", false, mode) + "}"); + write(pack, "regions/forest.json", "{\"landBiomes\":[\"plains\"]," + placement("region", "tower", false, mode) + "}"); + write(pack, "biomes/plains.json", "{\"name\":\"Plains\"," + placement("biome", "farm", false, mode) + "}"); + for (String structure : List.of("city", "tower", "farm")) { + write(pack, "structures/" + structure + ".json", "{\"startPool\":\"start\"}"); + } + write(pack, "jigsaw-pools/start.json", "{\"pieces\":[]}"); - PackStructurePlacementValidator.validateStructurePlacements( - pack, Set.of("dimension_city", "forest_tower", "plains_farm"), false, errors); - - String suffix = ".terrain.mode " + mode + " cannot target editable Iris structures; " - + "use nativeStructures or importedStructures.adjustments for native terrain preparation."; + String suffix = ": structures[0].terrain.mode " + mode + " cannot target editable Iris structures;" + + " use nativeStructures or importedStructures.adjustments for native terrain preparation"; assertEquals(List.of( - "Dimension 'main' structures[0]" + suffix, - "Region 'forest' structures[0]" + suffix, - "Biome 'plains' structures[0]" + suffix - ), errors); + packName + ":dimension/main" + suffix, + packName + ":region/forest" + suffix, + packName + ":biome/plains" + suffix + ), terrainModeErrors(pack)); } } @Test public void acceptsNativeOnlyTerrainModesForNativeStructurePlacements() throws Exception { for (String mode : List.of("VACUUM", "ENCASE")) { - File pack = temporaryFolder.newFolder("native-" + mode.toLowerCase(Locale.ROOT)); - writePlacement(pack, "dimensions/main.json", "native-" + mode, - "minecraft:village_plains", true, mode); - List errors = new ArrayList<>(); + File pack = singleDimensionPack("native-" + mode.toLowerCase(Locale.ROOT), + placement("native", "minecraft:village_plains", true, mode)); - PackStructurePlacementValidator.validateStructurePlacements(pack, Set.of(), false, errors); - - assertTrue(mode + ": " + errors, errors.isEmpty()); + assertTrue(mode + ": " + terrainModeErrors(pack), terrainModeErrors(pack).isEmpty()); } } @Test public void acceptsSupportedTerrainModesForEditablePlacements() throws Exception { for (String mode : List.of("SOURCE", "PRESERVE", "BORE", "FORCE_CARVE")) { - File pack = temporaryFolder.newFolder("editable-" + mode.toLowerCase(Locale.ROOT)); - writePlacement(pack, "dimensions/main.json", "editable-" + mode, - "dimension_city", false, mode); - List errors = new ArrayList<>(); + File pack = singleDimensionPack("editable-" + mode.toLowerCase(Locale.ROOT), + placement("editable", "city", false, mode)); + write(pack, "structures/city.json", "{\"startPool\":\"start\"}"); + write(pack, "jigsaw-pools/start.json", "{\"pieces\":[]}"); - PackStructurePlacementValidator.validateStructurePlacements( - pack, Set.of("dimension_city"), false, errors); - - assertTrue(mode + ": " + errors, errors.isEmpty()); + assertTrue(mode + ": " + terrainModeErrors(pack), terrainModeErrors(pack).isEmpty()); } } - private void writePlacement(File pack, String relativePath, String placementId, - String structureKey, boolean nativeStructure, - String terrainMode) throws Exception { + private File singleDimensionPack(String packName, String dimensionMembers) throws Exception { + File pack = temporaryFolder.newFolder(packName); + write(pack, "dimensions/main.json", "{\"regions\":[\"region\"]," + dimensionMembers + "}"); + write(pack, "regions/region.json", "{\"landBiomes\":[\"biome\"]}"); + write(pack, "biomes/biome.json", "{\"name\":\"Biome\"}"); + return pack; + } + + /** A {@code structures} member holding one placement of {@code structureKey} with terrain {@code terrainMode}. */ + private static String placement(String placementId, String structureKey, boolean nativeStructure, String terrainMode) { String source = nativeStructure ? "\"nativeStructures\":[{\"structure\":\"" + structureKey + "\"}]" : "\"structures\":[\"" + structureKey + "\"]"; - write(pack, relativePath, "{\"structures\":[{\"placementId\":\"" + placementId - + "\"," + source + ",\"terrain\":{\"mode\":\"" + terrainMode + "\"}}]}"); + return "\"structures\":[{\"placementId\":\"" + placementId + "\"," + source + + ",\"terrain\":{\"mode\":\"" + terrainMode + "\"}}]"; + } + + private static List terrainModeErrors(File pack) { + return PackValidator.validate(pack).getBlockingErrors().stream() + .filter(error -> error.contains(TERRAIN_MODE_PATH)) + .toList(); } private void write(File root, String relativePath, String content) throws Exception { diff --git a/core/src/test/java/art/arcane/iris/core/service/StudioSVCProjectSafetyTest.java b/core/src/test/java/art/arcane/iris/core/service/StudioSVCProjectSafetyTest.java index 5bcf18719..6fdf7b327 100644 --- a/core/src/test/java/art/arcane/iris/core/service/StudioSVCProjectSafetyTest.java +++ b/core/src/test/java/art/arcane/iris/core/service/StudioSVCProjectSafetyTest.java @@ -1,5 +1,6 @@ package art.arcane.iris.core.service; +import art.arcane.iris.core.IrisSettings; import art.arcane.iris.core.pack.PackValidationResult; import art.arcane.iris.core.pack.PackValidator; import org.junit.Assume; @@ -21,8 +22,13 @@ public class StudioSVCProjectSafetyTest { @Test public void createsLocalStarterWithoutARepositoryDownload() throws IOException { File workspace = temporaryFolder.newFolder("starter-workspace"); - - StudioSVC.createStarterProject(workspace, "new_pack"); + IrisSettings previous = IrisSettings.settings; + IrisSettings.settings = new IrisSettings(); + try { + StudioSVC.createStarterProject(workspace, "new_pack"); + } finally { + IrisSettings.settings = previous; + } Path project = workspace.toPath().resolve("new_pack"); assertTrue(Files.isRegularFile(project.resolve("dimensions/new_pack.json"))); diff --git a/core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java b/core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java index 84a51389e..d6b2e4dba 100644 --- a/core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java +++ b/core/src/test/java/art/arcane/iris/engine/loot/LootValidatorTest.java @@ -13,6 +13,7 @@ import com.volmit.config.MaxNumber; import com.volmit.config.PackSettings; import com.volmit.config.SettingsStack; import com.volmit.resource.PackResources; +import com.volmit.resource.PlatformRegistries; import com.volmit.resource.ResourceId; import com.volmit.validation.Problem; import com.volmit.validation.Severity; @@ -23,6 +24,7 @@ import org.junit.Test; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -219,6 +221,11 @@ public class LootValidatorTest { }; } + @Override + public Optional platform() { + return Optional.empty(); + } + @Override public void report(Problem problem) { problems.add(problem);