diff --git a/core/src/main/java/art/arcane/iris/core/modules/StructureCommands.java b/core/src/main/java/art/arcane/iris/core/modules/StructureCommands.java new file mode 100644 index 000000000..d1ae69a6c --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/StructureCommands.java @@ -0,0 +1,95 @@ +/* + * 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 art.arcane.iris.core.structure.StructureIndexService; +import art.arcane.iris.core.tooling.IrisToolPack; +import art.arcane.iris.engine.framework.PlacedStructurePiece; +import art.arcane.iris.engine.framework.structure.StructureAssemblyResult; +import art.arcane.iris.engine.framework.structure.StructureResources; +import art.arcane.iris.engine.object.structure.IrisStructure; +import art.arcane.iris.engine.object.value.IrisPosition; +import art.arcane.volmlib.util.math.RNG; +import com.volmit.resource.ResourceId; +import com.volmit.tooling.Argument; +import com.volmit.tooling.Command; +import com.volmit.tooling.CommandContext; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +/** The {@code /iris structure} commands of {@link StructureModelModule}: the index, one structure's graph, and the verification of a world's structures. */ +final class StructureCommands { + private static final String ROOT_NAME = "structure"; + private static final long INFO_SAMPLE_SEED = 1234L; + private static final int INFO_ORIGIN_Y = 64; + + private static final Argument STRUCTURE = Argument.resource("structure", StructureResources.STRUCTURES) + .describe("The Iris structure to inspect"); + + private StructureCommands() { + } + + static Command root() { + return Command.named(ROOT_NAME).alias("struct", "str") + .describe("Iris structure tools") + .child(Command.named("list").alias("ls") + .describe("Write the index of every vanilla, datapack and Iris structure of the pack") + .runs(StructureCommands::list)) + .child(Command.named("info") + .describe("Resolve an Iris structure's jigsaw graph and report its piece count and footprint") + .argument(STRUCTURE) + .runs(StructureCommands::info)) + .child(Command.named("verify").alias("locateall") + .describe("Verify native structure eligibility and locate Iris-placed structures in the world you stand in") + .argument(StructureVerification.RADIUS) + .runs(StructureVerification::run)); + } + + private static void list(CommandContext context) throws IOException { + File index = context.pack().edit(packRoot -> StructureIndexService.write(IrisToolPack.dataOf(context.pack()))); + context.sender().success("Wrote the structure index: " + index.getPath()); + } + + private static void info(CommandContext context) { + ResourceId id = context.get(STRUCTURE); + IrisStructure structure = context.pack().resources().require(StructureResources.STRUCTURES, id); + StructureAssemblyResult assembly = StructureAssemblies + .forData(IrisToolPack.dataOf(context.pack()), structure, new IrisPosition(0, INFO_ORIGIN_Y, 0)) + .assemble(new RNG(INFO_SAMPLE_SEED)); + if (!assembly.hasOutput()) { + context.sender().error("Structure " + id + " assembled 0 pieces (check startPool '" + structure.getStartPool() + "')"); + return; + } + List pieces = assembly.pieces(); + int minX = Integer.MAX_VALUE; + int minZ = Integer.MAX_VALUE; + int maxX = Integer.MIN_VALUE; + int maxZ = Integer.MIN_VALUE; + for (PlacedStructurePiece piece : pieces) { + minX = Math.min(minX, piece.getMinX()); + minZ = Math.min(minZ, piece.getMinZ()); + maxX = Math.max(maxX, piece.getMaxX()); + maxZ = Math.max(maxZ, piece.getMaxZ()); + } + context.sender().success("Structure " + id + ": " + pieces.size() + " pieces, footprint " + (maxX - minX + 1) + "x" + + (maxZ - minZ + 1) + " blocks (sample seed " + INFO_SAMPLE_SEED + ")"); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/modules/StructureModelModule.java b/core/src/main/java/art/arcane/iris/core/modules/StructureModelModule.java index 33af51654..48d556773 100644 --- a/core/src/main/java/art/arcane/iris/core/modules/StructureModelModule.java +++ b/core/src/main/java/art/arcane/iris/core/modules/StructureModelModule.java @@ -40,6 +40,8 @@ import com.volmit.service.VanillaStructures; * ({@link StructureVanillaStructures}): the dimension's {@code importedStructures} settings disable, move, fit and set * them up, and the pack's structure placements replace them, place them alongside, start them where their * {@code nativeStructures} grids say and fit them into the terrain. + *

+ * It mounts {@code /iris structure list|info|verify} ({@link StructureCommands}) through the tooling api. */ public final class StructureModelModule implements IrisModule { private static final String VERSION = "built-in"; @@ -55,5 +57,6 @@ public final class StructureModelModule implements IrisModule { registry.registerValidator(new StructureValidator()); registry.registerService(StructureLocator.class, new StructureLocating()); registry.registerService(VanillaStructures.class, new StructureVanillaStructures()); + setup.tooling().registerCommand(StructureCommands.root()); } } diff --git a/core/src/main/java/art/arcane/iris/core/modules/StructureVerification.java b/core/src/main/java/art/arcane/iris/core/modules/StructureVerification.java new file mode 100644 index 000000000..3872fcc02 --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/modules/StructureVerification.java @@ -0,0 +1,163 @@ +/* + * 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 art.arcane.iris.engine.framework.Engine; +import art.arcane.iris.engine.framework.NativeStructureGenerationPolicy; +import art.arcane.iris.engine.framework.NativeStructureGenerationStatus; +import art.arcane.iris.engine.framework.StructureReachability; +import com.volmit.config.Reference; +import com.volmit.tooling.Argument; +import com.volmit.tooling.CommandContext; +import com.volmit.tooling.Sender; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.TreeSet; + +/** + * {@code /iris structure verify}: for every structure the platform registers and every structure the pack's modules place, + * whether it can generate in the world the sender stands in, searching around the world origin for those the pack places. + * Native eligibility is decided without the platform's blocking locate. + */ +final class StructureVerification { + private static final long DEFAULT_RADIUS_CHUNKS = 48L; + private static final long MAX_RADIUS_CHUNKS = 1000L; + private static final int ORIGIN_BLOCK = 0; + + static final Argument RADIUS = Argument.integer("radius", 1, MAX_RADIUS_CHUNKS) + .orElse(DEFAULT_RADIUS_CHUNKS) + .describe("Search radius in chunks around the world origin (larger is much slower)"); + + private final Engine engine; + private final CommandContext context; + private final int radiusChunks; + private final List lines = new ArrayList<>(); + private int located; + private int nativeEligible; + private int disabled; + private int unreachable; + private int searchLimited; + private int errors; + + private StructureVerification(Engine engine, CommandContext context, int radiusChunks) { + this.engine = engine; + this.context = context; + this.radiusChunks = radiusChunks; + } + + static void run(CommandContext context) { + Sender sender = context.sender(); + Engine engine = context.world().flatMap(world -> world.extension(Engine.class)).orElse(null); + if (engine == null) { + sender.error("Stand in a world generated with this pack: verify reads the running world"); + return; + } + int radiusChunks = Math.toIntExact(context.get(RADIUS)); + sender.info("Verifying structures within " + radiusChunks + " chunks of the world origin..."); + new StructureVerification(engine, context, radiusChunks).report(); + } + + private void report() { + List structureKeys = structureKeys(); + if (!verifyAll(structureKeys)) { + return; + } + lines.add("Structure verify: " + located + " Iris placement plans found, " + nativeEligible + " native structures eligible, " + + disabled + " disabled by policy, " + unreachable + " biome-unreachable, " + searchLimited + + " density searches safety-limited, " + errors + " errors. Native eligibility is checked without running blocking live locates."); + lines.forEach(context.sender()::info); + } + + private List structureKeys() { + Set keys = new TreeSet<>(); + context.platform().ifPresent(registries -> registries.ids(Reference.STRUCTURE).forEach(id -> keys.add(id.toString()))); + List ordered = new ArrayList<>(keys); + for (String placed : ModuleServices.placedStructures(engine)) { + if (!keys.contains(placed)) { + ordered.add(placed); + } + } + return ordered; + } + + private boolean verifyAll(List structureKeys) { + Set reachable; + try { + reachable = reachableNativeKeys(structureKeys); + } catch (RuntimeException failure) { + context.pack().log().error("Could not resolve native biome reachability for verification", failure); + context.sender().error("Structure verification could not resolve native biome reachability."); + return false; + } + for (String key : structureKeys) { + verify(key, reachable); + } + return true; + } + + private Set reachableNativeKeys(List structureKeys) { + boolean needsReachability = structureKeys.stream().anyMatch(key -> !ModuleServices.placesStructure(engine, key) + && NativeStructureGenerationPolicy.resolve(engine, key) == NativeStructureGenerationStatus.GENERATE_NATIVE); + return needsReachability ? StructureReachability.reachableKeys(engine) : Set.of(); + } + + private void verify(String key, Set reachable) { + if (ModuleServices.placesStructure(engine, key)) { + locatePlaced(key); + return; + } + if (NativeStructureGenerationPolicy.resolve(engine, key) != NativeStructureGenerationStatus.GENERATE_NATIVE) { + disabled++; + lines.add("[disabled] " + key); + return; + } + if (!reachable.contains(key.toLowerCase(Locale.ROOT))) { + unreachable++; + List missing = StructureReachability.missingBiomeKeys(engine, key); + lines.add("[unreachable] " + key + (missing.isEmpty() ? "" : " needs " + String.join("/", missing))); + return; + } + nativeEligible++; + lines.add("[native-eligible] " + key); + } + + private void locatePlaced(String key) { + try { + ModuleServices.StructureSearch result = ModuleServices.locateStructure(engine, key, ORIGIN_BLOCK, ORIGIN_BLOCK, radiusChunks); + if (result.outcome() == ModuleServices.StructureSearch.Outcome.SEARCH_LIMIT_REACHED) { + searchLimited++; + lines.add("[iris-search-limit] " + key + ": unable to complete the density search before its safety limit was reached"); + return; + } + if (!result.found()) { + lines.add("[iris-not-found] " + key); + return; + } + located++; + lines.add("[iris-planned] " + key + " @ " + result.x() + "," + result.y() + "," + result.z()); + } catch (RuntimeException failure) { + errors++; + lines.add("[error] " + key + ": " + failure.getClass().getSimpleName()); + context.pack().log().error("Could not verify Iris-placed structure '" + key + "'", failure); + } + } +} diff --git a/core/src/test/java/art/arcane/iris/core/modules/StructureVerificationContractTest.java b/core/src/test/java/art/arcane/iris/core/modules/StructureVerificationContractTest.java new file mode 100644 index 000000000..e25702187 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/modules/StructureVerificationContractTest.java @@ -0,0 +1,43 @@ +package art.arcane.iris.core.modules; + +import org.junit.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class StructureVerificationContractTest { + private static String verificationSource() throws IOException { + return Files.readString(Path.of("src/main/java/art/arcane/iris/core/modules/StructureVerification.java")) + .replace("\r\n", "\n"); + } + + @Test + public void reportsDensityLimitAndUsesExactLocatedOrigin() throws IOException { + String source = verificationSource(); + + assertTrue(source.contains("[iris-search-limit]")); + assertTrue(source.contains("density searches safety-limited")); + assertTrue(source.contains("result.x() + \",\" + result.y() + \",\" + result.z()")); + assertFalse(source.contains("at[0] + 8")); + assertFalse(source.contains("at[2] + 8")); + } + + @Test + public void partitionsPolicyBeforeNativeReachability() throws IOException { + String source = verificationSource(); + int methodStart = source.indexOf("private Set reachableNativeKeys("); + int methodEnd = source.indexOf("private void verify(", methodStart); + String method = source.substring(methodStart, methodEnd); + int placedCheck = method.indexOf("!ModuleServices.placesStructure(engine, key)"); + int policyResolution = method.indexOf("NativeStructureGenerationPolicy.resolve(engine, key) == NativeStructureGenerationStatus.GENERATE_NATIVE", placedCheck); + int reachabilityLookup = method.indexOf("StructureReachability.reachableKeys(engine)", policyResolution); + + assertTrue(placedCheck >= 0); + assertTrue(policyResolution > placedCheck); + assertTrue(reachabilityLookup > policyResolution); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/tooling/CommandRootCollisionTest.java b/core/src/test/java/art/arcane/iris/core/tooling/CommandRootCollisionTest.java new file mode 100644 index 000000000..e1089101e --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/tooling/CommandRootCollisionTest.java @@ -0,0 +1,84 @@ +package art.arcane.iris.core.tooling; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.ModuleResourceFixture; +import art.arcane.iris.core.modules.StructureModelModule; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.ModuleSetup; +import com.volmit.tooling.Command; +import org.junit.Test; + +import java.io.File; +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class CommandRootCollisionTest { + private static IrisModule registering(String id, Command root) { + return new IrisModule() { + @Override + public ModuleInfo info() { + return ModuleInfo.of(id, id, "1"); + } + + @Override + public void setup(ModuleSetup setup) { + setup.tooling().registerCommand(root); + } + }; + } + + @Test + public void aModuleCannotTakeTheRootNameOfTheStructureModule() { + var collision = assertThrows(IllegalArgumentException.class, () -> ModuleResourceFixture.catalogOf( + new StructureModelModule(), registering("test:rival", Command.named("structure")))); + + assertTrue(collision.getMessage(), collision.getMessage().contains("Command root structure is registered by module")); + assertTrue(collision.getMessage(), collision.getMessage().contains("iris:structure-model")); + assertTrue(collision.getMessage(), collision.getMessage().contains("test:rival")); + } + + @Test + public void aModuleCannotTakeAnAliasOfTheStructureModule() { + var collision = assertThrows(IllegalArgumentException.class, () -> ModuleResourceFixture.catalogOf( + registering("test:rival", Command.named("shapes").alias("str")), new StructureModelModule())); + + assertTrue(collision.getMessage(), collision.getMessage().contains("Command root str is registered by module")); + assertTrue(collision.getMessage(), collision.getMessage().contains("test:rival")); + assertTrue(collision.getMessage(), collision.getMessage().contains("iris:structure-model")); + } + + @Test + public void aPackWhoseModulesCollideAnswersEveryLineWithTheReason() { + IrisData data = mock(IrisData.class); + when(data.getDataFolder()).thenReturn(new File("clashing")); + when(data.getModules()).thenThrow(new IllegalArgumentException("Command root structure is registered by module " + + "iris:structure-model already, and module test:rival registers it too")); + ServedPack clashing = new IrisServedPack(data); + RecordingSender sender = new RecordingSender(); + sender.studio = Optional.of(clashing); + ToolingCommands dispatcher = new ToolingCommands(new PackDirectory() { + @Override + public Optional find(String name) { + return Optional.empty(); + } + + @Override + public List names() { + return List.of(); + } + }, Runnable::run, Optional::empty); + + assertTrue(dispatcher.execute(sender, List.of("structure", "list"))); + + assertEquals(1, sender.errors.size()); + assertTrue(sender.errors.get(0), sender.errors.get(0).startsWith("The modules of pack clashing did not load: Command root structure")); + assertTrue(sender.errors.get(0), sender.errors.get(0).contains("test:rival")); + } +} diff --git a/core/src/test/java/art/arcane/iris/core/tooling/StructureCommandsTest.java b/core/src/test/java/art/arcane/iris/core/tooling/StructureCommandsTest.java new file mode 100644 index 000000000..9c8d81437 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/tooling/StructureCommandsTest.java @@ -0,0 +1,147 @@ +package art.arcane.iris.core.tooling; + +import art.arcane.iris.core.loader.IrisData; +import art.arcane.iris.core.modules.ModuleResourceFixture; +import art.arcane.iris.core.modules.StructureModelModule; +import art.arcane.iris.engine.framework.structure.StructureResources; +import art.arcane.iris.engine.mantle.components.StructureModule; +import art.arcane.iris.engine.object.structure.IrisStructure; +import art.arcane.iris.spi.IrisPlatform; +import art.arcane.iris.spi.IrisPlatforms; +import art.arcane.iris.spi.PlatformStructureHooks; +import com.volmit.resource.ResourceId; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.nio.file.Files; +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class StructureCommandsTest { + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + private IrisPlatform previousPlatform; + private File packFolder; + private IrisData data; + private ToolingCommands dispatcher; + private final RecordingSender sender = new RecordingSender(); + + @Before + public void aPackServingTheStructureModule() throws Exception { + previousPlatform = IrisPlatforms.isBound() ? IrisPlatforms.get() : null; + IrisPlatforms.unbind(); + IrisPlatform platform = mock(IrisPlatform.class); + PlatformStructureHooks hooks = mock(PlatformStructureHooks.class); + when(platform.structureHooks()).thenReturn(hooks); + when(hooks.structureKeys()).thenReturn(List.of("minecraft:village", "example:castle")); + when(hooks.structureSetKeys()).thenReturn(List.of("minecraft:villages")); + IrisPlatforms.bind(platform); + + packFolder = temporaryFolder.newFolder("overworld"); + data = mock(IrisData.class); + ModuleResourceFixture.serveModules(data, new StructureModelModule(), new StructureModule()); + when(data.getDataFolder()).thenReturn(packFolder); + IrisStructure emptyCastle = new IrisStructure(); + emptyCastle.setStartPool("ghost-pool"); + ModuleResourceFixture.serve(data).resource(StructureResources.STRUCTURES, "empty-castle", emptyCastle); + when(data.getPackResources().require(StructureResources.STRUCTURES, new ResourceId("test", "empty-castle"))) + .thenReturn(emptyCastle); + + ServedPack served = new IrisServedPack(data); + dispatcher = new ToolingCommands(new PackDirectory() { + @Override + public Optional find(String name) { + return name.equals("overworld") ? Optional.of(served) : Optional.empty(); + } + + @Override + public List names() { + return List.of("overworld"); + } + }, Runnable::run, Optional::empty); + } + + @After + public void restorePlatform() { + IrisPlatforms.unbind(); + if (previousPlatform != null) { + IrisPlatforms.bind(previousPlatform); + } + } + + private boolean run(String line) { + return dispatcher.execute(sender, List.of(line.split(" "))); + } + + @Test + public void listWritesTheStructureIndexThroughAnEditAndReloadsOnce() throws Exception { + assertTrue(run("structure list pack=overworld")); + + File index = new File(packFolder, ".iris/structure-index.json"); + assertTrue(index.isFile()); + assertTrue(Files.readString(index.toPath()).contains("example:castle")); + assertEquals(List.of("Wrote the structure index: " + index.getPath()), sender.successes); + assertTrue(sender.errors.isEmpty()); + verify(data, times(1)).invalidateStructureResources(); + } + + @Test + public void theAliasesOfTheRootAndTheCommandAnswerToo() { + assertTrue(run("str ls pack=overworld")); + + assertEquals(1, sender.successes.size()); + } + + @Test + public void infoNamesTheStructureByTheResourcesOfThePack() { + assertTrue(run("structure info nowhere pack=overworld")); + + assertEquals(List.of("No structures resource 'nowhere' in this pack"), sender.errors); + assertEquals(List.of("Use: structure info "), sender.infos); + } + + @Test + public void infoAssemblesTheStructureAndReportsAnInvalidGraphAsTheCommandsFailure() { + assertTrue(run("structure info empty-castle pack=overworld")); + + assertEquals(1, sender.errors.size()); + assertTrue(sender.errors.get(0), sender.errors.get(0).startsWith("structure info failed: ")); + assertTrue(sender.errors.get(0), sender.errors.get(0).contains("references missing start pool 'ghost-pool'")); + } + + @Test + public void verifyNeedsTheWorldOfTheSender() { + assertTrue(run("structure verify pack=overworld")); + + assertEquals(List.of("Stand in a world generated with this pack: verify reads the running world"), sender.errors); + } + + @Test + public void theGroupListsTheThreeCommands() { + assertTrue(run("structure pack=overworld")); + + assertEquals(4, sender.infos.size()); + assertTrue(sender.infos.get(1).startsWith(" structure list")); + assertTrue(sender.infos.get(2).startsWith(" structure info ")); + assertTrue(sender.infos.get(3).startsWith(" structure verify [radius]")); + } + + @Test + public void completionOffersTheStructuresOfThePack() { + when(data.getPackResources().packId()).thenReturn(new ResourceId("test", "overworld")); + + assertEquals(List.of("empty-castle"), dispatcher.complete(sender, List.of("structure", "info", "pack=overworld", "e"))); + } +}