diff --git a/README.md b/README.md index dbb14d9f4..c2b3b66e1 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,11 @@ mantle components outside the stage graph any more. Their stage constants, and t types packs may read, live in `src/main/java/art/arcane/iris/builtin`, the package Iris exposes to pack modules; their stage bodies live beside the features they replace. +Built-in modules also own pack resources and checks of their own. `iris:structure` reads structures, jigsaw +pools and jigsaw pieces as resource kinds (`StructureResources`), from the folders and files packs have always +used, and checks them with its validator (`StructureValidator`: assembly samples and vanilla structure +replacement) wherever Iris validates a pack; Iris core has no loader or validator of its own for them any more. + Every built-in stage is a full port: the module owns its logic and per-engine state, and the mantle stages work out their reach from the pack when it loads. A dimension's `disabledComponents` turns a mantle stage off by its flag (`CARVED`, `OBJECT`, `FLOATING_OBJECT`, `JIGSAW`) or by its stage id. diff --git a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java index b6975b753..a3e1672bb 100644 --- a/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java +++ b/src/main/java/art/arcane/iris/engine/framework/IrisStructureLocator.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.framework; +import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.core.loader.IrisData; import art.arcane.iris.engine.framework.structure.StructureGraphCatalog; import art.arcane.iris.engine.framework.structure.StructureGraphCompilation; @@ -502,7 +503,7 @@ public final class IrisStructureLocator { if (selectedKey == null || selectedKey.isBlank()) { throw new IllegalStateException("Iris structure placement selected a blank structure key"); } - IrisStructure structure = engine.getData().load(IrisStructure.class, selectedKey, false); + IrisStructure structure = StructureResources.structure(engine.getData(), selectedKey); if (structure == null) { throw new IllegalStateException("Iris structure placement references missing structure '" + selectedKey + "'"); @@ -1024,7 +1025,7 @@ public final class IrisStructureLocator { if (structureKey == null || structureKey.isBlank()) { continue; } - IrisStructure structure = data.load(IrisStructure.class, structureKey, false); + IrisStructure structure = StructureResources.structure(data, structureKey); if (structure == null) { continue; } @@ -1085,7 +1086,7 @@ public final class IrisStructureLocator { continue; } for (String structureKey : placement.getStructures()) { - IrisStructure structure = data.load(IrisStructure.class, structureKey, false); + IrisStructure structure = StructureResources.structure(data, structureKey); if (structure == null) { throw new IllegalStateException( "Iris structure placement references missing structure '" + structureKey + "'"); @@ -1208,7 +1209,7 @@ public final class IrisStructureLocator { ? "REPLACE_SOURCE contains a blank Iris structure reference" : "Iris structure placement contains a blank structure reference"); } - IrisStructure structure = data.load(IrisStructure.class, structureKey, false); + IrisStructure structure = StructureResources.structure(data, structureKey); if (structure == null) { throw new IllegalStateException((replacesNative ? "REPLACE_SOURCE references missing Iris structure '" diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java b/src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java new file mode 100644 index 000000000..22cc602f9 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/NativeReplacementValidation.java @@ -0,0 +1,393 @@ +/* + * 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.core.pack.PackValidationIo; +import art.arcane.iris.engine.object.placement.ObjectPlaceMode; +import art.arcane.volmlib.util.json.JSONArray; +import art.arcane.volmlib.util.json.JSONObject; +import com.volmit.validation.Problem; +import com.volmit.validation.Subject; + +import java.io.File; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; + +/** + * Checks the structure placements of a pack's dimensions, regions and biomes that replace a vanilla structure with + * an Iris one ({@code nativeSuppression: REPLACE_SOURCE}): only a dimension may, it must name Iris structures, each + * with a namespaced {@code vanillaSource}, that {@link StructureGraphValidation} found always produce output, and + * whose sampled pieces fit the placement's height band inside the dimension. Reads the pack's JSON as written, so a + * value of the wrong type is reported rather than read as a default. Every problem is an error about the file of the + * dimension, region or biome. It runs with the structure graph check, whose samples it needs. + */ +public final class NativeReplacementValidation { + private static final List STRUCTURE_HOST_FOLDERS = List.of("dimensions", "regions", "biomes"); + private static final String DIMENSIONS_FOLDER = "dimensions"; + private static final String JSON_EXTENSION = ".json"; + private static final Pattern RESOURCE_KEY_PATTERN = Pattern.compile("[a-z0-9_.-]+:[a-z0-9/._-]+"); + + private NativeReplacementValidation() { + } + + /** + * Checks the pack in {@code packFolder}. + * + * @param replacementOutputStructures the structures that always produce output, which alone may replace a vanilla one + * @param sampledVerticalEnvelopes each viable structure's sampled envelopes + */ + public static List validate( + File packFolder, + Set replacementOutputStructures, + Map> sampledVerticalEnvelopes + ) { + List problems = new ArrayList<>(); + if (packFolder == null || !packFolder.isDirectory()) { + return problems; + } + Set viableStructures = replacementOutputStructures == null + ? Set.of() : replacementOutputStructures; + Map> verticalEnvelopes = + sampledVerticalEnvelopes == null ? Map.of() : sampledVerticalEnvelopes; + Map structures = readStructures(packFolder); + for (String folderName : STRUCTURE_HOST_FOLDERS) { + File resourceFolder = new File(packFolder, folderName); + if (!resourceFolder.isDirectory()) { + continue; + } + List resourceFiles = PackValidationIo.listJsonRecursive(resourceFolder); + resourceFiles.sort(Comparator.comparing(File::getPath)); + for (File resourceFile : resourceFiles) { + JSONObject resource = PackValidationIo.readJson(resourceFile); + if (resource == null) { + continue; + } + String resourceKey = PackValidationIo.deriveKey(resourceFolder, resourceFile); + Subject file = Subject.file(folderName + "/" + resourceKey + JSON_EXTENSION); + for (String error : validateResource(folderName, resourceKey, resource, structures, viableStructures, verticalEnvelopes)) { + problems.add(Problem.error(file, error)); + } + } + } + return problems; + } + + private static Map readStructures(File packFolder) { + File structuresFolder = new File(packFolder, StructureResources.STRUCTURES.folder()); + Map structures = new HashMap<>(); + for (File structureFile : PackValidationIo.listJsonRecursive(structuresFolder)) { + JSONObject structure = PackValidationIo.readJson(structureFile); + if (structure != null) { + structures.put(PackValidationIo.deriveKey(structuresFolder, structureFile), structure); + } + } + return structures; + } + + private static List validateResource( + String folderName, + String resourceKey, + JSONObject resource, + Map structures, + Set viableStructures, + Map> verticalEnvelopes + ) { + List blockingErrors = new ArrayList<>(); + JSONArray placements = resource.optJSONArray("structures"); + if (placements == null) { + return blockingErrors; + } + String resourceType = structureHostType(folderName); + for (int placementIndex = 0; placementIndex < placements.length(); placementIndex++) { + JSONObject placement = placements.optJSONObject(placementIndex); + if (placement == null || !placement.has("nativeSuppression")) { + continue; + } + Object rawSuppression = placement.opt("nativeSuppression"); + if (!(rawSuppression instanceof String suppression)) { + blockingErrors.add(resourceType + " '" + resourceKey + "' structures[" + + placementIndex + "].nativeSuppression must be NONE or REPLACE_SOURCE."); + continue; + } + if ("NONE".equals(suppression)) { + continue; + } + if (!"REPLACE_SOURCE".equals(suppression)) { + blockingErrors.add(resourceType + " '" + resourceKey + "' structures[" + + placementIndex + "].nativeSuppression has unsupported value '" + + suppression + "'. Use NONE or REPLACE_SOURCE."); + continue; + } + if (!DIMENSIONS_FOLDER.equals(folderName)) { + blockingErrors.add(resourceType + " '" + resourceKey + "' structures[" + + placementIndex + "] requests REPLACE_SOURCE, but native replacement is only" + + " valid on dimension-level placements."); + continue; + } + JSONArray references = placement.optJSONArray("structures"); + JSONArray nativeStructures = placement.optJSONArray("nativeStructures"); + if (nativeStructures != null && nativeStructures.length() > 0) { + continue; + } + if (references == null || references.length() == 0) { + blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex + + "] requests REPLACE_SOURCE without any structure backend."); + continue; + } + for (int referenceIndex = 0; referenceIndex < references.length(); referenceIndex++) { + Object rawReference = references.opt(referenceIndex); + if (!(rawReference instanceof String structureKey) || structureKey.isBlank()) { + blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex + + "].structures[" + referenceIndex + + "] must name an Iris structure for REPLACE_SOURCE."); + continue; + } + JSONObject structure = structures.get(structureKey); + if (structure == null) { + blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex + + "] cannot REPLACE_SOURCE with missing or invalid structure '" + + structureKey + "'."); + continue; + } + String vanillaSource = structure.optString("vanillaSource", "").trim(); + if (!RESOURCE_KEY_PATTERN.matcher(vanillaSource).matches()) { + blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex + + "] requests REPLACE_SOURCE for structure '" + structureKey + + "', but its vanillaSource is not a valid namespaced registry key."); + } + if (!viableStructures.contains(structureKey)) { + blockingErrors.add("Dimension '" + resourceKey + "' structures[" + placementIndex + + "] requests REPLACE_SOURCE for structure '" + structureKey + + "', but that structure is not runtime-viable. Native generation will not" + + " be used as a fallback."); + continue; + } + validateReplacementVerticalEnvelope( + resourceKey, + resource, + placementIndex, + placement, + structureKey, + structure, + verticalEnvelopes.get(structureKey), + blockingErrors); + } + } + return blockingErrors; + } + + private static String structureHostType(String folderName) { + return switch (folderName) { + case "dimensions" -> "Dimension"; + case "regions" -> "Region"; + case "biomes" -> "Biome"; + default -> "Resource"; + }; + } + + private static void validateReplacementVerticalEnvelope( + String dimensionKey, + JSONObject dimension, + int placementIndex, + JSONObject placement, + String structureKey, + JSONObject structure, + List sampledVerticalEnvelopes, + List blockingErrors + ) { + String context = "Dimension '" + dimensionKey + "' structures[" + placementIndex + + "] REPLACE_SOURCE structure '" + structureKey + "'"; + if (sampledVerticalEnvelopes == null || sampledVerticalEnvelopes.isEmpty()) { + blockingErrors.add(context + " has no sampled vertical envelope. Native generation will not" + + " be used as a fallback."); + return; + } + + DimensionVerticalBounds worldBounds = resolveDimensionVerticalBounds(dimension, context, blockingErrors); + PlacementVerticalBounds placementBounds = resolvePlacementVerticalBounds(placement, context, blockingErrors); + ObjectPlaceMode placeMode = resolvePlaceMode(structure, context, blockingErrors); + if (worldBounds == null || placementBounds == null || placeMode == null) { + return; + } + + for (StructureGraphValidation.SampledVerticalEnvelope sampled : sampledVerticalEnvelopes) { + boolean exactY = placementBounds.underground() + || sampled.pieceCount() > 1 + || placeMode == ObjectPlaceMode.STRUCTURE_PIECE + || placeMode == ObjectPlaceMode.FLOATING; + if (!exactY) { + continue; + } + + long minimumYOffset = sampled.minimumYOffset(); + long maximumYOffset = sampled.maximumYOffset(); + boolean surfaceAligned = !placementBounds.underground() + && sampled.pieceCount() > 1 + && placeMode != ObjectPlaceMode.STRUCTURE_PIECE + && placeMode != ObjectPlaceMode.FLOATING; + if (surfaceAligned) { + maximumYOffset -= minimumYOffset; + minimumYOffset = 0L; + } + + boolean fitsConfiguredRange; + if (placementBounds.underground()) { + long minimumAnchor = Math.max( + Math.max(placementBounds.minimumY(), worldBounds.minimumY()), + worldBounds.minimumY() - minimumYOffset); + long maximumAnchor = Math.min( + Math.min(placementBounds.maximumY(), worldBounds.maximumY()), + worldBounds.maximumY() - maximumYOffset); + fitsConfiguredRange = minimumAnchor <= maximumAnchor; + } else { + long minimumTerrainY = Math.max(placementBounds.minimumY(), worldBounds.minimumY()); + long maximumTerrainY = Math.min(placementBounds.maximumY(), worldBounds.maximumY()); + fitsConfiguredRange = minimumTerrainY <= maximumTerrainY + && minimumTerrainY + minimumYOffset >= worldBounds.minimumY() + && maximumTerrainY + maximumYOffset <= worldBounds.maximumY(); + } + if (fitsConfiguredRange) { + continue; + } + + String alignment = surfaceAligned ? "surface-aligned " : ""; + blockingErrors.add(context + " sampled seed " + sampled.seed() + " has an " + alignment + + "exact-Y piece envelope " + minimumYOffset + ".." + maximumYOffset + + " relative to its anchor, which cannot fit placement band " + + placementBounds.minimumY() + ".." + placementBounds.maximumY() + + " inside writable world " + worldBounds.minimumY() + ".." + worldBounds.maximumY() + + ". Native generation will not be used as a fallback."); + return; + } + } + + private static DimensionVerticalBounds resolveDimensionVerticalBounds( + JSONObject dimension, + String context, + List blockingErrors + ) { + long dimensionMinimum = -64L; + long dimensionMaximum = 320L; + if (dimension.has("dimensionHeight")) { + JSONObject dimensionHeight = dimension.optJSONObject("dimensionHeight"); + if (dimensionHeight == null) { + blockingErrors.add(context + " cannot validate its vertical envelope because dimensionHeight" + + " must be an object."); + return null; + } + Long configuredMinimum = integralJsonNumber(dimensionHeight, "min", 16L); + Long configuredMaximum = integralJsonNumber(dimensionHeight, "max", 32L); + if (configuredMinimum == null || configuredMaximum == null) { + blockingErrors.add(context + " cannot validate its vertical envelope because dimensionHeight" + + " min and max must be finite integer values."); + return null; + } + dimensionMinimum = configuredMinimum; + dimensionMaximum = configuredMaximum; + } + + long writableMinimum = dimensionMinimum + 1L; + long writableMaximum = dimensionMaximum - 1L; + if (writableMinimum > writableMaximum) { + blockingErrors.add(context + " cannot validate its vertical envelope because dimensionHeight " + + dimensionMinimum + ".." + dimensionMaximum + " has no writable structure range."); + return null; + } + return new DimensionVerticalBounds(writableMinimum, writableMaximum); + } + + private static PlacementVerticalBounds resolvePlacementVerticalBounds( + JSONObject placement, + String context, + List blockingErrors + ) { + boolean underground = false; + if (placement.has("underground")) { + Object rawUnderground = placement.opt("underground"); + if (!(rawUnderground instanceof Boolean configuredUnderground)) { + blockingErrors.add(context + " cannot validate its vertical envelope because underground" + + " must be true or false."); + return null; + } + underground = configuredUnderground; + } + Long configuredMinimum = integralJsonNumber(placement, "minHeight", -2032L); + Long configuredMaximum = integralJsonNumber(placement, "maxHeight", 2032L); + if (configuredMinimum == null || configuredMaximum == null) { + blockingErrors.add(context + " cannot validate its vertical envelope because minHeight and" + + " maxHeight must be finite integer values."); + return null; + } + long minimumY = underground + ? Math.min(configuredMinimum, configuredMaximum) : configuredMinimum; + long maximumY = underground + ? Math.max(configuredMinimum, configuredMaximum) : configuredMaximum; + return new PlacementVerticalBounds(minimumY, maximumY, underground); + } + + private static ObjectPlaceMode resolvePlaceMode( + JSONObject structure, + String context, + List blockingErrors + ) { + if (!structure.has("placeMode")) { + return ObjectPlaceMode.STRUCTURE_PIECE; + } + Object rawPlaceMode = structure.opt("placeMode"); + if (!(rawPlaceMode instanceof String placeModeName)) { + blockingErrors.add(context + " cannot validate its vertical envelope because placeMode must name" + + " an Iris object place mode."); + return null; + } + try { + return ObjectPlaceMode.valueOf(placeModeName); + } catch (IllegalArgumentException exception) { + blockingErrors.add(context + " cannot validate its vertical envelope because placeMode '" + + placeModeName + "' is not supported."); + return null; + } + } + + private static Long integralJsonNumber(JSONObject owner, String field, long defaultValue) { + if (!owner.has(field)) { + return defaultValue; + } + Object rawValue = owner.opt(field); + if (!(rawValue instanceof Number number)) { + return null; + } + double value = number.doubleValue(); + if (!Double.isFinite(value) || value != Math.rint(value) + || value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) { + return null; + } + return (long) value; + } + + private record DimensionVerticalBounds(long minimumY, long maximumY) { + } + + private record PlacementVerticalBounds(long minimumY, long maximumY, boolean underground) { + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java index e9688dcea..5b96dd060 100644 --- a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphResolver.java @@ -32,12 +32,12 @@ final class IrisDataStructureGraphResolver implements StructureGraphResolver { @Override public IrisJigsawPool loadPool(String key) { - return data.load(IrisJigsawPool.class, key, false); + return StructureResources.pool(data, key); } @Override public IrisJigsawPiece loadPiece(String key) { - return data.load(IrisJigsawPiece.class, key, false); + return StructureResources.piece(data, key); } @Override diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidation.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidation.java new file mode 100644 index 000000000..715215451 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureGraphValidation.java @@ -0,0 +1,324 @@ +/* + * 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.core.loader.IrisData; +import art.arcane.iris.engine.framework.PlacedStructurePiece; +import art.arcane.iris.engine.framework.StructureAssembler; +import art.arcane.iris.engine.object.prefab.IrisObject; +import art.arcane.iris.engine.object.structure.IrisStructure; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; +import art.arcane.iris.engine.object.value.IrisPosition; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.resource.ResourceId; +import com.volmit.validation.Problem; +import com.volmit.validation.Severity; +import com.volmit.validation.Subject; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Checks that the structures of a pack assemble: each one's jigsaw graph is compiled, the compiler's diagnostics + * become problems, and a viable graph is assembled from every seed of {@link #GEOMETRY_SAMPLE_SEEDS} with collisions + * and radius checked. What the samples show tells {@link NativeReplacementValidation} which structures always give + * output and how far their pieces reach above and below the anchor. + *

+ * Structures, pools and pieces are the pack's {@link StructureResources}; objects are read only as far as their + * bounds, straight from their files. A structure file that fails to load is skipped here: Iris's own structure graph + * check reports malformed JSON. Every problem concerns the structure's file. + */ +public final class StructureGraphValidation { + private static final List GEOMETRY_SAMPLE_SEEDS = List.of( + 0L, 1L, 2L, 3L, 5L, 8L, 13L, 21L, 34L, 55L, 89L, 144L, 233L, 377L, 610L, 987L); + private static final int GEOMETRY_SAMPLE_ORIGIN_Y = 64; + private static final String LEGACY_INDEX_KEY = "structure-index"; + private static final String OBJECTS_FOLDER = "objects"; + private static final String OBJECT_EXTENSION = ".iob"; + private static final String JSON_EXTENSION = ".json"; + + private StructureGraphValidation() { + } + + /** Checks every structure of the pack {@code data} holds. */ + public static Validation validate(IrisData data) { + return validate(data, null); + } + + /** Checks the structures of the pack {@code data} holds whose keys are in {@code activeStructureKeys}, or all when it is null. */ + public static Validation validate(IrisData data, Set activeStructureKeys) { + List problems = new ArrayList<>(); + Set replacementOutputStructures = new LinkedHashSet<>(); + Map> sampledVerticalEnvelopes = new LinkedHashMap<>(); + PackStructureResolver resolver = new PackStructureResolver(data); + for (ResourceId id : data.getPackResources().ids(IrisStructure.class)) { + String structureKey = id.path(); + if (structureKey.equals(LEGACY_INDEX_KEY) || (activeStructureKeys != null && !activeStructureKeys.contains(structureKey))) { + continue; + } + IrisStructure structure = StructureResources.structure(data, structureKey); + if (structure == null) { + continue; + } + validateStructure(structure, resolver, problems, replacementOutputStructures, sampledVerticalEnvelopes); + } + return new Validation(problems, replacementOutputStructures, sampledVerticalEnvelopes); + } + + private static void validateStructure( + IrisStructure structure, + StructureGraphResolver resolver, + List problems, + Set replacementOutputStructures, + Map> sampledVerticalEnvelopes + ) { + String structureKey = structure.getLoadKey(); + Subject file = Subject.file(StructureResources.STRUCTURES.folder() + "/" + structureKey + JSON_EXTENSION); + StructureGraphCompilation compilation; + try { + compilation = StructureGraphCompiler.compile(structure, resolver); + } catch (MalformedObjectResourceException e) { + problems.add(Problem.error(file, e.getMessage())); + return; + } + for (StructureGraphDiagnostic diagnostic : compilation.getDiagnostics()) { + problems.add(diagnostic.severity() == StructureGraphDiagnostic.Severity.ERROR + ? Problem.error(file, diagnostic.message()) + : Problem.warning(file, diagnostic.message())); + } + if (!compilation.isAssemblyViable()) { + problems.add(Problem.error(file, "Structure '" + structureKey + + "' does not produce a complete deterministic assembly and will not generate" + + failedSampleSummary(compilation) + ".")); + return; + } + RuntimeGeometryValidation geometry = validateRuntimeGeometry(compilation); + if (!geometry.failures().isEmpty()) { + problems.add(Problem.error(file, "Structure '" + structureKey + + "' fails sampled collision- and radius-aware assembly: " + + String.join("; ", geometry.failures()) + ".")); + return; + } + sampledVerticalEnvelopes.put(structureKey, geometry.sampledVerticalEnvelopes()); + if (compilation.guaranteesAssemblyOutput() && geometry.outputForEverySample()) { + replacementOutputStructures.add(structureKey); + } + } + + private static RuntimeGeometryValidation validateRuntimeGeometry( + StructureGraphCompilation compilation + ) { + List failures = new ArrayList<>(); + List sampledVerticalEnvelopes = new ArrayList<>(); + boolean outputForEverySample = true; + for (long seed : GEOMETRY_SAMPLE_SEEDS) { + try { + StructureAssembler assembler = StructureAssembler.forCompilation( + compilation, new IrisPosition(0, GEOMETRY_SAMPLE_ORIGIN_Y, 0)); + StructureAssemblyResult result = assembler.assemble(new RNG(seed)); + if (result.status().isFailure()) { + failures.add("seed " + seed + " returned " + result.status() + ": " + result.detail()); + } else if (!result.hasOutput()) { + outputForEverySample = false; + } else { + sampledVerticalEnvelopes.add(sampleVerticalEnvelope(seed, result.pieces())); + } + } catch (RuntimeException e) { + failures.add("seed " + seed + " threw " + e.getClass().getSimpleName() + + ": " + failureMessage(e)); + } + } + return new RuntimeGeometryValidation( + List.copyOf(failures), outputForEverySample, List.copyOf(sampledVerticalEnvelopes)); + } + + private static SampledVerticalEnvelope sampleVerticalEnvelope( + long seed, + List pieces + ) { + int minimumY = Integer.MAX_VALUE; + int maximumY = Integer.MIN_VALUE; + for (PlacedStructurePiece piece : pieces) { + minimumY = Math.min(minimumY, piece.getMinY()); + maximumY = Math.max(maximumY, piece.getMaxY()); + } + return new SampledVerticalEnvelope( + seed, + pieces.size(), + Math.subtractExact(minimumY, GEOMETRY_SAMPLE_ORIGIN_Y), + Math.subtractExact(maximumY, GEOMETRY_SAMPLE_ORIGIN_Y)); + } + + private static Map> immutableEnvelopes( + Map> sampledVerticalEnvelopes + ) { + Map> immutable = new LinkedHashMap<>(); + for (Map.Entry> entry : sampledVerticalEnvelopes.entrySet()) { + immutable.put(entry.getKey(), List.copyOf(entry.getValue())); + } + return Map.copyOf(immutable); + } + + private static String failureMessage(RuntimeException exception) { + return exception.getMessage() == null || exception.getMessage().isBlank() + ? "no failure detail" : exception.getMessage(); + } + + private static String failedSampleSummary(StructureGraphCompilation compilation) { + List failures = new ArrayList<>(); + for (StructureGraphAssemblySample sample : compilation.getAssemblySamples()) { + if (sample.outcome().isComplete()) { + continue; + } + failures.add("seed " + sample.seed() + " placed " + sample.outcome().pieceKeys().size() + + " piece(s), status=" + sample.outcome().status() + + ": " + sample.outcome().detail()); + if (failures.size() == 3) { + break; + } + } + return failures.isEmpty() ? "" : " (" + String.join("; ", failures) + ")"; + } + + /** + * What the check found: its problems, the structures that gave output for every sample of a graph that + * guarantees output (the only ones that may replace a vanilla structure), and each viable structure's sampled + * vertical envelopes. + */ + public record Validation( + List problems, + Set replacementOutputStructures, + Map> sampledVerticalEnvelopes + ) { + public Validation { + problems = List.copyOf(problems); + replacementOutputStructures = Set.copyOf(replacementOutputStructures); + sampledVerticalEnvelopes = immutableEnvelopes(sampledVerticalEnvelopes); + } + + /** The messages of the problems that stop the pack from loading. */ + public List errors() { + return messages(Severity.ERROR); + } + + /** The messages of the problems that are only shown. */ + public List warnings() { + return messages(Severity.WARNING); + } + + private List messages(Severity severity) { + return problems.stream().filter(problem -> problem.severity() == severity).map(Problem::message).distinct().toList(); + } + } + + /** Where one sampled assembly's pieces reach, relative to its anchor. */ + public record SampledVerticalEnvelope(long seed, int pieceCount, int minimumYOffset, int maximumYOffset) { + public SampledVerticalEnvelope { + if (pieceCount <= 0) { + throw new IllegalArgumentException("Sampled vertical envelope must contain at least one piece"); + } + if (maximumYOffset < minimumYOffset) { + throw new IllegalArgumentException("Sampled vertical envelope maximum Y cannot be below minimum Y"); + } + } + } + + private record RuntimeGeometryValidation( + List failures, + boolean outputForEverySample, + List sampledVerticalEnvelopes + ) { + } + + /** Pools and pieces from the pack's structure resources; objects as far as their bounds, read from their files once each. */ + private static final class PackStructureResolver implements StructureGraphResolver { + private final IrisData data; + private final Path objectsRoot; + private final Map objects = new HashMap<>(); + private final Set missingObjects = new LinkedHashSet<>(); + + private PackStructureResolver(IrisData data) { + this.data = data; + this.objectsRoot = data.getDataFolder().toPath().toAbsolutePath().normalize().resolve(OBJECTS_FOLDER); + } + + @Override + public IrisJigsawPool loadPool(String key) { + return StructureResources.pool(data, key); + } + + @Override + public IrisJigsawPiece loadPiece(String key) { + return StructureResources.piece(data, key); + } + + @Override + public IrisObject loadObject(String key) { + if (objects.containsKey(key)) { + return objects.get(key); + } + if (missingObjects.contains(key)) { + return null; + } + Path file = resolveObject(key); + IrisObject object = file == null ? null : readObjectBounds(file); + if (object == null) { + missingObjects.add(key); + return null; + } + objects.put(key, object); + return object; + } + + private Path resolveObject(String key) { + if (key == null || key.isBlank() || key.indexOf('\\') >= 0 || key.indexOf(':') >= 0) { + return null; + } + Path file = objectsRoot.resolve(key + OBJECT_EXTENSION).normalize(); + if (!file.startsWith(objectsRoot) || !Files.isRegularFile(file)) { + return null; + } + return file; + } + + private IrisObject readObjectBounds(Path file) { + try (BufferedInputStream input = new BufferedInputStream(Files.newInputStream(file))) { + return IrisObjectFrameReader.readBounds(input, file.toString()); + } catch (IOException e) { + throw new MalformedObjectResourceException(e.getMessage(), e); + } + } + } + + private static final class MalformedObjectResourceException extends RuntimeException { + private MalformedObjectResourceException(String message, IOException cause) { + super(message, cause); + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java new file mode 100644 index 000000000..e4f22b51e --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureResources.java @@ -0,0 +1,94 @@ +/* + * 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.engine.framework.structure; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.IrisPackResources; +import art.arcane.iris.engine.object.structure.IrisStructure; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPiece; +import art.arcane.iris.engine.object.structure.jigsaw.IrisJigsawPool; +import com.volmit.resource.ResourceId; +import com.volmit.resource.ResourceKind; + +import java.util.List; + +/** + * The resource kinds of module {@code iris:structure}, which keep the folders and files Iris packs have always used, + * and lookups by pack key for code that still names structures, pools and pieces by key. Every lookup goes through + * the pack's {@link com.volmit.resource.PackResources}, so it sees the pack's current snapshot: a hotload, or + * {@link IrisData#invalidateStructureResources()} after a tool rewrote the files, reads them again. + *

+ * Lookups answer null where Iris's loaders did: for a blank key, a key the pack has no file for, and a file that + * fails to load, which was reported when it was read. + */ +public final class StructureResources { + /** Jigsaw structures, in {@code structures/}. */ + public static final ResourceKind STRUCTURES = ResourceKind.of("iris:structure/structure", "structures", IrisStructure.class); + /** Jigsaw pools a structure starts from and connectors lead to, in {@code jigsaw-pools/}. */ + public static final ResourceKind POOLS = ResourceKind.of("iris:structure/pool", "jigsaw-pools", IrisJigsawPool.class); + /** Jigsaw pieces pools hold, each an object with connectors, in {@code jigsaw-pieces/}. */ + public static final ResourceKind PIECES = ResourceKind.of("iris:structure/piece", "jigsaw-pieces", IrisJigsawPiece.class); + + private StructureResources() { + } + + /** Every resource kind of the structure module. */ + public static List> kinds() { + return List.of(STRUCTURES, POOLS, PIECES); + } + + public static IrisStructure structure(IrisData data, String key) { + return find(data, STRUCTURES, key); + } + + public static IrisJigsawPool pool(IrisData data, String key) { + return find(data, POOLS, key); + } + + public static IrisJigsawPiece piece(IrisData data, String key) { + return find(data, PIECES, key); + } + + /** The key of every structure of the pack, in key order. */ + public static List structureKeys(IrisData data) { + return keys(data, STRUCTURES); + } + + /** The key of every jigsaw piece of the pack, in key order. */ + public static List pieceKeys(IrisData data) { + return keys(data, PIECES); + } + + private static T find(IrisData data, ResourceKind kind, String key) { + if (key == null || key.isBlank()) { + return null; + } + IrisPackResources resources = data.getPackResources(); + try { + return resources.find(kind.key(resources.idOf(key))).orElse(null); + } catch (IllegalStateException failedToLoad) { + return null; + } + } + + /** A key's id has the key as its path, so the path names the resource again wherever a key is expected. */ + private static List keys(IrisData data, ResourceKind kind) { + return data.getPackResources().ids(kind.type()).stream().map(ResourceId::path).toList(); + } +} diff --git a/src/main/java/art/arcane/iris/engine/framework/structure/StructureValidator.java b/src/main/java/art/arcane/iris/engine/framework/structure/StructureValidator.java new file mode 100644 index 000000000..d98603420 --- /dev/null +++ b/src/main/java/art/arcane/iris/engine/framework/structure/StructureValidator.java @@ -0,0 +1,92 @@ +/* + * 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.engine.framework.structure; + +import art.arcane.iris.core.loader.IrisData; +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.ValidationContext; +import com.volmit.validation.Validator; + +import java.io.File; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * 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}). 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 { + private static final List STRUCTURE_HOST_FOLDERS = List.of("dimensions", "regions", "biomes"); + private static final String STRUCTURES_FIELD = "structures"; + + @Override + public void validate(ValidationContext pack) { + IrisData data = IrisValidationContext.of(pack).data(); + StructureGraphValidation.Validation graphs = StructureGraphValidation.validate(data, placedStructureKeys(data.getDataFolder())); + graphs.problems().forEach(pack::report); + NativeReplacementValidation.validate(data.getDataFolder(), graphs.replacementOutputStructures(), graphs.sampledVerticalEnvelopes()) + .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. + */ + public static Set placedStructureKeys(File packFolder) { + Set structureKeys = new LinkedHashSet<>(); + if (packFolder == null || !packFolder.isDirectory()) { + return structureKeys; + } + for (String folderName : STRUCTURE_HOST_FOLDERS) { + File resourceFolder = new File(packFolder, folderName); + if (!resourceFolder.isDirectory()) { + continue; + } + for (File resourceFile : PackValidationIo.listJsonRecursive(resourceFolder)) { + addPlacedKeys(structureKeys, PackValidationIo.readJson(resourceFile)); + } + } + return Set.copyOf(structureKeys); + } + + private static void addPlacedKeys(Set structureKeys, JSONObject resource) { + JSONArray placements = resource == null ? null : resource.optJSONArray(STRUCTURES_FIELD); + if (placements == null) { + return; + } + for (int placementIndex = 0; placementIndex < placements.length(); placementIndex++) { + JSONObject placement = placements.optJSONObject(placementIndex); + JSONArray references = placement == null ? null : placement.optJSONArray(STRUCTURES_FIELD); + if (references == null) { + continue; + } + for (int referenceIndex = 0; referenceIndex < references.length(); referenceIndex++) { + if (references.opt(referenceIndex) instanceof String structureKey && !structureKey.isBlank()) { + structureKeys.add(structureKey); + } + } + } + } +} diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java index 1c606762c..8611724c6 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructureModule.java @@ -22,6 +22,9 @@ import art.arcane.iris.builtin.IrisStages; import art.arcane.iris.core.modules.IrisMantleChunk; import art.arcane.iris.core.modules.IrisPackSettings; import art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.structure.StructureResources; +import art.arcane.iris.engine.framework.structure.StructureValidator; +import com.volmit.FeatureRegistry; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.config.PackSettings; @@ -32,6 +35,10 @@ import com.volmit.stage.StageGraph; * Module {@code iris:structure}: Iris structures, written into the mantle after objects, whose trees they clear * where they intersect, and after floating objects. A port of what was Iris's structure mantle component, its * work done by {@link StructurePlacing}, one per engine runtime. Its reach is the pack's largest structure. + *

+ * The module owns the pack's structures, jigsaw pools and jigsaw pieces as resource kinds + * ({@link StructureResources}), read from the folders packs have always used, and checks them with + * {@link StructureValidator} wherever Iris validates a pack. */ public final class StructureModule implements IrisModule { private static final String VERSION = "built-in"; @@ -47,6 +54,12 @@ public final class StructureModule implements IrisModule { .reach(StructureModule::reach).run(StructureModule::place); } + @Override + public void register(FeatureRegistry registry) { + StructureResources.kinds().forEach(registry::registerResourceKind); + registry.registerValidator(new StructureValidator()); + } + private static void place(MantleStageContext context) { IrisMantleChunk chunk = IrisMantleChunk.current(); placing(chunk.engine()).place(chunk.writer(), chunk.chunkX(), chunk.chunkZ(), chunk.context()); diff --git a/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java b/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java index fede31277..c09f31c7a 100644 --- a/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java +++ b/src/main/java/art/arcane/iris/engine/mantle/components/StructurePlacing.java @@ -18,6 +18,7 @@ package art.arcane.iris.engine.mantle.components; +import art.arcane.iris.engine.framework.structure.StructureResources; import art.arcane.iris.engine.object.placement.IrisObjectPlacement; import art.arcane.iris.core.IrisSettings; import art.arcane.iris.core.loader.IrisData; @@ -608,7 +609,7 @@ public class StructurePlacing { || terrain.resolvedMode() == IrisStructureTerrainMode.BORE ? Math.max(0, terrain.getHorizontalPadding()) : 0; for (String key : placement.getStructures()) { - IrisStructure structure = engine.getData().load(IrisStructure.class, key, false); + IrisStructure structure = StructureResources.structure(engine.getData(), key); if (structure != null) { max = Math.max(max, Math.max(1, structure.getMaxSizeChunks()) * 16 + carvePadding); }